Initial pocketkv: dashboard, read-only API, OpenAPI spec

A self-hosted key-value store for serving JSON values to static sites.

- Dashboard behind HTTP Basic Auth (credentials from .env) to manage
  stores, edit JSON values in an Ace editor, and create read-only API keys
- Read-only API authenticated with bearer tokens, CORS enabled
- OpenAPI 3.1 spec served at /openapi.yaml
- Go standard library only; data persisted to a single JSON file

Co-Authored-By: Claude Opus 5.5 <[email protected]>
This commit is contained in:
Paul TalandClaude Opus 5.5 committed 2026-11-22 22:25:23 +02:00
commit cb29d58aa2
16 files changed
+1318

No files matched your search

+7
View File
@@ -0,0 +1,7 @@
# Dashboard login (HTTP Basic Auth). Both are required.
DASHBOARD_USER=admin
DASHBOARD_PASSWORD=change-me
# Optional
ADDR=:8080
DATA_FILE=data/pocketkv.json
+3
View File
@@ -0,0 +1,3 @@
.env
data/
/pocketkv
+55
View File
@@ -0,0 +1,55 @@
# pocketkv
Simple minimal self hostable kv datastore you can use to serve dynamic read-only values to static sites.
- **Dashboard** (HTTP Basic Auth): create stores, edit JSON values in a code editor, create read-only API keys.
- **API** (read-only, CORS `*`): read one value or all values of a store with an API key. Keys are safe to embed in static sites.
- Go standard library only. All data lives in one JSON file.
## Run
```sh
cp .env.example .env # set DASHBOARD_USER / DASHBOARD_PASSWORD
go run ./cmd/pocketkv
```
Open http://localhost:8080.
| Variable | Default | |
|----------------------|----------------------|----------------------------------|
| `DASHBOARD_USER` | required | dashboard login |
| `DASHBOARD_PASSWORD` | required | dashboard password |
| `ADDR` | `:8080` | listen address |
| `DATA_FILE` | `data/pocketkv.json` | where everything is stored |
Real environment variables take precedence over `.env`. Back up by copying `DATA_FILE`.
Basic Auth sends the password with every request, so put the dashboard behind HTTPS (e.g. a reverse proxy) if it is reachable from outside your network.
## API
The OpenAPI spec is served at `/openapi.yaml` (source: [`internal/api/openapi.yaml`](internal/api/openapi.yaml)).
```js
const headers = { Authorization: "Bearer pkv_..." };
// one value
const hero = await fetch("https://kv.example.com/api/v1/values/hero", { headers }).then(r => r.json());
// all values in the store, as { key: value }
const all = await fetch("https://kv.example.com/api/v1/values", { headers }).then(r => r.json());
```
The API key is sent as a bearer token: `Authorization: Bearer <key>`.
Values must be valid JSON (any type: object, array, string, number, …). Keys use letters, digits and `. _ : -`.
## Layout
```
cmd/pocketkv/ main: config, routing, graceful shutdown
internal/config/ .env + environment loading
internal/store/ stores, values, API keys; persisted to one JSON file
internal/api/ public read-only API + openapi.yaml
internal/web/ dashboard handlers + html/template pages
```
The JSON editor is [Ace](https://ace.c9.io), loaded from jsDelivr. If the CDN can't be reached, the editor falls back to a plain textarea.
+55
View File
@@ -0,0 +1,55 @@
// Command pocketkv serves the dashboard and the read-only KV API.
package main
import (
"context"
"errors"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"github.com/katistix/pocketkv/internal/api"
"github.com/katistix/pocketkv/internal/config"
"github.com/katistix/pocketkv/internal/store"
"github.com/katistix/pocketkv/internal/web"
)
func main() {
cfg, err := config.Load(".env")
if err != nil {
log.Fatal(err)
}
db, err := store.Open(cfg.DataFile)
if err != nil {
log.Fatal(err)
}
mux := http.NewServeMux()
mux.Handle("/api/", api.New(db))
mux.HandleFunc("GET /openapi.yaml", api.Spec)
mux.HandleFunc("GET /healthz", func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("ok")) })
mux.Handle("/", web.New(db, cfg.DashboardUser, cfg.DashboardPassword))
srv := &http.Server{
Addr: cfg.Addr,
Handler: mux,
ReadHeaderTimeout: 10 * time.Second,
}
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt, syscall.SIGTERM)
defer stop()
go func() {
<-ctx.Done()
shutdownCtx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
srv.Shutdown(shutdownCtx)
}()
log.Printf("pocketkv listening on %s (data: %s)", cfg.Addr, cfg.DataFile)
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatal(err)
}
}
+3
View File
@@ -0,0 +1,3 @@
module github.com/katistix/pocketkv
go 1.25
+106
View File
@@ -0,0 +1,106 @@
// Package api serves the public, read-only HTTP API described in openapi.yaml.
package api
import (
_ "embed"
"encoding/json"
"errors"
"net/http"
"strings"
"github.com/katistix/pocketkv/internal/store"
)
//go:embed openapi.yaml
var spec []byte
// New returns the handler for everything under /api/.
func New(db *store.DB) http.Handler {
h := &handler{db: db}
mux := http.NewServeMux()
mux.HandleFunc("GET /api/v1/values", h.list)
mux.HandleFunc("GET /api/v1/values/{key}", h.get)
mux.HandleFunc("/api/", func(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusNotFound, "not found")
})
return cors(mux)
}
// Spec serves the OpenAPI document.
func Spec(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Content-Type", "application/yaml")
w.Write(spec)
}
type handler struct{ db *store.DB }
func (h *handler) list(w http.ResponseWriter, r *http.Request) {
name, ok := h.auth(w, r)
if !ok {
return
}
s, err := h.db.Get(name)
if err != nil {
writeError(w, http.StatusNotFound, "store not found")
return
}
writeJSON(w, s.Values)
}
func (h *handler) get(w http.ResponseWriter, r *http.Request) {
name, ok := h.auth(w, r)
if !ok {
return
}
v, err := h.db.Value(name, r.PathValue("key"))
if errors.Is(err, store.ErrNotFound) {
writeError(w, http.StatusNotFound, "key not found")
return
}
writeJSON(w, v)
}
// auth resolves the API key, sent as "Authorization: Bearer <key>", to a
// store name.
func (h *handler) auth(w http.ResponseWriter, r *http.Request) (string, bool) {
key, _ := strings.CutPrefix(r.Header.Get("Authorization"), "Bearer ")
name, ok := h.db.StoreForAPIKey(key)
if !ok {
w.Header().Set("WWW-Authenticate", "Bearer")
writeError(w, http.StatusUnauthorized, "missing or invalid API key")
}
return name, ok
}
// cors allows any origin: keys are meant to be embedded in static sites.
func cors(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
if r.Method == http.MethodOptions {
w.Header().Set("Access-Control-Allow-Methods", "GET, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Authorization")
w.Header().Set("Access-Control-Max-Age", "86400")
w.WriteHeader(http.StatusNoContent)
return
}
next.ServeHTTP(w, r)
})
}
func writeJSON(w http.ResponseWriter, v any) {
data, err := json.Marshal(v)
if err != nil {
writeError(w, http.StatusInternalServerError, "encode response")
return
}
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Cache-Control", "no-cache")
w.Write(data)
}
func writeError(w http.ResponseWriter, status int, msg string) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(status)
json.NewEncoder(w).Encode(map[string]string{"error": msg})
}
+52
View File
@@ -0,0 +1,52 @@
package api
import (
"net/http"
"net/http/httptest"
"path/filepath"
"testing"
"github.com/katistix/pocketkv/internal/store"
)
func TestAPI(t *testing.T) {
db, _ := store.Open(filepath.Join(t.TempDir(), "db.json"))
db.CreateStore("s")
db.SetValue("s", "hero", []byte(`{"a":1}`), false)
k, _ := db.CreateAPIKey("s", "")
h := New(db)
auth := http.Header{"Authorization": {"Bearer " + k.Key}}
tests := []struct {
name, path string
header http.Header
status int
body string
}{
{"get", "/api/v1/values/hero", auth, 200, `{"a":1}`},
{"list", "/api/v1/values", auth, 200, `{"hero":{"a":1}}`},
{"missing key", "/api/v1/values/nope", auth, 404, ""},
{"no auth", "/api/v1/values/hero", nil, 401, ""},
{"bad token", "/api/v1/values/hero", http.Header{"Authorization": {"Bearer pkv_wrong"}}, 401, ""},
{"query param not accepted", "/api/v1/values/hero?key=" + k.Key, nil, 401, ""},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req := httptest.NewRequest("GET", tt.path, nil)
for k, v := range tt.header {
req.Header[k] = v
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != tt.status {
t.Fatalf("status = %d, want %d (%s)", rec.Code, tt.status, rec.Body)
}
if tt.body != "" && rec.Body.String() != tt.body {
t.Fatalf("body = %s, want %s", rec.Body, tt.body)
}
if rec.Header().Get("Access-Control-Allow-Origin") != "*" {
t.Fatal("missing CORS header")
}
})
}
}
+94
View File
@@ -0,0 +1,94 @@
openapi: 3.1.0
info:
title: pocketkv
version: 1.0.0
description: |
Read-only API for a pocketkv store.
Each API key belongs to exactly one store, so the key alone decides which
store you read from. Keys are read-only and safe to embed in static sites.
Send the key as a bearer token: `Authorization: Bearer <key>`.
Values are JSON documents and are returned exactly as stored.
All endpoints send `Access-Control-Allow-Origin: *`.
Example:
```js
const res = await fetch("https://kv.example.com/api/v1/values/hero", {
headers: { Authorization: "Bearer pkv_..." },
});
const hero = await res.json();
```
servers:
- url: /
security:
- bearer: []
paths:
/api/v1/values:
get:
operationId: listValues
summary: Get every value in the store
description: Returns one JSON object mapping each key to its value.
responses:
"200":
description: All values in the store, keyed by name.
content:
application/json:
schema:
type: object
additionalProperties: true
example:
hero: { "title": "Hello", "subtitle": "World" }
open: true
"401":
$ref: "#/components/responses/Unauthorized"
/api/v1/values/{key}:
get:
operationId: getValue
summary: Get one value
parameters:
- name: key
in: path
required: true
description: The value's key.
schema:
type: string
pattern: "^[A-Za-z0-9_][A-Za-z0-9._:-]{0,255}$"
responses:
"200":
description: The stored JSON value (any JSON type).
content:
application/json:
schema: {}
example: { "title": "Hello", "subtitle": "World" }
"401":
$ref: "#/components/responses/Unauthorized"
"404":
description: The store has no value under this key.
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
example: { "error": "key not found" }
components:
securitySchemes:
bearer:
type: http
scheme: bearer
description: A pocketkv API key, e.g. `pkv_...`.
schemas:
Error:
type: object
required: [error]
properties:
error:
type: string
responses:
Unauthorized:
description: The API key is missing or invalid.
content:
application/json:
schema:
$ref: "#/components/schemas/Error"
example: { "error": "missing or invalid API key" }
+74
View File
@@ -0,0 +1,74 @@
// Package config loads settings from the environment and an optional .env file.
package config
import (
"bufio"
"errors"
"fmt"
"io/fs"
"os"
"strings"
)
type Config struct {
Addr string // listen address, e.g. ":8080"
DataFile string // path to the JSON data file
DashboardUser string
DashboardPassword string
}
// Load reads envFile (if it exists) into the process environment without
// overriding variables that are already set, then builds a Config.
func Load(envFile string) (Config, error) {
if err := loadDotEnv(envFile); err != nil && !errors.Is(err, fs.ErrNotExist) {
return Config{}, fmt.Errorf("read %s: %w", envFile, err)
}
c := Config{
Addr: getenv("ADDR", ":8080"),
DataFile: getenv("DATA_FILE", "data/pocketkv.json"),
DashboardUser: os.Getenv("DASHBOARD_USER"),
DashboardPassword: os.Getenv("DASHBOARD_PASSWORD"),
}
if c.DashboardUser == "" || c.DashboardPassword == "" {
return Config{}, errors.New("DASHBOARD_USER and DASHBOARD_PASSWORD must be set (see .env.example)")
}
return c, nil
}
func getenv(key, fallback string) string {
if v := os.Getenv(key); v != "" {
return v
}
return fallback
}
// loadDotEnv parses simple KEY=VALUE lines. Blank lines and lines starting
// with # are ignored; values may be wrapped in single or double quotes.
func loadDotEnv(path string) error {
f, err := os.Open(path)
if err != nil {
return err
}
defer f.Close()
sc := bufio.NewScanner(f)
for sc.Scan() {
line := strings.TrimSpace(sc.Text())
if line == "" || strings.HasPrefix(line, "#") {
continue
}
line = strings.TrimPrefix(line, "export ")
key, val, ok := strings.Cut(line, "=")
if !ok {
continue
}
key, val = strings.TrimSpace(key), strings.TrimSpace(val)
if len(val) >= 2 && (val[0] == '"' || val[0] == '\'') && val[len(val)-1] == val[0] {
val = val[1 : len(val)-1]
}
if _, set := os.LookupEnv(key); !set {
os.Setenv(key, val)
}
}
return sc.Err()
}
+271
View File
@@ -0,0 +1,271 @@
// Package store holds all KV stores in memory and persists them to a single
// JSON file. Every mutation rewrites the file atomically (temp file + rename).
package store
import (
"bytes"
"crypto/rand"
"encoding/json"
"errors"
"fmt"
"io/fs"
"maps"
"os"
"path/filepath"
"regexp"
"slices"
"strings"
"sync"
"time"
)
var (
ErrNotFound = errors.New("not found")
ErrExists = errors.New("already exists")
)
var (
storeNameRe = regexp.MustCompile(`^[a-z0-9][a-z0-9-]{0,62}$`)
valueKeyRe = regexp.MustCompile(`^[A-Za-z0-9_][A-Za-z0-9._:-]{0,255}$`)
)
// Store is a named collection of JSON values plus the read-only API keys
// that can read it.
type Store struct {
Name string `json:"name"`
CreatedAt time.Time `json:"created_at"`
Values map[string]json.RawMessage `json:"values"`
APIKeys []APIKey `json:"api_keys"`
}
type APIKey struct {
Key string `json:"key"`
Label string `json:"label"`
CreatedAt time.Time `json:"created_at"`
}
type Summary struct {
Name string
CreatedAt time.Time
Values int
APIKeys int
}
type DB struct {
mu sync.RWMutex
path string
stores map[string]*Store
keyIndex map[string]string // API key -> store name
}
type fileFormat struct {
Stores map[string]*Store `json:"stores"`
}
// Open loads the data file at path, or starts empty if it does not exist.
func Open(path string) (*DB, error) {
db := &DB{path: path, stores: map[string]*Store{}, keyIndex: map[string]string{}}
if err := os.MkdirAll(filepath.Dir(path), 0o700); err != nil {
return nil, err
}
data, err := os.ReadFile(path)
if errors.Is(err, fs.ErrNotExist) {
return db, nil
}
if err != nil {
return nil, err
}
var f fileFormat
if err := json.Unmarshal(data, &f); err != nil {
return nil, fmt.Errorf("parse %s: %w", path, err)
}
for name, s := range f.Stores {
if s.Values == nil {
s.Values = map[string]json.RawMessage{}
}
// The file is pretty-printed; serve values compact.
for k, v := range s.Values {
var buf bytes.Buffer
if err := json.Compact(&buf, v); err != nil {
return nil, fmt.Errorf("store %q key %q: %w", name, k, err)
}
s.Values[k] = buf.Bytes()
}
db.stores[name] = s
for _, k := range s.APIKeys {
db.keyIndex[k.Key] = name
}
}
return db, nil
}
// List returns a summary of every store, sorted by name.
func (db *DB) List() []Summary {
db.mu.RLock()
defer db.mu.RUnlock()
out := make([]Summary, 0, len(db.stores))
for _, s := range db.stores {
out = append(out, Summary{Name: s.Name, CreatedAt: s.CreatedAt, Values: len(s.Values), APIKeys: len(s.APIKeys)})
}
slices.SortFunc(out, func(a, b Summary) int { return strings.Compare(a.Name, b.Name) })
return out
}
// Get returns a copy of the named store.
func (db *DB) Get(name string) (Store, error) {
db.mu.RLock()
defer db.mu.RUnlock()
s, ok := db.stores[name]
if !ok {
return Store{}, ErrNotFound
}
c := *s
c.Values = maps.Clone(s.Values) // values are never mutated in place
c.APIKeys = slices.Clone(s.APIKeys)
return c, nil
}
func (db *DB) CreateStore(name string) error {
if !storeNameRe.MatchString(name) {
return errors.New("store name must be 1-63 characters: lowercase letters, digits and dashes")
}
db.mu.Lock()
defer db.mu.Unlock()
if _, ok := db.stores[name]; ok {
return fmt.Errorf("store %q %w", name, ErrExists)
}
db.stores[name] = &Store{Name: name, CreatedAt: time.Now().UTC(), Values: map[string]json.RawMessage{}}
return db.save()
}
func (db *DB) DeleteStore(name string) error {
db.mu.Lock()
defer db.mu.Unlock()
s, ok := db.stores[name]
if !ok {
return ErrNotFound
}
for _, k := range s.APIKeys {
delete(db.keyIndex, k.Key)
}
delete(db.stores, name)
return db.save()
}
// SetValue stores value (which must be valid JSON) under key. If overwrite is
// false and the key already exists, it returns ErrExists.
func (db *DB) SetValue(name, key string, value []byte, overwrite bool) error {
if !valueKeyRe.MatchString(key) {
return errors.New("key must be 1-256 characters: letters, digits and . _ : - (starting with a letter, digit or _)")
}
var buf bytes.Buffer
if err := json.Compact(&buf, value); err != nil {
return fmt.Errorf("value is not valid JSON: %w", err)
}
db.mu.Lock()
defer db.mu.Unlock()
s, ok := db.stores[name]
if !ok {
return ErrNotFound
}
if _, exists := s.Values[key]; exists && !overwrite {
return fmt.Errorf("key %q %w", key, ErrExists)
}
s.Values[key] = json.RawMessage(buf.Bytes())
return db.save()
}
func (db *DB) DeleteValue(name, key string) error {
db.mu.Lock()
defer db.mu.Unlock()
s, ok := db.stores[name]
if !ok {
return ErrNotFound
}
if _, ok := s.Values[key]; !ok {
return ErrNotFound
}
delete(s.Values, key)
return db.save()
}
// Value returns the JSON value for key in the named store.
func (db *DB) Value(name, key string) (json.RawMessage, error) {
db.mu.RLock()
defer db.mu.RUnlock()
s, ok := db.stores[name]
if !ok {
return nil, ErrNotFound
}
v, ok := s.Values[key]
if !ok {
return nil, ErrNotFound
}
return v, nil
}
// CreateAPIKey generates a new read-only API key for the named store.
func (db *DB) CreateAPIKey(name, label string) (APIKey, error) {
label = strings.TrimSpace(label)
if len(label) > 64 {
return APIKey{}, errors.New("label must be at most 64 characters")
}
db.mu.Lock()
defer db.mu.Unlock()
s, ok := db.stores[name]
if !ok {
return APIKey{}, ErrNotFound
}
k := APIKey{Key: "pkv_" + rand.Text(), Label: label, CreatedAt: time.Now().UTC()}
s.APIKeys = append(s.APIKeys, k)
db.keyIndex[k.Key] = name
return k, db.save()
}
func (db *DB) DeleteAPIKey(name, key string) error {
db.mu.Lock()
defer db.mu.Unlock()
s, ok := db.stores[name]
if !ok || db.keyIndex[key] != name {
return ErrNotFound
}
s.APIKeys = slices.DeleteFunc(s.APIKeys, func(k APIKey) bool { return k.Key == key })
delete(db.keyIndex, key)
return db.save()
}
// StoreForAPIKey returns the name of the store an API key grants access to.
func (db *DB) StoreForAPIKey(key string) (string, bool) {
if key == "" {
return "", false
}
db.mu.RLock()
defer db.mu.RUnlock()
name, ok := db.keyIndex[key]
return name, ok
}
// save writes all stores to disk atomically. The caller must hold db.mu.
func (db *DB) save() error {
data, err := json.MarshalIndent(fileFormat{Stores: db.stores}, "", " ")
if err != nil {
return err
}
tmp, err := os.CreateTemp(filepath.Dir(db.path), ".pocketkv-*.tmp")
if err != nil {
return err
}
defer os.Remove(tmp.Name()) // no-op after a successful rename
if _, err := tmp.Write(data); err != nil {
tmp.Close()
return err
}
if err := tmp.Sync(); err != nil {
tmp.Close()
return err
}
if err := tmp.Close(); err != nil {
return err
}
return os.Rename(tmp.Name(), db.path)
}
+66
View File
@@ -0,0 +1,66 @@
package store
import (
"errors"
"path/filepath"
"testing"
)
func TestPersistAndReload(t *testing.T) {
path := filepath.Join(t.TempDir(), "db.json")
db, err := Open(path)
if err != nil {
t.Fatal(err)
}
if err := db.CreateStore("site"); err != nil {
t.Fatal(err)
}
if err := db.SetValue("site", "hero", []byte(`{ "title": "hi" }`), false); err != nil {
t.Fatal(err)
}
k, err := db.CreateAPIKey("site", "blog")
if err != nil {
t.Fatal(err)
}
db2, err := Open(path)
if err != nil {
t.Fatal(err)
}
name, ok := db2.StoreForAPIKey(k.Key)
if !ok || name != "site" {
t.Fatalf("StoreForAPIKey = %q, %v", name, ok)
}
v, err := db2.Value("site", "hero")
if err != nil || string(v) != `{"title":"hi"}` {
t.Fatalf("Value = %s, %v", v, err)
}
}
func TestValidation(t *testing.T) {
db, _ := Open(filepath.Join(t.TempDir(), "db.json"))
if db.CreateStore("Bad Name") == nil {
t.Error("accepted invalid store name")
}
db.CreateStore("s")
if db.SetValue("s", "k", []byte(`{nope`), true) == nil {
t.Error("accepted invalid JSON")
}
if db.SetValue("s", "a/b", []byte(`1`), true) == nil {
t.Error("accepted invalid key")
}
db.SetValue("s", "k", []byte(`1`), false)
if err := db.SetValue("s", "k", []byte(`2`), false); !errors.Is(err, ErrExists) {
t.Errorf("create over existing key: %v", err)
}
}
func TestDeleteStoreRevokesKeys(t *testing.T) {
db, _ := Open(filepath.Join(t.TempDir(), "db.json"))
db.CreateStore("s")
k, _ := db.CreateAPIKey("s", "")
db.DeleteStore("s")
if _, ok := db.StoreForAPIKey(k.Key); ok {
t.Error("key still valid after store deletion")
}
}
+23
View File
@@ -0,0 +1,23 @@
{{define "content"}}
<h1>Stores</h1>
{{if .Error}}<p class="error">{{.Error}}</p>{{end}}
<form method="post" action="/stores" class="row">
<input type="text" name="name" placeholder="new-store-name" required autocomplete="off">
<button class="primary" type="submit">Create store</button>
</form>
{{if .Stores}}
<table>
<tr><th>Name</th><th>Values</th><th>API keys</th><th>Created</th></tr>
{{range .Stores}}
<tr>
<td><a href="/stores/{{.Name}}">{{.Name}}</a></td>
<td>{{.Values}}</td>
<td>{{.APIKeys}}</td>
<td class="muted">{{.CreatedAt.Format "2006-01-02"}}</td>
</tr>
{{end}}
</table>
{{else}}
<p class="muted">No stores yet.</p>
{{end}}
{{end}}
+45
View File
@@ -0,0 +1,45 @@
{{define "layout"}}<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{block "title" .}}pocketkv{{end}}</title>
<style>
:root { --bg:#fff; --fg:#1a1a1a; --muted:#6b6b6b; --line:#e3e3e3; --accent:#2f6fde; --danger:#c62828; --code:#f4f4f4; color-scheme: light dark; }
@media (prefers-color-scheme: dark) { :root { --bg:#151515; --fg:#e8e8e8; --muted:#999; --line:#2c2c2c; --accent:#6ea0ff; --danger:#ef6461; --code:#1f1f1f; } }
* { box-sizing: border-box; }
body { margin:0; background:var(--bg); color:var(--fg); font:15px/1.5 system-ui, sans-serif; }
header { display:flex; justify-content:space-between; align-items:center; padding:12px 20px; border-bottom:1px solid var(--line); }
header .brand { font-weight:700; color:var(--fg); text-decoration:none; }
main { max-width:960px; margin:0 auto; padding:20px; }
a { color:var(--accent); }
h1 { font-size:1.4rem; margin:0 0 16px; } h2 { font-size:1.1rem; margin:32px 0 12px; }
table { width:100%; border-collapse:collapse; }
th, td { text-align:left; padding:8px 6px; border-bottom:1px solid var(--line); vertical-align:middle; }
th { color:var(--muted); font-weight:500; font-size:.85rem; }
td.actions { text-align:right; white-space:nowrap; }
code, pre { font-family:ui-monospace, SFMono-Regular, Menlo, monospace; font-size:.85rem; background:var(--code); border-radius:4px; }
code { padding:1px 4px; } pre { padding:12px; overflow-x:auto; }
.preview { color:var(--muted); max-width:420px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
form.inline { display:inline; }
.row { display:flex; gap:8px; align-items:center; flex-wrap:wrap; margin:12px 0; }
input[type=text] { padding:7px 9px; border:1px solid var(--line); border-radius:6px; background:var(--bg); color:var(--fg); font:inherit; min-width:240px; }
button, .button { padding:7px 14px; border:1px solid var(--line); border-radius:6px; background:var(--code); color:var(--fg); font:inherit; cursor:pointer; text-decoration:none; display:inline-block; }
button.primary, .button.primary { background:var(--accent); border-color:var(--accent); color:#fff; }
button.danger { color:var(--danger); background:none; border-color:transparent; padding:4px 8px; }
.error { color:var(--danger); }
.muted { color:var(--muted); }
.tablist { display:flex; gap:2px; border-bottom:1px solid var(--line); }
.tablist button { background:none; border:none; border-bottom:2px solid transparent; border-radius:0; padding:6px 12px; color:var(--muted); }
.tablist button[aria-selected=true] { color:var(--fg); border-bottom-color:var(--accent); }
.tablist .copy { margin-left:auto; }
.tabs pre { margin-top:0; border-top-left-radius:0; border-top-right-radius:0; }
.crumbs { color:var(--muted); margin:0 0 8px; }
</style>
{{block "head" .}}{{end}}
</head>
<body>
<header><a class="brand" href="/">pocketkv</a><a href="/openapi.yaml">API spec</a></header>
<main>{{template "content" .}}</main>
</body>
</html>{{end}}
+137
View File
@@ -0,0 +1,137 @@
{{define "title"}}{{.Store.Name}} · pocketkv{{end}}
{{define "content"}}
<p class="crumbs"><a href="/">Stores</a> /</p>
<h1>{{.Store.Name}}</h1>
{{if .Error}}<p class="error">{{.Error}}</p>{{end}}
<h2>Values</h2>
<div class="row"><a class="button primary" href="/stores/{{.Store.Name}}/value">New value</a></div>
{{if .Values}}
<table>
<tr><th>Key</th><th>Value</th><th>Size</th><th></th></tr>
{{range .Values}}
<tr>
<td><a href="/stores/{{$.Store.Name}}/value?key={{.Key}}"><code>{{.Key}}</code></a></td>
<td class="preview"><code>{{.Preview}}</code></td>
<td class="muted">{{.Size}} B</td>
<td class="actions">
<form class="inline" method="post" action="/stores/{{$.Store.Name}}/value/delete" onsubmit="return confirm('Delete {{.Key}}?')">
<input type="hidden" name="key" value="{{.Key}}">
<button class="danger" type="submit">Delete</button>
</form>
</td>
</tr>
{{end}}
</table>
{{else}}
<p class="muted">No values yet.</p>
{{end}}
<h2 id="keys">Read-only API keys</h2>
<form method="post" action="/stores/{{.Store.Name}}/keys" class="row">
<input type="text" name="label" placeholder="label, e.g. my-blog" maxlength="64" autocomplete="off">
<button type="submit">Create API key</button>
</form>
{{if .Store.APIKeys}}
<table>
<tr><th>Label</th><th>Key</th><th>Created</th><th></th></tr>
{{range .Store.APIKeys}}
<tr>
<td>{{if .Label}}{{.Label}}{{else}}<span class="muted">—</span>{{end}}</td>
<td><code>{{.Key}}</code> <button type="button" onclick="navigator.clipboard.writeText('{{.Key}}'); this.textContent='Copied'">Copy</button></td>
<td class="muted">{{.CreatedAt.Format "2006-01-02"}}</td>
<td class="actions">
<form class="inline" method="post" action="/stores/{{$.Store.Name}}/keys/delete" onsubmit="return confirm('Revoke this key? Sites using it will stop working.')">
<input type="hidden" name="key" value="{{.Key}}">
<button class="danger" type="submit">Revoke</button>
</form>
</td>
</tr>
{{end}}
</table>
{{with index .Store.APIKeys 0}}
<h2>Usage</h2>
<div class="tabs" id="usage">
<div class="tablist" role="tablist">
<button type="button" role="tab" data-tab="js" aria-selected="true">JavaScript</button>
<button type="button" role="tab" data-tab="html">HTML</button>
<button type="button" role="tab" data-tab="curl">curl</button>
<button type="button" role="tab" data-tab="python">Python</button>
<button type="button" role="tab" data-tab="go">Go</button>
<button type="button" class="copy">Copy</button>
</div>
<pre data-panel="js">const headers = { Authorization: "Bearer {{.Key}}" };
// one value
const value = await fetch("{{$.BaseURL}}/api/v1/values/{{$.SampleKey}}", { headers }).then(r =&gt; r.json());
// every value in the store, as { key: value }
const all = await fetch("{{$.BaseURL}}/api/v1/values", { headers }).then(r =&gt; r.json());</pre>
<pre data-panel="html" hidden>&lt;pre id="value"&gt;loading…&lt;/pre&gt;
&lt;script type="module"&gt;
const res = await fetch("{{$.BaseURL}}/api/v1/values/{{$.SampleKey}}", {
headers: { Authorization: "Bearer {{.Key}}" },
});
const value = await res.json();
document.getElementById("value").textContent = JSON.stringify(value, null, 2);
&lt;/script&gt;</pre>
<pre data-panel="curl" hidden># one value
curl -H "Authorization: Bearer {{.Key}}" \
{{$.BaseURL}}/api/v1/values/{{$.SampleKey}}
# every value in the store
curl -H "Authorization: Bearer {{.Key}}" \
{{$.BaseURL}}/api/v1/values</pre>
<pre data-panel="python" hidden>import json
import urllib.request
req = urllib.request.Request(
"{{$.BaseURL}}/api/v1/values/{{$.SampleKey}}",
headers={"Authorization": "Bearer {{.Key}}"},
)
with urllib.request.urlopen(req) as res:
value = json.load(res)</pre>
<pre data-panel="go" hidden>req, _ := http.NewRequest("GET", "{{$.BaseURL}}/api/v1/values/{{$.SampleKey}}", nil)
req.Header.Set("Authorization", "Bearer {{.Key}}")
res, err := http.DefaultClient.Do(req)
if err != nil {
log.Fatal(err)
}
defer res.Body.Close()
var value any
if err := json.NewDecoder(res.Body).Decode(&amp;value); err != nil {
log.Fatal(err)
}</pre>
</div>
<script>
(() => {
const root = document.getElementById("usage");
const tabs = root.querySelectorAll("[data-tab]");
const panels = root.querySelectorAll("[data-panel]");
const show = (name) => {
tabs.forEach(t => t.setAttribute("aria-selected", t.dataset.tab === name));
panels.forEach(p => p.hidden = p.dataset.panel !== name);
try { localStorage.setItem("pocketkv-usage-tab", name); } catch {}
};
tabs.forEach(t => t.onclick = () => show(t.dataset.tab));
try { const saved = localStorage.getItem("pocketkv-usage-tab"); if (saved && root.querySelector(`[data-tab="${saved}"]`)) show(saved); } catch {}
root.querySelector(".copy").onclick = (e) => {
navigator.clipboard.writeText(root.querySelector("[data-panel]:not([hidden])").textContent);
e.target.textContent = "Copied";
setTimeout(() => e.target.textContent = "Copy", 1500);
};
})();
</script>
<p class="muted">Full reference: <a href="/openapi.yaml">openapi.yaml</a></p>
{{end}}
{{else}}
<p class="muted">No API keys yet. Create one to read this store from your sites.</p>
{{end}}
<h2>Danger zone</h2>
<form method="post" action="/stores/{{.Store.Name}}/delete" onsubmit="return confirm('Delete store {{.Store.Name}} with all its values and keys?')">
<button class="danger" type="submit" style="border-color:currentColor">Delete store</button>
</form>
{{end}}
+72
View File
@@ -0,0 +1,72 @@
{{define "title"}}{{if .IsNew}}New value{{else}}{{.Key}}{{end}} · {{.Store}} · pocketkv{{end}}
{{define "head"}}
<script src="https://cdn.jsdelivr.net/npm/[email protected]/src-min-noconflict/ace.js"></script>
<style>
#editor { height:65vh; border:1px solid var(--line); border-radius:6px; }
#value { width:100%; height:65vh; font-family:ui-monospace, Menlo, monospace; font-size:14px; }
</style>
{{end}}
{{define "content"}}
<p class="crumbs"><a href="/">Stores</a> / <a href="/stores/{{.Store}}">{{.Store}}</a> /</p>
<form method="post" action="/stores/{{.Store}}/value" id="form">
{{if .IsNew}}
<input type="hidden" name="new" value="1">
<div class="row"><input type="text" name="key" value="{{.Key}}" placeholder="key, e.g. site.hero" required autofocus autocomplete="off"></div>
{{else}}
<h1><code>{{.Key}}</code></h1>
<input type="hidden" name="key" value="{{.Key}}">
{{end}}
{{if .Error}}<p class="error">{{.Error}}</p>{{end}}
<div id="editor" hidden></div>
<textarea name="value" id="value" spellcheck="false">{{.Value}}</textarea>
<div class="row">
<button class="primary" type="submit">Save</button>
<button type="button" id="format">Format</button>
<span class="muted">⌘/Ctrl+S saves</span>
<span id="status" class="error"></span>
</div>
</form>
<script>
(() => {
const form = document.getElementById("form");
const textarea = document.getElementById("value");
const status = document.getElementById("status");
let get = () => textarea.value, set = (v) => { textarea.value = v; };
// Use Ace when the CDN is reachable; otherwise the plain textarea still works.
if (window.ace) {
const el = document.getElementById("editor");
el.hidden = false;
textarea.hidden = true;
ace.config.set("basePath", "https://cdn.jsdelivr.net/npm/[email protected]/src-min-noconflict/");
const dark = matchMedia("(prefers-color-scheme: dark)").matches;
const editor = ace.edit(el, {
mode: "ace/mode/json",
theme: dark ? "ace/theme/tomorrow_night" : "ace/theme/chrome",
value: textarea.value,
tabSize: 2, useSoftTabs: true, showPrintMargin: false, fontSize: 14,
});
editor.commands.addCommand({
name: "save", bindKey: { win: "Ctrl-S", mac: "Command-S" },
exec: () => form.requestSubmit(),
});
editor.focus();
get = () => editor.getValue();
set = (v) => editor.setValue(v, -1);
}
const parse = () => {
try { status.textContent = ""; return [JSON.parse(get()), true]; }
catch (e) { status.textContent = "Invalid JSON: " + e.message; return [null, false]; }
};
document.getElementById("format").onclick = () => {
const [v, ok] = parse();
if (ok) set(JSON.stringify(v, null, 2));
};
form.addEventListener("submit", (e) => {
if (!parse()[1]) { e.preventDefault(); return; }
textarea.value = get();
});
})();
</script>
{{end}}
+255
View File
@@ -0,0 +1,255 @@
// Package web serves the dashboard: server-rendered html/template pages
// behind HTTP Basic Auth.
package web
import (
"bytes"
"crypto/sha256"
"crypto/subtle"
"embed"
"encoding/json"
"errors"
"html/template"
"log"
"net/http"
"slices"
"strings"
"github.com/katistix/pocketkv/internal/store"
)
//go:embed templates/*.html
var templateFS embed.FS
const maxFormBytes = 5 << 20 // 5 MiB per request
type server struct {
db *store.DB
pages map[string]*template.Template
}
// New returns the dashboard handler, protected by Basic Auth and by
// cross-origin request protection on every non-GET request.
func New(db *store.DB, user, password string) http.Handler {
s := &server{db: db, pages: map[string]*template.Template{}}
for _, p := range []string{"index", "store", "value"} {
s.pages[p] = template.Must(template.ParseFS(templateFS, "templates/layout.html", "templates/"+p+".html"))
}
mux := http.NewServeMux()
mux.HandleFunc("GET /{$}", s.index)
mux.HandleFunc("POST /stores", s.createStore)
mux.HandleFunc("GET /stores/{store}", s.showStore)
mux.HandleFunc("POST /stores/{store}/delete", s.deleteStore)
mux.HandleFunc("GET /stores/{store}/value", s.editValue)
mux.HandleFunc("POST /stores/{store}/value", s.saveValue)
mux.HandleFunc("POST /stores/{store}/value/delete", s.deleteValue)
mux.HandleFunc("POST /stores/{store}/keys", s.createAPIKey)
mux.HandleFunc("POST /stores/{store}/keys/delete", s.deleteAPIKey)
var h http.Handler = mux
h = http.NewCrossOriginProtection().Handler(h)
h = http.MaxBytesHandler(h, maxFormBytes)
return basicAuth(user, password, h)
}
func basicAuth(user, password string, next http.Handler) http.Handler {
wantUser, wantPass := sha256.Sum256([]byte(user)), sha256.Sum256([]byte(password))
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
u, p, ok := r.BasicAuth()
gotUser, gotPass := sha256.Sum256([]byte(u)), sha256.Sum256([]byte(p))
userOK := subtle.ConstantTimeCompare(gotUser[:], wantUser[:]) == 1
passOK := subtle.ConstantTimeCompare(gotPass[:], wantPass[:]) == 1
if !ok || !userOK || !passOK {
w.Header().Set("WWW-Authenticate", `Basic realm="pocketkv", charset="UTF-8"`)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
next.ServeHTTP(w, r)
})
}
// --- pages ---
type indexData struct {
Stores []store.Summary
Error string
}
func (s *server) index(w http.ResponseWriter, r *http.Request) {
s.render(w, http.StatusOK, "index", indexData{Stores: s.db.List()})
}
func (s *server) createStore(w http.ResponseWriter, r *http.Request) {
name := strings.TrimSpace(r.FormValue("name"))
if err := s.db.CreateStore(name); err != nil {
s.render(w, http.StatusBadRequest, "index", indexData{Stores: s.db.List(), Error: err.Error()})
return
}
redirect(w, r, "/stores/"+name)
}
func (s *server) deleteStore(w http.ResponseWriter, r *http.Request) {
if err := s.db.DeleteStore(r.PathValue("store")); err != nil {
s.fail(w, err)
return
}
redirect(w, r, "/")
}
type valueRow struct {
Key string
Preview string
Size int
}
type storeData struct {
Store store.Store
Values []valueRow
BaseURL string
SampleKey string // a real key from this store for the usage examples
Error string
}
func (s *server) showStore(w http.ResponseWriter, r *http.Request) {
s.renderStore(w, r, http.StatusOK, "")
}
func (s *server) renderStore(w http.ResponseWriter, r *http.Request, status int, errMsg string) {
st, err := s.db.Get(r.PathValue("store"))
if err != nil {
s.fail(w, err)
return
}
rows := make([]valueRow, 0, len(st.Values))
for k, v := range st.Values {
rows = append(rows, valueRow{Key: k, Preview: truncate(string(v), 80), Size: len(v)})
}
slices.SortFunc(rows, func(a, b valueRow) int { return strings.Compare(a.Key, b.Key) })
sample := "my-key"
if len(rows) > 0 {
sample = rows[0].Key
}
s.render(w, status, "store", storeData{Store: st, Values: rows, BaseURL: baseURL(r), SampleKey: sample, Error: errMsg})
}
type valueData struct {
Store string
Key string
Value string
IsNew bool
Error string
}
func (s *server) editValue(w http.ResponseWriter, r *http.Request) {
name, key := r.PathValue("store"), r.URL.Query().Get("key")
if _, err := s.db.Get(name); err != nil {
s.fail(w, err)
return
}
d := valueData{Store: name, Key: key, IsNew: key == "", Value: "{\n \n}"}
if key != "" {
v, err := s.db.Value(name, key)
if err != nil {
s.fail(w, err)
return
}
var buf bytes.Buffer
json.Indent(&buf, v, "", " ")
d.Value = buf.String()
}
s.render(w, http.StatusOK, "value", d)
}
func (s *server) saveValue(w http.ResponseWriter, r *http.Request) {
name := r.PathValue("store")
d := valueData{
Store: name,
Key: strings.TrimSpace(r.FormValue("key")),
Value: r.FormValue("value"),
IsNew: r.FormValue("new") == "1",
}
if err := s.db.SetValue(name, d.Key, []byte(d.Value), !d.IsNew); err != nil {
if errors.Is(err, store.ErrNotFound) {
s.fail(w, err)
return
}
d.Error = err.Error()
s.render(w, http.StatusBadRequest, "value", d)
return
}
redirect(w, r, "/stores/"+name)
}
func (s *server) deleteValue(w http.ResponseWriter, r *http.Request) {
name := r.PathValue("store")
if err := s.db.DeleteValue(name, r.FormValue("key")); err != nil {
s.fail(w, err)
return
}
redirect(w, r, "/stores/"+name)
}
func (s *server) createAPIKey(w http.ResponseWriter, r *http.Request) {
name := r.PathValue("store")
if _, err := s.db.CreateAPIKey(name, r.FormValue("label")); err != nil {
if errors.Is(err, store.ErrNotFound) {
s.fail(w, err)
return
}
s.renderStore(w, r, http.StatusBadRequest, err.Error())
return
}
redirect(w, r, "/stores/"+name+"#keys")
}
func (s *server) deleteAPIKey(w http.ResponseWriter, r *http.Request) {
name := r.PathValue("store")
if err := s.db.DeleteAPIKey(name, r.FormValue("key")); err != nil {
s.fail(w, err)
return
}
redirect(w, r, "/stores/"+name+"#keys")
}
// --- helpers ---
func (s *server) render(w http.ResponseWriter, status int, page string, data any) {
var buf bytes.Buffer
if err := s.pages[page].ExecuteTemplate(&buf, "layout", data); err != nil {
log.Printf("render %s: %v", page, err)
http.Error(w, "internal error", http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(status)
buf.WriteTo(w)
}
func (s *server) fail(w http.ResponseWriter, err error) {
if errors.Is(err, store.ErrNotFound) {
http.Error(w, "Not found", http.StatusNotFound)
return
}
log.Printf("dashboard: %v", err)
http.Error(w, "internal error", http.StatusInternalServerError)
}
func redirect(w http.ResponseWriter, r *http.Request, to string) {
http.Redirect(w, r, to, http.StatusSeeOther)
}
func baseURL(r *http.Request) string {
scheme := "http"
if r.TLS != nil || r.Header.Get("X-Forwarded-Proto") == "https" {
scheme = "https"
}
return scheme + "://" + r.Host
}
func truncate(s string, n int) string {
if r := []rune(s); len(r) > n {
return string(r[:n]) + "…"
}
return s
}