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(v0.23.0): the profile page & bring your own key — per-user AI providers

Ashiq Hussain Mir8369e5e8062e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index a30e4b1..ad2ead2 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,7 +7,35 @@ The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).
### Added
-- Nothing yet.
+- **Profile page + bring your own key** (v0.23): every signed-in user
+ gets a profile dialog (dashboard → account menu → *Profile & AI keys*)
+ with their account card and their own AI providers. A user-saved key
+ answers its capability slots **before** the instance-wide chain —
+ per-user BYOK without touching the operator's quota:
+ - new `UserAIProvider` model (migration `0012_user_ai_providers_byok`):
+ label, base URL, write-only API key, slots (`text`/`vision`/`image`/
+ `imageEdit`/`video`), optional per-slot model ids
+ - `src/lib/ai/byok.ts` — validation (reuses the admin table's rules),
+ masked listing, per-slot resolution; `provider.ts` gained
+ `resolveSlotForUser` and `withProvider` now resolves the session
+ user's slots first (anonymous path unchanged)
+ - `/api/profile/ai-providers` (GET/POST/PUT/DELETE) + `/test` —
+ session-scoped, same-origin, rate-limited; keys are never returned
+ - `/api/ai/capabilities` is user-aware: the editor enables exactly
+ the features the signed-in user can run on their own keys
+ - 17 new tests (validators, slot precedence, fallback parity);
+ full suite 1401/1401
+
+### Security
+
+- **All 8 Dependabot alerts fixed and auto-closed** (verified `fixed`
+ on the security tab): sharp 0.35.5 (librsvg/libheif/libvips CVEs),
+ zod 4.6.7, deepmerge-ts 8.0.2, minimatch 11.0.8, glob 14.0.5/14.0.6 —
+ `npm audit` reports **0 vulnerabilities**
+- `.github/dependabot.yml` — weekly grouped version updates (npm +
+ GitHub Actions) with per-advisory security PRs, so alerts never sit
+ unscanned again (the 2026-11 wave sat open for 29h before a rescan
+ poke)
## [0.22.1] — 2026-11-12
diff --git a/README.md b/README.md
index 27b9f5a..d704fbf 100644
--- a/README.md
+++ b/README.md
@@ -805,6 +805,34 @@ by updating the credentials in `.env` or the admin console and restarting. No
code changes, no migrations, no editor redeploy — the slot, the probes and the
feature gates all follow.
+### Bring your own key — per-user AI providers (v0.23)
+
+The AI features do not have to run on the operator's keys. Every signed-in
+user gets a **profile page** (dashboard → account menu → *Profile & AI keys*)
+where they can save their own provider credentials — a label, an
+OpenAI-compatible base URL, an API key, and which capability slots
+(`text`, `vision`, `image`, `imageEdit`, `video`) the key should answer,
+with an optional model id per slot.
+
+Resolution is **user-first**: a saved key answers its slots *before* the
+instance-wide chain (multi-provider table → legacy override → env →
+`.z-ai-config`), so a user's AI work never spends the operator's quota —
+and `/api/ai/capabilities` reflects it, so the editor enables exactly the
+features the *user* can run. Anonymous visitors resolve the instance-wide
+slots exactly as before; a user with no saved keys notices nothing.
+
+Security posture (same as the admin console, `docs/ADMIN.md`):
+
+- keys are **write-only** — every read returns a mask (`sk-…last4`), the
+ API never sends the stored key back; editing a label never demands the
+ credential again
+- the key lives server-side in Postgres and is resolved per request — it
+ never reaches the browser (the capabilities endpoint stays booleans-only)
+- validation reuses the admin table's rules: http(s) base URLs, no
+ credentials embedded in the URL, model ids against a strict charset
+- a **Test connection** button runs a minimal round-trip against the
+ provider and reports the scrubbed reason on failure
+
### Local-only vs provider-backed features
| Feature | Works without a provider? |
diff --git a/SECURITY.md b/SECURITY.md
index bfc51ec..7df0e04 100644
--- a/SECURITY.md
+++ b/SECURITY.md
@@ -58,8 +58,13 @@ will not be met with legal action:
**In scope:** the application code in this repository — the Next.js app, API
routes, editor, collaboration/SSE layer, plugin manifest validation and
-bundled-plugin pipeline, MCP server, export pipelines, admin console, and the
-default deployment configurations documented in `README.md`.
+bundled-plugin pipeline, MCP server, export pipelines, admin console, the
+per-user AI provider storage (BYOK, v0.23), and the default deployment
+configurations documented in `README.md`.
+
+Per-user API keys (v0.23 "bring your own key") are stored server-side,
+masked on every read path, and never returned by any API — reports about
+key exposure or cross-user leakage are treated as highest severity.
**Out of scope:**
diff --git a/package-lock.json b/package-lock.json
index db64fc6..2c3e10b 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "canvix",
- "version": "0.22.1",
+ "version": "0.23.0",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "canvix",
- "version": "0.22.1",
+ "version": "0.23.0",
"hasInstallScript": true,
"dependencies": {
"@imgly/background-removal": "^1.7.0",
diff --git a/package.json b/package.json
index 7a6486d..b61ddde 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "canvix",
- "version": "0.22.1",
+ "version": "0.23.0",
"private": false,
"description": "Canvix — free & open-source graphic design tool. A community-built Canva alternative.",
"scripts": {
diff --git a/prisma/migrations/0012_user_ai_providers_byok/migration.sql b/prisma/migrations/0012_user_ai_providers_byok/migration.sql
new file mode 100644
index 0000000..efc473b
--- /dev/null
+++ b/prisma/migrations/0012_user_ai_providers_byok/migration.sql
@@ -0,0 +1,25 @@
+-- v0.23: BYOK — per-user AI providers (profile page).
+-- Signed-in users can save their own provider credentials and route
+-- provider-backed features through them instead of the operator slots.
+
+-- CreateTable
+CREATE TABLE "UserAIProvider" (
+ "id" TEXT NOT NULL,
+ "userId" TEXT NOT NULL,
+ "label" TEXT NOT NULL,
+ "baseUrl" TEXT NOT NULL,
+ "apiKey" TEXT NOT NULL,
+ "slots" TEXT NOT NULL DEFAULT 'text',
+ "models" JSONB NOT NULL DEFAULT '{}',
+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,
+ "updatedAt" TIMESTAMP(3) NOT NULL,
+
+ CONSTRAINT "UserAIProvider_pkey" PRIMARY KEY ("id")
+);
+
+-- AddForeignKey
+ALTER TABLE "UserAIProvider" ADD CONSTRAINT "UserAIProvider_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;
+
+-- CreateIndex
+CREATE INDEX "UserAIProvider_userId_idx" ON "UserAIProvider"("userId");
+
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index 74cba4b..afb3837 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -45,6 +45,34 @@ model User {
designs Design[] @relation("DesignOwner")
folders Folder[] @relation("FolderOwner")
sessions Session[]
+ aiProviders UserAIProvider[]
+}
+
+// ── v0.23: BYOK — per-user AI providers (profile page) ────────
+// A signed-in user can save their own AI credentials and use them
+// for every provider-backed feature, instead of the operator's
+// instance-wide slots. Mirrors the admin multi-provider shape
+// (baseUrl + apiKey + optional model per slot) but scoped to one
+// user row. Keys are write-only through the API: reads return the
+// same mask the admin console shows, never the stored key.
+model UserAIProvider {
+ id String @id @default(cuid())
+ userId String
+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)
+ // 3–60 chars — shown in the profile list and usage accounting
+ label String
+ // http(s) URL, no embedded credentials (validated like the admin table)
+ baseUrl String
+ // write-only credential — masked on every read path
+ apiKey String
+ // capability slots this provider answers ('text','vision','image','imageEdit','video')
+ slots String @default("text")
+ // model id per slot, JSON: {"text":"glm-4.7",…} (validated against MODEL_RE)
+ models Json @default("{}")
+ createdAt DateTime @default(now())
+ updatedAt DateTime @updatedAt
+
+ @@index([userId])
}
// Opaque server-side sessions. The cookie carries the raw token; the row
diff --git a/src/app/api/ai/capabilities/route.ts b/src/app/api/ai/capabilities/route.ts
index 3d9d7ed..bfa2f62 100644
--- a/src/app/api/ai/capabilities/route.ts
+++ b/src/app/api/ai/capabilities/route.ts
@@ -1,8 +1,9 @@
-import { NextResponse } from 'next/server'
-import { hasProviderForSlot } from '@/lib/ai/provider'
+import { NextResponse, type NextRequest } from 'next/server'
+import { hasProviderForSlotForUser } from '@/lib/ai/provider'
import { stockPhotoAvailable } from '@/lib/stock-photo'
import { stockSoundAvailable } from '@/lib/stock-sound'
import { getFeatures } from '@/lib/admin/config'
+import { getSessionUser } from '@/lib/auth/session'
import { withLogging } from '@/lib/observability'
export const runtime = 'nodejs'
@@ -14,7 +15,7 @@ export const dynamic = 'force-dynamic'
* show "requires server AI provider" states before the user tries a feature.
* Only ever exposes which capabilities exist — never config, never keys.
*/
-async function __canvix_get() {
+async function __canvix_get(req: NextRequest) {
// v0.16 (A1): a capability is available when a provider answers AND
// the admin console has not switched the feature off. v0.16.2 (A2):
// the provider check is per capability SLOT — with the multi-provider
@@ -27,12 +28,19 @@ async function __canvix_get() {
// trio (plan/notes/theme), vision-slot alt text, the video slot,
// and the two LOCAL image tools that need no provider at all.
// Sound wave: soundSearch rides the Freesound stock key.
+ // v0.23 (BYOK): when the request carries a session, the user's saved
+ // providers answer the probes first — so people who bring their own keys
+ // see the AI features enabled even on an unconfigured instance. Anonymous
+ // requests resolve the instance-wide slots exactly as before. Booleans
+ // only, still — never config, never keys.
+ const user = await getSessionUser(req)
+ const uid = user?.id ?? null
const [text, vision, image, imageEdit, video, stockPhotos, stockSounds] = await Promise.all([
- hasProviderForSlot('text'),
- hasProviderForSlot('vision'),
- hasProviderForSlot('image'),
- hasProviderForSlot('imageEdit'),
- hasProviderForSlot('video'),
+ hasProviderForSlotForUser('text', uid),
+ hasProviderForSlotForUser('vision', uid),
+ hasProviderForSlotForUser('image', uid),
+ hasProviderForSlotForUser('imageEdit', uid),
+ hasProviderForSlotForUser('video', uid),
stockPhotoAvailable(), // async since A5 — keys resolve console-first
stockSoundAvailable(),
])
diff --git a/src/app/api/profile/ai-providers/route.ts b/src/app/api/profile/ai-providers/route.ts
new file mode 100644
index 0000000..702c6cb
--- /dev/null
+++ b/src/app/api/profile/ai-providers/route.ts
@@ -0,0 +1,115 @@
+import { NextRequest, NextResponse } from 'next/server'
+import { getSessionUser } from '@/lib/auth/session'
+import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'
+import { rateLimit } from '@/lib/ai/provider'
+import { listUserProviders, validateUserProvider, saveUserProvider, updateUserProvider, deleteUserProvider } from '@/lib/ai/byok'
+import { withLogging } from '@/lib/observability'
+
+export const runtime = 'nodejs'
+export const dynamic = 'force-dynamic'
+
+// ─────────────────────────────────────────────────────────────
+// /api/profile/ai-providers — the BYOK CRUD surface (v0.23).
+//
+// GET → the user's saved providers (keys masked — never returned)
+// POST → save a new one { label, baseUrl, apiKey, slots, models? }
+// PUT → edit one { id, label, baseUrl, apiKey?, slots, models? }
+// (absent/empty apiKey KEEPS the stored key — write-only)
+// DELETE → remove one ?id=…
+//
+// Signed-in users only; same-origin enforced on every mutation; a
+// generous-but-bounded rate limit stops scripted abuse. Validation
+// reuses the admin table's rules so both surfaces accept the same
+// shapes (documented in README → "Bring your own key").
+// ─────────────────────────────────────────────────────────────
+
+const NO_SESSION = { error: 'Sign in to manage your AI providers.' } as const
+
+async function __canvix_get(req: NextRequest) {
+ const user = await getSessionUser(req)
+ if (!user) return NextResponse.json(NO_SESSION, { status: 401 })
+ const providers = await listUserProviders(user.id)
+ return NextResponse.json({ providers })
+}
+
+async function __canvix_post(req: NextRequest) {
+ if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })
+ const user = await getSessionUser(req)
+ if (!user) return NextResponse.json(NO_SESSION, { status: 401 })
+ const rl = rateLimit('byok:save', req, 20, 600)
+ if (!rl.ok) {
+ return NextResponse.json(
+ { error: `Too many saves — try again in ${rl.retryAfterSec}s.` },
+ { status: 429, headers: { 'Retry-After': String(rl.retryAfterSec) } }
+ )
+ }
+ try {
+ const body = await req.json().catch(() => null)
+ const check = validateUserProvider(body)
+ if (!check.ok) return NextResponse.json({ error: check.error }, { status: 400 })
+ const saved = await saveUserProvider(user.id, check.value)
+ if (!saved.ok) return NextResponse.json({ error: saved.error }, { status: 400 })
+ return NextResponse.json({ provider: saved.value }, { status: 201 })
+ } catch (error) {
+ console.error('POST /api/profile/ai-providers failed', error)
+ return NextResponse.json({ error: 'Could not save the provider.' }, { status: 500 })
+ }
+}
+
+async function __canvix_put(req: NextRequest) {
+ if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })
+ const user = await getSessionUser(req)
+ if (!user) return NextResponse.json(NO_SESSION, { status: 401 })
+ const rl = rateLimit('byok:save', req, 20, 600)
+ if (!rl.ok) {
+ return NextResponse.json(
+ { error: `Too many saves — try again in ${rl.retryAfterSec}s.` },
+ { status: 429, headers: { 'Retry-After': String(rl.retryAfterSec) } }
+ )
+ }
+ try {
+ const body = (await req.json().catch(() => null)) as Record<string, unknown> | null
+ if (!body || typeof body.id !== 'string' || !body.id) {
+ return NextResponse.json({ error: 'Provider id is required.' }, { status: 400 })
+ }
+ // The edit path may omit the apiKey — the stored key is kept then.
+ const check = validateUserProvider(body)
+ if (!check.ok) return NextResponse.json({ error: check.error }, { status: 400 })
+ const saved = await updateUserProvider(user.id, body.id, check.value)
+ if (!saved.ok) return NextResponse.json({ error: saved.error }, { status: 404 })
+ return NextResponse.json({ provider: saved.value })
+ } catch (error) {
+ console.error('PUT /api/profile/ai-providers failed', error)
+ return NextResponse.json({ error: 'Could not update the provider.' }, { status: 500 })
+ }
+}
+
+async function __canvix_delete(req: NextRequest) {
+ if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })
+ const user = await getSessionUser(req)
+ if (!user) return NextResponse.json(NO_SESSION, { status: 401 })
+ const rl = rateLimit('byok:save', req, 20, 600)
+ if (!rl.ok) {
+ return NextResponse.json(
+ { error: `Too many requests — try again in ${rl.retryAfterSec}s.` },
+ { status: 429, headers: { 'Retry-After': String(rl.retryAfterSec) } }
+ )
+ }
+ try {
+ const id = req.nextUrl.searchParams.get('id')
+ if (!id) return NextResponse.json({ error: 'Provider id is required.' }, { status: 400 })
+ const removed = await deleteUserProvider(user.id, id)
+ if (!removed) return NextResponse.json({ error: 'Provider not found.' }, { status: 404 })
+ return NextResponse.json({ ok: true })
+ } catch (error) {
+ console.error('DELETE /api/profile/ai-providers failed', error)
+ return NextResponse.json({ error: 'Could not remove the provider.' }, { status: 500 })
+ }
+}
+
+// v0.12.5 (H7): opt-in request logging wrapper — passthrough
+// unless CANVIX_LOG=requests (see src/lib/observability.ts)
+export const GET = withLogging('GET /api/profile/ai-providers', __canvix_get)
+export const POST = withLogging('POST /api/profile/ai-providers', __canvix_post)
+export const PUT = withLogging('PUT /api/profile/ai-providers', __canvix_put)
+export const DELETE = withLogging('DELETE /api/profile/ai-providers', __canvix_delete)
diff --git a/src/components/dashboard/Dashboard.tsx b/src/components/dashboard/Dashboard.tsx
index 4832c86..736eed8 100644
--- a/src/components/dashboard/Dashboard.tsx
+++ b/src/components/dashboard/Dashboard.tsx
@@ -34,6 +34,7 @@ import {
FolderPlus,
FolderMinus,
Check,
+ UserRound,
Maximize,
Smartphone,
Monitor,
@@ -48,6 +49,7 @@ import { Input } from '@/components/ui/input'
import { DesignPreview } from '@/components/design-preview'
import { McpCard } from '@/components/dashboard/McpCard'
import { AuthDialog } from '@/components/auth/AuthDialog'
+import { ProfilePanel } from '@/components/dashboard/ProfilePanel'
import { useAuth, adoptAllDesigns, adoptDesign } from '@/lib/auth/client'
import { TEMPLATES } from '@/lib/templates'
import { createPage, TEMPLATE_CATEGORIES, type TemplateRecord } from '@/lib/types'
@@ -152,6 +154,8 @@ export function Dashboard() {
const { user, login, register, logout, refresh: refreshAuth } = useAuth()
const [authOpen, setAuthOpen] = useState(false)
const [authMode, setAuthMode] = useState<'login' | 'register'>('login')
+ // v0.23: the profile dialog — account card + BYOK AI providers
+ const [profileOpen, setProfileOpen] = useState(false)
const [adopting, setAdopting] = useState(false)
// v0.9.1: the BULK action only claims designs attributed to THIS browser
// (server enforces the same). Legacy (pre-accounts) designs are claimable
@@ -598,6 +602,9 @@ export function Dashboard() {
<FolderInput size={14} /> Adopt legacy (pre-accounts) designs ({legacyCount})
</DropdownMenuItem>
)}
+ <DropdownMenuItem className="gap-2" onClick={() => setProfileOpen(true)}>
+ <UserRound size={14} /> Profile &amp; AI keys
+ </DropdownMenuItem>
<DropdownMenuItem className="gap-2" onClick={() => void logout().then(() => { void refreshAuth(); void refresh() })}>
<LogOut size={14} /> Sign out
</DropdownMenuItem>
@@ -1458,6 +1465,11 @@ export function Dashboard() {
void refreshFolders()
}}
/>
+
+ {/* ── v0.23: profile — account card + BYOK AI providers ── */}
+ {user ? (
+ <ProfilePanel open={profileOpen} onOpenChange={setProfileOpen} user={user} />
+ ) : null}
</div>
)
}
diff --git a/src/components/dashboard/ProfilePanel.tsx b/src/components/dashboard/ProfilePanel.tsx
new file mode 100644
index 0000000..9da61b5
--- /dev/null
+++ b/src/components/dashboard/ProfilePanel.tsx
@@ -0,0 +1,393 @@
+'use client'
+
+// ─────────────────────────────────────────────────────────────
+// ProfilePanel (v0.23) — the user's own corner of Canvix.
+//
+// Opened from the dashboard's account menu. Shows the account
+// card (name, member since) and manages BYOK AI providers:
+// save / edit / delete / test your own provider credentials,
+// routed ahead of the instance-wide slots for every provider-
+// backed feature (README → "Bring your own key").
+//
+// Keys are WRITE-ONLY: the API returns a mask (sk-…last4), never
+// the stored key. Editing a provider without re-entering the key
+// keeps the saved one.
+// ─────────────────────────────────────────────────────────────
+
+import { useCallback, useEffect, useState } from 'react'
+import {
+ UserRound,
+ KeyRound,
+ Plus,
+ Trash2,
+ PlugZap,
+ Loader2,
+ Pencil,
+ Check,
+ AlertTriangle,
+ Bot,
+ Eye,
+ ImageIcon,
+ Clapperboard,
+ PenLine,
+} from 'lucide-react'
+import { Dialog, DialogContent, DialogDescription, DialogHeader, DialogTitle } from '@/components/ui/dialog'
+import { Button } from '@/components/ui/button'
+import { Input } from '@/components/ui/input'
+import { toast } from '@/hooks/use-toast'
+import { cn } from '@/lib/utils'
+
+export interface ProfileUser {
+ id: string
+ username: string
+ createdAt: string
+ admin?: boolean
+}
+
+interface ProviderRow {
+ id: string
+ label: string
+ baseUrl: string
+ slots: string[]
+ models: Record<string, string>
+ keyMask: string
+ createdAt: string
+ updatedAt: string
+}
+
+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' },
+ { id: 'image', label: 'Image', icon: ImageIcon, hint: 'Image generation' },
+ { id: 'imageEdit', label: 'Image edit', icon: PenLine, hint: 'Magic Eraser / Enhance' },
+ { id: 'video', label: 'Video', icon: Clapperboard, hint: 'Text-to-video' },
+] as const
+
+const EMPTY_FORM = {
+ id: '' as string,
+ label: '',
+ baseUrl: '',
+ apiKey: '',
+ slots: ['text'] as string[],
+ models: { text: '' } as Record<string, string>,
+}
+
+export function ProfilePanel({ open, onOpenChange, user }: { open: boolean; onOpenChange: (o: boolean) => void; user: ProfileUser }) {
+ const [providers, setProviders] = useState<ProviderRow[] | null>(null)
+ const [loadError, setLoadError] = useState<string | null>(null)
+ const [formOpen, setFormOpen] = useState(false)
+ const [editing, setEditing] = useState<ProviderRow | null>(null)
+ const [form, setForm] = useState(EMPTY_FORM)
+ const [saving, setSaving] = useState(false)
+ const [testingId, setTestingId] = useState<string | null>(null)
+ const [testResult, setTestResult] = useState<Record<string, { ok: boolean; msg: string }>>({})
+
+ const load = useCallback(async () => {
+ try {
+ const res = await fetch('/api/profile/ai-providers', { cache: 'no-store' })
+ if (res.status === 401) {
+ setProviders([])
+ setLoadError(null)
+ return
+ }
+ const data = (await res.json()) as { providers?: ProviderRow[]; error?: string }
+ if (!res.ok) throw new Error(data.error ?? 'Could not load providers.')
+ setProviders(data.providers ?? [])
+ setLoadError(null)
+ } catch (err) {
+ setLoadError(err instanceof Error ? err.message : 'Could not load providers.')
+ setProviders([])
+ }
+ }, [])
+
+ // Load when the dialog opens. The fetch is kicked off in a microtask
+ // so the effect body itself never calls setState synchronously
+ // (react-hooks/set-state-in-effect — same pattern as useDesigns);
+ // load() only sets state after its awaits resolve anyway.
+ useEffect(() => {
+ if (!open) return
+ void Promise.resolve().then(() => load())
+ }, [open, load])
+
+ const openAdd = () => {
+ setEditing(null)
+ setForm(EMPTY_FORM)
+ setFormOpen(true)
+ }
+ const openEdit = (p: ProviderRow) => {
+ setEditing(p)
+ setForm({
+ id: p.id,
+ label: p.label,
+ baseUrl: p.baseUrl,
+ apiKey: '', // write-only: blank keeps the stored key
+ slots: [...p.slots],
+ models: Object.fromEntries(p.slots.map((s) => [s, p.models?.[s] ?? ''])),
+ })
+ setFormOpen(true)
+ }
+
+ const toggleSlot = (slot: string) => {
+ setForm((f) => {
+ const has = f.slots.includes(slot)
+ const slots = has ? f.slots.filter((s) => s !== slot) : [...f.slots, slot]
+ const models: Record<string, string> = {}
+ for (const s of slots) models[s] = f.models[s] ?? ''
+ return { ...f, slots, models }
+ })
+ }
+
+ const save = async () => {
+ if (saving) return
+ setSaving(true)
+ try {
+ const models: Record<string, string> = {}
+ for (const [slot, id] of Object.entries(form.models)) if (id.trim()) models[slot] = id.trim()
+ const body = editing
+ ? { id: form.id, label: form.label, baseUrl: form.baseUrl, apiKey: form.apiKey || undefined, slots: form.slots, models }
+ : { label: form.label, baseUrl: form.baseUrl, apiKey: form.apiKey, slots: form.slots, models }
+ const res = await fetch('/api/profile/ai-providers', {
+ method: editing ? 'PUT' : 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(body),
+ })
+ const data = (await res.json()) as { error?: string }
+ if (!res.ok) throw new Error(data.error ?? 'Could not save the provider.')
+ toast({ title: editing ? 'Provider updated' : 'Provider saved' })
+ setFormOpen(false)
+ await load()
+ } catch (err) {
+ toast({ title: err instanceof Error ? err.message : 'Could not save the provider.', variant: 'destructive' })
+ } finally {
+ setSaving(false)
+ }
+ }
+
+ const remove = async (p: ProviderRow) => {
+ if (!window.confirm(`Remove provider “${p.label}”? Features it covers fall back to this instance's providers.`)) return
+ try {
+ const res = await fetch(`/api/profile/ai-providers?id=${encodeURIComponent(p.id)}`, { method: 'DELETE' })
+ const data = (await res.json()) as { error?: string }
+ if (!res.ok) throw new Error(data.error ?? 'Could not remove the provider.')
+ toast({ title: 'Provider removed' })
+ await load()
+ } catch (err) {
+ toast({ title: err instanceof Error ? err.message : 'Could not remove the provider.', variant: 'destructive' })
+ }
+ }
+
+ const test = async (p: ProviderRow) => {
+ setTestingId(p.id)
+ try {
+ const res = await fetch('/api/profile/ai-providers/test', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ id: p.id }),
+ })
+ const data = (await res.json()) as { ok?: boolean; error?: string; sample?: string }
+ setTestResult((r) => ({
+ ...r,
+ [p.id]: res.ok && data.ok
+ ? { ok: true, msg: `Connection ok — model answered “${(data.sample ?? 'ok').slice(0, 24)}”` }
+ : { ok: false, msg: data.error ?? 'Test failed.' },
+ }))
+ } catch {
+ setTestResult((r) => ({ ...r, [p.id]: { ok: false, msg: 'Test failed — network error.' } }))
+ } finally {
+ setTestingId(null)
+ }
+ }
+
+ const memberSince = new Date(user.createdAt).toLocaleDateString(undefined, { year: 'numeric', month: 'long' })
+
+ return (
+ <Dialog open={open} onOpenChange={onOpenChange}>
+ <DialogContent className="max-w-2xl max-h-[85vh] overflow-y-auto bg-[#16181D] border-white/10 text-white">
+ <DialogHeader>
+ <DialogTitle>Your profile</DialogTitle>
+ <DialogDescription>Your account and your own AI provider keys (used before this instance&apos;s providers).</DialogDescription>
+ </DialogHeader>
+
+ {/* ── account card ── */}
+ <div className="rounded-xl border border-white/10 bg-white/[0.03] p-4 flex items-center gap-4">
+ <div className="h-12 w-12 rounded-full bg-gradient-to-br from-[#02C0CC] to-[#7630D7] text-white text-sm font-extrabold flex items-center justify-center shrink-0">
+ {user.username.slice(0, 2).toUpperCase()}
+ </div>
+ <div className="min-w-0">
+ <div className="text-[15px] font-semibold text-[#00C4CC] flex items-center gap-2">
+ <UserRound size={14} className="shrink-0" /> @{user.username}
+ {user.admin && (
+ <span className="text-[10px] font-bold uppercase tracking-wide bg-[#7630D7]/25 text-white/80 border border-[#7630D7]/40 rounded px-1.5 py-0.5">
+ admin
+ </span>
+ )}
+ </div>
+ <div className="text-[12px] text-white/45">Member since {memberSince} · designs stay private to your account</div>
+ </div>
+ </div>
+
+ {/* ── BYOK providers ── */}
+ <div className="rounded-xl border border-white/10 bg-white/[0.03] p-4">
+ <div className="flex items-center justify-between mb-3">
+ <div className="flex items-center gap-2 font-semibold text-[14px]">
+ <KeyRound size={15} className="text-[#00C4CC]" /> Your AI providers
+ </div>
+ <Button size="sm" className="btn-cv rounded-full px-3 h-8 gap-1.5" onClick={openAdd}>
+ <Plus size={14} /> Add provider
+ </Button>
+ </div>
+ <p className="text-[12px] text-white/50 leading-relaxed mb-3">
+ Bring your own key: providers you save here answer the AI features <span className="text-white/75 font-medium">before</span> the
+ instance-wide ones — your work never spends the operator&apos;s quota. Keys stay on the server and are never shown back.
+ </p>
+
+ {providers === null ? (
+ <div className="flex items-center justify-center gap-2 py-8 text-white/50 text-sm">
+ <Loader2 size={15} className="animate-spin" /> Loading…
+ </div>
+ ) : loadError ? (
+ <div className="flex items-start gap-2 rounded-lg border border-red-500/30 bg-red-500/10 p-3 text-[13px] text-red-200">
+ <AlertTriangle size={15} className="shrink-0 mt-0.5" /> {loadError}
+ </div>
+ ) : providers.length === 0 && !formOpen ? (
+ <div className="text-center py-8 text-white/45 text-[13px]">
+ No providers yet — add one to power the AI features with your own key.
+ </div>
+ ) : (
+ <div className="space-y-2">
+ {providers.map((p) => (
+ <div key={p.id} className="rounded-lg border border-white/10 bg-[#0F1115] p-3">
+ <div className="flex items-center gap-3">
+ <div className="min-w-0 flex-1">
+ <div className="text-[13px] font-semibold truncate">{p.label}</div>
+ <div className="text-[11px] text-white/45 truncate">
+ {p.baseUrl} · <span className="font-mono">{p.keyMask}</span>
+ </div>
+ </div>
+ <div className="flex items-center gap-1 shrink-0">
+ <Button size="sm" variant="ghost" className="h-8 w-8 p-0 text-white/70 hover:text-white" title="Test connection" disabled={testingId === p.id} onClick={() => void test(p)}>
+ {testingId === p.id ? <Loader2 size={14} className="animate-spin" /> : <PlugZap size={14} />}
+ </Button>
+ <Button size="sm" variant="ghost" className="h-8 w-8 p-0 text-white/70 hover:text-white" title="Edit" onClick={() => openEdit(p)}>
+ <Pencil size={14} />
+ </Button>
+ <Button size="sm" variant="ghost" className="h-8 w-8 p-0 text-white/70 hover:text-red-300" title="Remove" onClick={() => void remove(p)}>
+ <Trash2 size={14} />
+ </Button>
+ </div>
+ </div>
+ <div className="flex flex-wrap gap-1.5 mt-2">
+ {p.slots.map((s) => {
+ const opt = SLOT_OPTIONS.find((o) => o.id === s)
+ const model = p.models?.[s]
+ return (
+ <span key={s} className="text-[11px] rounded-full border border-[#00C4CC]/25 bg-[#00C4CC]/10 text-[#8fe8ef] px-2 py-0.5">
+ {opt?.label ?? s}
+ {model ? <span className="text-white/40 font-mono"> · {model}</span> : null}
+ </span>
+ )
+ })}
+ </div>
+ {testResult[p.id] && (
+ <div className={cn('mt-2 flex items-start gap-1.5 text-[12px] rounded-md px-2 py-1.5', testResult[p.id].ok ? 'text-emerald-300 bg-emerald-500/10' : 'text-red-300 bg-red-500/10')}>
+ {testResult[p.id].ok ? <Check size={13} className="shrink-0 mt-0.5" /> : <AlertTriangle size={13} className="shrink-0 mt-0.5" />}
+ {testResult[p.id].msg}
+ </div>
+ )}
+ </div>
+ ))}
+ </div>
+ )}
+
+ {/* ── add / edit form ── */}
+ {formOpen && (
+ <div className="mt-3 rounded-lg border border-white/10 bg-[#0F1115] p-4 space-y-3">
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
+ <div>
+ <label className="text-[11px] font-medium text-white/60 uppercase tracking-wide">Label</label>
+ <Input
+ className="mt-1 bg-white/[0.05] border-white/10 text-white placeholder:text-white/30 h-9 text-[13px]"
+ placeholder="My OpenAI key"
+ value={form.label}
+ maxLength={60}
+ onChange={(e) => setForm((f) => ({ ...f, label: e.target.value }))}
+ />
+ </div>
+ <div>
+ <label className="text-[11px] font-medium text-white/60 uppercase tracking-wide">API key</label>
+ <Input
+ className="mt-1 bg-white/[0.05] border-white/10 text-white placeholder:text-white/30 h-9 text-[13px] font-mono"
+ type="password"
+ placeholder={editing ? 'unchanged — leave blank to keep' : 'sk-…'}
+ value={form.apiKey}
+ onChange={(e) => setForm((f) => ({ ...f, apiKey: e.target.value }))}
+ />
+ </div>
+ </div>
+ <div>
+ <label className="text-[11px] font-medium text-white/60 uppercase tracking-wide">Base URL (OpenAI-compatible)</label>
+ <Input
+ className="mt-1 bg-white/[0.05] border-white/10 text-white placeholder:text-white/30 h-9 text-[13px]"
+ placeholder="https://api.openai.com/v1"
+ value={form.baseUrl}
+ onChange={(e) => setForm((f) => ({ ...f, baseUrl: e.target.value }))}
+ />
+ </div>
+ <div>
+ <label className="text-[11px] font-medium text-white/60 uppercase tracking-wide">Capability slots</label>
+ <div className="flex flex-wrap gap-1.5 mt-1.5">
+ {SLOT_OPTIONS.map((o) => {
+ const active = form.slots.includes(o.id)
+ const Icon = o.icon
+ return (
+ <button
+ key={o.id}
+ type="button"
+ title={o.hint}
+ onClick={() => toggleSlot(o.id)}
+ className={cn(
+ 'text-[12px] rounded-full border px-2.5 py-1 flex items-center gap-1.5 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'
+ )}
+ >
+ <Icon size={12} /> {o.label}
+ </button>
+ )
+ })}
+ </div>
+ </div>
+ {form.slots.length > 0 && (
+ <div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
+ {form.slots.map((slot) => (
+ <div key={slot}>
+ <label className="text-[11px] font-medium text-white/60 uppercase tracking-wide">
+ {SLOT_OPTIONS.find((o) => o.id === slot)?.label ?? slot} model <span className="text-white/30 normal-case">(optional)</span>
+ </label>
+ <Input
+ className="mt-1 bg-white/[0.05] border-white/10 text-white placeholder:text-white/30 h-9 text-[13px] font-mono"
+ placeholder="provider default"
+ maxLength={120}
+ value={form.models[slot] ?? ''}
+ onChange={(e) => setForm((f) => ({ ...f, models: { ...f.models, [slot]: e.target.value } }))}
+ />
+ </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={() => setFormOpen(false)}>
+ Cancel
+ </Button>
+ <Button size="sm" className="btn-cv h-8 gap-1.5" disabled={saving || !form.label.trim() || !form.baseUrl.trim() || (!editing && !form.apiKey)} onClick={() => void save()}>
+ {saving ? <Loader2 size={14} className="animate-spin" /> : <Check size={14} />} {editing ? 'Save changes' : 'Save provider'}
+ </Button>
+ </div>
+ </div>
+ )}
+ </div>
+ </DialogContent>
+ </Dialog>
+ )
+}
diff --git a/src/lib/ai/byok-resolution.test.ts b/src/lib/ai/byok-resolution.test.ts
new file mode 100644
index 0000000..ad2804b
--- /dev/null
+++ b/src/lib/ai/byok-resolution.test.ts
@@ -0,0 +1,102 @@
+// Unit tests for the v0.23 BYOK integration in the provider layer:
+// resolveSlotForUser puts the user's saved providers ahead of every
+// instance-wide layer, and anonymous callers resolve unchanged.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+// Mock the BYOK db-backed resolver — resolveSlotForUser's user layer.
+const resolveUserSlot = vi.hoisted(() => vi.fn())
+vi.mock('@/lib/ai/byok', () => ({ resolveUserSlot }))
+
+// Mock the admin config module resolveSlot depends on (getProviders /
+// getProviderOverride / getModels / aiFeatureEnabled) — same approach
+// as slot-resolution.test.ts, but self-contained here because we only
+// assert the BYOK layer and the fallback shape.
+const { getProviders, getProviderOverride, getModels, aiFeatureEnabled } = vi.hoisted(() => ({
+ getProviders: vi.fn(),
+ getProviderOverride: vi.fn(),
+ getModels: vi.fn(),
+ aiFeatureEnabled: vi.fn(),
+}))
+vi.mock('@/lib/admin/config', () => ({
+ getProviders,
+ getProviderOverride,
+ getModels,
+ aiFeatureEnabled,
+ maskApiKey: (k: string) => (k.length > 6 ? `${k.slice(0, 3)}…${k.slice(-4)}` : '***'),
+ validateProvider: (i: { baseUrl?: string; apiKey?: string }) =>
+ i.baseUrl && i.apiKey ? { ok: true, value: { baseUrl: i.baseUrl, apiKey: i.apiKey } } : { ok: false, error: 'nope' },
+}))
+
+import { resolveSlotForUser } from './provider'
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ vi.unstubAllEnvs()
+ // instance chain defaults: nothing configured anywhere
+ getProviders.mockResolvedValue(null)
+ getProviderOverride.mockResolvedValue(null)
+ getModels.mockResolvedValue({})
+ aiFeatureEnabled.mockResolvedValue(true)
+ resolveUserSlot.mockResolvedValue(null)
+})
+
+describe('resolveSlotForUser (v0.23 BYOK precedence)', () => {
+ it('returns the USER provider when one answers the slot', async () => {
+ resolveUserSlot.mockResolvedValue({
+ baseUrl: 'https://mine.example/v1',
+ apiKey: 'sk-mine',
+ model: 'glm-4.7',
+ providerId: 'u1',
+ label: 'My key',
+ source: 'user',
+ })
+ const out = await resolveSlotForUser('text', 'user-1')
+ expect(out?.source).toBe('user')
+ expect(out?.baseUrl).toBe('https://mine.example/v1')
+ expect(out?.model).toBe('glm-4.7')
+ // the user layer was asked for THIS user
+ expect(resolveUserSlot).toHaveBeenCalledWith('text', 'user-1')
+ })
+
+ it('falls back to the instance chain when the user has no provider for the slot', async () => {
+ const envUrl = 'https://instance.example/v1'
+ const envKey = 'sk-instance'
+ vi.stubEnv('ZAI_BASE_URL', envUrl)
+ vi.stubEnv('ZAI_API_KEY', envKey)
+ resolveUserSlot.mockResolvedValue(null)
+ const out = await resolveSlotForUser('text', 'user-1')
+ expect(out?.source).toBe('env')
+ expect(out?.baseUrl).toBe(envUrl)
+ })
+
+ it('anonymous callers never touch the BYOK layer', async () => {
+ const envUrl = 'https://instance.example/v1'
+ vi.stubEnv('ZAI_BASE_URL', envUrl)
+ vi.stubEnv('ZAI_API_KEY', 'sk-instance')
+ const out = await resolveSlotForUser('text', null)
+ expect(out?.source).toBe('env')
+ expect(resolveUserSlot).not.toHaveBeenCalled()
+ })
+
+ it('a BYOK failure degrades to the instance chain instead of erroring', async () => {
+ resolveUserSlot.mockRejectedValue(new Error('db down'))
+ const envUrl = 'https://instance.example/v1'
+ vi.stubEnv('ZAI_BASE_URL', envUrl)
+ vi.stubEnv('ZAI_API_KEY', 'sk-instance')
+ const out = await resolveSlotForUser('text', 'user-1')
+ expect(out?.source).toBe('env')
+ expect(out?.baseUrl).toBe(envUrl)
+ })
+
+ it('with no user provider it equals the instance chain (resolveSlot passthrough)', async () => {
+ // The machine may legitimately carry a .z-ai-config (the file layer
+ // reads cwd → HOME → /etc, and /etc is not stub-able) or env vars.
+ // What matters for BYOK: an empty user layer changes NOTHING —
+ // resolveSlotForUser === resolveSlot, byte for byte.
+ resolveUserSlot.mockResolvedValue(null)
+ const [withUser, anonymous] = await Promise.all([resolveSlotForUser('video', 'user-1'), resolveSlotForUser('video', null)])
+ expect(withUser).toEqual(anonymous)
+ expect(resolveUserSlot).toHaveBeenCalledTimes(1) // only the user-1 call went through BYOK
+ })
+})
diff --git a/src/lib/ai/byok.test.ts b/src/lib/ai/byok.test.ts
new file mode 100644
index 0000000..5acee51
--- /dev/null
+++ b/src/lib/ai/byok.test.ts
@@ -0,0 +1,116 @@
+// Unit tests for the BYOK module (v0.23): validators, slot picking,
+// masked listing — all against a mocked db, same pattern as
+// admin/config.test.ts.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+const findMany = vi.hoisted(() => vi.fn())
+const count = vi.hoisted(() => vi.fn())
+const create = vi.hoisted(() => vi.fn())
+const findFirst = vi.hoisted(() => vi.fn())
+const update = vi.hoisted(() => vi.fn())
+const del = vi.hoisted(() => vi.fn())
+const dbMock = vi.hoisted(() => ({
+ userAIProvider: { findMany, count, create, findFirst, update, delete: del },
+}))
+vi.mock('@/lib/db', () => ({ db: dbMock }))
+
+import { parseSlots, validateUserProvider, pickUserSlot } from './byok'
+
+beforeEach(() => {
+ vi.clearAllMocks()
+})
+
+describe('parseSlots', () => {
+ it('parses a comma list and drops unknowns', () => {
+ expect(parseSlots('text,vision')).toEqual(['text', 'vision'])
+ expect(parseSlots('text, bogus ,video')).toEqual(['text', 'video'])
+ })
+ it('tolerates empty/absent input', () => {
+ expect(parseSlots(undefined)).toEqual([])
+ expect(parseSlots('')).toEqual([])
+ expect(parseSlots(null)).toEqual([])
+ })
+})
+
+describe('validateUserProvider (v0.23)', () => {
+ it('accepts a clean provider', () => {
+ const out = validateUserProvider({ label: 'My key', baseUrl: 'https://api.example.com/v1', apiKey: 'sk-123', slots: ['text'] })
+ expect(out.ok).toBe(true)
+ if (out.ok) {
+ expect(out.value.label).toBe('My key')
+ expect(out.value.slots).toEqual(['text'])
+ }
+ })
+ it('normalizes the URL like the admin table', () => {
+ const out = validateUserProvider({ label: 'My key', baseUrl: 'https://api.example.com/v1/', apiKey: 'sk-123', slots: 'text' })
+ expect(out.ok).toBe(true)
+ })
+ it('rejects short/long labels', () => {
+ expect(validateUserProvider({ label: 'ab', baseUrl: 'https://x.example/v1', apiKey: 'sk-1', slots: ['text'] }).ok).toBe(false)
+ expect(
+ validateUserProvider({ label: 'x'.repeat(61), baseUrl: 'https://x.example/v1', apiKey: 'sk-1', slots: ['text'] }).ok
+ ).toBe(false)
+ })
+ it('rejects non-http(s) and credential-embedding URLs (admin rules reuse)', () => {
+ expect(validateUserProvider({ label: 'My key', baseUrl: 'ftp://x/v1', apiKey: 'sk-1', slots: ['text'] }).ok).toBe(false)
+ expect(validateUserProvider({ label: 'My key', baseUrl: 'https://user:pass@x/v1', apiKey: 'sk-1', slots: ['text'] }).ok).toBe(false)
+ })
+ it('requires at least one known slot', () => {
+ const out = validateUserProvider({ label: 'My key', baseUrl: 'https://x.example/v1', apiKey: 'sk-1', slots: [] })
+ expect(out.ok).toBe(false)
+ })
+ it('validates per-slot model ids, drops unknown keys', () => {
+ const out = validateUserProvider({
+ label: 'My key',
+ baseUrl: 'https://x.example/v1',
+ apiKey: 'sk-1',
+ slots: ['text', 'vision'],
+ models: { text: 'glm-4.7', vision: 'bad model!', bogus: 'x' },
+ })
+ expect(out.ok).toBe(false) // 'bad model!' fails MODEL_RE (space + !)
+ const out2 = validateUserProvider({
+ label: 'My key',
+ baseUrl: 'https://x.example/v1',
+ apiKey: 'sk-1',
+ slots: ['text', 'vision'],
+ models: { text: 'glm-4.7', bogus: 'dropped' },
+ })
+ expect(out2.ok).toBe(true)
+ if (out2.ok) expect(out2.value.models).toEqual({ text: 'glm-4.7' })
+ })
+})
+
+describe('pickUserSlot (BYOK precedence per slot)', () => {
+ const row = (over: Partial<Parameters<typeof pickUserSlot>[1][number]> = {}) => ({
+ id: 'p1',
+ label: 'First',
+ baseUrl: 'https://one.example/v1',
+ apiKey: 'sk-one',
+ slots: 'text,vision',
+ models: { text: 'glm-4.7' },
+ ...over,
+ })
+
+ it('answers the first provider covering the slot, in insertion order', () => {
+ const rows = [row(), row({ id: 'p2', label: 'Second', slots: 'text' })]
+ const picked = pickUserSlot('text', rows)
+ expect(picked?.providerId).toBe('p1')
+ expect(picked?.source).toBe('user')
+ expect(picked?.model).toBe('glm-4.7')
+ })
+ it('skips providers that do not cover the slot', () => {
+ const rows = [row({ slots: 'vision' }), row({ id: 'p2', label: 'Second', baseUrl: 'https://two.example/v1', apiKey: 'sk-two', slots: 'text' })]
+ const picked = pickUserSlot('text', rows)
+ expect(picked?.providerId).toBe('p2')
+ expect(picked?.apiKey).toBe('sk-two')
+ })
+ it('returns null when nothing covers the slot (fallback to instance chain)', () => {
+ expect(pickUserSlot('video', [row()])).toBeNull()
+ expect(pickUserSlot('text', [])).toBeNull()
+ })
+ it('carries no model when the slot has none configured', () => {
+ const picked = pickUserSlot('vision', [row()])
+ expect(picked?.model).toBeUndefined()
+ })
+})
diff --git a/src/lib/ai/byok.ts b/src/lib/ai/byok.ts
new file mode 100644
index 0000000..cf4214d
--- /dev/null
+++ b/src/lib/ai/byok.ts
@@ -0,0 +1,266 @@
+// ─────────────────────────────────────────────────────────────
+// BYOK — per-user AI providers (v0.23).
+//
+// The profile page lets a signed-in user store their own provider
+// credentials (baseUrl + apiKey + slots + per-slot models). Every
+// provider-backed feature then prefers the USER's provider over the
+// instance-wide slots, so people can bring their own keys to a
+// self-hosted (or operator-limited) instance and still use the AI
+// features — the operator's keys are never consumed for their work.
+//
+// Precedence per slot (documented in README → "Bring your own key"):
+// 1. the user's own provider that answers the slot (first by
+// createdAt, most recent update wins within the same slot)
+// 2. the instance-wide chain: multi-provider table → legacy
+// override → env → .z-ai-config file (unchanged, v0.16.2 A2)
+//
+// SECURITY POSTURE (mirrors the admin console, docs/ADMIN.md):
+// • Keys are write-only: every read path returns maskApiKey(),
+// never the stored credential. The API never sends it back.
+// • The key lives server-side in Postgres, exactly like the admin
+// table's keys — it is resolved server-side per request and
+// never reaches the browser (same contract as secrets never
+// reaching the browser in provider.ts).
+// • Validation reuses the admin validators (baseUrl http(s), no
+// embedded credentials, key length caps, MODEL_RE for ids).
+//
+// CONTRACT: server-only (Prisma + credentials in memory).
+// ─────────────────────────────────────────────────────────────
+
+import { db } from '@/lib/db'
+import { maskApiKey, validateProvider, type AiSlot } from '@/lib/admin/config'
+
+/** The AI slots a user provider can answer — same universe as the admin table. */
+export const BYOK_SLOTS: readonly AiSlot[] = ['text', 'vision', 'image', 'imageEdit', 'video'] as const
+
+/** Hard cap — mirrors the admin table's PROVIDERS_MAX (8). */
+export const BYOK_PROVIDERS_MAX = 8
+
+/** One stored user provider, as the profile page sees it (key masked). */
+export interface UserProviderView {
+ id: string
+ label: string
+ baseUrl: string
+ slots: AiSlot[]
+ models: Partial<Record<AiSlot, string>>
+ keyMask: string
+ createdAt: string
+ updatedAt: string
+}
+
+export type ByokCheck<T> = { ok: true; value: T } | { ok: false; error: string }
+
+// ── validation (pure, unit-tested) ────────────────────────────
+
+/** Parse the comma-separated slots string ('text,vision') into slot values. */
+export function parseSlots(raw: string | undefined | null): AiSlot[] {
+ if (!raw) return []
+ return raw
+ .split(',')
+ .map((s) => s.trim())
+ .filter((s): s is AiSlot => (BYOK_SLOTS as readonly string[]).includes(s))
+}
+
+/**
+ * Validate a save-provider payload: label + baseUrl + apiKey + slots +
+ * optional per-slot model ids. Reuses the admin base checks so the
+ * accepted input shapes stay identical.
+ */
+export function validateUserProvider(input: unknown): ByokCheck<{
+ label: string
+ baseUrl: string
+ apiKey: string
+ slots: AiSlot[]
+ models: Partial<Record<AiSlot, string>>
+}> {
+ if (typeof input !== 'object' || input === null) return { ok: false, error: 'Provider must be an object.' }
+ const raw = input as Record<string, unknown>
+ // label: 3–60 chars, no control characters (shown in lists and logs)
+ if (typeof raw.label !== 'string' || raw.label.trim().length < 3 || raw.label.trim().length > 60) {
+ return { ok: false, error: 'Label must be 3–60 characters.' }
+ }
+ // baseUrl + apiKey: same rules as the admin table (http(s), no
+ // embedded credentials, length caps) — validateProvider does both.
+ const prov = validateProvider({ baseUrl: raw.baseUrl, apiKey: raw.apiKey })
+ if (!prov.ok) return prov
+ // slots: at least one known slot
+ let slots: AiSlot[] = []
+ if (Array.isArray(raw.slots)) {
+ slots = raw.slots.filter((s): s is AiSlot => (BYOK_SLOTS as readonly string[]).includes(s as string))
+ } else if (typeof raw.slots === 'string') {
+ slots = parseSlots(raw.slots)
+ }
+ if (!slots.length) return { ok: false, error: 'Pick at least one capability slot (text, vision, image, imageEdit, video).' }
+ // models: optional per-slot ids — strings under MODEL_RE (validated
+ // per entry; the admin table checks the same pattern in validateSlots)
+ const models: Partial<Record<AiSlot, string>> = {}
+ if (raw.models !== undefined && raw.models !== null) {
+ if (typeof raw.models !== 'object' || Array.isArray(raw.models)) {
+ return { ok: false, error: 'models must be an object of { slot: modelId }.' }
+ }
+ for (const [slot, id] of Object.entries(raw.models as Record<string, unknown>)) {
+ if (!(BYOK_SLOTS as readonly string[]).includes(slot)) continue // unknown keys dropped, not fatal
+ if (typeof id !== 'string' || !id.trim()) continue
+ const MODEL_RE = /^[A-Za-z0-9._:+/@-]{1,120}$/
+ if (!MODEL_RE.test(id.trim())) return { ok: false, error: `Invalid model id for the ${slot} slot.` }
+ models[slot as AiSlot] = id.trim()
+ }
+ }
+ return { ok: true, value: { label: raw.label.trim(), baseUrl: prov.value.baseUrl, apiKey: prov.value.apiKey, slots, models } }
+}
+
+// ── reads (masked) ────────────────────────────────────────────
+
+/** All of a user's providers, masked — the profile page list. */
+export async function listUserProviders(userId: string): Promise<UserProviderView[]> {
+ const rows = await db.userAIProvider.findMany({ where: { userId }, orderBy: { createdAt: 'asc' } })
+ return rows.map((r) => ({
+ id: r.id,
+ label: r.label,
+ baseUrl: r.baseUrl,
+ slots: parseSlots(r.slots),
+ models: (r.models ?? {}) as Partial<Record<AiSlot, string>>,
+ keyMask: maskApiKey(r.apiKey),
+ createdAt: r.createdAt.toISOString(),
+ updatedAt: r.updatedAt.toISOString(),
+ }))
+}
+
+// ── slot resolution (the BYOK layer of resolveSlot) ──────────
+
+/** Resolved user slot — same shape ResolvedSlot uses, source: 'user'. */
+export interface UserResolvedSlot {
+ baseUrl: string
+ apiKey: string
+ model?: string
+ providerId: string
+ label: string
+ source: 'user'
+}
+
+/**
+ * Resolve ONE slot from the user's own providers. First provider row
+ * (by createdAt — insertion order is the user's declared priority)
+ * whose slots list contains the slot. Returns null when none matches.
+ *
+ * Pure data in, data out — no client construction, so it unit-tests
+ * without a DB.
+ */
+export function pickUserSlot(
+ slot: AiSlot,
+ rows: { id: string; label: string; baseUrl: string; apiKey: string; slots: string; models: unknown }[]
+): UserResolvedSlot | null {
+ for (const r of rows) {
+ if (!parseSlots(r.slots).includes(slot)) continue
+ const models = (r.models ?? {}) as Partial<Record<AiSlot, string>>
+ return {
+ baseUrl: r.baseUrl,
+ apiKey: r.apiKey,
+ model: models[slot],
+ providerId: r.id,
+ label: r.label,
+ source: 'user',
+ }
+ }
+ return null
+}
+
+/** DB-backed picker — the one the request path uses. */
+export async function resolveUserSlot(slot: AiSlot, userId: string): Promise<UserResolvedSlot | null> {
+ const rows = await db.userAIProvider.findMany({
+ where: { userId },
+ orderBy: { createdAt: 'asc' },
+ select: { id: true, label: true, baseUrl: true, apiKey: true, slots: true, models: true },
+ })
+ return pickUserSlot(slot, rows)
+}
+
+/** Which slots does this user cover? (capabilities integration) */
+export async function userCoveredSlots(userId: string): Promise<AiSlot[]> {
+ const rows = await db.userAIProvider.findMany({ where: { userId }, select: { slots: true } })
+ const set = new Set<AiSlot>()
+ for (const r of rows) for (const s of parseSlots(r.slots)) set.add(s)
+ return [...set]
+}
+
+// ── writes ────────────────────────────────────────────────────
+
+/** Save (insert) a validated provider. Caps the list at BYOK_PROVIDERS_MAX. */
+export async function saveUserProvider(
+ userId: string,
+ value: { label: string; baseUrl: string; apiKey: string; slots: AiSlot[]; models: Partial<Record<AiSlot, string>> }
+): Promise<ByokCheck<UserProviderView>> {
+ const count = await db.userAIProvider.count({ where: { userId } })
+ if (count >= BYOK_PROVIDERS_MAX) {
+ return { ok: false, error: `Provider limit reached (${BYOK_PROVIDERS_MAX}) — remove one first.` }
+ }
+ const row = await db.userAIProvider.create({
+ data: {
+ userId,
+ label: value.label,
+ baseUrl: value.baseUrl,
+ apiKey: value.apiKey,
+ slots: value.slots.join(','),
+ models: value.models as object,
+ },
+ })
+ return {
+ ok: true,
+ value: {
+ id: row.id,
+ label: row.label,
+ baseUrl: row.baseUrl,
+ slots: value.slots,
+ models: value.models,
+ keyMask: maskApiKey(row.apiKey),
+ createdAt: row.createdAt.toISOString(),
+ updatedAt: row.updatedAt.toISOString(),
+ },
+ }
+}
+
+/**
+ * Replace an existing provider row (edit path). The key is write-only:
+ * when apiKey is absent or empty, the stored key is KEPT (same
+ * posture as the admin table — editing a label never demands the
+ * credential again).
+ */
+export async function updateUserProvider(
+ userId: string,
+ id: string,
+ value: { label: string; baseUrl: string; apiKey?: string; slots: AiSlot[]; models: Partial<Record<AiSlot, string>> }
+): Promise<ByokCheck<UserProviderView>> {
+ const existing = await db.userAIProvider.findFirst({ where: { id, userId } })
+ if (!existing) return { ok: false, error: 'Provider not found.' }
+ const row = await db.userAIProvider.update({
+ where: { id },
+ data: {
+ label: value.label,
+ baseUrl: value.baseUrl,
+ ...(value.apiKey ? { apiKey: value.apiKey } : {}),
+ slots: value.slots.join(','),
+ models: value.models as object,
+ },
+ })
+ return {
+ ok: true,
+ value: {
+ id: row.id,
+ label: row.label,
+ baseUrl: row.baseUrl,
+ slots: parseSlots(row.slots),
+ models: (row.models ?? {}) as Partial<Record<AiSlot, string>>,
+ keyMask: maskApiKey(row.apiKey),
+ createdAt: row.createdAt.toISOString(),
+ updatedAt: row.updatedAt.toISOString(),
+ },
+ }
+}
+
+/** Delete one of the user's providers. No-op-safe. */
+export async function deleteUserProvider(userId: string, id: string): Promise<boolean> {
+ const existing = await db.userAIProvider.findFirst({ where: { id, userId } })
+ if (!existing) return false
+ await db.userAIProvider.delete({ where: { id } })
+ return true
+}
diff --git a/src/lib/ai/provider.ts b/src/lib/ai/provider.ts
index 0e5c8f1..25890c2 100644
--- a/src/lib/ai/provider.ts
+++ b/src/lib/ai/provider.ts
@@ -143,7 +143,7 @@ function providerHeadersFrom(cfg: { token?: string; userId?: string; chatId?: st
// ── per-slot resolution (v0.16.2 A2) ─────────────────────────
-export type SlotSource = 'multi' | 'db' | 'env' | 'file'
+export type SlotSource = 'multi' | 'db' | 'env' | 'file' | 'user'
/** What one capability slot resolved to — never the key, but enough to act. */
export interface ResolvedSlot {
@@ -162,6 +162,33 @@ export interface ResolvedSlot {
headers?: Record<string, string>
}
+// ── BYOK (v0.23): per-user providers ─────────────────────────
+//
+// The profile page stores per-user credentials (src/lib/ai/byok.ts).
+// resolveSlotForUser() puts them at the TOP of the chain for that
+// user: user provider → multi table → legacy → env → file. Users
+// without saved providers resolve exactly as before.
+
+/**
+ * Resolve one slot for a signed-in user: their own providers first
+ * (BYOK), then the instance-wide chain. `userId === null` is the
+ * anonymous path — identical to resolveSlot().
+ */
+export async function resolveSlotForUser(slot: AiSlot, userId: string | null): Promise<ResolvedSlot | null> {
+ if (userId) {
+ try {
+ const { resolveUserSlot } = await import('@/lib/ai/byok')
+ const userSlot = await resolveUserSlot(slot, userId)
+ if (userSlot) return userSlot
+ } catch (err) {
+ // BYOK must never break the fallback chain — a DB hiccup here
+ // degrades to the instance-wide slots, same as resolveSlot.
+ console.error(`[ai/byok] user slot resolution failed (${slot})`, err)
+ }
+ }
+ return resolveSlot(slot)
+}
+
/**
* Pure layer-picker (unit-tested): multi-provider table → legacy single
* override → env vars → .z-ai-config file → null. Exported for tests;
@@ -247,6 +274,16 @@ export async function hasProviderForSlot(slot: AiSlot): Promise<boolean> {
return (await resolveSlot(slot)) !== null
}
+/**
+ * v0.23 (BYOK): the user-aware probe — the user's providers first,
+ * then the instance chain. `capabilities` and the MCP endpoint use
+ * this so a signed-in user with saved keys sees features enabled
+ * even on an otherwise unconfigured instance.
+ */
+export async function hasProviderForSlotForUser(slot: AiSlot, userId: string | null): Promise<boolean> {
+ return (await resolveSlotForUser(slot, userId)) !== null
+}
+
// ── legacy single-chain resolution (v0.16 A1) ────────────────
// Kept for the console's legacy provider card and MCP capability text.
@@ -527,6 +564,11 @@ export const FEATURE_DISABLED = {
* context: { zai, model } (v0.16.2 A2 — the handler no longer resolves
* the model itself, so a per-slot provider+model pair can never drift
* apart between the client and the model id).
+ *
+ * v0.23 (BYOK): when the request carries a session, the user's own
+ * saved providers are tried FIRST for the feature's slot — the
+ * instance chain stays the fallback. Anonymous requests resolve
+ * exactly as before.
*/
export async function withProvider(
feature: string,
@@ -556,7 +598,19 @@ export async function withProvider(
)
}
const slot = FEATURE_SLOTS[feature] ?? 'text'
- const ctx = await getClientForSlot(slot)
+ // v0.23 (BYOK): resolve the session user (null when anonymous) and
+ // try their providers first for this slot.
+ const user = await import('@/lib/auth/session').then((m) => m.getSessionUser(req))
+ const resolved = await resolveSlotForUser(slot, user?.id ?? null)
+ let ctx: ProviderContext | null = null
+ if (resolved) {
+ try {
+ const zai = await makeClient(resolved.baseUrl, resolved.apiKey)
+ ctx = { zai, model: resolved.model, label: resolved.label, source: resolved.source }
+ } catch (err) {
+ console.error(`[ai] provider initialization failed (${slot}${user ? `, user ${user.username}` : ''})`, err)
+ }
+ }
if (!ctx) {
await recordUsage(feature, `no-provider (${slot})`, false, {
status: 503,