Add personal API keys, superbrain-mcp, and fix Markdown prose styling

API keys & MCP (the mcpserver-link prerequisite from STRATEGY.md):
- ApiKey table (migration 017 + schema.sql): hash-only storage of personal
  "sb_..." Bearer credentials, unique keyHash, owner cascade.
- internal/auth/apikeys.go + AuthMiddleware fork: keys resolve before the
  assertion/cookie channels; gated on the mcp-core connector at issuance
  AND at every use (downgrade 403s); independent of tokenVersion so "sign
  out everywhere" never breaks a gateway link; view-as stays browser-only.
- /api/keys GET/POST/DELETE: plaintext shown exactly once, 10-key cap under
  the user lock, owner-scoped revocation; Settings -> API Keys tab.
- mcp/: superbrain-mcp, a pip-installable stdio MCP server (listmonk-mcp
  pattern) with bookmarks/tags/pages tools, version-safe updates; the
  federated gateway spawns it via config_mcpserver_superbrain() in
  deploy/federated/lib-superbrain.sh (mints the gateway key in-db, points
  it at http://superbrain-app:8080). STRATEGY.md records the remaining
  suite-side registry work.
- Tests: TestAPIKeys (plan gate, cap, revocation, tokenVersion semantics,
  downgrade-at-use); full DB-backed suite, db-converge, live MCP-client
  smoke all pass.

Markdown (Gitea issue #3): add @tailwindcss/typography and enable it in
tailwind.config.ts. The prose wrapper was a no-op without it, so Tailwind
Preflight flattened headings/blockquotes to body text while bold/italic
survived - exactly the reported symptom. Verified in the built CSS.

Gitea: #2 and #3 closed with reference notes; #1 stays open pending the
Superpanel core-AI walkthrough.
This commit is contained in:
Andrew S Erwin
2026-11-02 14:27:58 -06:00
parent febc7b2195
commit e6ab778bd5
20 changed files with 1283 additions and 14 deletions
+145
View File
@@ -0,0 +1,145 @@
package auth
// Personal API keys: long-lived Bearer credentials ("sb_...") for machine
// clients — the superbrain-mcp server the federated mcpserver gateway
// spawns, or any REST client. They exist because the browser channels are
// deliberately short-lived (60-second assertions, 30-day cookies) and a
// gateway needs a stable credential.
//
// Storage is hash-only (SHA-256 of the full key; the plaintext is shown
// exactly once at creation). Revocation is deletion of the row — there is
// no soft state to drift. Keys are independent of User.tokenVersion:
// "sign out everywhere" targets browser sessions, and silently killing a
// gateway link on a password change would be operationally hostile;
// machine credentials must be revoked explicitly (Settings → API Keys).
//
// Issuance AND use are gated on the tenant's mcp-core connector
// (entitlements catalog), mirroring the notify discipline of gating at
// creation AND at delivery: a plan downgrade stops existing keys with 403
// rather than leaving them quietly working.
import (
"context"
"crypto/rand"
"crypto/sha256"
"database/sql"
"encoding/base64"
"encoding/hex"
"errors"
"net/http"
"strings"
"time"
"github.com/andrew/superbrain/internal/db"
)
const (
// APIKeyPrefix is the human-recognizable token prefix (house style for
// grep-able secrets; also lets the middleware route the Bearer channel
// without touching the JWT parser).
APIKeyPrefix = "sb_"
// apiKeyEntropyBytes is the random payload; base64url renders it as 43
// characters, so a full key is exactly 46.
apiKeyEntropyBytes = 32
// APIKeyDisplayPrefix is how much of a key the list projection shows
// ("sb_" + 8 chars) — enough to recognize, not enough to narrow a guess.
APIKeyDisplayPrefix = 11
)
// ErrAPIKeyPlan is returned when a valid key belongs to a tenant whose plan
// no longer includes the mcp-core connector. Distinct from ErrUnauthorized
// so the middleware can answer 403 (a plan fact) instead of 401 (a
// credential fact).
var ErrAPIKeyPlan = errors.New("auth: api keys not available on this plan")
// GenerateAPIKey returns a fresh plaintext key, its stored SHA-256 hash and
// the display prefix. The plaintext never touches the database.
func GenerateAPIKey() (plain, hash, displayPrefix string, err error) {
b := make([]byte, apiKeyEntropyBytes)
if _, err = rand.Read(b); err != nil {
return "", "", "", err
}
plain = APIKeyPrefix + base64.RawURLEncoding.EncodeToString(b)
return plain, HashAPIKey(plain), plain[:APIKeyDisplayPrefix], nil
}
// HashAPIKey is the one-way transform used for storage and lookup. SHA-256
// (not bcrypt) is deliberate: the key is 256 bits of random entropy, so
// there is nothing to brute-force offline, and lookup must be a single
// indexed equality probe on every request.
func HashAPIKey(plain string) string {
sum := sha256.Sum256([]byte(plain))
return hex.EncodeToString(sum[:])
}
// IsAPIKeyToken reports whether a Bearer token has the exact shape of an
// API key (prefix + 43 base64url chars). Shape-checked before any database
// work so junk tokens never become queries.
func IsAPIKeyToken(tok string) bool {
if !strings.HasPrefix(tok, APIKeyPrefix) || len(tok) != 46 {
return false
}
rest := tok[len(APIKeyPrefix):]
for i := 0; i < len(rest); i++ {
c := rest[i]
if (c < 'a' || c > 'z') && (c < 'A' || c > 'Z') && (c < '0' || c > '9') && c != '-' && c != '_' {
return false
}
}
return true
}
// APIKeyFromRequest extracts an API-key Bearer token, if present. Only the
// exact "Bearer sb_..." shape counts; anything else falls through to the
// assertion/cookie channels.
func APIKeyFromRequest(r *http.Request) (string, bool) {
h := r.Header.Get("Authorization")
if !strings.HasPrefix(h, "Bearer ") {
return "", false
}
tok := strings.TrimPrefix(h, "Bearer ")
if !IsAPIKeyToken(tok) {
return "", false
}
return tok, true
}
// ResolveAPIKey authenticates a plaintext key and returns the owner's
// session skeleton (ID + APIKeyID; Ver stays 0 so the tokenVersion check in
// AuthMiddleware is skipped by design — see the file comment). The plan
// gate runs here, on every use. lastUsedAt is touched at most once a
// minute per key so a chatty MCP client cannot turn every request into a
// write.
func ResolveAPIKey(ctx context.Context, d *db.DB, plain string) (*SessionUser, error) {
var (
keyID, ownerID string
tenantID *string
)
err := d.QueryRowContext(ctx,
`SELECT k.id, k."ownerId", u."tenantId" FROM "ApiKey" k JOIN "User" u ON u.id=k."ownerId" WHERE k."keyHash"=$1`,
HashAPIKey(plain)).Scan(&keyID, &ownerID, &tenantID)
if errors.Is(err, sql.ErrNoRows) {
return nil, ErrUnauthorized
}
if err != nil {
return nil, err
}
tid := ""
if tenantID != nil {
tid = *tenantID
}
lim, err := db.NewTenantRepo(d).Limits(ctx, tid)
if err != nil {
return nil, err
}
if !lim.AllowConnector("mcp-core") {
return nil, ErrAPIKeyPlan
}
_, err = d.ExecContext(ctx,
`UPDATE "ApiKey" SET "lastUsedAt"=now() WHERE id=$1 AND ("lastUsedAt" IS NULL OR "lastUsedAt" < $2)`,
keyID, time.Now().Add(-time.Minute))
if err != nil {
return nil, err
}
return &SessionUser{ID: ownerID, APIKeyID: keyID}, nil
}
+32 -4
View File
@@ -20,8 +20,14 @@ type SessionUser struct {
// Ver is the tokenVersion embedded in the credential (0 = no claim:
// pre-revocation legacy cookies only — assertions must carry it), checked
// against the user row so signout revokes cookie sessions AND NextAuth
// assertions alike (review SEC-02).
// assertions alike (review SEC-02). API-key sessions always carry 0:
// keys are deliberately independent of tokenVersion (explicit revocation
// only — see apikeys.go).
Ver int
// APIKeyID is set when the request authenticated with a personal API
// key ("sb_..." Bearer) instead of a browser session. Machine requests
// never impersonate (view-as is cookie-driven and stays browser-only).
APIKeyID string
}
func identity(u *models.User) map[string]any {
@@ -29,8 +35,27 @@ func identity(u *models.User) map[string]any {
}
func AuthMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
s, e := ReadSession(r, config.Load().Secret())
if e != nil {
// Bearer channel fork: an "sb_..." API key resolves against the
// database (hash lookup + plan gate); anything else must be a
// short-lived NextAuth assertion (ReadSession). A DB failure on the
// key path is 503, never 401 (review CORR-03 discipline).
var s *SessionUser
var e error
if tok, ok := APIKeyFromRequest(r); ok {
s, e = ResolveAPIKey(r.Context(), db.FromContext(r.Context()), tok)
if e != nil {
switch {
case errors.Is(e, ErrAPIKeyPlan):
failure(w, 403, "Not available on your plan")
case errors.Is(e, ErrUnauthorized):
failure(w, 401, "Unauthorized")
default:
log.Printf("auth: api key lookup failed: %v", e)
failure(w, 503, "Service unavailable")
}
return
}
} else if s, e = ReadSession(r, config.Load().Secret()); e != nil {
failure(w, 401, "Unauthorized")
return
}
@@ -73,7 +98,10 @@ func AuthMiddleware(next http.Handler) http.Handler {
}
s.RealID, s.RealRole, s.RealUser = u.ID, u.Role, identity(u)
s.ID, s.Role, s.Name, s.Email = u.ID, u.Role, u.Name, u.Email
if u.Role == "ADMIN" {
// View-as impersonation is a browser affordance; a machine credential
// always acts as its owner (a cookie on an API-key request is not a
// trusted signal — the key IS the identity).
if u.Role == "ADMIN" && s.APIKeyID == "" {
if c, e := r.Cookie(ViewAsCookie); e == nil && c.Value != "" && c.Value != u.ID {
if target, e := repo.FindByID(r.Context(), c.Value); e == nil {
s.ID, s.Role, s.Name, s.Email = target.ID, target.Role, target.Name, target.Email
+145
View File
@@ -0,0 +1,145 @@
package handlers
// Personal API keys (Settings → API Keys): long-lived "sb_..." Bearer
// credentials for machine clients — the superbrain-mcp server the federated
// mcpserver gateway spawns, or any REST client talking to the Go API
// directly. The web proxy signs browser assertions and never forwards a
// client-supplied Authorization header, so keys are a direct-API surface by
// design (see internal/auth/apikeys.go for the auth channel).
//
// Secrets are write-once like every other credential in the product: the
// plaintext is returned exactly once by POST and never again; list
// responses carry only the display prefix. Revocation is deletion.
// Issuance is gated on the tenant's mcp-core connector (entitlements
// catalog: core plan) and use is gated again in the auth middleware, so a
// downgrade stops existing keys (the notify creation+delivery discipline).
import (
"database/sql"
"net/http"
"strings"
"unicode/utf8"
"github.com/andrew/superbrain/internal/auth"
"github.com/andrew/superbrain/internal/db"
)
// maxAPIKeys caps live keys per user — a product limit against credential
// sprawl, not a storage limit. Gateways need one; a handful of scripts is
// the realistic ceiling.
const maxAPIKeys = 10
// mcpCoreAllowed resolves the caller's tenant limits and reports whether
// the mcp-core connector is included (mirrors userTenantAllows, which is
// channel-shaped).
func mcpCoreAllowed(r *http.Request) (bool, error) {
var tenantID *string
if e := database(r).QueryRowContext(r.Context(),
`SELECT "tenantId" FROM "User" WHERE id=$1`, user(r)).Scan(&tenantID); e != nil {
return false, e
}
tid := ""
if tenantID != nil {
tid = *tenantID
}
lim, e := db.NewTenantRepo(database(r)).Limits(r.Context(), tid)
if e != nil {
return false, e
}
return lim.AllowConnector("mcp-core"), nil
}
// apiKeyProjection is the only shape key data ever leaves the server in.
// The hash is internal; the plaintext exists solely in the POST response.
func apiKeyProjection(row object) object {
return object{
"id": row["id"], "name": row["name"], "prefix": row["prefix"],
"createdAt": row["createdAt"], "lastUsedAt": row["lastUsedAt"],
}
}
// HandleAPIKeysList returns the caller's keys (masked) plus whether their
// plan allows issuing new ones, so the UI can gate without guessing
// entitlements client-side.
func HandleAPIKeysList(w http.ResponseWriter, r *http.Request) {
rows, e := db.Many(r.Context(), database(r),
`SELECT to_jsonb(t) FROM "ApiKey" t WHERE "ownerId"=$1 ORDER BY "createdAt" DESC`, user(r))
if e != nil {
respond(w, 0, nil, e)
return
}
allowed, e := mcpCoreAllowed(r)
if e != nil {
respond(w, 0, nil, e)
return
}
keys := make([]object, 0, len(rows))
for _, row := range rows {
keys = append(keys, apiKeyProjection(row))
}
respond(w, 200, object{"keys": keys, "allowed": allowed}, nil)
}
// HandleAPIKeysCreate mints a key. The plaintext is returned once, here.
func HandleAPIKeysCreate(w http.ResponseWriter, r *http.Request) {
allowed, e := mcpCoreAllowed(r)
if e != nil {
respond(w, 0, nil, e)
return
}
if !allowed {
planGate(w)
return
}
b, ok := read(w, r)
if !ok {
return
}
name := strings.TrimSpace(str(b, "name"))
if name == "" || utf8.RuneCountInString(name) > 100 {
respond(w, 0, nil, bad("name is required (max 100 characters)"))
return
}
plain, hash, prefix, e := auth.GenerateAPIKey()
if e != nil {
respond(w, 0, nil, e)
return
}
var row object
e = db.Transaction(r.Context(), database(r), func(tx *sql.Tx) error {
// Count under the user lock so two racing creates cannot both slip
// under the cap (the house discipline for version-bump paths).
if e := lockUser(r, tx); e != nil {
return e
}
var n int
if e := tx.QueryRowContext(r.Context(),
`SELECT count(*) FROM "ApiKey" WHERE "ownerId"=$1`, user(r)).Scan(&n); e != nil {
return e
}
if n >= maxAPIKeys {
return bad("API key limit reached; revoke an existing key first")
}
row, e = db.Insert(r.Context(), tx, "ApiKey", object{
"id": db.NewID(), "ownerId": user(r), "name": name,
"prefix": prefix, "keyHash": hash,
})
return e
})
if e != nil {
respond(w, 0, nil, e)
return
}
out := apiKeyProjection(row)
out["key"] = plain
respond(w, 201, out, nil)
}
// HandleAPIKeysDelete revokes (deletes) one of the caller's keys.
func HandleAPIKeysDelete(w http.ResponseWriter, r *http.Request) {
if e := remove(r, "ApiKey", r.PathValue("id"), "ownerId"); e != nil {
respond(w, 0, nil, e)
return
}
respond(w, 200, object{"ok": true}, nil)
}
+168
View File
@@ -0,0 +1,168 @@
package http
import (
"bytes"
"encoding/json"
"io"
"net/http"
"net/http/cookiejar"
"strings"
"testing"
"github.com/andrew/superbrain/internal/db"
)
// machineReq calls the API with an API-key Bearer header and no cookies —
// the shape a gateway-spawned MCP server uses.
func machineReq(t *testing.T, base, method, path, apiKey string, body any) (int, map[string]any) {
t.Helper()
var b io.Reader
if body != nil {
raw, _ := json.Marshal(body)
b = bytes.NewReader(raw)
}
req, _ := http.NewRequest(method, base+path, b)
req.Header.Set("Content-Type", "application/json")
if apiKey != "" {
req.Header.Set("Authorization", "Bearer "+apiKey)
}
res, e := http.DefaultClient.Do(req)
if e != nil {
t.Fatal(e)
}
defer res.Body.Close()
raw, _ := io.ReadAll(res.Body)
var v map[string]any
json.Unmarshal(raw, &v)
return res.StatusCode, v
}
func TestAPIKeys(t *testing.T) {
srv, d := testServerDB(t)
newClient := func() apiClient { jar, _ := cookiejar.New(nil); return apiClient{t, &http.Client{Jar: jar}, srv.URL} }
alice, bob := newClient(), newClient()
post := func(email string) map[string]any {
return map[string]any{"email": email, "password": "a-long-test-password"}
}
alice.request("POST", "/api/signup", post("alice@superbrain.test"), 201)
alice.request("POST", "/api/auth/login", post("alice@superbrain.test"), 200)
bob.request("POST", "/api/signup", post("bob@superbrain.test"), 201)
bob.request("POST", "/api/auth/login", post("bob@superbrain.test"), 200)
au := meID(alice)
// Plan gate: the test deployment derives the selfhosted plan, whose
// connectors do NOT include mcp-core — issuance is refused and the list
// reports the feature as unavailable (the UI gates on this flag).
alice.request("POST", "/api/keys", map[string]any{"name": "mcpserver"}, 403)
v := alice.request("GET", "/api/keys", nil, 200)
if v["allowed"] != false {
t.Fatalf("expected allowed=false on a plan without mcp-core: %v", v)
}
// Upgrade the implicit tenant to the core plan (catalog data, not env).
if _, e := d.Exec(`UPDATE "Tenant" SET plan='core' WHERE id=$1`, db.DefaultTenantID); e != nil {
t.Fatal(e)
}
out := alice.request("POST", "/api/keys", map[string]any{"name": "mcpserver"}, 201)
key, _ := out["key"].(string)
if !strings.HasPrefix(key, "sb_") || len(key) != 46 {
t.Fatalf("unexpected key shape: %q", key)
}
if out["prefix"] != key[:11] {
t.Fatalf("prefix %v does not match key", out["prefix"])
}
if _, leaked := out["keyHash"]; leaked {
t.Fatal("keyHash leaked into the API response")
}
id, _ := out["id"].(string)
// Bad input.
alice.request("POST", "/api/keys", map[string]any{"name": ""}, 400)
alice.request("POST", "/api/keys", map[string]any{"name": strings.Repeat("x", 101)}, 400)
// The key authenticates machine requests: identity resolves to the
// owner and data endpoints work without any cookie.
code, body := machineReq(t, srv.URL, "GET", "/api/me", key, nil)
if code != 200 || body["user"].(map[string]any)["id"] != au {
t.Fatalf("api key did not resolve to its owner: %d %v", code, body)
}
code, _ = machineReq(t, srv.URL, "POST", "/api/bookmarks", key,
map[string]any{"url": "https://127.0.0.1/mcp", "title": "via key"})
if code != 201 {
t.Fatalf("bookmark create with api key: wanted 201, got %d", code)
}
// Unknown and malformed keys are 401 (a malformed token falls through
// to the assertion channel, which also rejects it).
code, _ = machineReq(t, srv.URL, "GET", "/api/me", "sb_"+strings.Repeat("A", 43), nil)
if code != 401 {
t.Fatalf("unknown api key: wanted 401, got %d", code)
}
code, _ = machineReq(t, srv.URL, "GET", "/api/me", "sb_short", nil)
if code != 401 {
t.Fatalf("malformed api key: wanted 401, got %d", code)
}
// List projection: masked, owner-scoped, lastUsedAt touched by the use
// above (throttled to once a minute, but this is the first use).
v = alice.request("GET", "/api/keys", nil, 200)
if v["allowed"] != true {
t.Fatalf("expected allowed=true on the core plan: %v", v)
}
keys := v["keys"].([]any)
first := keys[0].(map[string]any)
if first["name"] != "mcpserver" || first["lastUsedAt"] == nil {
t.Fatalf("unexpected list projection: %v", first)
}
if _, hasKey := first["key"]; hasKey {
t.Fatal("plaintext key echoed by the list endpoint")
}
// Owner-scoped revocation.
bob.request("DELETE", "/api/keys/"+id, nil, 404)
// Cap: 10 live keys per user (1 exists; create 9 more, then refuse).
for i := 0; i < maxTestKeys-1; i++ {
alice.request("POST", "/api/keys", map[string]any{"name": "script"}, 201)
}
alice.request("POST", "/api/keys", map[string]any{"name": "one-too-many"}, 400)
// Revocation is immediate: the row is deleted and the key stops working.
alice.request("DELETE", "/api/keys/"+id, nil, 200)
code, _ = machineReq(t, srv.URL, "GET", "/api/me", key, nil)
if code != 401 {
t.Fatalf("revoked api key: wanted 401, got %d", code)
}
// Deliberate semantics (apikeys.go): keys are independent of
// tokenVersion. A revocation bump kills the browser session (existing
// SEC-02 contract) but NOT the machine credential — gateways must not
// break because a user changed their password.
keys = alice.request("GET", "/api/keys", nil, 200)["keys"].([]any)
alice.request("DELETE", "/api/keys/"+keys[0].(map[string]any)["id"].(string), nil, 200)
out = alice.request("POST", "/api/keys", map[string]any{"name": "survivor"}, 201)
key2 := out["key"].(string)
if _, e := d.Exec(`UPDATE "User" SET "tokenVersion"="tokenVersion"+1 WHERE id=$1`, au); e != nil {
t.Fatal(e)
}
alice.request("GET", "/api/me", nil, 401) // cookie session revoked (SEC-02)
code, _ = machineReq(t, srv.URL, "GET", "/api/me", key2, nil)
if code != 200 {
t.Fatalf("api key must survive a tokenVersion bump: got %d", code)
}
// Downgrade fails closed at USE time too: the key is valid but the plan
// no longer includes mcp-core.
if _, e := d.Exec(`UPDATE "Tenant" SET plan='free' WHERE id=$1`, db.DefaultTenantID); e != nil {
t.Fatal(e)
}
code, _ = machineReq(t, srv.URL, "GET", "/api/me", key2, nil)
if code != 403 {
t.Fatalf("downgraded plan: wanted 403 for a valid key, got %d", code)
}
}
// maxTestKeys mirrors handlers.maxAPIKeys (kept local so the test states the
// product number explicitly).
const maxTestKeys = 10
+8
View File
@@ -149,6 +149,14 @@ func NewServer(cfg *config.Config, database *db.DB) *http.Server {
// as the compiler — confirm-before-create on the client).
mux.HandleFunc("POST /api/ai/chat", authed(handlers.ChatLimiter(handlers.HandleAiChat)))
// 4.7e Personal API keys (Settings → API Keys): long-lived "sb_..."
// Bearer credentials for machine clients — the superbrain-mcp server the
// federated gateway spawns talks to the Go API with one. Issuance and
// use are gated on the mcp-core connector (core plan).
mux.HandleFunc("GET /api/keys", authed(handlers.HandleAPIKeysList))
mux.HandleFunc("POST /api/keys", authed(handlers.HandleAPIKeysCreate))
mux.HandleFunc("DELETE /api/keys/{id}", authed(handlers.HandleAPIKeysDelete))
// 4.8 Alerts, contacts, email, dates, users
mux.HandleFunc("GET /api/alerts/check", authed(handlers.HandleAlertsCheck))
mux.HandleFunc("DELETE /api/alerts/{bookmarkId}", authed(handlers.HandleAlertsDismiss))