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:
@@ -0,0 +1,181 @@
|
||||
'use client'
|
||||
|
||||
// Settings → API Keys: personal long-lived "sb_..." Bearer credentials for
|
||||
// machine clients — the superbrain-mcp server (federated mcpserver gateway,
|
||||
// Claude/any MCP client) or plain REST scripts pointed at the Go API. The
|
||||
// plaintext is shown exactly once, right after creation; list rows carry
|
||||
// only the display prefix (write-once secret, house pattern). Plan gating
|
||||
// is the server's job: `allowed` comes from GET /api/keys and a 403 on
|
||||
// create surfaces its message — the UI never guesses entitlements.
|
||||
|
||||
import { useCallback, useEffect, useState } from 'react'
|
||||
import { Button } from '@/components/ui/button'
|
||||
import { Input } from '@/components/ui/input'
|
||||
import { Badge } from '@/components/ui/badge'
|
||||
import { SafeDate } from '@/components/safe-format'
|
||||
import { KeyRound, Loader2, Plus, Trash2, Copy, Check } from 'lucide-react'
|
||||
import { toast } from 'sonner'
|
||||
|
||||
type ApiKey = {
|
||||
id: string; name: string; prefix: string
|
||||
createdAt: string; lastUsedAt: string | null
|
||||
}
|
||||
|
||||
async function api(path: string, init?: RequestInit): Promise<Response> {
|
||||
return fetch(path, { headers: { 'Content-Type': 'application/json' }, cache: 'no-store', ...init })
|
||||
}
|
||||
|
||||
export function ApiKeysSettings() {
|
||||
const [keys, setKeys] = useState<ApiKey[]>([])
|
||||
const [allowed, setAllowed] = useState(false)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [creating, setCreating] = useState(false)
|
||||
const [name, setName] = useState('')
|
||||
// The one-and-only plaintext reveal; cleared on the next reload.
|
||||
const [newKey, setNewKey] = useState<string | null>(null)
|
||||
const [copied, setCopied] = useState(false)
|
||||
|
||||
// Promise-chain loading (house pattern: no synchronous setState in
|
||||
// effects — the SSR lint refuses cascading renders).
|
||||
const reload = useCallback(() =>
|
||||
api('/api/keys')
|
||||
.then(r => r.json())
|
||||
.then(data => {
|
||||
setKeys(Array.isArray(data?.keys) ? data.keys : [])
|
||||
setAllowed(data?.allowed === true)
|
||||
})
|
||||
.catch(() => { toast.error('Could not load API keys') })
|
||||
.finally(() => { setLoading(false) }), [])
|
||||
|
||||
useEffect(() => { reload() }, [reload])
|
||||
|
||||
const create = async () => {
|
||||
const trimmed = name.trim()
|
||||
if (!trimmed) { toast.error('Give the key a name'); return }
|
||||
setCreating(true)
|
||||
try {
|
||||
const res = await api('/api/keys', { method: 'POST', body: JSON.stringify({ name: trimmed }) })
|
||||
const data = await res.json().catch(() => null)
|
||||
if (res.ok && data?.key) {
|
||||
setNewKey(data.key)
|
||||
setCopied(false)
|
||||
setName('')
|
||||
toast.success('API key created — copy it now, it is only shown once')
|
||||
await reload()
|
||||
} else {
|
||||
toast.error(data?.error ?? 'Could not create the key')
|
||||
}
|
||||
} catch { toast.error('Could not create the key') }
|
||||
finally { setCreating(false) }
|
||||
}
|
||||
|
||||
const revoke = async (key: ApiKey) => {
|
||||
try {
|
||||
const res = await api(`/api/keys/${key.id}`, { method: 'DELETE' })
|
||||
if (res.ok) {
|
||||
if (newKey && key.prefix === newKey.slice(0, key.prefix.length)) setNewKey(null)
|
||||
toast.success(`Revoked ${key.name}`)
|
||||
await reload()
|
||||
} else {
|
||||
const data = await res.json().catch(() => null)
|
||||
toast.error(data?.error ?? 'Could not revoke the key')
|
||||
}
|
||||
} catch { toast.error('Could not revoke the key') }
|
||||
}
|
||||
|
||||
const copyKey = async () => {
|
||||
if (!newKey) return
|
||||
try {
|
||||
await navigator.clipboard.writeText(newKey)
|
||||
setCopied(true)
|
||||
toast.success('Copied to clipboard')
|
||||
} catch { toast.error('Copy failed — select the key text manually') }
|
||||
}
|
||||
|
||||
if (loading) {
|
||||
return (
|
||||
<div className="rounded-lg border p-4 flex items-center gap-2 text-sm text-muted-foreground">
|
||||
<Loader2 className="h-4 w-4 animate-spin" /> Loading API keys…
|
||||
</div>
|
||||
)
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="rounded-lg border p-4 space-y-4">
|
||||
<div>
|
||||
<h3 className="font-medium flex items-center gap-2"><KeyRound className="h-4 w-4" /> API Keys</h3>
|
||||
<p className="text-sm text-muted-foreground mt-1">
|
||||
Long-lived credentials for machine clients: the Superbrain MCP server (AI tools such as
|
||||
Claude or your federated core’s gateway) and REST scripts. Keys authenticate against the
|
||||
Go API directly (<span className="font-mono text-xs">Authorization: Bearer sb_…</span>);
|
||||
the browser session proxy does not forward them.
|
||||
</p>
|
||||
</div>
|
||||
|
||||
{!allowed && (
|
||||
<div className="rounded-md bg-amber-500/10 p-3 text-sm text-amber-800 dark:text-amber-300">
|
||||
API keys are not available on your current plan.
|
||||
</div>
|
||||
)}
|
||||
|
||||
{newKey && (
|
||||
<div className="rounded-md border bg-muted/40 p-3 space-y-2">
|
||||
<p className="text-xs font-medium">
|
||||
Copy this key now — it is only shown once:
|
||||
</p>
|
||||
<div className="flex items-center gap-2">
|
||||
<code className="flex-1 text-xs font-mono bg-background border rounded px-2 py-1.5 break-all select-all">{newKey}</code>
|
||||
<Button size="sm" variant="outline" onClick={copyKey} aria-label="Copy API key">
|
||||
{copied ? <Check className="h-3.5 w-3.5" /> : <Copy className="h-3.5 w-3.5" />}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{allowed && (
|
||||
<div className="flex gap-2">
|
||||
<Input
|
||||
value={name}
|
||||
onChange={(e: React.ChangeEvent<HTMLInputElement>) => setName(e.target.value)}
|
||||
placeholder="Key name (e.g. mcpserver, backup script)"
|
||||
maxLength={100}
|
||||
onKeyDown={(e: React.KeyboardEvent<HTMLInputElement>) => { if (e.key === 'Enter') create() }}
|
||||
/>
|
||||
<Button onClick={create} loading={creating} disabled={keys.length >= 10}>
|
||||
<Plus className="h-4 w-4 mr-1" /> Create
|
||||
</Button>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{keys.length === 0 ? (
|
||||
<p className="text-sm text-muted-foreground">No API keys yet.</p>
|
||||
) : (
|
||||
<ul className="divide-y rounded-md border">
|
||||
{keys.map(k => (
|
||||
<li key={k.id} className="flex items-center gap-3 p-3">
|
||||
<div className="flex-1 min-w-0">
|
||||
<div className="flex items-center gap-2">
|
||||
<span className="text-sm font-medium truncate">{k.name}</span>
|
||||
<Badge variant="outline" className="font-mono text-xs shrink-0">{k.prefix}…</Badge>
|
||||
</div>
|
||||
<p className="text-xs text-muted-foreground mt-0.5">
|
||||
Created <SafeDate date={k.createdAt} localize />
|
||||
{' · '}
|
||||
{k.lastUsedAt ? <>Last used <SafeDate date={k.lastUsedAt} localize /></> : 'Never used'}
|
||||
</p>
|
||||
</div>
|
||||
<Button size="sm" variant="ghost" onClick={() => revoke(k)} aria-label={`Revoke ${k.name}`}>
|
||||
<Trash2 className="h-4 w-4 text-muted-foreground hover:text-destructive" />
|
||||
</Button>
|
||||
</li>
|
||||
))}
|
||||
</ul>
|
||||
)}
|
||||
|
||||
<p className="text-xs text-muted-foreground">
|
||||
Revoking deletes the key immediately. Keys are not affected by “sign out
|
||||
everywhere” — revoke them here.
|
||||
</p>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user