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

+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" }