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