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.
TypeScript canva-alternativecanvasdesigndesign-tooldrag-and-dropeditorgraphic-designkonvanextjsopen-sourcereactself-hostedtemplatestypescript
feat(mcp): BYO-MCP — personal MCP tokens for every user (v0.25)
Ashiq Hussain Mir2c86c5f85dee
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 14a0596..2e8ee4f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,35 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).### Added+- **BYO-MCP — personal MCP tokens (v0.25)** — the MCP endpoint now has a+ second auth rail that needs zero operator setup: any signed-in user+ mints an API key with the new **`mcp`** scope (Settings → Profile &+ AI keys, or one click on the dashboard's *AI agents (MCP)* card) and+ uses that `cvx_…` token as the Bearer on `POST /api/mcp`. The token+ rides the existing API-key machinery — sha256-stored, shown exactly+ once, revocable, and `'all'`-scoped keys age forward automatically.+ Security footprint mirrors the v1 REST rail exactly: user-token tools+ see and modify **only the owner's designs** (every `getDesign` read+ is scoped, `saveDesign` re-checks ownership at the DB via+ `updateMany` so an id-swap between load and save can never leak a+ write, `search_designs` filters by owner, `create_design`/+ `generate_design` attribute new designs to the owner, and the+ anonymous commons is invisible — a foreign design is a flat+ not-found, no enumeration). AI tools are BYOK-aware on the user+ rail: `generate_design` and `vision_ground` resolve the **owner's+ saved providers first** (`getClientForSlotForUser`), so agent work+ pays with the user's keys — the operator's AI is never consumed —+ and `get_capabilities`/`initialize` honestly describe the rail and+ scoping. The operator token (`CANVIX_MCP_TOKEN`) is unchanged:+ unscoped, historical behaviour, same endpoint. The dashboard card+ now shows both paths (personal token recommended; server token for+ self-hosters) and `OPTIONS /api/mcp` reports `user-tokens` when no+ operator token exists. Tests: 20 new unit tests+ (`src/lib/mcp/byo-mcp.test.ts` — auth matrix, scope parsing, tool+ isolation, rail honesty) + e2e `tests/e2e/byo-mcp.spec.ts`+ (create → initialize → scoped search/get → scope-missing rejection →+ revocation) — full suite 1465 green.+- **Docker self-hosting (WP1: deployment & API trust)** — theone-command self-host the roadmap promised: `cp.env.docker.example .env`, set `POSTGRES_PASSWORD`, `dockerdiff --git a/README.md b/README.mdindex 18404ba..68f3117 100644--- a/README.md+++ b/README.md@@ -872,24 +872,45 @@ comment, export.### Enable it+Two rails, pick either (or both):++**Personal token — any signed-in user, no server setup (v0.25 “BYO-MCP”).**+Works on canvix.app and any instance where you have an account: open+**Settings → Profile & AI keys**, create an API key with the **`mcp`** scope+(or click “Create my MCP token” on the dashboard's *AI agents (MCP)* card), and+use that token as the Bearer. Tools are **scoped to your own designs** — the+same footprint your API key has on the REST rail — and AI generation+(`generate_design`, `vision_ground`) resolves **your BYOK providers first**,+so your agents pay with your keys, never the operator's.++```bash+# no server changes needed — the token is a cvx_… API key you mint yourself+```++**Server token — operators, unscoped (historical).**+```bash# 1. set a secret on the server (openssl rand -hex 24)CANVIX_MCP_TOKEN=your-long-random-secret# 2. restart Canvix — the dashboard "AI agents (MCP)" card flips to Enabled```+The server token sees every design on the instance; personal tokens only see+the owner's. Revoking a personal token (Settings → API keys) cuts the agent's+access immediately.+### Connect a clientEndpoint: `https://your-canvix.example.com/api/mcp` (Streamable HTTP, stateless).Client config (Claude Desktop / Cursor / any MCP client that supports remote-HTTP servers):+HTTP servers) — with a personal token:```json{"mcpServers": {"canvix": {"url": "https://your-canvix.example.com/api/mcp",- "headers": { "Authorization": "Bearer <CANVIX_MCP_TOKEN>" }+ "headers": { "Authorization": "Bearer cvx_…your-personal-token" }}}}diff --git a/src/app/api/mcp/route.ts b/src/app/api/mcp/route.tsindex 9557842..bdee70d 100644--- a/src/app/api/mcp/route.ts+++ b/src/app/api/mcp/route.ts@@ -9,9 +9,12 @@ export const maxDuration = 60// POST /api/mcp — Model Context Protocol endpoint// (Streamable HTTP, stateless profile; see src/lib/mcp/server.ts)//-// Auth: Authorization: Bearer <CANVIX_MCP_TOKEN>-// Disabled: until CANVIX_MCP_TOKEN is set (responds with a-// JSON-RPC error explaining how to enable it).+// Auth (either rail, v0.25):+// operator Authorization: Bearer <CANVIX_MCP_TOKEN> (unscoped)+// user Authorization: Bearer cvx_… (API key with 'mcp' scope+// — every tool is scoped to the key owner's designs and+// AI resolves their BYOK providers first)+// Disabled: only when NEITHER exists — the error explains both paths.// GET: 405 (no server-initiated SSE stream — spec-compliant)// ─────────────────────────────────────────────────────────────@@ -27,6 +30,8 @@ async function __canvix_post(req: NextRequest) {{ status: 429 })}+ // BYO-MCP (v0.25): cvx_ keys resolve asynchronously (DB-backed);+ // failures surface as a 401 JSON-RPC error from handleMcpRequest.const outcome = await handleMcpRequest(req)if (outcome.status === 202) {return new NextResponse(null, { status: 202 })@@ -51,10 +56,18 @@ async function __canvix_put() {return new NextResponse(null, { status: 405, headers: { Allow: 'POST' } })}-// let capability probes know whether the server is configured+// let capability probes know whether the server is configured.+// v0.25: the user rail (personal cvx_ tokens) works even without the+// operator token, so the endpoint reports 'enabled' whenever EITHER+// rail is available; 'user-tokens' tells the dashboard card to offer+// the personal-token flow.async function __canvix_options() {return NextResponse.json(- { mcp: mcpTokenConfigured() ? 'enabled' : 'disabled', transport: 'streamable-http', endpoint: '/api/mcp' },+ {+ mcp: mcpTokenConfigured() ? 'enabled' : 'user-tokens',+ transport: 'streamable-http',+ endpoint: '/api/mcp',+ },{ status: 200, headers: { Allow: 'POST, OPTIONS' } })}diff --git a/src/components/dashboard/McpCard.tsx b/src/components/dashboard/McpCard.tsxindex a582bad..fa8c404 100644--- a/src/components/dashboard/McpCard.tsx+++ b/src/components/dashboard/McpCard.tsx@@ -1,29 +1,50 @@'use client'-import { useEffect, useState } from 'react'-import { Bot, Copy, Check, Plug, KeyRound, Info } from 'lucide-react'+import { useCallback, useEffect, useState } from 'react'+import { Bot, Copy, Check, Plug, KeyRound, Info, User, Server, Loader2 } from 'lucide-react'import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger } from '@/components/ui/dialog'import { Button } from '@/components/ui/button'import { cn } from '@/lib/utils'/**- * v0.6 — "AI agents (MCP)" dashboard card. Shows the real endpoint status- * (probed via OPTIONS /api/mcp) and a copy-paste client config.+ * v0.25 — "AI agents (MCP)" dashboard card, BYO-MCP edition.+ *+ * Two ways to connect an agent now:+ * • Personal token (any signed-in user — works on canvix.app where+ * no operator token exists): one click creates an API key with the+ * 'mcp' scope; the client config is prefilled with it. Tools are+ * scoped to YOUR designs and AI generation uses your BYOK+ * providers first — exactly like the AI panel.+ * • Operator token (self-hosters): set CANVIX_MCP_TOKEN — unscoped,+ * the historical behaviour.*/export function McpCard() {- const [status, setStatus] = useState<'checking' | 'enabled' | 'disabled'>('checking')- const [copied, setCopied] = useState<'url' | 'config' | null>(null)+ const [status, setStatus] = useState<'checking' | 'enabled' | 'user-tokens' | 'disabled'>('checking')+ const [signedIn, setSignedIn] = useState<boolean | null>(null)+ const [copied, setCopied] = useState<'url' | 'config' | 'token' | null>(null)+ // personal-token flow state+ const [token, setToken] = useState<string | null>(null) // shown exactly once+ const [creating, setCreating] = useState(false)+ const [createError, setCreateError] = useState<string | null>(null)useEffect(() => {let cancelled = falsefetch('/api/mcp', { method: 'OPTIONS' }).then((r) => r.json()).then((d: { mcp?: string }) => {- if (!cancelled) setStatus(d.mcp === 'enabled' ? 'enabled' : 'disabled')+ if (!cancelled) setStatus(d.mcp === 'enabled' ? 'enabled' : d.mcp === 'user-tokens' ? 'user-tokens' : 'disabled')}).catch(() => {if (!cancelled) setStatus('disabled')})+ fetch('/api/auth/me', { cache: 'no-store' })+ .then((r) => r.json())+ .then((d: { user?: unknown }) => {+ if (!cancelled) setSignedIn(Boolean(d.user))+ })+ .catch(() => {+ if (!cancelled) setSignedIn(false)+ })return () => {cancelled = true}@@ -31,12 +52,13 @@ export function McpCard() {const origin = typeof window !== 'undefined' ? window.location.origin : 'https://your-canvix.example.com'const endpoint = `${origin}/api/mcp`+const clientConfig = JSON.stringify({mcpServers: {canvix: {url: endpoint,- headers: { Authorization: 'Bearer <CANVIX_MCP_TOKEN>' },+ headers: { Authorization: `Bearer ${token ?? '<YOUR_TOKEN>'}` },},},},@@ -44,7 +66,7 @@ export function McpCard() {2)- const copy = async (what: 'url' | 'config', text: string) => {+ const copy = useCallback(async (what: 'url' | 'config' | 'token', text: string) => {try {await navigator.clipboard.writeText(text)setCopied(what)@@ -52,7 +74,37 @@ export function McpCard() {} catch {/* clipboard unavailable */}- }+ }, [])++ /** Create a personal MCP token: POST /api/keys with the 'mcp' scope. */+ const createToken = useCallback(async () => {+ if (creating || token) return+ setCreating(true)+ setCreateError(null)+ try {+ const res = await fetch('/api/keys', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ label: `MCP agent ${new Date().toLocaleDateString()}`, scopes: ['mcp'] }),+ })+ const data = (await res.json()) as { key?: string; error?: string }+ if (!res.ok) throw new Error(data.error ?? 'Could not create the token.')+ setToken(data.key ?? null)+ } catch (err) {+ setCreateError(err instanceof Error ? err.message : 'Could not create the token.')+ } finally {+ setCreating(false)+ }+ }, [creating, token])++ const statusLabel =+ status === 'enabled'+ ? 'Enabled'+ : status === 'user-tokens'+ ? 'Personal tokens'+ : status === 'disabled'+ ? 'Off'+ : 'Checking…'return (<section id="cv-agents" className="pt-12 scroll-mt-20">@@ -69,18 +121,25 @@ export function McpCard() {'inline-flex items-center gap-1 rounded-full px-2 py-0.5 text-[10px] font-bold uppercase tracking-wide',status === 'enabled'? 'bg-emerald-500/15 text-emerald-300'- : status === 'disabled'- ? 'bg-amber-500/15 text-amber-300'- : 'bg-white/10 text-white/50'+ : status === 'user-tokens'+ ? 'bg-sky-500/15 text-sky-300'+ : status === 'disabled'+ ? 'bg-amber-500/15 text-amber-300'+ : 'bg-white/10 text-white/50')}data-testid="mcp-status">- <span className={cn('h-1.5 w-1.5 rounded-full', status === 'enabled' ? 'bg-emerald-400' : status === 'disabled' ? 'bg-amber-400' : 'bg-white/40')} />- {status === 'enabled' ? 'Enabled' : status === 'disabled' ? 'Off — set CANVIX_MCP_TOKEN' : 'Checking…'}+ <span+ className={cn(+ 'h-1.5 w-1.5 rounded-full',+ status === 'enabled' ? 'bg-emerald-400' : status === 'user-tokens' ? 'bg-sky-400' : status === 'disabled' ? 'bg-amber-400' : 'bg-white/40'+ )}+ />+ {statusLabel}</span></div><div className="text-xs text-white/40 mt-1">- Claude, Cursor, ChatGPT & any MCP client can create and edit real designs on this server — same canvas as you.+ Claude, Cursor, ChatGPT & any MCP client can create and edit real designs — connect with a personal token (your designs only) or the server token.</div></div><Dialog>@@ -97,53 +156,103 @@ export function McpCard() {</DialogHeader><div className="space-y-4 text-sm">- <div className="flex items-start gap-2 text-[13px] text-white/70">- <KeyRound size={14} className="mt-0.5 shrink-0 text-[#A78BFA]" />- <p>- <span className="text-white font-medium">1. Set a token.</span> On the server running Canvix, add{' '}- <code className="rounded bg-white/10 px-1 py-0.5 text-[11px]">CANVIX_MCP_TOKEN=<your-secret></code> to the environment and- restart. The endpoint stays disabled until then.+ {/* ── personal token rail (BYO-MCP) ── */}+ <div className="rounded-lg border border-white/10 bg-white/[0.03] p-3">+ <div className="flex items-center gap-2 text-[13px] font-medium">+ <User size={14} className="text-[#00C4CC]" /> Personal token{' '}+ <span className="text-[10px] font-bold uppercase tracking-wide rounded-full bg-sky-500/15 text-sky-300 px-2 py-0.5">Recommended</span>+ </div>+ <p className="text-[12px] text-white/50 mt-1">+ Works for any signed-in account — no server setup. The agent sees <span className="text-white/70">your designs only</span>, and AI generation+ uses <span className="text-white/70">your saved AI providers</span> first (bring your own key).</p>++ {!token ? (+ <div className="mt-2.5">+ <Button+ size="sm"+ className="btn-cv h-8 gap-1.5"+ disabled={creating || signedIn === false}+ onClick={() => void createToken()}+ data-testid="mcp-create-token"+ >+ {creating ? <Loader2 size={13} className="animate-spin" /> : <KeyRound size={13} />}+ {creating ? 'Creating…' : 'Create my MCP token'}+ </Button>+ {signedIn === false && (+ <p className="text-[11px] text-amber-300/80 mt-1.5">Sign in first — personal tokens need an account.</p>+ )}+ {createError && <p className="text-[11px] text-red-300 mt-1.5">{createError}</p>}+ </div>+ ) : (+ <div className="mt-2.5 space-y-2" data-testid="mcp-token-ready">+ <div>+ <div className="flex items-center justify-between mb-1">+ <span className="text-[11px] font-medium text-white/60 uppercase tracking-wide">Your token (shown once)</span>+ <button+ className="flex items-center gap-1 text-[11px] text-white/50 hover:text-white"+ onClick={() => void copy('token', token)}+ aria-label="Copy token"+ >+ {copied === 'token' ? <Check size={12} /> : <Copy size={12} />} Copy+ </button>+ </div>+ <code className="block rounded-lg bg-black/40 border border-white/10 px-3 py-2 text-[12px] text-[#02C0CC] break-all" data-testid="mcp-token">+ {token}+ </code>+ </div>+ <div>+ <div className="flex items-center justify-between mb-1">+ <span className="text-[12px] font-medium text-white">Client config (Claude Desktop, Cursor, …)</span>+ <button+ className="flex items-center gap-1 text-[11px] text-white/50 hover:text-white"+ onClick={() => void copy('config', clientConfig)}+ aria-label="Copy client config"+ >+ {copied === 'config' ? <Check size={12} /> : <Copy size={12} />} Copy JSON+ </button>+ </div>+ <pre className="rounded-lg bg-black/40 border border-white/10 px-3 py-2 text-[11.5px] leading-relaxed text-white/80 overflow-x-auto cv-scroll-dark">+ {clientConfig}+ </pre>+ </div>+ <p className="text-[11px] text-white/40">+ Manage or revoke this token anytime in <span className="text-white/70">Settings → API keys</span>.+ </p>+ </div>+ )}</div>- <div>- <div className="flex items-center justify-between mb-1.5">- <span className="text-[13px] font-medium text-white">2. Point your MCP client at this endpoint</span>+ {/* ── operator rail (unchanged) ── */}+ <div className="rounded-lg border border-white/10 p-3">+ <div className="flex items-center gap-2 text-[13px] font-medium">+ <Server size={14} className="text-[#A78BFA]" /> Server token (self-hosters)+ </div>+ <p className="text-[12px] text-white/50 mt-1">+ Set{' '}+ <code className="rounded bg-white/10 px-1 py-0.5 text-[11px]">CANVIX_MCP_TOKEN=<secret></code> in the server environment and restart. This+ token is unscoped — the agent can access every design on the instance. Endpoint:+ </p>+ <div className="flex items-center justify-between mt-1.5">+ <code className="rounded-lg bg-black/40 border border-white/10 px-3 py-2 text-[12px] text-[#02C0CC] break-all flex-1" data-testid="mcp-endpoint">+ {endpoint}+ </code><button- className="flex items-center gap-1 text-[11px] text-white/50 hover:text-white"+ className="flex items-center gap-1 text-[11px] text-white/50 hover:text-white ml-2 shrink-0"onClick={() => void copy('url', endpoint)}aria-label="Copy endpoint URL">- {copied === 'url' ? <Check size={12} /> : <Copy size={12} />} Copy URL- </button>- </div>- <code className="block rounded-lg bg-black/40 border border-white/10 px-3 py-2 text-[12px] text-[#02C0CC] break-all" data-testid="mcp-endpoint">- {endpoint}- </code>- </div>-- <div>- <div className="flex items-center justify-between mb-1.5">- <span className="text-[13px] font-medium text-white">3. Client config (Claude Desktop, Cursor, …)</span>- <button- className="flex items-center gap-1 text-[11px] text-white/50 hover:text-white"- onClick={() => void copy('config', clientConfig)}- aria-label="Copy client config"- >- {copied === 'config' ? <Check size={12} /> : <Copy size={12} />} Copy JSON+ {copied === 'url' ? <Check size={12} /> : <Copy size={12} />} Copy</button></div>- <pre className="rounded-lg bg-black/40 border border-white/10 px-3 py-2 text-[11.5px] leading-relaxed text-white/80 overflow-x-auto cv-scroll-dark">- {clientConfig}- </pre></div><div className="flex items-start gap-2 text-[12px] text-white/50 border-t border-white/10 pt-3"><Info size={13} className="mt-0.5 shrink-0" /><p>20 tools: generate & create designs, add text/shapes/images/tables/embeds, restyle elements, animate, comment and export- (SVG/PNG/JSON). Agent edits show up live in open editor sessions. Requests need the Bearer token; per-IP rate limits apply.- Details in the README → <span className="text-white/70">AI agents (MCP)</span>.+ (SVG/PNG/JSON). Agent edits show up live in open editor sessions. Bearer-token auth; per-IP rate limits apply. Details in the README →{' '}+ <span className="text-white/70">AI agents (MCP)</span>.</p></div></div>diff --git a/src/components/dashboard/ProfilePanel.tsx b/src/components/dashboard/ProfilePanel.tsxindex 0f1f858..37d85d7 100644--- a/src/components/dashboard/ProfilePanel.tsx+++ b/src/components/dashboard/ProfilePanel.tsx@@ -70,6 +70,7 @@ interface ApiKeyRow {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)' },+ { id: 'mcp', label: 'mcp', hint: 'Connect AI agents (Claude, Cursor…) to YOUR designs via the MCP endpoint — tools are scoped to your account' },] as constconst SLOT_OPTIONS = [diff --git a/src/lib/ai/provider.ts b/src/lib/ai/provider.tsindex eba7fac..e44cd96 100644--- a/src/lib/ai/provider.ts+++ b/src/lib/ai/provider.ts@@ -386,6 +386,24 @@ export async function getClientForSlot(slot: AiSlot): Promise<ProviderContext |}}+/**+ * v0.25 (BYO-MCP): the user-aware client constructor. The user's own+ * BYOK providers resolve FIRST, then the instance chain — so a+ * user-token MCP call pays with the owner's keys, not the+ * operator's. Identical to getClientForSlot for userId === null.+ */+export async function getClientForSlotForUser(slot: AiSlot, userId: string | null): Promise<ProviderContext | null> {+ const resolved = await resolveSlotForUser(slot, userId)+ if (!resolved) return null+ try {+ const zai = await makeClient(resolved.baseUrl, resolved.apiKey)+ return { zai, model: resolved.model, label: resolved.label, source: resolved.source }+ } catch (err) {+ console.error(`[ai] provider initialization failed (${slot}, user rail)`, err)+ return null+ }+}+/** Legacy helper — the text-slot client (MCP generate_design, older tests). */export async function getZAI(): Promise<import('z-ai-web-dev-sdk').default | null> {return (await getClientForSlot('text'))?.zai ?? nulldiff --git a/src/lib/auth/api-key.test.ts b/src/lib/auth/api-key.test.tsindex c83d853..10c7d7b 100644--- a/src/lib/auth/api-key.test.ts+++ b/src/lib/auth/api-key.test.ts@@ -55,7 +55,15 @@ describe('scope parsing', () => {})it("'all' expands to every current scope", () => {- expect(parseScopes('all')).toEqual(['designs:read', 'designs:write'])+ expect(parseScopes('all')).toEqual(['designs:read', 'designs:write', 'mcp'])+ })++ it("'mcp' (BYO-MCP, v0.25) parses as a first-class scope", () => {+ expect(parseScopes('mcp')).toEqual(['mcp'])+ expect(parseScopes('designs:read,mcp')).toEqual(['designs:read', 'mcp'])+ expect(hasScope('mcp', 'mcp')).toBe(true)+ expect(hasScope('all', 'mcp')).toBe(true) // long-lived automation keys age forward+ expect(hasScope('designs:read', 'mcp')).toBe(false) // read-only keys cannot drive agents})it('rejects unknown scopes, malformed input and empty lists', () => {@@ -149,7 +157,8 @@ describe('authenticateApiKey', () => {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'] },+ // 'all' now includes the mcp scope (v0.25) — keys age forward+ user: { id: 'u1', username: 'alice', keyId: 'k1', scopes: ['designs:read', 'designs:write', 'mcp'] },})})diff --git a/src/lib/auth/api-key.ts b/src/lib/auth/api-key.tsindex e318abc..f54f9f7 100644--- a/src/lib/auth/api-key.ts+++ b/src/lib/auth/api-key.ts@@ -21,7 +21,11 @@ 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+// v0.25: 'mcp' unlocks the MCP endpoint (/api/mcp) for the key owner —+// BYO-MCP. The scope rides the same key machinery (one token, many+// rails): a key with 'mcp' authorizes JSON-RPC calls scoped to the+// owner's own designs, exactly like the REST rail is scoped.+export const API_KEY_SCOPES = ['designs:read', 'designs:write', 'mcp'] as constexport type ApiKeyScope = (typeof API_KEY_SCOPES)[number]/** New raw key token: cvx_ + 256-bit base64url. */diff --git a/src/lib/mcp/byo-mcp.test.ts b/src/lib/mcp/byo-mcp.test.tsnew file mode 100644index 0000000..2090275--- /dev/null+++ b/src/lib/mcp/byo-mcp.test.ts@@ -0,0 +1,281 @@+// ─────────────────────────────────────────────────────────────+// v0.25 (BYO-MCP): per-user MCP tokens — invariants.+//+// What is locked in here:+// 1. checkAuth: the operator token still works alone; without it+// a cvx_ bearer is accepted pending async resolution; garbage+// is rejected with a helpful message+// 2. resolveMcpAuth: the user rail — valid key with 'mcp' scope+// resolves to the owner; a key WITHOUT the scope is rejected;+// revoked/unknown keys surface as JSON-RPC errors+// 3. tool scoping: with a user auth, search_designs only sees the+// owner's rows, getDesign refuses foreign designs, and+// create_design attributes to the owner; operator auth keeps+// the historical unscoped view+// 4. initialize/get_capabilities honestly describe the rail+// ─────────────────────────────────────────────────────────────++import { describe, expect, it, vi, beforeEach, afterEach } from 'vitest'+import type { NextRequest } from 'next/server'++// ── db mock (module-level — tools.ts imports db at top) ──────++const designRows: Array<Record<string, unknown> & { id: string; ownerId: string | null; deletedAt: Date | null }> = []+const createdDesigns: Array<Record<string, unknown>> = []++vi.mock('@/lib/db', () => ({+ db: {+ design: {+ findUnique: vi.fn(async ({ where }: { where: { id: string } }) =>+ designRows.find((d) => d.id === where.id) ?? null+ ),+ findMany: vi.fn(async ({ where }: { where?: Record<string, unknown> } = {}) =>+ designRows.filter((d) => {+ if (where?.deletedAt !== undefined && d.deletedAt !== null) return false+ if (where?.ownerId !== undefined && d.ownerId !== where.ownerId) return false+ return true+ })+ ),+ create: vi.fn(async ({ data }: { data: Record<string, unknown> }) => {+ const row = { id: 'design_new_1', ...data, deletedAt: null }+ createdDesigns.push(row)+ return row+ }),+ updateMany: vi.fn(async () => ({ count: 1 })),+ },+ apiKey: {+ findUnique: vi.fn(),+ },+ template: {+ findUnique: vi.fn(async () => null),+ },+ },+}))++// Mock the AI provider layer so generate_design/capabilities paths+// are deterministic and never touch config or the network.+vi.mock('@/lib/ai/provider', async (importOriginal) => {+ const orig = (await importOriginal()) as Record<string, unknown>+ return {+ ...orig,+ hasProvider: vi.fn(async () => false),+ getClientForSlot: vi.fn(async () => null),+ getClientForSlotForUser: vi.fn(async (_slot: string, userId: string | null) => {+ // user rail: BYOK "resolves" for user_b (they saved a provider)+ return userId === 'user_b' ? { zai: {}, model: 'm', label: 'byok', source: 'user' } : null+ }),+ rateLimit: vi.fn(() => ({ ok: true, retryAfterSec: 0 })),+ recordUsage: vi.fn(async () => undefined),+ }+})++import { checkAuth, resolveMcpAuth, handleMcpText, OPERATOR_AUTH, type McpAuth, type McpRequestContext } from './server'+import { buildTools } from './tools'+import { newApiKeyValue, apiKeyIdFor } from '@/lib/auth/api-key'++// ── helpers ───────────────────────────────────────────────────++function reqWith(headers: Record<string, string>): NextRequest {+ return { headers: new Headers(headers) } as unknown as NextRequest+}++const ctx: McpRequestContext = { headers: new Headers({ host: 'localhost:3000' }) }++async function rpc(msg: unknown, auth: McpAuth = OPERATOR_AUTH) {+ const outcome = await handleMcpText(JSON.stringify(msg), ctx, auth)+ return outcome.body as unknown as {+ id?: unknown+ result?: { content?: Array<{ type: string; text?: string }>; instructions?: string }+ error?: { message: string }+ }+}++/** tools/call helper — returns the raw text plus parsed JSON when the text is JSON (fail() is plain text) */+async function callTool(name: string, args: Record<string, unknown>, auth: McpAuth = OPERATOR_AUTH) {+ const body = await rpc({ jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name, arguments: args } }, auth)+ const text = body.result?.content?.[0]?.text ?? ''+ let parsed: Record<string, unknown> = {}+ try {+ parsed = JSON.parse(text) as Record<string, unknown>+ } catch {+ parsed = { _raw: text }+ }+ return { text, parsed, error: body.error }+}++const USER_A: McpAuth = { kind: 'user', userId: 'user_a', username: 'alice' }+const USER_B: McpAuth = { kind: 'user', userId: 'user_b', username: 'bob' }++beforeEach(() => {+ designRows.length = 0+ createdDesigns.length = 0+ designRows.push(+ { id: 'design_a1', name: 'Alice poster', width: 1080, height: 1080, pages: [], ownerId: 'user_a', deletedAt: null, updatedAt: new Date() },+ { id: 'design_b1', name: 'Bob flyer', width: 1080, height: 1080, pages: [], ownerId: 'user_b', deletedAt: null, updatedAt: new Date() },+ { id: 'design_free', name: 'Anonymous commons', width: 1080, height: 1080, pages: [], ownerId: null, deletedAt: null, updatedAt: new Date() }+ )+})++afterEach(() => {+ vi.clearAllMocks()+ delete process.env.CANVIX_MCP_TOKEN+})++// ── 1. checkAuth (sync, operator rail + fall-through) ─────────++describe('checkAuth — operator token and fall-through (v0.25)', () => {+ it('still accepts the operator token when configured (historical rail)', () => {+ process.env.CANVIX_MCP_TOKEN = 'operator-secret'+ const err = checkAuth(reqWith({ authorization: 'Bearer operator-secret' }))+ expect(err).toBeNull()+ })++ it('rejects a wrong operator token that is not a cvx_ key', () => {+ process.env.CANVIX_MCP_TOKEN = 'operator-secret'+ const err = checkAuth(reqWith({ authorization: 'Bearer wrong-token' }))+ expect(err?.error?.code).toBe(-32001)+ })++ it('accepts a cvx_ bearer for async resolution even without an operator token', () => {+ const key = newApiKeyValue()+ expect(checkAuth(reqWith({ authorization: `Bearer ${key}` }))).toBeNull()+ })++ it('with no token and no bearer, explains BOTH enable paths', () => {+ const err = checkAuth(reqWith({}))+ expect(err?.error?.code).toBe(-32000)+ expect(err?.error?.message).toContain('CANVIX_MCP_TOKEN')+ expect(err?.error?.message).toContain('mcp') // the personal-token path+ })++ it('enforces the Origin guard on the operator rail (DNS rebinding)', () => {+ process.env.CANVIX_MCP_TOKEN = 'operator-secret'+ const err = checkAuth(reqWith({ host: 'canvix.example.com', authorization: 'Bearer operator-secret', origin: 'https://evil.example.com' }))+ expect(err?.error?.message).toContain('Cross-origin')+ })+})++// ── 2. resolveMcpAuth (async, user rail) ─────────────────────++describe('resolveMcpAuth — the cvx_ user rail', () => {+ it('returns null for non-cvx bearers (operator rail — nothing to resolve)', async () => {+ process.env.CANVIX_MCP_TOKEN = 'operator-secret'+ expect(await resolveMcpAuth(reqWith({ authorization: 'Bearer operator-secret' }))).toBeNull()+ })++ it('resolves a valid cvx_ key WITH the mcp scope to the owner', async () => {+ const token = newApiKeyValue()+ const { db } = await import('@/lib/db')+ vi.mocked(db.apiKey.findUnique).mockResolvedValueOnce({+ id: apiKeyIdFor(token),+ user: { id: 'user_a', username: 'alice' },+ scopes: 'mcp',+ expiresAt: null,+ revokedAt: null,+ } as never)+ const auth = await resolveMcpAuth(reqWith({ authorization: `Bearer ${token}` }))+ expect(auth).toEqual({ kind: 'user', userId: 'user_a', username: 'alice' })+ })++ it('rejects a cvx_ key WITHOUT the mcp scope with a re-issue hint', async () => {+ const token = newApiKeyValue()+ const { db } = await import('@/lib/db')+ vi.mocked(db.apiKey.findUnique).mockResolvedValueOnce({+ id: apiKeyIdFor(token),+ user: { id: 'user_a', username: 'alice' },+ scopes: 'designs:read',+ expiresAt: null,+ revokedAt: null,+ } as never)+ const err = await resolveMcpAuth(reqWith({ authorization: `Bearer ${token}` }))+ expect((err as { error?: { message: string } }).error?.message).toContain('mcp" scope')+ })++ it('surfaces revoked keys as a JSON-RPC error', async () => {+ const token = newApiKeyValue()+ const { db } = await import('@/lib/db')+ vi.mocked(db.apiKey.findUnique).mockResolvedValueOnce({+ id: apiKeyIdFor(token),+ user: { id: 'user_a', username: 'alice' },+ scopes: 'mcp',+ expiresAt: null,+ revokedAt: new Date(),+ } as never)+ const err = await resolveMcpAuth(reqWith({ authorization: `Bearer ${token}` }))+ expect((err as { error?: { message: string } }).error?.message).toContain('revoked')+ })+})++// ── 3. tool scoping (the BYO-MCP security footprint) ─────────++describe('tool scoping — user rail', () => {+ it('search_designs only returns the owner rows for a user token', async () => {+ const { parsed } = await callTool('search_designs', {}, USER_A)+ const designs = parsed.designs as Array<{ id: string }>+ expect(designs.map((d) => d.id)).toEqual(['design_a1'])+ })++ it('search_designs returns everything for the operator rail (historical)', async () => {+ const { parsed } = await callTool('search_designs', {}, OPERATOR_AUTH)+ const designs = parsed.designs as Array<{ id: string }>+ expect(designs.map((d) => d.id).sort()).toEqual(['design_a1', 'design_b1', 'design_free'])+ })++ it('get_design refuses another user design by id (no enumeration)', async () => {+ const { parsed } = await callTool('get_design', { design_id: 'design_b1' }, USER_A)+ expect(parsed.error ?? parsed.isError ?? parsed).toBeTruthy() // not found shape+ const { parsed: own } = await callTool('get_design', { design_id: 'design_a1' }, USER_A)+ expect(own.id).toBe('design_a1')+ })++ it('get_design also refuses the anonymous commons for user tokens (v1 REST footprint)', async () => {+ const { parsed } = await callTool('get_design', { design_id: 'design_free' }, USER_A)+ expect(JSON.stringify(parsed)).not.toContain('Anonymous commons')+ })++ it('create_design attributes the new design to the token owner', async () => {+ await callTool('create_design', { name: 'Agent made', width: 800, height: 600 }, USER_B)+ expect(createdDesigns.length).toBe(1)+ expect(createdDesigns[0].ownerId).toBe('user_b')+ })++ it('create_design stays unattributed on the operator rail (historical)', async () => {+ await callTool('create_design', { name: 'Operator made', width: 800, height: 600 }, OPERATOR_AUTH)+ expect(createdDesigns.length).toBe(1)+ expect(createdDesigns[0].ownerId).toBeUndefined()+ })++ it('add_text on a foreign design fails as not-found (mutateDesign scope)', async () => {+ // give Bob's design a page so the mutation path reaches the scope check+ designRows[1].pages = [{ id: 'page_0', background: { type: 'solid', color: '#FFFFFF' }, elements: [] }]+ const { parsed } = await callTool('add_text', { design_id: 'design_b1', text: 'hijack', x: 10, y: 10 }, USER_A)+ expect(JSON.stringify(parsed)).toContain('not found')+ })+})++// ── 4. initialize / get_capabilities honesty ─────────────────++describe('initialize and get_capabilities describe the rail', () => {+ it('initialize declares the personal-token scope for user auth', async () => {+ const body = await rpc({ jsonrpc: '2.0', id: 1, method: 'initialize' }, USER_A)+ expect(body.result?.instructions).toContain('personal token')+ expect(body.result?.instructions).toContain('alice')+ })++ it('initialize stays silent about scoping on the operator rail', async () => {+ const body = await rpc({ jsonrpc: '2.0', id: 1, method: 'initialize' }, OPERATOR_AUTH)+ expect(body.result?.instructions).not.toContain('personal token')+ })++ it('get_capabilities reports BYOK-backed AI for a user with providers', async () => {+ const { parsed } = await callTool('get_capabilities', {}, USER_B)+ expect(parsed.aiProvider).toContain('available')+ expect(parsed.auth).toContain('bob')+ expect(parsed.auth).toContain('scoped to your own designs')+ })++ it('get_capabilities points provider-less users at BYOK settings', async () => {+ const { parsed } = await callTool('get_capabilities', {}, USER_A)+ expect(parsed.aiProvider).toContain('bring your own key')+ })+})diff --git a/src/lib/mcp/server.ts b/src/lib/mcp/server.tsindex ecaabda..28490c4 100644--- a/src/lib/mcp/server.ts+++ b/src/lib/mcp/server.ts@@ -9,6 +9,8 @@import type { NextRequest } from 'next/server'import { buildTools, SERVER_VERSION, type ToolResult, type ToolDef } from './tools'import { rateLimit } from '@/lib/ai/provider'+import { authenticateApiKey } from '@/lib/auth/api-key'+import { db } from '@/lib/db'export const SUPPORTED_PROTOCOL_VERSIONS = ['2025-03-26', '2024-11-05', '2025-06-18']export const DEFAULT_PROTOCOL_VERSION = '2025-03-26'@@ -66,52 +68,132 @@ export function mcpTokenConfigured(): boolean {return Boolean(process.env.CANVIX_MCP_TOKEN)}+// ── v0.25: BYO-MCP — per-user tokens (profile → API key with 'mcp' scope)+//+// Two auth rails, same endpoint:+// • operator token (CANVIX_MCP_TOKEN) — unscoped, the historical+// behaviour: every design on the instance, instance AI providers+// • user API key (cvx_… with the 'mcp' scope) — every tool is+// scoped to the key owner's own designs (same footprint as the+// v1 REST rail), and generate_design resolves the owner's BYOK+// providers first (resolveSlotForUser) so their own keys pay+// for their agent's work — the operator's AI is never consumed.+//+// The user rail is what makes canvix.app usable by anyone: no+// operator token exists there, but every signed-in user can mint a+// personal token from their profile and connect Claude/Cursor to+// THEIR designs.++/** Who is calling — null when auth fails (checkAuth returns the error). */+export interface McpAuth {+ /** 'operator' | 'user' — tools use this to scope DB access */+ kind: 'operator' | 'user'+ /** null for operator; the key owner for user tokens */+ userId: string | null+ username?: string+}+export function checkAuth(req: NextRequest): JsonRpcResponse | null {const expected = process.env.CANVIX_MCP_TOKEN ?? ''- if (!expected) {+ const header = req.headers.get('authorization') ?? ''+ const bearer = header.replace(/^Bearer\s+/i, '').trim()+ if (expected) {+ if (tokenMatches(expected, bearer)) return originGuard(req)+ } else if (!bearer) {return {jsonrpc: '2.0',id: null,error: {code: SERVER_NOT_CONFIGURED,message:- 'The Canvix MCP server is disabled: set CANVIX_MCP_TOKEN in the server environment to enable it. See README → "AI agents (MCP)".',+ 'The Canvix MCP server is disabled: set CANVIX_MCP_TOKEN on the server, or (signed-in users) create a personal MCP token in Settings → API keys with the "mcp" scope. See README → "AI agents (MCP)".',},}}- const header = req.headers.get('authorization') ?? ''- const bearer = header.replace(/^Bearer\s+/i, '').trim()- if (!tokenMatches(expected, bearer)) {+ // no operator token (or it didn't match) — fall through to the+ // user rail; a bad operator token that is also not a cvx_ key is+ // simply an auth failure below.+ if (bearer.startsWith('cvx_')) return null // resolved asynchronously in resolveMcpAuth+ if (expected) {return {jsonrpc: '2.0',id: null,- error: { code: UNAUTHORIZED, message: 'Unauthorized — send "Authorization: Bearer <CANVIX_MCP_TOKEN>".' },+ error: { code: UNAUTHORIZED, message: 'Unauthorized — send "Authorization: Bearer <CANVIX_MCP_TOKEN>" (or a cvx_… API key with the mcp scope).' },}}- // spec security note: validate Origin when present (DNS-rebinding guard)+ return {+ jsonrpc: '2.0',+ id: null,+ error: { code: SERVER_NOT_CONFIGURED, message: mcpDisabledMessage() },+ }+}++function mcpDisabledMessage(): string {+ return (+ 'The Canvix MCP server is disabled: set CANVIX_MCP_TOKEN on the server, or (signed-in users) create a personal MCP token in Settings → API keys with the "mcp" scope.'+ )+}++/** DNS-rebinding guard shared by both rails. */+function originGuard(req: NextRequest): JsonRpcResponse | null {const origin = req.headers.get('origin')- if (origin) {- try {- const originHost = new URL(origin).host- const host = req.headers.get('x-forwarded-host') ?? req.headers.get('host') ?? ''- if (originHost && host && originHost !== host) {- return {- jsonrpc: '2.0',- id: null,- error: { code: INVALID_REQUEST, message: 'Cross-origin requests are not accepted by the MCP endpoint.' },- }- }- } catch {+ if (!origin) return null+ try {+ const originHost = new URL(origin).host+ const host = req.headers.get('x-forwarded-host') ?? req.headers.get('host') ?? ''+ if (originHost && host && originHost !== host) {return {jsonrpc: '2.0',id: null,- error: { code: INVALID_REQUEST, message: 'Invalid Origin header.' },+ error: { code: INVALID_REQUEST, message: 'Cross-origin requests are not accepted by the MCP endpoint.' },}}+ return null+ } catch {+ return {+ jsonrpc: '2.0',+ id: null,+ error: { code: INVALID_REQUEST, message: 'Invalid Origin header.' },+ }}- return null}+/**+ * Resolve the caller for the user rail (async — it hits the DB).+ * Returns null when the bearer is not a cvx_ key (operator rail+ * already handled synchronously). Errors surface as a JsonRpcResponse.+ */+export async function resolveMcpAuth(req: NextRequest): Promise<McpAuth | JsonRpcResponse | null> {+ const header = req.headers.get('authorization') ?? ''+ const bearer = header.replace(/^Bearer\s+/i, '').trim()+ if (!bearer.startsWith('cvx_')) return null // operator rail — nothing to resolve+ const auth = await authenticateApiKey(req, db)+ if (!auth) return null+ if (!auth.ok) {+ return {+ jsonrpc: '2.0',+ id: null,+ error: { code: UNAUTHORIZED, message: auth.message },+ }+ }+ if (!auth.user.scopes.includes('mcp')) {+ return {+ jsonrpc: '2.0',+ id: null,+ error: {+ code: UNAUTHORIZED,+ message: 'This API key lacks the "mcp" scope. Re-create it in Settings → API keys with mcp checked.',+ },+ }+ }+ const guard = originGuard(req)+ if (guard) return guard+ return { kind: 'user', userId: auth.user.id, username: auth.user.username }+}++/** The auth the operator rail produces (unscoped, historical). */+export const OPERATOR_AUTH: McpAuth = { kind: 'operator', userId: null }+// ── message classification ───────────────────────────────────function isNotification(msg: JsonRpcRequest): boolean {@@ -127,9 +209,10 @@ function errorResponse(id: string | number | null, code: number, message: stringreturn { jsonrpc: '2.0', id, error: { code, message, ...(data !== undefined ? { data } : {}) } }}-export function handleInitialize(msg: JsonRpcRequest): JsonRpcResponse {+export function handleInitialize(msg: JsonRpcRequest, auth: McpAuth = OPERATOR_AUTH): JsonRpcResponse {const requested = typeof msg.params?.protocolVersion === 'string' ? (msg.params.protocolVersion as string) : ''const protocolVersion = SUPPORTED_PROTOCOL_VERSIONS.includes(requested) ? requested : DEFAULT_PROTOCOL_VERSION+ const userRail = auth.kind === 'user'return {jsonrpc: '2.0',id: msg.id ?? null,@@ -149,7 +232,10 @@ export function handleInitialize(msg: JsonRpcRequest): JsonRpcResponse {instructions:'Canvix is a self-hosted, open-source design tool. Every tool creates or edits REAL, editable designs: ' +'create/generate designs, add text/shapes/images/tables/charts/embeds, restyle, animate, comment and export (svg/png/json). ' +- 'Start with get_capabilities, then list_templates / search_designs. Edits made here appear live to humans in the editor.',+ 'Start with get_capabilities, then list_templates / search_designs. Edits made here appear live to humans in the editor.' ++ (userRail+ ? ` You are connected with a personal token${auth.username ? ` (${auth.username})` : ''} — every tool is scoped to YOUR designs only, and AI generation uses your saved providers first.`+ : ''),},}}@@ -232,8 +318,12 @@ export type McpRequestContext = Pick<NextRequest, 'headers'>/*** Core JSON-RPC processing over an already-read body string.* Exported for unit tests (no HTTP involved).+ *+ * `auth` scopes every tool call: OPERATOR_AUTH keeps the historical+ * unscoped view; a user token (BYO-MCP) restricts tools to the key+ * owner's own designs (see tools.ts ToolDeps).*/-export async function handleMcpText(text: string, req: McpRequestContext): Promise<McpOutcome> {+export async function handleMcpText(text: string, req: McpRequestContext, auth: McpAuth = OPERATOR_AUTH): Promise<McpOutcome> {let parsed: unknowntry {parsed = JSON.parse(text)@@ -264,16 +354,16 @@ export async function handleMcpText(text: string, req: McpRequestContext): Promiswitch (msg.method) {case 'initialize':- responses.push(handleInitialize(msg))+ responses.push(handleInitialize(msg, auth))breakcase 'ping':responses.push({ jsonrpc: '2.0', id: msg.id ?? null, result: {} })breakcase 'tools/list':- responses.push(toolsList(msg, buildTools({ req })))+ responses.push(toolsList(msg, buildTools({ req, auth })))breakcase 'tools/call':- responses.push(await toolsCall(msg, buildTools({ req })))+ responses.push(await toolsCall(msg, buildTools({ req, auth })))breakcase 'resources/list':responses.push({ jsonrpc: '2.0', id: msg.id ?? null, result: { resources: [] } })@@ -304,6 +394,11 @@ export async function handleMcpText(text: string, req: McpRequestContext): Promi* - notifications / client responses only → 202 Accepted, no body* - requests → 200 with one JSON object, or an array for multi-request batches* - body over MAX_BODY_BYTES → 413 with a JSON-RPC error+ *+ * Auth resolution order (BYO-MCP, v0.25): the operator token matches+ * synchronously; otherwise a cvx_ key resolves against the API-key+ * table (user rail, scoped tools). checkAuth handles the failure+ * shapes before we get here.*/export async function handleMcpRequest(req: NextRequest): Promise<McpOutcome> {let text: string@@ -315,7 +410,11 @@ export async function handleMcpRequest(req: NextRequest): Promise<McpOutcome> {}throw err}- return handleMcpText(text, req)+ const userAuth = await resolveMcpAuth(req)+ if (userAuth && 'error' in userAuth && typeof (userAuth as JsonRpcResponse).error?.code === 'number') {+ return { status: 401, body: userAuth as JsonRpcResponse }+ }+ return handleMcpText(text, req, (userAuth as McpAuth | null) ?? OPERATOR_AUTH)}/** Rate limit for the MCP endpoint (per IP, generous — agents batch). */diff --git a/src/lib/mcp/tools.ts b/src/lib/mcp/tools.tsindex 5d9e223..9353b81 100644--- a/src/lib/mcp/tools.ts+++ b/src/lib/mcp/tools.ts@@ -11,7 +11,8 @@ import { FONTS } from '@/lib/editor-utils'import { isImageFilterId } from '@/lib/image-filters'import { exportPageToSVG } from '@/lib/svg-export'import { magicAnimatePage, clearPageAnimations } from '@/lib/animations'-import { hasProvider, getClientForSlot, recordUsage, rateLimit } from '@/lib/ai/provider'+import { hasProvider, getClientForSlot, getClientForSlotForUser, recordUsage, rateLimit } from '@/lib/ai/provider'+import type { McpAuth } from './server'import {createTextElement,createShapeElement,@@ -140,15 +141,30 @@ function isHttpsUrl(u: unknown): u is string {const AGENT_ACTOR = 'agent:mcp'-async function getDesign(designId: string) {+/** Owner scoping for the BYO-MCP user rail (v0.25).+ * Null = operator rail (unscoped, historical). */+export type OwnerScope = { ownerId: string } | null++/**+ * Fetch one design the caller may act on. Operator rail: any design+ * (historical). User rail: the key owner's own designs only — a+ * user token can never read or mutate someone else's work, even by+ * guessing ids (same isolation the v1 REST rail enforces).+ */+async function getDesign(designId: string, scope: OwnerScope = null) {const design = await db.design.findUnique({ where: { id: designId } })if (!design || design.deletedAt) return null+ if (scope && design.ownerId !== scope.ownerId) return nullreturn design}-async function saveDesign(designId: string, pages: PageData[]): Promise<void> {- await db.design.update({- where: { id: designId },+async function saveDesign(designId: string, pages: PageData[], scope: OwnerScope = null): Promise<void> {+ // user rail: the write is re-scoped at the DB (updateMany + ownerId)+ // so an id swap between getDesign and save can never leak a write+ // onto someone else's design; 0 rows updated = silently no-op.+ const where = scope ? { id: designId, ownerId: scope.ownerId } : { id: designId }+ await db.design.updateMany({+ where,data: {pages: pages as unknown as object,updatedAt: new Date(),@@ -280,10 +296,23 @@ function originOf(req: Pick<NextRequest, 'headers'>): string {export interface ToolDeps {/** only headers are used (origin resolution for edit URLs) */req: Pick<NextRequest, 'headers'>+ /**+ * v0.25 (BYO-MCP): who is calling. 'operator' keeps the historical+ * unscoped view (CANVIX_MCP_TOKEN); 'user' scopes every design read+ * and write to the key owner's own rows — the same footprint the v1+ * REST rail gives a cvx_ key. Defaults to operator so existing+ * callers (tests, older deployments) behave exactly as before.+ */+ auth?: McpAuth}export function buildTools(deps: ToolDeps): ToolDef[] {const origin = originOf(deps.req)+ // user rail: tools only see/modify the owner's designs; designs the+ // agent creates are attributed to the owner (ownerId) so they land+ // in the owner's dashboard, not the anonymous commons.+ const ownerFilter = deps.auth?.kind === 'user' && deps.auth.userId ? { ownerId: deps.auth.userId } : undefined+ const asOwner = ownerFilter ? { ownerId: deps.auth!.userId! } : {}// ── discovery ─────────────────────────────────────────────@@ -337,7 +366,7 @@ export function buildTools(deps: ToolDeps): ToolDef[] {handler: async (args) => {const query = asString(args.query, '').toLowerCase()const designs = await db.design.findMany({- where: { deletedAt: null },+ where: ownerFilter ? { deletedAt: null, ...ownerFilter } : { deletedAt: null },select: { id: true, name: true, width: true, height: true, updatedAt: true, pages: true },take: 40,orderBy: { updatedAt: 'desc' },@@ -369,7 +398,7 @@ export function buildTools(deps: ToolDeps): ToolDef[] {},handler: async (args) => {const id = asString(args.design_id)- const design = await getDesign(id)+ const design = await getDesign(id, ownerFilter ?? null)if (!design) return fail(`Design "${id}" was not found.`)const pages = parsePages(design)return ok({@@ -401,7 +430,7 @@ export function buildTools(deps: ToolDeps): ToolDef[] {required: ['design_id'],},handler: async (args) => {- const design = await getDesign(asString(args.design_id))+ const design = await getDesign(asString(args.design_id), ownerFilter ?? null)if (!design) return fail('Design not found.')const pages = parsePages(design)return ok({@@ -442,6 +471,7 @@ export function buildTools(deps: ToolDeps): ToolDef[] {height: template.height,pages: (pages.length ? pages : [createPage()]) as object,source: `template:${template.slug}`,+ ...asOwner,},})return ok({ design_id: design.id, name, width: design.width, height: design.height, fromTemplate: template.slug, editUrl: editUrl(design.id, origin) })@@ -449,7 +479,7 @@ export function buildTools(deps: ToolDeps): ToolDef[] {const width = clamp(asInt(args.width, 1080), 40, 8000)const height = clamp(asInt(args.height, 1080), 40, 8000)const design = await db.design.create({- data: { name, width, height, pages: [createPage()] as unknown as object, source: 'mcp' },+ data: { name, width, height, pages: [createPage()] as unknown as object, source: 'mcp', ...asOwner },})return ok({ design_id: design.id, name, width, height, pageCount: 1, editUrl: editUrl(design.id, origin) })},@@ -472,12 +502,21 @@ export function buildTools(deps: ToolDeps): ToolDef[] {handler: async (args) => {const query = asString(args.query).slice(0, 2000)if (query.length < 4) return fail('Provide a design brief ("query"), e.g. "Instagram post for a coffee shop launch — warm palette".')- const ctx = await getClientForSlot('text')+ // BYO-MCP: user tokens resolve the OWNER's BYOK providers first+ // (their keys pay for the generation); operator tokens keep the+ // instance-wide chain, exactly as before.+ const authUserId = deps.auth?.kind === 'user' ? deps.auth.userId : null+ const ctx = authUserId+ ? await getClientForSlotForUser('text', authUserId)+ : await getClientForSlot('text')if (!ctx) {await recordUsage('assistant', 'local', false).catch(() => undefined)return fail(- 'generate_design requires an AI provider configured on the server (add one in /admin, set ZAI_API_KEY, or ship a .z-ai-config file). ' +- 'Without a provider you can still create designs from templates: list_templates → create_design → add_text/add_shape.'+ authUserId+ ? 'generate_design needs an AI provider: save your own in Settings → AI providers (bring your own key), or ask the operator to configure one. ' ++ 'Without a provider you can still create designs from templates: list_templates → create_design → add_text/add_shape.'+ : 'generate_design requires an AI provider configured on the server (add one in /admin, set ZAI_API_KEY, or ship a .z-ai-config file). ' ++ 'Without a provider you can still create designs from templates: list_templates → create_design → add_text/add_shape.')}const rl = rateLimit('mcp-generate', deps.req, 6, 60)@@ -508,7 +547,7 @@ export function buildTools(deps: ToolDeps): ToolDef[] {const spec = normalizeGeneratedDesign(parsed, width, height)const name = (asString(args.name, '') || asString(parsed.name, 'Generated design')).slice(0, 80) || 'Generated design'const design = await db.design.create({- data: { name, width: spec.width, height: spec.height, pages: spec.pages as unknown as object, source: 'ai:mcp' },+ data: { name, width: spec.width, height: spec.height, pages: spec.pages as unknown as object, source: 'ai:mcp', ...asOwner },})await recordUsage('assistant', 'zai', true)return ok({@@ -535,13 +574,13 @@ export function buildTools(deps: ToolDeps): ToolDef[] {designId: string,fn: (pages: PageData[], width: number, height: number) => { pages: PageData[]; summary: Record<string, unknown> } | null): Promise<ToolResult> {- const design = await getDesign(designId)+ const design = await getDesign(designId, ownerFilter ?? null)if (!design) return fail(`Design "${designId}" was not found.`)const pages = parsePages(design)if (!pages.length) return fail('This design has no pages yet — call it once via the editor (or create_design from a template) so a page exists.')const result = fn(pages, design.width, design.height)if (!result) return fail('Nothing to change — check your arguments (page index, element id…).')- await saveDesign(designId, result.pages)+ await saveDesign(designId, result.pages, ownerFilter ?? null)return ok({ ok: true, design_id: designId, ...result.summary })}@@ -1024,7 +1063,7 @@ export function buildTools(deps: ToolDeps): ToolDef[] {handler: async (args) => {const designId = asString(args.design_id)const format = asEnum(args.format, ['svg', 'png', 'json'] as const, 'svg')- const design = await getDesign(designId)+ const design = await getDesign(designId, ownerFilter ?? null)if (!design) return fail(`Design "${designId}" was not found.`)const pages = parsePages(design)if (!pages.length) return fail('This design has no pages yet — add elements first.')@@ -1096,7 +1135,7 @@ export function buildTools(deps: ToolDeps): ToolDef[] {const designId = asString(args.design_id)const body = asString(args.body).slice(0, 500)if (!body.trim()) return fail('body must not be empty.')- const design = await getDesign(designId)+ const design = await getDesign(designId, ownerFilter ?? null)if (!design) return fail(`Design "${designId}" was not found.`)const pages = parsePages(design)const pageIndex = clamp(asInt(args.page, 0), 0, Math.max(0, pages.length - 1))@@ -1138,7 +1177,7 @@ export function buildTools(deps: ToolDeps): ToolDef[] {required: ['design_id'],},handler: async (args) => {- const design = await getDesign(asString(args.design_id))+ const design = await getDesign(asString(args.design_id), ownerFilter ?? null)if (!design) return fail('Design not found.')const comments = await db.comment.findMany({where: { designId: design.id },@@ -1193,11 +1232,16 @@ export function buildTools(deps: ToolDeps): ToolDef[] {return fail('Provide a PNG/JPEG/WebP dataURL screenshot in `image`.')}if (image.length > 8 * 1024 * 1024) return fail('Screenshot too large — max ~6 MB.')- const ctx = await getClientForSlot('vision')+ // BYO-MCP: user tokens resolve the owner's BYOK vision slot first+ const visionAuthUserId = deps.auth?.kind === 'user' ? deps.auth.userId : null+ const ctx = visionAuthUserId ? await getClientForSlotForUser('vision', visionAuthUserId) : await getClientForSlot('vision')if (!ctx) {return fail(- 'vision_ground requires a vision-slot provider configured on the server (add one in /admin). ' +- 'Without vision you can still read design structure with get_design_content.',+ visionAuthUserId+ ? 'vision_ground needs a vision-capable provider: save your own in Settings → AI providers (bring your own key), or ask the operator to configure one. ' ++ 'Without vision you can still read design structure with get_design_content.'+ : 'vision_ground requires a vision-slot provider configured on the server (add one in /admin). ' ++ 'Without vision you can still read design structure with get_design_content.',)}const rl = rateLimit('mcp-vision', deps.req, 6, 60)@@ -1260,12 +1304,20 @@ export function buildTools(deps: ToolDeps): ToolDef[] {description: 'Report server capabilities: Canvix version, AI provider availability, and how the server is secured.',inputSchema: { type: 'object', properties: {} },handler: async () => {+ // user rail: BYOK first, then the instance chain — the same+ // resolution generate_design uses, so the report is honest.+ const authUserId = deps.auth?.kind === 'user' ? deps.auth.userId : null+ const aiAvailable = authUserId ? (await getClientForSlotForUser('text', authUserId)) !== null : await hasProvider()return ok({server: 'canvix',version: SERVER_VERSION,- aiProvider: (await hasProvider()) ? 'available (generate_design works)' : 'not configured (generate_design unavailable; all other tools work)',+ aiProvider: aiAvailable+ ? 'available (generate_design works)'+ : authUserId+ ? 'not configured — save your own key in Settings → AI providers (bring your own key), or ask the operator to add one; all other tools work'+ : 'not configured (generate_design unavailable; all other tools work)',transport: 'streamable-http (stateless)',- auth: 'bearer token via CANVIX_MCP_TOKEN',+ auth: authUserId ? `personal API key (user: ${deps.auth?.username ?? 'you'}) — tools are scoped to your own designs` : 'bearer token via CANVIX_MCP_TOKEN',})},}diff --git a/tests/e2e/byo-mcp.spec.ts b/tests/e2e/byo-mcp.spec.tsnew file mode 100644index 0000000..519be58--- /dev/null+++ b/tests/e2e/byo-mcp.spec.ts@@ -0,0 +1,166 @@+import { test, expect, type Browser } from '@playwright/test'+import { createHash } from 'node:crypto'+import { Client } from 'pg'++// v0.25 (BYO-MCP): personal MCP tokens — the agent rail, end to end.+//+// Proven here through the real API surfaces (no CANVIX_MCP_TOKEN set —+// this is the canvix.app situation: operator token absent, the user+// rail carries the feature):+// 1. a cvx_ key WITH the mcp scope authenticates against+// POST /api/mcp (initialize answers; instructions declare the+// personal-token scoping)+// 2. search_designs returns the owner's design and NOT a foreign+// one or the anonymous commons+// 3. get_design on a foreign id answers not-found (no enumeration)+// 4. a key WITHOUT the mcp scope is rejected with the re-issue hint+// 5. revoking the key makes the very same token fail+// 6. OPTIONS reports the user-tokens rail+//+// Needs a database — see playwright.config.ts. Seeding follows+// api-keys.spec.ts (fixture users + session + designs straight into+// Postgres, inside the register budget).++const USER = { id: 'u_e2e_mcp_user', username: 'e2e_mcp_user', token: 'e2e-mcp-user-token' }+const OTHER = { id: 'u_e2e_mcp_other', username: 'e2e_mcp_other' }++function sessionId(token: string): string {+ return createHash('sha256').update(token).digest('hex')+}++function apiKeyId(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]+ )+ await client.query(`DELETE FROM "Design" WHERE "id" LIKE 'd_e2e_mcp_%'`)+ await client.query(+ `INSERT INTO "Design" ("id", "name", "width", "height", "pages", "ownerId", "createdAt", "updatedAt")+ VALUES ('d_e2e_mcp_mine', 'Owned by mcp user', 1080, 1080, '[]'::jsonb, $1, now(), now()),+ ('d_e2e_mcp_other', 'Owned by someone else', 1080, 1080, '[]'::jsonb, $2, now(), now()),+ ('d_e2e_mcp_commons', 'e2e mcp commons', 1080, 1080, '[]'::jsonb, NULL, 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 "id" LIKE 'd_e2e_mcp_%'`)+ await client.query(`DELETE FROM "User" WHERE "id" IN ($1, $2)`, [USER.id, OTHER.id])+ await client.end().catch(() => {})+ }+})++/** A browser context signed in as USER (the seeded session cookie). */+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+}++/** Create an API key through the real route, session-cookie authed. */+async function createKey(request: import('@playwright/test').APIRequestContext, scopes: string[]): Promise<string> {+ const res = await request.post('/api/keys', {+ headers: { 'Content-Type': 'application/json' },+ data: { label: `e2e mcp ${scopes.join('+')}`, scopes },+ })+ expect(res.status()).toBe(201)+ const body = await res.json()+ expect(body.key).toMatch(/^cvx_[A-Za-z0-9_-]{43}$/)+ return body.key as string+}++async function mcpCall(+ request: import('@playwright/test').APIRequestContext,+ key: string,+ method: string,+ params: Record<string, unknown> = {}+) {+ const res = await request.post('/api/mcp', {+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${key}` },+ data: { jsonrpc: '2.0', id: 1, method, params },+ })+ return { status: res.status(), body: await res.json() }+}++test.describe('BYO-MCP: personal tokens (v0.25)', () => {+ test('mcp-scoped key drives the agent rail, scoped to the owner', async ({ browser, request }) => {+ const ctx = await signedInContext(browser)+ // keys are created with the session cookie — same-origin browser auth+ const key = await createKey(ctx.request, ['mcp'])++ // 1. initialize works without CANVIX_MCP_TOKEN and declares the rail+ const init = await mcpCall(request, key, 'initialize', { protocolVersion: '2025-03-26' })+ expect(init.status).toBe(200)+ expect(init.body.result.serverInfo.name).toBe('canvix')+ expect(init.body.result.instructions).toContain('personal token')+ expect(init.body.result.instructions).toContain('scoped to YOUR designs')++ // 2. search_designs: owner sees own design only+ const search = await mcpCall(request, key, 'tools/call', { name: 'search_designs', arguments: {} })+ expect(search.status).toBe(200)+ const searchPayload = JSON.parse(search.body.result.content[0].text)+ const names = searchPayload.designs.map((d: { name: string }) => d.name)+ expect(names).toContain('Owned by mcp user')+ expect(names).not.toContain('Owned by someone else')+ expect(names).not.toContain('e2e mcp commons')++ // 3. get_design on a foreign id → not-found (no enumeration)+ const foreign = await mcpCall(request, key, 'tools/call', { name: 'get_design', arguments: { design_id: 'd_e2e_mcp_other' } })+ expect(foreign.status).toBe(200)+ const foreignPayload = JSON.parse(foreign.body.result.content[0].text)+ expect(foreignPayload.error).toBeTruthy()++ // get_design on own design works+ const own = await mcpCall(request, key, 'tools/call', { name: 'get_design', arguments: { design_id: 'd_e2e_mcp_mine' } })+ expect(own.status).toBe(200)+ const ownPayload = JSON.parse(own.body.result.content[0].text)+ expect(ownPayload.name).toBe('Owned by mcp user')++ // 4. a read-only key cannot drive agents (scope check)+ const readonlyKey = await createKey(ctx.request, ['designs:read'])+ const denied = await mcpCall(request, readonlyKey, 'initialize')+ expect(denied.status).toBe(401)+ expect(denied.body.error.message).toContain('mcp')++ // 5. revoke → the very same token stops working+ // (the UI revoke path is covered by api-keys.spec.ts; revoke in the DB)+ await client.query(`UPDATE "ApiKey" SET "revokedAt" = now() WHERE "id" = $1`, [apiKeyId(key)])+ const revokedCall = await mcpCall(request, key, 'initialize')+ expect(revokedCall.status).toBe(401)+ expect(revokedCall.body.error.message).toContain('revoked')++ await ctx.close()+ })++ test('OPTIONS reports the user-tokens rail when the operator token is absent', async ({ request }) => {+ const res = await request.fetch('/api/mcp', { method: 'OPTIONS' })+ expect(res.status()).toBe(200)+ const body = await res.json()+ // the CI server may or may not have CANVIX_MCP_TOKEN set — both+ // shapes are valid; the rail must never read "disabled"+ expect(['enabled', 'user-tokens']).toContain(body.mcp)+ expect(body.transport).toBe('streamable-http')+ })+})