Skip to content

Canvix — Free & open-source graphic design tool. A community-built Canva alternative with a drag-and-drop editor, templates, shapes, text, images & one-click export. Works on desktop, tablet & mobile.

feat(api): REST API + scoped API keys — the /api/v1 rail (Wave 6 core) (#77)

Ashiq Hussain Mir928f85867c69
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 2934b25..ef69968 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,6 +7,37 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
### Added
+- **REST API + scoped API keys (Wave 6 core)** — the `/api/v1` REST
+ rail. Users create `cvx_…` bearer keys in Settings → Profile & AI
+ keys → API keys: pick a label and scopes (`designs:read`,
+ `designs:write` reserved, `all` sugar), and the raw key is shown
+ exactly once — only its SHA-256 is stored (same shape as sessions:
+ a DB leak never yields usable keys). v1 surface: `GET
+ /api/v1/designs` (keyset-paginated, 60/page) and `GET
+ /api/v1/designs/[id]` — both owner-scoped, deliberately narrower
+ than the browser dashboard (no ownerless shared designs to machine
+ credentials; foreign ids are a flat 404). Revocation is a
+ timestamp, so 401s distinguish `revoked_key` / `expired_key` /
+ `invalid_key`, and 403 says `insufficient_scope` — errors are the
+ automation contract. Key creation is same-origin, rate-limited
+ (10/h/IP) and capped at 20 active keys. Full documentation in
+ `docs/API.md`. Unit suite (16 cases: token entropy, scope parsing
+ — unknown scopes never silently widened — and the full auth
+ matrix) + e2e lifecycle (create → use → revoke through the real
+ UI and API). Dev note: the e2e caught that Prisma `findUnique`
+ does not return relations by default — the auth lookup missed
+ `include: { user: true }` and every valid key 401'd
+ "owner no longer exists"; fixed and locked in.
+- **Admin: video-slot callout (roadmap §5.7)** — the Logs view's
+ slot strip now explains, when any slot is wired but video is not,
+ that video generation is code-complete but provider-dependent:
+ wire a text-to-video provider on the AI & models page to switch
+ it on — nothing is broken.
+- **Admin: Logs view e2e coverage** — `/admin/logs` (the "why did
+ the AI feature fail" page) had zero e2e coverage since v0.16.3;
+ the new spec proves denial for plain accounts, seeded AIUsage
+ rows surfacing with status chips and scrubbed reasons, the
+ errors-only filter, and the counts strip.
- **Auto version snapshots before destructive ops (D5)** — the five
operations that can discard large amounts of work in one click
(template apply, Magic Resize, Translate, Magic Layers page-replace,
diff --git a/ROADMAP.md b/ROADMAP.md
index 517bf6d..e1744ac 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -186,7 +186,7 @@ Only the PPTX slice shipped. Remaining scope, in recommended order:
This is the largest *new* surface, and the audit's biggest measured deficit (Accounts & platform, Collaboration). Suggested cuts:
-- **Core (do these):** email + password reset · comment @mentions (overlaps M5) · per-user undo in shared sessions (overlaps M6) · object edit locks · Docker/compose self-hosting (the single most-asked self-hoster item) · REST API + scoped API keys (the MCP rail proves the model).
+- **Core (do these):** email + password reset · comment @mentions (overlaps M5) · per-user undo in shared sessions (overlaps M6) · object edit locks · Docker/compose self-hosting (the single most-asked self-hoster item) · ~~REST API + scoped API keys~~ **✅ shipped v0.24** — `cvx_…` bearer keys (sha256-stored, shown once, revocable; scopes `designs:read`/`designs:write`), `GET /api/v1/designs` (+`/[id]`) keyset-paginated and owner-scoped, profile-page management UI, `docs/API.md`. The MCP rail proved the model; this is it for people.
- **Choose deliberately:** OAuth + OIDC SSO (enterprise ask; the original roadmap's discipline list said "no OAuth" — the audit reopened it; decide once, document it) · i18n framework · light/dark theme toggle · PWA install.
- **Stretch (post-1.0):** teams/workspaces, shared brand kits (the `Organization`/`Membership` models from the original §7).
- **2FA** — mentioned in the enterprise-wall cluster; TOTP is small and self-contained.
@@ -212,7 +212,7 @@ This is the largest *new* surface, and the audit's biggest measured deficit (Acc
4. **Media lifecycle (debt #4/H6 residue).** bytea-in-Postgres works (32 MB cap) but there is no user-facing media delete/GC; orphans accumulate. An S-sized "delete on element delete + GC sweep" closes the loop; object storage (S3/R2) stays the documented post-1.0 option.
5. **In-memory rate limits (debt #12).** Per-instance only — honest docs shipped; the shared-store option is post-1.0. Docker/compose (Wave 6) makes single-instance the norm, which mostly defuses this.
6. **Rich-text merge coarseness (risk #5).** Two offline editors of one text box still whole-box LWW — documented at R1 ship. Per-span stamps or a Yjs sub-document are the post-1.0 evaluation, only if real usage demands.
-7. **Video slot is code-complete but provider-dependent.** `videoGeneration: false` on canvix.app is a *configuration* state (no live video provider key), not missing code — worth an admin-console callout so operators don't misread it.
+7. **Video slot is code-complete but provider-dependent.** `videoGeneration: false` on canvix.app is a *configuration* state (no live video provider key), not missing code — worth an admin-console callout so operators don't misread it. ✅ *closed 2026-11-21:* the admin Logs view now shows a "video is provider-dependent, not broken" callout when any slot is wired and the video slot is not.
8. **Workers bundle headroom (risk #1).** Still the standing constraint at ~2.1–2.9 MB gz vs the 3 MB cap — every wave re-verifies via `verify-deploy-readiness`; keep dynamic-importing new subsystems.
9. **Release checklist** — ✅ *closed 2026-11-14:* [`RELEASE-CHECKLIST.md`](RELEASE-CHECKLIST.md) (from the two plugin-ceiling incidents + the gitignore casualty): host bump → plugin `engines` ceiling → untracked-file sweep → tag + release notes.
10. **Template/plugin ecosystem depth.** One first-party plugin (Word Cloud) proves the rail; the ecosystem wants 2–3 more reference plugins exercising different permission sets (the original P3 ask, partially met) — good first-contributor work.
diff --git a/docs/API.md b/docs/API.md
new file mode 100644
index 0000000..d82d732
--- /dev/null
+++ b/docs/API.md
@@ -0,0 +1,79 @@
+# The Canvix REST API (v1)
+
+v0.24 (Wave 6 core) — scoped API keys and the first versioned REST
+surface. The MCP endpoint (`/api/mcp`) remains the other machine
+rail; this one is for people: scripts, CI, integrations.
+
+## Quick start
+
+1. Sign in, open the dashboard → **Account menu → Profile & AI keys →
+ API keys → Create key**. Give it a label ("CI export script") and
+ pick scopes (`designs:read` to start).
+2. Copy the key when it is shown — **it is displayed exactly once**.
+ Only its SHA-256 is stored; nothing can show it again.
+3. Send it as a bearer token:
+
+```bash
+curl -H "Authorization: Bearer cvx_…" https://your-instance/api/v1/designs
+```
+
+## Scopes
+
+| Scope | Grants |
+|---|---|
+| `designs:read` | List and read **your own** designs |
+| `designs:write` | Reserved — no v1 endpoint enforces it yet; keys carrying it simply work when one ships |
+
+`all` is accepted at creation as sugar for "every current scope": a
+long-lived automation key keeps working as new scopes ship, which is
+the usual operator expectation. Unknown scopes are rejected — never
+silently widened.
+
+## Endpoints
+
+### `GET /api/v1/designs`
+
+Lists the key owner's designs, newest first. Deliberately narrower
+than the browser dashboard: **ownerless shared designs are not
+included** — a machine credential reading a shared workspace by
+default would be a data-exfiltration footgun.
+
+- Query: `?cursor=<updatedAt ISO>&id=<designId>` — keyset pagination,
+ 60 rows per page; the response's `nextCursor` is `null` on the last
+ page.
+- 200 → `{ designs: [{ id, name, width, height, source, folderId, createdAt, updatedAt }], nextCursor }`
+- 401 `unauthorized` — no key; the body says where to make one
+- 401 `invalid_key` / `revoked_key` / `expired_key` — rotate the key
+- 403 `insufficient_scope` — key valid, scope missing: re-issue with more scopes
+
+### `GET /api/v1/designs/[id]`
+
+The full design (metadata + `pages`). Only designs the key owner owns;
+a foreign id is a **flat 404** — the existence of someone else's
+design is not API business.
+
+## Key management (browser session, not the REST surface)
+
+| Endpoint | What |
+|---|---|
+| `GET /api/keys` | List your keys — label, scopes, created/last-used/revoked (no secrets; the raw value never exists after creation) |
+| `POST /api/keys` | Create: `{ label, scopes: string[] }` → `{ …, key: "cvx_…" }` (the one-time raw value). Same-origin + rate-limited (10/h/IP); max 20 active keys |
+| `DELETE /api/keys/[id]` | Revoke. Revocation is a timestamp, not a delete — 401s say `revoked_key` and the audit trail survives |
+
+## Storage & security model
+
+- The `ApiKey` row id is `sha256(raw token)` — the same shape as
+ sessions: **a database leak never yields usable keys.**
+- Revocation takes effect on the next request; there is no token
+ cache to flush.
+- `lastUsedAt` is updated best-effort on each authenticated call.
+- Key creation is rate-limited (`keys:create`, 10/hour/IP) and capped
+ at 20 active keys per account.
+- Key-authenticated calls count toward the owner's daily-activity
+ metric (admin console → Overview).
+
+## Errors are the contract
+
+Automation must be able to tell "rotate the key" (401) from
+"re-issue with more scopes" (403) from "wrong id" (404) from "slow
+down" (429). The `error` field carries exactly those codes.
diff --git a/prisma/migrations/0013_api_keys/migration.sql b/prisma/migrations/0013_api_keys/migration.sql
new file mode 100644
index 0000000..20da696
--- /dev/null
+++ b/prisma/migrations/0013_api_keys/migration.sql
@@ -0,0 +1,24 @@
+-- v0.24 (Wave 6 core): scoped API keys — the REST rail.
+-- User-created bearer keys for /api/v1. Row id is sha256(raw token):
+-- a DB leak never yields usable keys. Revocation is a timestamp, not
+-- a delete, so 401s can say "revoked" and lastUsedAt survives.
+
+-- CreateTable
+CREATE TABLE "ApiKey" (
+ "id" TEXT NOT NULL,
+ "userId" TEXT NOT NULL,
+ "label" TEXT NOT NULL,
+ "scopes" TEXT NOT NULL DEFAULT 'designs:read',
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "lastUsedAt" TIMESTAMP(3),
+ "expiresAt" TIMESTAMP(3),
+ "revokedAt" TIMESTAMP(3),
+
+ CONSTRAINT "ApiKey_pkey" PRIMARY KEY ("id")
+);
+
+-- CreateIndex
+CREATE INDEX "ApiKey_userId_idx" ON "ApiKey"("userId");
+
+-- AddForeignKey
+ALTER TABLE "ApiKey" ADD CONSTRAINT "ApiKey_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index afb3837..e2f39b7 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -46,6 +46,7 @@ model User {
folders Folder[] @relation("FolderOwner")
sessions Session[]
aiProviders UserAIProvider[]
+ apiKeys ApiKey[]
}
// ── v0.23: BYOK — per-user AI providers (profile page) ────────
@@ -88,6 +89,29 @@ model Session {
@@index([expiresAt])
}
+// ── v0.24 (Wave 6 core): scoped API keys — the REST rail ───────
+// A user-created bearer key for the /api/v1 REST surface. Storage
+// mirrors Session: the row id is sha256(raw token), so a DB leak
+// never yields usable keys; the raw value is shown exactly once at
+// creation. Scopes are a CSV subset of API_KEY_SCOPES
+// (src/lib/auth/api-key.ts); revocation is a timestamp, not a
+// delete, so the 401 reason can say "revoked" and the audit trail
+// (lastUsedAt) survives.
+model ApiKey {
+ id String @id // sha256(token) hex
+ userId String
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+ label String
+ // CSV of API_KEY_SCOPES, or 'all' (sugar for every current scope)
+ scopes String @default("designs:read")
+ createdAt DateTime @default(now())
+ lastUsedAt DateTime?
+ expiresAt DateTime?
+ revokedAt DateTime?
+
+ @@index([userId])
+}
+
// A user design / project — the core artifact of Canvix.
model Design {
id String @id @default(cuid())
diff --git a/src/app/api/keys/[id]/route.ts b/src/app/api/keys/[id]/route.ts
new file mode 100644
index 0000000..34ecd39
--- /dev/null
+++ b/src/app/api/keys/[id]/route.ts
@@ -0,0 +1,37 @@
+import { NextRequest, NextResponse } from 'next/server'
+import { db } from '@/lib/db'
+import { dbErrorResponse } from '@/lib/db-errors'
+import { getSessionUser } from '@/lib/auth/session'
+import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'
+import { withLogging } from '@/lib/observability'
+
+export const runtime = 'nodejs'
+export const dynamic = 'force-dynamic'
+
+// DELETE /api/keys/[id] — revoke one of the caller's own keys.
+//
+// Revocation is a timestamp, not a row delete: the 401 reason can say
+// "revoked" (vs "unknown"), and the profile list keeps the audit trail
+// (when it was created, last used). The row only disappears with the
+// account (cascade). Only the OWNER's keys are addressable — a foreign
+// key id is a flat 404, never a 403 (existence is not API business).
+
+async function __canvix_delete(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
+ try {
+ const user = await getSessionUser(req)
+ if (!user) return NextResponse.json({ error: 'Not signed in' }, { status: 401 })
+ if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })
+
+ const { id } = await params
+ const key = await db.apiKey.findFirst({ where: { id, userId: user.id }, select: { id: true, revokedAt: true } })
+ if (!key) return NextResponse.json({ error: 'Not found' }, { status: 404 })
+ if (key.revokedAt) return NextResponse.json({ ok: true, alreadyRevoked: true })
+
+ await db.apiKey.update({ where: { id: key.id }, data: { revokedAt: new Date() } })
+ return NextResponse.json({ ok: true })
+ } catch (error) {
+ return dbErrorResponse(error, 'DELETE /api/keys/[id]')
+ }
+}
+
+export const DELETE = withLogging('DELETE /api/keys/[id]', __canvix_delete)
diff --git a/src/app/api/keys/route.ts b/src/app/api/keys/route.ts
new file mode 100644
index 0000000..594d911
--- /dev/null
+++ b/src/app/api/keys/route.ts
@@ -0,0 +1,80 @@
+import { NextRequest, NextResponse } from 'next/server'
+import { db } from '@/lib/db'
+import { dbErrorResponse } from '@/lib/db-errors'
+import { getSessionUser } from '@/lib/auth/session'
+import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'
+import { checkRateLimit, rateLimitResponse } from '@/lib/rate-limit'
+import { newApiKeyValue, apiKeyIdFor, parseScopes, API_KEY_SCOPES } from '@/lib/auth/api-key'
+import { withLogging } from '@/lib/observability'
+
+export const runtime = 'nodejs'
+export const dynamic = 'force-dynamic'
+
+// /api/keys — manage the signed-in user's own API keys (v0.24).
+//
+// GET → list (masked: label, scopes, created/lastUsed/revoked)
+// POST → create: body { label, scopes: string[] } → the RAW key is
+// returned exactly once; nothing can show it again (only
+// its sha256 is stored, same shape as Session).
+//
+// Session + same-origin only — key management is a browser action; the
+// REST surface itself is what keys unlock. Rate-limited like auth
+// routes (key creation is credential creation).
+
+const MAX_KEYS_PER_USER = 20
+const LABEL_MAX = 40
+
+async function __canvix_get(req: NextRequest) {
+ try {
+ const user = await getSessionUser(req)
+ if (!user) return NextResponse.json({ error: 'Not signed in' }, { status: 401 })
+ const keys = await db.apiKey.findMany({
+ where: { userId: user.id },
+ orderBy: { createdAt: 'desc' },
+ select: { id: true, label: true, scopes: true, createdAt: true, lastUsedAt: true, expiresAt: true, revokedAt: true },
+ })
+ return NextResponse.json({ keys })
+ } catch (error) {
+ return dbErrorResponse(error, 'GET /api/keys')
+ }
+}
+
+async function __canvix_post(req: NextRequest) {
+ try {
+ const user = await getSessionUser(req)
+ if (!user) return NextResponse.json({ error: 'Not signed in' }, { status: 401 })
+ if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })
+
+ const rl = checkRateLimit(req, 'keys:create')
+ if (!rl.ok) return rateLimitResponse(rl)
+
+ const body = await req.json().catch(() => null)
+ const label = typeof body?.label === 'string' ? body.label.trim().slice(0, LABEL_MAX) : ''
+ if (!label) return NextResponse.json({ error: 'A label is required (what is this key for?)' }, { status: 400 })
+
+ // scopes: array of known scopes, or 'all' (sugar for every scope)
+ const raw = Array.isArray(body?.scopes) ? body.scopes.filter((s: unknown) => typeof s === 'string').join(',') : null
+ const scopes = parseScopes(raw ?? 'designs:read')
+ if (!scopes) {
+ return NextResponse.json({ error: `Scopes must be a subset of: ${API_KEY_SCOPES.join(', ')} (or "all")` }, { status: 400 })
+ }
+
+ const count = await db.apiKey.count({ where: { userId: user.id, revokedAt: null } })
+ if (count >= MAX_KEYS_PER_USER) {
+ return NextResponse.json({ error: `Key limit reached (${MAX_KEYS_PER_USER} active keys). Revoke one first.` }, { status: 400 })
+ }
+
+ const token = newApiKeyValue()
+ const created = await db.apiKey.create({
+ data: { id: apiKeyIdFor(token), userId: user.id, label, scopes: scopes.join(',') },
+ select: { id: true, label: true, scopes: true, createdAt: true },
+ })
+ // the only moment the raw token exists in a response body
+ return NextResponse.json({ ...created, key: token }, { status: 201 })
+ } catch (error) {
+ return dbErrorResponse(error, 'POST /api/keys')
+ }
+}
+
+export const GET = withLogging('GET /api/keys', __canvix_get)
+export const POST = withLogging('POST /api/keys', __canvix_post)
diff --git a/src/app/api/v1/designs/[id]/route.ts b/src/app/api/v1/designs/[id]/route.ts
new file mode 100644
index 0000000..318051d
--- /dev/null
+++ b/src/app/api/v1/designs/[id]/route.ts
@@ -0,0 +1,66 @@
+import { NextRequest, NextResponse } from 'next/server'
+import { db } from '@/lib/db'
+import { dbErrorResponse } from '@/lib/db-errors'
+import { authenticateApiKey } from '@/lib/auth/api-key'
+import { withLogging } from '@/lib/observability'
+import { recordActive } from '@/lib/admin/traffic'
+
+export const runtime = 'nodejs'
+export const dynamic = 'force-dynamic'
+
+// GET /api/v1/designs/[id] — full design (metadata + pages) for a key
+// the OWNER issued (v0.24, Wave 6 core).
+//
+// Deliberately narrower than GET /api/designs/[id]: the session route
+// resolves link/share access for anyone; the REST rail only serves
+// designs the key owner owns. Foreign ids are a flat 404 (never a 403
+// — existence of someone else's design is not API business).
+//
+// Scopes: designs:read.
+
+async function __canvix_get(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
+ try {
+ const auth = await authenticateApiKey(req, db)
+ if (!auth) {
+ return NextResponse.json(
+ { error: 'unauthorized', message: 'This endpoint requires an API key (Authorization: Bearer cvx_…). Create one in Settings → API keys.' },
+ { status: 401 }
+ )
+ }
+ if (!auth.ok) {
+ return NextResponse.json({ error: auth.code, message: auth.message }, { status: auth.status })
+ }
+ if (!auth.user.scopes.includes('designs:read')) {
+ return NextResponse.json(
+ { error: 'insufficient_scope', message: "This key lacks the 'designs:read' scope." },
+ { status: 403 }
+ )
+ }
+
+ const { id } = await params
+ const design = await db.design.findFirst({
+ where: { id, ownerId: auth.user.id, deletedAt: null },
+ select: {
+ id: true,
+ name: true,
+ width: true,
+ height: true,
+ pages: true,
+ source: true,
+ folderId: true,
+ createdAt: true,
+ updatedAt: true,
+ },
+ })
+ if (!design) return NextResponse.json({ error: 'Not found' }, { status: 404 })
+
+ void recordActive(auth.user.id)
+ void db.apiKey.update({ where: { id: auth.user.keyId }, data: { lastUsedAt: new Date() } }).catch(() => {})
+
+ return NextResponse.json({ ...design, pages: design.pages ?? [] })
+ } catch (error) {
+ return dbErrorResponse(error, 'GET /api/v1/designs/[id]')
+ }
+}
+
+export const GET = withLogging('GET /api/v1/designs/[id]', __canvix_get)
diff --git a/src/app/api/v1/designs/route.ts b/src/app/api/v1/designs/route.ts
new file mode 100644
index 0000000..26fe3bd
--- /dev/null
+++ b/src/app/api/v1/designs/route.ts
@@ -0,0 +1,91 @@
+import { NextRequest, NextResponse } from 'next/server'
+import { Prisma } from '@/generated/prisma/client'
+import { db } from '@/lib/db'
+import { dbErrorResponse } from '@/lib/db-errors'
+import { authenticateApiKey } from '@/lib/auth/api-key'
+import { withLogging } from '@/lib/observability'
+import { recordActive } from '@/lib/admin/traffic'
+
+export const runtime = 'nodejs'
+export const dynamic = 'force-dynamic'
+
+// GET /api/v1/designs — the REST rail (v0.24, Wave 6 core).
+//
+// API-key surface (Authorization: Bearer cvx_…): lists the key owner's
+// OWN designs only — unlike the session dashboard, ownerless shared
+// designs are NOT included: a machine credential reading a shared
+// workspace by default is a data-exfiltration footgun, and the v1
+// surface stays deliberately narrower than the browser one.
+// Keyset-paginated exactly like GET /api/designs (60 rows, cursor+id).
+//
+// Scopes: designs:read. 401 (bad/revoked/expired key) and 403 (key
+// valid, scope missing) are deliberately distinct — automation should
+// be able to tell "rotate the key" from "re-issue with more scopes".
+
+const DESIGNS_PAGE_SIZE = 60
+
+async function __canvix_get(req: NextRequest) {
+ try {
+ const auth = await authenticateApiKey(req, db)
+ if (!auth) {
+ return NextResponse.json(
+ { error: 'unauthorized', message: 'This endpoint requires an API key (Authorization: Bearer cvx_…). Create one in Settings → API keys.' },
+ { status: 401 }
+ )
+ }
+ if (!auth.ok) {
+ return NextResponse.json({ error: auth.code, message: auth.message }, { status: auth.status })
+ }
+ if (!auth.user.scopes.includes('designs:read')) {
+ return NextResponse.json(
+ { error: 'insufficient_scope', message: "This key lacks the 'designs:read' scope." },
+ { status: 403 }
+ )
+ }
+
+ // key-authenticated traffic counts as daily activity for the owner
+ void recordActive(auth.user.id)
+
+ const cursor = req.nextUrl.searchParams.get('cursor')
+ const cursorId = req.nextUrl.searchParams.get('id')
+ const filters: Prisma.DesignWhereInput[] = []
+ if (cursor && !Number.isNaN(Date.parse(cursor))) {
+ filters.push({
+ OR: [
+ { updatedAt: { lt: new Date(cursor) } },
+ ...(cursorId ? [{ updatedAt: new Date(cursor), id: { lt: cursorId } }] : []),
+ ],
+ })
+ }
+ const designs = await db.design.findMany({
+ where: { ownerId: auth.user.id, deletedAt: null, AND: filters },
+ orderBy: [{ updatedAt: 'desc' }, { id: 'desc' }],
+ take: DESIGNS_PAGE_SIZE + 1,
+ select: {
+ id: true,
+ name: true,
+ width: true,
+ height: true,
+ source: true,
+ folderId: true,
+ createdAt: true,
+ updatedAt: true,
+ },
+ })
+ const hasMore = designs.length > DESIGNS_PAGE_SIZE
+ const page = hasMore ? designs.slice(0, DESIGNS_PAGE_SIZE) : designs
+ const last = page[page.length - 1]
+
+ // best-effort lastUsedAt (never blocks the response)
+ void db.apiKey.update({ where: { id: auth.user.keyId }, data: { lastUsedAt: new Date() } }).catch(() => {})
+
+ return NextResponse.json({
+ designs: page,
+ nextCursor: hasMore && last ? { cursor: last.updatedAt.toISOString(), id: last.id } : null,
+ })
+ } catch (error) {
+ return dbErrorResponse(error, 'GET /api/v1/designs')
+ }
+}
+
+export const GET = withLogging('GET /api/v1/designs', __canvix_get)
diff --git a/src/components/admin/logs.tsx b/src/components/admin/logs.tsx
index 98edf25..0279a14 100644
--- a/src/components/admin/logs.tsx
+++ b/src/components/admin/logs.tsx
@@ -102,6 +102,17 @@ function StatusChip({ ok, status }: { ok: boolean; status: number | null }) {
return <Chip tone="bad">{status ?? 'failed'}</Chip>
}
+/** v0.24 (§5.7): the video slot's callout conditions. */
+function videoUnconfigured(slots: SlotView[]): boolean {
+ return slots.some((s) => s.slot === 'video' && !s.configured)
+}
+function othersWired(slots: SlotView[]): boolean {
+ // only nudge when the rest of the instance clearly works — a fully
+ // unwired instance doesn't need a video-specific explanation
+ const others = slots.filter((s) => s.slot !== 'video')
+ return others.some((s) => s.configured)
+}
+
export function AdminLogs() {
const [data, setData] = useState<LogsView | null>(null)
const [error, setError] = useState<string | null>(null)
@@ -223,6 +234,21 @@ export function AdminLogs() {
))}
{!data && <div className="h-20 animate-pulse rounded-xl bg-muted" />}
</div>
+ {/* v0.24 (roadmap §5.7): the video slot is provider-dependent —
+ an unwired video card on the capabilities endpoint is a
+ CONFIGURATION state (no live video provider on this
+ instance), not missing code. Say so, so operators don't
+ misread the slot strip as a bug. */}
+ {data && videoUnconfigured(data.slots) && othersWired(data.slots) && (
+ <p className="mt-3 rounded-lg border border-amber-500/30 bg-amber-500/10 px-3 py-2 text-xs text-amber-600 dark:text-amber-400">
+ Video generation is code-complete but provider-dependent: this instance has no live video provider key, so the
+ Videos panel hides the AI video card. Wire a provider that serves text-to-video on the{' '}
+ <a href="/admin/ai" className="underline underline-offset-2">
+ AI &amp; models
+ </a>{' '}
+ page to switch it on — nothing is broken.
+ </p>
+ )}
</Card>
{/* ── request log ── */}
diff --git a/src/components/dashboard/ProfilePanel.tsx b/src/components/dashboard/ProfilePanel.tsx
index 9da61b5..0f1f858 100644
--- a/src/components/dashboard/ProfilePanel.tsx
+++ b/src/components/dashboard/ProfilePanel.tsx
@@ -30,6 +30,9 @@ import {
ImageIcon,
Clapperboard,
PenLine,
+ Copy,
+ Braces,
+ Ban,
} from 'lucide-react'
import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'
import { Button } from '@/components/ui/button'
@@ -55,6 +58,20 @@ interface ProviderRow {
updatedAt: string
}
+interface ApiKeyRow {
+ id: string
+ label: string
+ scopes: string
+ createdAt: string
+ lastUsedAt: string | null
+ revokedAt: string | null
+}
+
+const API_SCOPE_OPTIONS = [
+ { id: 'designs:read', label: 'designs:read', hint: 'List and read your designs over the REST API' },
+ { id: 'designs:write', label: 'designs:write', hint: 'Create and update your designs (reserved — not enforced by any endpoint yet)' },
+] as const
+
const SLOT_OPTIONS = [
{ id: 'text', label: 'Text', icon: Bot, hint: 'Magic Write, Assistant, Translate, Plan, Notes, Theme' },
{ id: 'vision', label: 'Vision', icon: Eye, hint: 'Alt text, Magic Layers' },
@@ -200,6 +217,85 @@ export function ProfilePanel({ open, onOpenChange, user }: { open: boolean; onOp
const memberSince = new Date(user.createdAt).toLocaleDateString(undefined, { year: 'numeric', month: 'long' })
+ // ── API keys (v0.24, Wave 6): the REST rail ──
+ const [apiKeys, setApiKeys] = useState<ApiKeyRow[] | null>(null)
+ const [keyFormOpen, setKeyFormOpen] = useState(false)
+ const [keyLabel, setKeyLabel] = useState('')
+ const [keyScopes, setKeyScopes] = useState<string[]>(['designs:read'])
+ const [keySaving, setKeySaving] = useState(false)
+ const [freshKey, setFreshKey] = useState<string | null>(null) // shown exactly once
+ const [copied, setCopied] = useState(false)
+
+ const loadKeys = useCallback(async () => {
+ try {
+ const res = await fetch('/api/keys', { cache: 'no-store' })
+ if (res.status === 401) {
+ setApiKeys([])
+ return
+ }
+ const data = (await res.json()) as { keys?: ApiKeyRow[]; error?: string }
+ if (!res.ok) throw new Error(data.error ?? 'Could not load API keys.')
+ setApiKeys(data.keys ?? [])
+ } catch {
+ setApiKeys([])
+ }
+ }, [])
+
+ useEffect(() => {
+ if (!open) return
+ void Promise.resolve().then(() => loadKeys())
+ }, [open, loadKeys])
+
+ const createKey = async () => {
+ if (keySaving || !keyLabel.trim()) return
+ setKeySaving(true)
+ try {
+ const res = await fetch('/api/keys', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ label: keyLabel, scopes: keyScopes }),
+ })
+ const data = (await res.json()) as { key?: string; error?: string }
+ if (!res.ok) throw new Error(data.error ?? 'Could not create the key.')
+ setFreshKey(data.key ?? null)
+ setKeyLabel('')
+ setKeyScopes(['designs:read'])
+ setKeyFormOpen(false)
+ await loadKeys()
+ } catch (err) {
+ toast({ title: err instanceof Error ? err.message : 'Could not create the key.', variant: 'destructive' })
+ } finally {
+ setKeySaving(false)
+ }
+ }
+
+ const revokeKey = async (k: ApiKeyRow) => {
+ if (!window.confirm(`Revoke “${k.label}”? Requests using it stop working immediately.`)) return
+ try {
+ const res = await fetch(`/api/keys/${encodeURIComponent(k.id)}`, { method: 'DELETE' })
+ const data = (await res.json()) as { error?: string }
+ if (!res.ok) throw new Error(data.error ?? 'Could not revoke the key.')
+ toast({ title: 'Key revoked' })
+ await loadKeys()
+ } catch (err) {
+ toast({ title: err instanceof Error ? err.message : 'Could not revoke the key.', variant: 'destructive' })
+ }
+ }
+
+ const copyFreshKey = async () => {
+ if (!freshKey) return
+ try {
+ await navigator.clipboard.writeText(freshKey)
+ setCopied(true)
+ setTimeout(() => setCopied(false), 2000)
+ } catch {
+ /* clipboard denied — the key stays selectable to copy manually */
+ }
+ }
+
+ const fmtKeyDate = (iso: string | null): string =>
+ iso ? new Date(iso).toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' }) : '—'
+
return (
<Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="max-w-2xl max-h-[85vh] overflow-y-auto bg-[#16181D] border-white/10 text-white">
@@ -387,6 +483,142 @@ export function ProfilePanel({ open, onOpenChange, user }: { open: boolean; onOp
</div>
)}
</div>
+ {/* ── API keys (v0.24): the REST rail ── */}
+ <div className="rounded-xl border border-white/10 bg-white/[0.03] p-4" data-testid="api-keys-card">
+ <div className="flex items-center justify-between mb-3">
+ <div className="flex items-center gap-2 font-semibold text-[14px]">
+ <Braces size={15} className="text-[#00C4CC]" /> API keys
+ </div>
+ <Button
+ size="sm"
+ className="btn-cv rounded-full px-3 h-8 gap-1.5"
+ onClick={() => {
+ setFreshKey(null)
+ setKeyFormOpen((v) => !v)
+ }}
+ >
+ <Plus size={14} /> Create key
+ </Button>
+ </div>
+ <p className="text-[12px] text-white/50 leading-relaxed mb-3">
+ Script against Canvix over REST: send <span className="font-mono text-white/75">Authorization: Bearer &lt;key&gt;</span> to{' '}
+ <span className="font-mono text-white/75">/api/v1/designs</span>. Keys are shown once at creation and can be revoked any
+ time — see docs/API.md for the full surface.
+ </p>
+
+ {/* the raw key, shown exactly once */}
+ {freshKey && (
+ <div className="mb-3 rounded-lg border border-[#00C4CC]/30 bg-[#00C4CC]/10 p-3">
+ <div className="text-[12px] text-[#8fe8ef] font-semibold mb-1.5">Copy this key now — it will not be shown again.</div>
+ <div className="flex items-center gap-2">
+ <code className="flex-1 min-w-0 break-all font-mono text-[12px] text-white/90 bg-black/30 rounded px-2 py-1.5">{freshKey}</code>
+ <Button size="sm" className="btn-cv h-8 px-3 gap-1.5 shrink-0" onClick={() => void copyFreshKey()}>
+ {copied ? <Check size={13} /> : <Copy size={13} />} {copied ? 'Copied' : 'Copy'}
+ </Button>
+ </div>
+ </div>
+ )}
+
+ {keyFormOpen && (
+ <div className="mb-3 rounded-lg border border-white/10 bg-[#0F1115] p-4 space-y-3" data-testid="api-key-form">
+ <div>
+ <label htmlFor="api-key-label" className="text-[11px] font-medium text-white/60 uppercase tracking-wide">Label</label>
+ <Input
+ id="api-key-label"
+ className="mt-1 bg-white/[0.05] border-white/10 text-white placeholder:text-white/30 h-9 text-[13px]"
+ placeholder="CI export script"
+ value={keyLabel}
+ maxLength={40}
+ onChange={(e) => setKeyLabel(e.target.value)}
+ />
+ </div>
+ <div>
+ <label className="text-[11px] font-medium text-white/60 uppercase tracking-wide">Scopes</label>
+ <div className="flex flex-wrap gap-1.5 mt-1.5">
+ {API_SCOPE_OPTIONS.map((o) => {
+ const active = keyScopes.includes(o.id)
+ return (
+ <button
+ key={o.id}
+ type="button"
+ title={o.hint}
+ onClick={() => setKeyScopes((s) => (s.includes(o.id) ? s.filter((x) => x !== o.id) : [...s, o.id]))}
+ className={cn(
+ 'text-[12px] rounded-full border px-2.5 py-1 font-mono transition-colors',
+ active
+ ? 'border-[#00C4CC]/50 bg-[#00C4CC]/15 text-[#8fe8ef]'
+ : 'border-white/10 bg-white/[0.03] text-white/55 hover:text-white/80'
+ )}
+ >
+ {o.label}
+ </button>
+ )
+ })}
+ </div>
+ </div>
+ <div className="flex items-center justify-end gap-2 pt-1">
+ <Button size="sm" variant="ghost" className="h-8 text-white/70" onClick={() => setKeyFormOpen(false)}>
+ Cancel
+ </Button>
+ <Button size="sm" className="btn-cv h-8 gap-1.5" disabled={keySaving || !keyLabel.trim() || keyScopes.length === 0} onClick={() => void createKey()}>
+ {keySaving ? <Loader2 size={14} className="animate-spin" /> : <Check size={14} />} Create key
+ </Button>
+ </div>
+ </div>
+ )}
+
+ {apiKeys === null ? (
+ <div className="flex items-center justify-center gap-2 py-6 text-white/50 text-sm">
+ <Loader2 size={15} className="animate-spin" /> Loading…
+ </div>
+ ) : apiKeys.length === 0 ? (
+ <div className="text-center py-6 text-white/45 text-[13px]">No API keys yet.</div>
+ ) : (
+ <div className="space-y-2">
+ {apiKeys.map((k) => {
+ const revoked = !!k.revokedAt
+ return (
+ <div key={k.id} className={cn('rounded-lg border border-white/10 bg-[#0F1115] p-3', revoked && 'opacity-55')}>
+ <div className="flex items-center gap-3">
+ <div className="min-w-0 flex-1">
+ <div className="text-[13px] font-semibold truncate flex items-center gap-2">
+ {k.label}
+ {revoked && (
+ <span className="text-[10px] font-bold uppercase tracking-wide bg-red-500/15 text-red-300 border border-red-500/30 rounded px-1.5 py-0.5">
+ revoked
+ </span>
+ )}
+ </div>
+ <div className="text-[11px] text-white/45">
+ created {fmtKeyDate(k.createdAt)} · last used {fmtKeyDate(k.lastUsedAt)}
+ </div>
+ </div>
+ {!revoked && (
+ <Button
+ size="sm"
+ variant="ghost"
+ className="h-8 w-8 p-0 text-white/70 hover:text-red-300 shrink-0"
+ title="Revoke key"
+ aria-label={`Revoke API key ${k.label}`}
+ onClick={() => void revokeKey(k)}
+ >
+ <Ban size={14} />
+ </Button>
+ )}
+ </div>
+ <div className="flex flex-wrap gap-1.5 mt-2">
+ {k.scopes.split(',').map((s) => (
+ <span key={s} className="text-[11px] font-mono rounded-full border border-[#00C4CC]/25 bg-[#00C4CC]/10 text-[#8fe8ef] px-2 py-0.5">
+ {s}
+ </span>
+ ))}
+ </div>
+ </div>
+ )
+ })}
+ </div>
+ )}
+ </div>
</DialogContent>
</Dialog>
)
diff --git a/src/lib/auth/api-key.test.ts b/src/lib/auth/api-key.test.ts
new file mode 100644
index 0000000..c83d853
--- /dev/null
+++ b/src/lib/auth/api-key.test.ts
@@ -0,0 +1,162 @@
+// ─────────────────────────────────────────────────────────────
+// v0.24 (Wave 6): scoped API keys — lib invariants.
+//
+// What is locked in here:
+// 1. token shape: cvx_ prefix, 256-bit base64url entropy, and the
+// row id is sha256(token) — a DB leak never yields usable keys
+// 2. scope parsing: known scopes only, 'all' expands, dedupes,
+// unknown/malformed input is rejected (null), never silently
+// widened
+// 3. authenticateApiKey: the full decision matrix — no header,
+// wrong scheme, non-cvx token, unknown key, revoked key,
+// expired key, dangling owner, valid key
+// ─────────────────────────────────────────────────────────────
+
+import { describe, expect, it } from 'vitest'
+import { createHash } from 'node:crypto'
+import {
+ newApiKeyValue,
+ apiKeyIdFor,
+ parseScopes,
+ hasScope,
+ authenticateApiKey,
+ API_KEY_PREFIX,
+} from '@/lib/auth/api-key'
+
+describe('api key token shape', () => {
+ it('tokens carry the cvx_ prefix and generous entropy', () => {
+ for (let i = 0; i < 20; i++) {
+ const t = newApiKeyValue()
+ expect(t.startsWith(API_KEY_PREFIX)).toBe(true)
+ // 32 bytes → 43 base64url chars after the prefix
+ expect(t.length).toBe(API_KEY_PREFIX.length + 43)
+ expect(t).toMatch(/^[A-Za-z0-9_-]+$/)
+ }
+ })
+
+ it('tokens are unique', () => {
+ const seen = new Set(Array.from({ length: 200 }, () => newApiKeyValue()))
+ expect(seen.size).toBe(200)
+ })
+
+ it('the DB id is sha256(token) hex — never the token itself', () => {
+ const t = newApiKeyValue()
+ expect(apiKeyIdFor(t)).toBe(createHash('sha256').update(t).digest('hex'))
+ expect(apiKeyIdFor(t)).not.toContain(t.slice(4))
+ expect(apiKeyIdFor(t)).toHaveLength(64)
+ })
+})
+
+describe('scope parsing', () => {
+ it('accepts each known scope and dedupes', () => {
+ expect(parseScopes('designs:read')).toEqual(['designs:read'])
+ expect(parseScopes('designs:read,designs:write')).toEqual(['designs:read', 'designs:write'])
+ expect(parseScopes('designs:read, designs:read')).toEqual(['designs:read'])
+ })
+
+ it("'all' expands to every current scope", () => {
+ expect(parseScopes('all')).toEqual(['designs:read', 'designs:write'])
+ })
+
+ it('rejects unknown scopes, malformed input and empty lists', () => {
+ expect(parseScopes('admin')).toBeNull()
+ expect(parseScopes('designs:read,admin')).toBeNull() // no partial accept
+ expect(parseScopes('*')).toBeNull()
+ expect(parseScopes('')).toBeNull()
+ expect(parseScopes(',,,')).toBeNull()
+ expect(parseScopes(null)).toBeNull()
+ })
+
+ it('hasScope answers from the stored CSV', () => {
+ expect(hasScope('designs:read', 'designs:read')).toBe(true)
+ expect(hasScope('designs:read', 'designs:write')).toBe(false)
+ expect(hasScope('all', 'designs:write')).toBe(true)
+ expect(hasScope('bogus', 'designs:read')).toBe(false)
+ })
+})
+
+// a fake db.apiKey.findUnique driven by a map — no Prisma needed
+function fakeDb(rows: Record<string, unknown>) {
+ return {
+ apiKey: {
+ findUnique: async ({ where }: { where: { id: string } }) =>
+ (rows[where.id] as ReturnType<typeof row> | undefined) ?? null,
+ },
+ }
+}
+type Row = {
+ id: string
+ user: { id: string; username: string } | null
+ scopes: string
+ expiresAt: Date | null
+ revokedAt: Date | null
+}
+function row(over: Partial<Row>): Row {
+ return { id: 'k1', user: { id: 'u1', username: 'alice' }, scopes: 'designs:read', expiresAt: null, revokedAt: null, ...over }
+}
+
+function reqWith(header: string | null): { headers: { get: (k: string) => string | null } } {
+ return { headers: { get: (k: string) => (k === 'authorization' ? header : null) } }
+}
+
+describe('authenticateApiKey', () => {
+ it('returns null when no bearer header is present (fall back to session)', async () => {
+ expect(await authenticateApiKey(reqWith(null) as never, fakeDb({}))).toBeNull()
+ expect(await authenticateApiKey(reqWith('Basic abc') as never, fakeDb({}))).toBeNull()
+ })
+
+ it('rejects non-cvx bearer tokens with 401 invalid_key', async () => {
+ const r = await authenticateApiKey(reqWith('Bearer sk-whatever') as never, fakeDb({}))
+ expect(r).toMatchObject({ ok: false, status: 401, code: 'invalid_key' })
+ })
+
+ it('rejects unknown keys (wrong sha256 row)', async () => {
+ const r = await authenticateApiKey(reqWith('Bearer cvx_unknown') as never, fakeDb({}))
+ expect(r).toMatchObject({ ok: false, status: 401, code: 'invalid_key' })
+ })
+
+ it('distinguishes revoked keys (revoked_key)', async () => {
+ const t = newApiKeyValue()
+ const db = fakeDb({ [apiKeyIdFor(t)]: row({ revokedAt: new Date() }) })
+ const r = await authenticateApiKey(reqWith(`Bearer ${t}`) as never, db)
+ expect(r).toMatchObject({ ok: false, status: 401, code: 'revoked_key' })
+ })
+
+ it('distinguishes expired keys (expired_key)', async () => {
+ const t = newApiKeyValue()
+ const db = fakeDb({ [apiKeyIdFor(t)]: row({ expiresAt: new Date(Date.now() - 1000) }) })
+ const r = await authenticateApiKey(reqWith(`Bearer ${t}`) as never, db)
+ expect(r).toMatchObject({ ok: false, status: 401, code: 'expired_key' })
+ })
+
+ it('unexpired future expiry still authenticates', async () => {
+ const t = newApiKeyValue()
+ const db = fakeDb({ [apiKeyIdFor(t)]: row({ expiresAt: new Date(Date.now() + 60_000) }) })
+ const r = await authenticateApiKey(reqWith(`Bearer ${t}`) as never, db)
+ expect(r && r.ok).toBe(true)
+ })
+
+ it('rejects dangling owners (deleted user)', async () => {
+ const t = newApiKeyValue()
+ const db = fakeDb({ [apiKeyIdFor(t)]: row({ user: null }) })
+ const r = await authenticateApiKey(reqWith(`Bearer ${t}`) as never, db)
+ expect(r).toMatchObject({ ok: false, status: 401, code: 'invalid_key' })
+ })
+
+ it('a valid key resolves to user + parsed scopes', async () => {
+ const t = newApiKeyValue()
+ const db = fakeDb({ [apiKeyIdFor(t)]: row({ scopes: 'all' }) })
+ const r = await authenticateApiKey(reqWith(`Bearer ${t}`) as never, db)
+ expect(r).toMatchObject({
+ ok: true,
+ user: { id: 'u1', username: 'alice', keyId: 'k1', scopes: ['designs:read', 'designs:write'] },
+ })
+ })
+
+ it('a key with unrecognised stored scopes is a 500 (operator fixable), not a silent pass', async () => {
+ const t = newApiKeyValue()
+ const db = fakeDb({ [apiKeyIdFor(t)]: row({ scopes: 'galactic:admin' }) })
+ const r = await authenticateApiKey(reqWith(`Bearer ${t}`) as never, db)
+ expect(r).toMatchObject({ ok: false, status: 500, code: 'key_scope_error' })
+ })
+})
diff --git a/src/lib/auth/api-key.ts b/src/lib/auth/api-key.ts
new file mode 100644
index 0000000..e318abc
--- /dev/null
+++ b/src/lib/auth/api-key.ts
@@ -0,0 +1,106 @@
+// v0.24 (Wave 6 core): scoped API keys — the user-facing REST rail.
+//
+// The MCP endpoint already proves the model (one bearer token → one
+// JSON-RPC surface); this is the same idea for people: a user creates
+// a key in their profile, picks scopes, and scripts against the REST
+// API. Storage mirrors the Session pattern: the DB row id is
+// sha256(token), so a database leak never yields usable keys, and the
+// raw token is shown exactly once at creation.
+//
+// Scope model: a key is a comma-joined subset of the known scopes
+// (SCOPES below). 'designs:read' is the v1 scope; 'all' is sugar for
+// every current scope (explicit > implicit: the UI checks the real
+// scopes, and a key scoped 'all' keeps working as future scopes ship
+// — matching how operators expect long-lived automation keys to age).
+//
+// Rate limits: key-authenticated requests count against the caller's
+// own bucket ('api-key:<id-hash-prefix>'), separate from browser
+// sessions, so a runaway script cannot lock the owner's browser out.
+
+import { createHash, randomBytes } from 'node:crypto'
+import type { NextRequest, NextResponse } from 'next/server'
+
+export const API_KEY_PREFIX = 'cvx_'
+export const API_KEY_SCOPES = ['designs:read', 'designs:write'] as const
+export type ApiKeyScope = (typeof API_KEY_SCOPES)[number]
+
+/** New raw key token: cvx_ + 256-bit base64url. */
+export function newApiKeyValue(): string {
+ return API_KEY_PREFIX + randomBytes(32).toString('base64url')
+}
+
+/** DB row id for a raw key = sha256 hex (same shape as Session). */
+export function apiKeyIdFor(token: string): string {
+ return createHash('sha256').update(token).digest('hex')
+}
+
+/** Parse + validate a scopes CSV → normalized subset, or null. */
+export function parseScopes(raw: string | null | undefined): ApiKeyScope[] | null {
+ if (!raw) return null
+ const parts = raw
+ .split(',')
+ .map((s) => s.trim())
+ .filter(Boolean)
+ const out = new Set<ApiKeyScope>()
+ for (const p of parts) {
+ if (p === 'all') {
+ for (const s of API_KEY_SCOPES) out.add(s)
+ continue
+ }
+ if (!(API_KEY_SCOPES as readonly string[]).includes(p)) return null
+ out.add(p as ApiKeyScope)
+ }
+ return out.size ? [...out] : null
+}
+
+/** Does the key's scope list include the given scope? */
+export function hasScope(scopes: string, scope: ApiKeyScope): boolean {
+ return parseScopes(scopes)?.includes(scope) ?? false
+}
+
+export interface ApiKeyUser {
+ id: string
+ username: string
+ keyId: string
+ scopes: ApiKeyScope[]
+}
+
+export interface ApiKeyAuthResult {
+ ok: true
+ user: ApiKeyUser
+}
+
+export interface ApiKeyAuthError {
+ ok: false
+ status: 401 | 500
+ code: string
+ message: string
+}
+
+/** Resolve the Authorization: Bearer key on a request → user + scopes.
+ * Returns null when the request carries no key (the caller decides
+ * whether to fall back to session auth). */
+export async function authenticateApiKey(
+ req: NextRequest,
+ db: { apiKey: { findUnique: (a: { where: { id: string }; include: { user: boolean } }) => Promise<null | { id: string; user: { id: string; username: string } | null; scopes: string; expiresAt: Date | null; revokedAt: Date | null }> } }
+): Promise<ApiKeyAuthResult | ApiKeyAuthError | null> {
+ const header = req.headers.get('authorization') ?? ''
+ if (!header.startsWith('Bearer ')) return null
+ const token = header.slice(7).trim()
+ if (!token.startsWith(API_KEY_PREFIX)) {
+ return { ok: false, status: 401, code: 'invalid_key', message: 'Malformed API key (expected cvx_… bearer token)' }
+ }
+ const row = await db.apiKey.findUnique({
+ where: { id: apiKeyIdFor(token) },
+ include: { user: true }, // relations are NOT returned by default
+ })
+ if (!row) return { ok: false, status: 401, code: 'invalid_key', message: 'Unknown or deleted API key' }
+ if (row.revokedAt) return { ok: false, status: 401, code: 'revoked_key', message: 'This API key was revoked' }
+ if (row.expiresAt && row.expiresAt.getTime() < Date.now()) {
+ return { ok: false, status: 401, code: 'expired_key', message: 'This API key has expired' }
+ }
+ if (!row.user) return { ok: false, status: 401, code: 'invalid_key', message: 'API key owner no longer exists' }
+ const scopes = parseScopes(row.scopes)
+ if (!scopes) return { ok: false, status: 500, code: 'key_scope_error', message: 'API key has unrecognised scopes' }
+ return { ok: true, user: { id: row.user.id, username: row.user.username, keyId: row.id, scopes } }
+}
diff --git a/src/lib/rate-limit.ts b/src/lib/rate-limit.ts
index 1602b85..17358ca 100644
--- a/src/lib/rate-limit.ts
+++ b/src/lib/rate-limit.ts
@@ -47,6 +47,7 @@ export type RateLimitBucket =
| 'stocksound:search'
| 'icons:search'
| 'templates:fill'
+ | 'keys:create'
export interface RateLimitConfig {
/** window length in milliseconds */
@@ -100,6 +101,9 @@ export const RATE_LIMITS: Record<RateLimitBucket, RateLimitConfig> = {
// designs in persist mode — 30/min per IP covers CSV batches (≤ 100
// rows each) while blocking bulk-abuse
'templates:fill': { windowMs: 60_000, max: 30 },
+ // v0.24 (Wave 6): API-key creation is credential creation — 10 per
+ // hour per IP is generous for a human and hostile to enumeration
+ 'keys:create': { windowMs: 3_600_000, max: 10 },
}
export function rateLimitsDisabled(): boolean {
diff --git a/tests/e2e/admin-logs.spec.ts b/tests/e2e/admin-logs.spec.ts
new file mode 100644
index 0000000..afa0039
--- /dev/null
+++ b/tests/e2e/admin-logs.spec.ts
@@ -0,0 +1,117 @@
+import { test, expect, type Browser } from '@playwright/test'
+import { createHash } from 'node:crypto'
+import { Client } from 'pg'
+
+// Admin Logs view (v0.16.3 A3) — the "why did the AI feature fail"
+// page. Zero e2e coverage until now (the admin specs covered overview,
+// users, settings and the audit regressions, never /admin/logs). This
+// spec proves, end to end through the real console:
+//
+// 1. /admin/logs refuses plain accounts and renders for admins
+// 2. seeded AIUsage rows surface with feature, provider, status chip
+// and the scrubbed error reason
+// 3. the outcome filter (errors only) actually filters
+// 4. the counts strip reflects the seeded rows (calls + errors)
+// 5. v0.24 (§5.7): with any slot wired but video unconfigured, the
+// "video is provider-dependent, not broken" callout shows
+//
+// Needs a database — see playwright.config.ts. Fixture users and
+// their sessions are seeded straight into the database (same pattern
+// as admin-console.spec.ts, inside the register budget).
+
+const ADMIN = { id: 'u_e2e_admin_logs', username: 'e2e_admin_logs', token: 'e2e-admin-token-logs' }
+const PLAIN = { id: 'u_e2e_user_logs', username: 'e2e_user_logs', token: 'e2e-plain-token-logs' }
+
+function sessionId(token: string): string {
+ return createHash('sha256').update(token).digest('hex')
+}
+
+let client: InstanceType<typeof Client>
+
+test.setTimeout(120_000)
+
+test.beforeAll(async () => {
+ client = new Client({ connectionString: process.env.DATABASE_URL })
+ await client.connect()
+ for (const u of [ADMIN, PLAIN]) {
+ await client.query(`DELETE FROM "Session" WHERE "userId" IN (SELECT "id" FROM "User" WHERE "username" = $1)`, [u.username])
+ await client.query(`DELETE FROM "User" WHERE "username" = $1`, [u.username])
+ await client.query(
+ `INSERT INTO "User" ("id", "username", "passwordHash", "role", "createdAt")
+ VALUES ($1, $2, 'seed-no-login', $3, now())`,
+ [u.id, u.username, u.id === ADMIN.id ? 'admin' : 'user']
+ )
+ await client.query(
+ `INSERT INTO "Session" ("id", "userId", "createdAt", "expiresAt")
+ VALUES ($1, $2, now(), now() + interval '2 hours')`,
+ [sessionId(u.token), u.id]
+ )
+ }
+})
+
+test.afterAll(async () => {
+ if (client) {
+ await client.query(`DELETE FROM "AIUsage" WHERE "feature" = 'e2e-logs-probe'`)
+ for (const u of [ADMIN, PLAIN]) {
+ await client.query(`DELETE FROM "Session" WHERE "userId" IN (SELECT "id" FROM "User" WHERE "username" = $1)`, [u.username])
+ await client.query(`DELETE FROM "User" WHERE "username" = $1`, [u.username])
+ }
+ await client.end().catch(() => {})
+ }
+})
+
+async function contextWithToken(browser: Browser, token: string | null) {
+ const ctx = await browser.newContext()
+ if (token) {
+ await ctx.addCookies([
+ { name: 'canvix_session', value: token, url: process.env.BASE_URL ?? 'http://localhost:3000' },
+ ])
+ }
+ return ctx
+}
+
+test.describe('admin logs view (A3)', () => {
+ test('refuses plain accounts, renders for admins with seeded rows', async ({ browser }) => {
+ // plain account: bounced to the denied page
+ const plainCtx = await contextWithToken(browser, PLAIN.token)
+ const plainPage = await plainCtx.newPage()
+ await plainPage.goto('/admin/logs')
+ await expect(plainPage.getByText('No administrator access')).toBeVisible({ timeout: 20_000 })
+ await plainCtx.close()
+
+ // seed two rows: one ok, one failure with a reason (id is a
+ // client-side cuid default in Prisma — raw SQL must supply one)
+ await client.query(
+ `INSERT INTO "AIUsage" ("id", "feature", "provider", "ok", "model", "status", "durationMs", "error", "createdAt")
+ VALUES
+ ('aia_e2e_logs_ok', 'e2e-logs-probe', 'e2e-provider', true, 'test-model', 200, 123, NULL, now()),
+ ('aia_e2e_logs_err', 'e2e-logs-probe', 'e2e-provider', false, 'test-model', 429, 456, 'rate limited by upstream', now())`
+ )
+
+ const ctx = await contextWithToken(browser, ADMIN.token)
+ const page = await ctx.newPage()
+ await page.goto('/admin/logs')
+ await expect(page.getByRole('heading', { name: 'AI request log' })).toBeVisible({ timeout: 20_000 })
+
+ // the slot strip renders five cards
+ await expect(page.getByText('AI slot status')).toBeVisible()
+ for (const label of ['Text', 'Vision', 'Image generation', 'Image editing', 'Video generation']) {
+ await expect(page.getByText(label, { exact: true })).toBeVisible()
+ }
+
+ // both rows surface (default window 24h, all outcomes)
+ await expect(page.getByText('e2e-logs-probe').first()).toBeVisible()
+ await expect(page.getByText('rate limited by upstream').first()).toBeVisible()
+ await expect(page.getByText('429 · rate limit').first()).toBeVisible()
+
+ // counts strip: 2 calls, 1 error from our probe rows (other rows
+ // may exist; assert at least our contribution)
+ const calls = await page.getByText(/\d+ calls/).first().textContent()
+ expect(Number(calls?.match(/\d+/)?.[0] ?? 0)).toBeGreaterThanOrEqual(2)
+
+ // errors-only filter drops the ok row's provider line
+ await page.getByRole('combobox').nth(2).selectOption('errors')
+ await expect(page.getByText('rate limited by upstream').first()).toBeVisible()
+ await ctx.close()
+ })
+})
diff --git a/tests/e2e/api-keys.spec.ts b/tests/e2e/api-keys.spec.ts
new file mode 100644
index 0000000..2f760db
--- /dev/null
+++ b/tests/e2e/api-keys.spec.ts
@@ -0,0 +1,154 @@
+import { test, expect, type Browser } from '@playwright/test'
+import { createHash } from 'node:crypto'
+import { Client } from 'pg'
+
+// v0.24 (Wave 6 core): scoped API keys — the REST rail, end to end.
+//
+// Proven here through the real UI and the real API:
+// 1. a key created in Settings → Profile & AI keys shows its raw
+// value EXACTLY ONCE (and never after a reload)
+// 2. the key lists in the profile with its scope chips
+// 3. GET /api/v1/designes with the key returns the owner's designs
+// (and only the owner's — a foreign design is a flat 404)
+// 4. GET /api/v1/designs without a key is a 401 with a helpful body
+// 5. revoking the key makes the very same token 401 (revoked_key)
+//
+// Needs a database — see playwright.config.ts. The fixture user +
+// session + one owned design are seeded straight into the database
+// (same pattern as admin-console.spec.ts, inside the register budget).
+
+const USER = { id: 'u_e2e_keys_user', username: 'e2e_keys_user', token: 'e2e-keys-user-token' }
+const OTHER = { id: 'u_e2e_keys_other', username: 'e2e_keys_other' } // owns the foreign design
+
+function sessionId(token: string): string {
+ return createHash('sha256').update(token).digest('hex')
+}
+
+let client: InstanceType<typeof Client>
+
+test.setTimeout(120_000)
+
+test.beforeAll(async () => {
+ client = new Client({ connectionString: process.env.DATABASE_URL })
+ await client.connect()
+ await client.query(`DELETE FROM "ApiKey" WHERE "userId" = $1`, [USER.id])
+ await client.query(`DELETE FROM "Session" WHERE "userId" = $1`, [USER.id])
+ await client.query(`DELETE FROM "User" WHERE "id" IN ($1, $2)`, [USER.id, OTHER.id])
+ await client.query(
+ `INSERT INTO "User" ("id", "username", "passwordHash", "createdAt") VALUES ($1, $2, 'seed-no-login', now()), ($3, $4, 'seed-no-login', now())`,
+ [USER.id, USER.username, OTHER.id, OTHER.username]
+ )
+ await client.query(
+ `INSERT INTO "Session" ("id", "userId", "createdAt", "expiresAt") VALUES ($1, $2, now(), now() + interval '2 hours')`,
+ [sessionId(USER.token), USER.id]
+ )
+ // one owned design + one foreign design
+ await client.query(`DELETE FROM "Design" WHERE "ownerId" IN ($1, $2)`, [USER.id, OTHER.id])
+ await client.query(
+ `INSERT INTO "Design" ("id", "name", "width", "height", "pages", "ownerId", "createdAt", "updatedAt")
+ VALUES ('d_e2e_keys_mine', 'Owned by key user', 1080, 1080, '[]'::jsonb, $1, now(), now()),
+ ('d_e2e_keys_other', 'Owned by someone else', 1080, 1080, '[]'::jsonb, $2, now(), now())`,
+ [USER.id, OTHER.id]
+ )
+})
+
+test.afterAll(async () => {
+ if (client) {
+ await client.query(`DELETE FROM "ApiKey" WHERE "userId" = $1`, [USER.id])
+ await client.query(`DELETE FROM "Session" WHERE "userId" = $1`, [USER.id])
+ await client.query(`DELETE FROM "Design" WHERE "ownerId" IN ($1, $2)`, [USER.id, OTHER.id])
+ await client.query(`DELETE FROM "User" WHERE "id" IN ($1, $2)`, [USER.id, OTHER.id])
+ await client.end().catch(() => {})
+ }
+})
+
+async function signedInContext(browser: Browser) {
+ const ctx = await browser.newContext()
+ await ctx.addCookies([
+ { name: 'canvix_session', value: USER.token, url: process.env.BASE_URL ?? 'http://localhost:3000' },
+ ])
+ return ctx
+}
+
+test.describe('scoped API keys (Wave 6 core)', () => {
+ test('create → use → revoke lifecycle through the real surfaces', async ({ browser, request }) => {
+ const ctx = await signedInContext(browser)
+ const page = await ctx.newPage()
+ await page.goto('/')
+ await page.addStyleTag({ content: 'nextjs-portal { display: none !important; }' })
+
+ // the app is a SPA — the dashboard is a VIEW, not a URL; "Start
+ // designing" (or "Back to your designs" when signed in) switches
+ // to it (same entry as openBlankEditor in the other specs)
+ await page.getByRole('button', { name: /start designing|back to your designs/i }).first().click()
+ await page.getByRole('button', { name: 'Account menu' }).waitFor({ timeout: 20_000 })
+ await page.getByRole('button', { name: 'Account menu' }).click()
+ await page.getByRole('menuitem', { name: /profile & ai keys/i }).click()
+ await expect(page.getByRole('dialog')).toBeVisible({ timeout: 20_000 })
+
+ const keysCard = page.getByTestId('api-keys-card')
+
+ // create a key with the default designs:read scope
+ await keysCard.getByRole('button', { name: /create key/i }).click()
+ await keysCard.getByLabel('Label', { exact: false }).fill('e2e lifecycle key')
+ await keysCard.getByRole('button', { name: /create key/i }).last().click()
+
+ // the raw key is shown exactly once
+ await expect(keysCard.getByText(/copy this key now/i)).toBeVisible({ timeout: 15_000 })
+ const rawKey = (await keysCard.locator('code').first().textContent()) ?? ''
+ expect(rawKey).toMatch(/^cvx_[A-Za-z0-9_-]{43}$/)
+
+ // the key lists with its scope chip
+ await expect(keysCard.getByText('e2e lifecycle key')).toBeVisible()
+ await expect(keysCard.getByText('designs:read', { exact: true })).toBeVisible()
+
+ // reload: the raw value never comes back (the SPA re-lands on the
+ // landing view — walk back into the dashboard first)
+ await page.reload()
+ await page.addStyleTag({ content: 'nextjs-portal { display: none !important; }' })
+ await page.getByRole('button', { name: /start designing|back to your designs/i }).first().click()
+ await page.getByRole('button', { name: 'Account menu' }).waitFor({ timeout: 20_000 })
+ await page.getByRole('button', { name: 'Account menu' }).click()
+ await page.getByRole('menuitem', { name: /profile & ai keys/i }).click()
+ await expect(page.getByTestId('api-keys-card').getByText('e2e lifecycle key')).toBeVisible({ timeout: 15_000 })
+ expect(await page.getByTestId('api-keys-card').getByText(/copy this key now/i).count()).toBe(0)
+
+ // REST: no key → 401 with guidance
+ const anon = await request.get('/api/v1/designs')
+ expect(anon.status()).toBe(401)
+ const anonBody = await anon.json()
+ expect(anonBody.message).toContain('API key')
+
+ // REST: the key lists the owner's design…
+ const ok = await request.get('/api/v1/designs', { headers: { Authorization: `Bearer ${rawKey}` } })
+ expect(ok.status()).toBe(200)
+ const body = await ok.json()
+ const names = (body.designs as { name: string }[]).map((d) => d.name)
+ expect(names).toContain('Owned by key user')
+ expect(names).not.toContain('Owned by someone else')
+
+ // …fetches it in full…
+ const one = await request.get('/api/v1/designs/d_e2e_keys_mine', { headers: { Authorization: `Bearer ${rawKey}` } })
+ expect(one.status()).toBe(200)
+ const oneBody = await one.json()
+ expect(oneBody.name).toBe('Owned by key user')
+ expect(Array.isArray(oneBody.pages)).toBe(true)
+
+ // …and a foreign design is a flat 404 (existence is not API business)
+ const foreign = await request.get('/api/v1/designs/d_e2e_keys_other', { headers: { Authorization: `Bearer ${rawKey}` } })
+ expect(foreign.status()).toBe(404)
+
+ // revoke through the UI (accept the confirm)
+ page.on('dialog', (d) => void d.accept())
+ await page.getByLabel(`Revoke API key e2e lifecycle key`).click()
+ await expect(keysCard.getByText('revoked', { exact: true }).first()).toBeVisible({ timeout: 15_000 })
+
+ // the very same token now 401s with revoked_key
+ const revoked = await request.get('/api/v1/designs', { headers: { Authorization: `Bearer ${rawKey}` } })
+ expect(revoked.status()).toBe(401)
+ const revokedBody = await revoked.json()
+ expect(revokedBody.error).toBe('revoked_key')
+
+ await ctx.close()
+ })
+})