commit cb29d58aa2193a1de6833c44b738bec87d4b5c46 Author: Paul Tal <2018.tpg@gmail.com> Date: Sun Nov 22 22:25:23 2026 +0200 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 diff --git a/.env.example b/.env.example new file mode 100644 index 0000000..0544624 --- /dev/null +++ b/.env.example @@ -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 diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..6b35931 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +.env +data/ +/pocketkv diff --git a/README.md b/README.md new file mode 100644 index 0000000..5a65e14 --- /dev/null +++ b/README.md @@ -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 `. + +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. diff --git a/cmd/pocketkv/main.go b/cmd/pocketkv/main.go new file mode 100644 index 0000000..b32fc03 --- /dev/null +++ b/cmd/pocketkv/main.go @@ -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) + } +} diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..61e840d --- /dev/null +++ b/go.mod @@ -0,0 +1,3 @@ +module github.com/katistix/pocketkv + +go 1.25 diff --git a/internal/api/api.go b/internal/api/api.go new file mode 100644 index 0000000..dcc97e3 --- /dev/null +++ b/internal/api/api.go @@ -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 ", 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}) +} diff --git a/internal/api/api_test.go b/internal/api/api_test.go new file mode 100644 index 0000000..b2c14be --- /dev/null +++ b/internal/api/api_test.go @@ -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") + } + }) + } +} diff --git a/internal/api/openapi.yaml b/internal/api/openapi.yaml new file mode 100644 index 0000000..1d7f4d7 --- /dev/null +++ b/internal/api/openapi.yaml @@ -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 `. + + 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" } diff --git a/internal/config/config.go b/internal/config/config.go new file mode 100644 index 0000000..7ac753a --- /dev/null +++ b/internal/config/config.go @@ -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() +} diff --git a/internal/store/store.go b/internal/store/store.go new file mode 100644 index 0000000..fe60d0d --- /dev/null +++ b/internal/store/store.go @@ -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) +} diff --git a/internal/store/store_test.go b/internal/store/store_test.go new file mode 100644 index 0000000..1452123 --- /dev/null +++ b/internal/store/store_test.go @@ -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") + } +} diff --git a/internal/web/templates/index.html b/internal/web/templates/index.html new file mode 100644 index 0000000..a41ba60 --- /dev/null +++ b/internal/web/templates/index.html @@ -0,0 +1,23 @@ +{{define "content"}} +

Stores

+{{if .Error}}

{{.Error}}

{{end}} +
+ + +
+{{if .Stores}} + + + {{range .Stores}} + + + + + + + {{end}} +
NameValuesAPI keysCreated
{{.Name}}{{.Values}}{{.APIKeys}}{{.CreatedAt.Format "2006-01-02"}}
+{{else}} +

No stores yet.

+{{end}} +{{end}} diff --git a/internal/web/templates/layout.html b/internal/web/templates/layout.html new file mode 100644 index 0000000..60c594c --- /dev/null +++ b/internal/web/templates/layout.html @@ -0,0 +1,45 @@ +{{define "layout"}} + + + + +{{block "title" .}}pocketkv{{end}} + +{{block "head" .}}{{end}} + + +
pocketkvAPI spec
+
{{template "content" .}}
+ +{{end}} diff --git a/internal/web/templates/store.html b/internal/web/templates/store.html new file mode 100644 index 0000000..3361d09 --- /dev/null +++ b/internal/web/templates/store.html @@ -0,0 +1,137 @@ +{{define "title"}}{{.Store.Name}} · pocketkv{{end}} +{{define "content"}} +

Stores /

+

{{.Store.Name}}

+{{if .Error}}

{{.Error}}

{{end}} + +

Values

+ +{{if .Values}} + + + {{range .Values}} + + + + + + + {{end}} +
KeyValueSize
{{.Key}}{{.Preview}}{{.Size}} B +
+ + +
+
+{{else}} +

No values yet.

+{{end}} + +

Read-only API keys

+
+ + +
+{{if .Store.APIKeys}} + + + {{range .Store.APIKeys}} + + + + + + + {{end}} +
LabelKeyCreated
{{if .Label}}{{.Label}}{{else}}—{{end}}{{.Key}} {{.CreatedAt.Format "2006-01-02"}} +
+ + +
+
+{{with index .Store.APIKeys 0}} +

Usage

+
+
+ + + + + + +
+
const headers = { Authorization: "Bearer {{.Key}}" };
+
+// one value
+const value = await fetch("{{$.BaseURL}}/api/v1/values/{{$.SampleKey}}", { headers }).then(r => r.json());
+
+// every value in the store, as { key: value }
+const all = await fetch("{{$.BaseURL}}/api/v1/values", { headers }).then(r => r.json());
+ + + + +
+ +

Full reference: openapi.yaml

+{{end}} +{{else}} +

No API keys yet. Create one to read this store from your sites.

+{{end}} + +

Danger zone

+
+ +
+{{end}} diff --git a/internal/web/templates/value.html b/internal/web/templates/value.html new file mode 100644 index 0000000..d513321 --- /dev/null +++ b/internal/web/templates/value.html @@ -0,0 +1,72 @@ +{{define "title"}}{{if .IsNew}}New value{{else}}{{.Key}}{{end}} · {{.Store}} · pocketkv{{end}} +{{define "head"}} + + +{{end}} +{{define "content"}} +

Stores / {{.Store}} /

+
+ {{if .IsNew}} + +
+ {{else}} +

{{.Key}}

+ + {{end}} + {{if .Error}}

{{.Error}}

{{end}} + + +
+ + + ⌘/Ctrl+S saves + +
+
+ +{{end}} diff --git a/internal/web/web.go b/internal/web/web.go new file mode 100644 index 0000000..a18b32b --- /dev/null +++ b/internal/web/web.go @@ -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 +}