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(v0.16.5): Pexels & Pixabay keys in the admin console — Stock media card (A5) (#46)
Ashiq Hussain Mir2cf9a8bc23e5
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3479067..d5db3d3 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,73 @@All notable changes to Canvix will be documented in this file.The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.1.0/).+## [0.16.5] — 2026-11-08++### Added++- **Pexels & Pixabay keys in the admin console — the Stock media+ card (A5).** The two free stock-media keys behind the Photos and+ Videos search rails are now managed on the AI & models page like+ the AI providers: write-only key fields (stored keys echo as+ masks only), a per-provider Test button and a per-provider Clear,+ in a fixed two-provider card below Model slots. They are library+ catalogs, not AI providers — the A4 decision, now manageable+ without editing `.env` and redeploying. Precedence mirrors every+ other credential in the console: a stored key wins over+ `PEXELS_API_KEY` / `PIXABAY_API_KEY`, clearing it restores the env+ fallback, and saving takes effect immediately (the key store rides+ `AppConfig` behind the config module's 10 s in-process cache —+ the same cost profile as the feature switches already sitting on+ every AI route). The Model-slots banner now points at the card+ instead of telling the operator to go edit environment variables.+- **Stock-key Test button** — one minimal one-result search through+ the provider's real search endpoint (`/v1/search` for Pexels,+ `/api/` for Pixabay) with the effective key: the same call the+ Photos rail makes, so a pass there is a pass in the panel, and a+ 401 says "rejected the key" in plain words. Admin-only,+ same-origin, rate-limited to one probe per 10 s — it is one of+ the only console actions that spends real provider quota. The+ verdict never echoes the key, the request URL (Pixabay's key+ rides the query string) or the provider's response body.++### Changed++- `stockPhotoProviders` / `stockVideoProviders` /+ `stockPhotoAvailable` are now **async** — key resolution reads the+ console store first. Internal API only; the routes that consume+ them await, and `/api/stock-photo/available` ++ `/api/stock-video/available` + `/api/ai/capabilities` answer+ exactly as before (booleans and provider names, never keys).++## [0.16.4] — 2026-11-07++### Added++- **Stock photo search on Pexels/Pixabay keys — the `imageSearch`+ AI slot is retired (A4, #44).** "Find me a photo of a coffee+ shop" is a library query against licensed stock catalogs, not a+ generative one, and almost no OpenAI-compatible vendor serves the+ `images/search` endpoint the old slot demanded — the standing 404+ behind the A3 incident. Photo search now rides the same+ self-hoster-key architecture as the Videos rail (v0.15 R6):+ Pexels + Pixabay, plain REST, one free key each, and the same two+ env keys (`PEXELS_API_KEY` / `PIXABAY_API_KEY`) activate both+ rails. Every result carries a sanitized, durable credit block+ (provider, author, license, source page) stored on the inserted+ element and shown at insert and on selection — never burned into+ the canvas or exports. No key configured ⇒ the Photos panel keeps+ its bundled library, search answers `503 NO_PROVIDER` with the+ operator hint, everything else is untouched (the F2b pattern). No+ migration — stored provider tables that still carry an+ `imageSearch` slot are read fine and drop it on the next save.++### Fixed++- **Photos categories are the results-mode exit hatch — always+ render (#45).** A category chip could disappear behind the+ results header after a web search, leaving no way back to the+ bundled library.+## [0.16.3] — 2026-11-07### Addeddiff --git a/docs/ADMIN.md b/docs/ADMIN.mdindex 43a9852..01ab6e1 100644--- a/docs/ADMIN.md+++ b/docs/ADMIN.md@@ -85,12 +85,31 @@ to a different provider + model:**Photo search is not a slot anymore (v0.16.4 A4).** It rode the AItable as `imageSearch` — an `images/search` endpoint almost noOpenAI-compatible vendor serves, the standing 404 behind the A3-incident. It now runs on the free stock-provider keys-(`PEXELS_API_KEY` / `PIXABAY_API_KEY`, the same keys as the Videos-rail — see docs/STOCK-PHOTO.md); the AI & models page's banner-states whether they are set. Stored tables that still carry an-`imageSearch` slot are read fine — unknown slot keys are dropped on-read and disappear on the next save. No migration.+incident. It now runs on the free stock-media keys — the same keys+as the Videos rail (see docs/STOCK-PHOTO.md). Stored tables that+still carry an `imageSearch` slot are read fine — unknown slot keys+are dropped on read and disappear on the next save. No migration.++**Stock media — the Pexels & Pixabay card (v0.16.5 A5).** Those+two keys are managed on this page, "like the others": a fixed+two-provider card below Model slots with write-only key fields+(stored keys echo as masks only, `sk-1…wxyz`), a per-provider+**Test** button and a per-provider **Clear**. The same two keys+power the Photos **and** Videos search rails — they are library+catalogs, not AI providers, which is exactly why they don't ride+the provider table. Precedence mirrors every other credential+here: a stored console key **wins over** `PEXELS_API_KEY` /+`PIXABAY_API_KEY`; clearing the stored key restores the env+fallback. Saving takes effect immediately — no redeploy — because+the key store rides `AppConfig` behind the config module's 10 s+in-process cache (the same cost profile as the feature switches,+which already sit on every AI route). The Test button runs one+minimal one-result search through the provider's real search+endpoint with the *effective* key — the same call the Photos rail+makes, so a pass there is a pass in the panel — rate-limited to+one probe per 10 s, and its verdict never echoes the key, the+request URL (Pixabay's key rides the query string) or the+provider's body.A slot left on “— fall back —” ignores the table and walks the legacychain below. `/api/ai/capabilities` now probes **per slot**, so wiring@@ -133,11 +152,13 @@ search). A switched-off feature:**Test connection** — one minimal chat completion (thinking disabled,one-word reply, 15 s circuit breaker), rate-limited to one probe per-10 s. It is the only console action that spends provider quota. Each-provider row has its own Test button; the fallback card tests the+10 s. It is one of the only console actions that spends provider quota.+Each provider row has its own Test button; the fallback card tests theresolved text slot. The probe goes through the SDK constructor with theresolved `{ baseUrl, apiKey }` — never `ZAI.create()`, whose file-only-lookup ignored env vars and broke every test since A1 (see D3).+lookup ignored env vars and broke every test since A1 (see D3). The+stock-media card's Test buttons spend stock-provider quota the same+way (one one-result search each).### Logsdiff --git a/docs/STOCK-PHOTO.md b/docs/STOCK-PHOTO.mdindex 77dd12d..02c2125 100644--- a/docs/STOCK-PHOTO.md+++ b/docs/STOCK-PHOTO.md@@ -39,15 +39,17 @@ next save. No migration.## Providers-| Provider | Env key | Where to get it | License |-|---|---|---|---|-| Pexels | `PEXELS_API_KEY` | https://www.pexels.com/api/ (free) | Pexels License |-| Pixabay | `PIXABAY_API_KEY` | https://pixabay.com/api/docs/ (free) | Pixabay Content License |--Optional base overrides exist for proxies and test rigs:-`PEXELS_API_BASE` (default `https://api.pexels.com`) and-`PIXABAY_API_BASE` (default `https://pixabay.com/api`) — the same-overrides the Videos rail uses.+| Provider | Console card | Env fallback | Where to get it | License |+|---|---|---|---|---|+| Pexels | Stock media → Pexels | `PEXELS_API_KEY` | https://www.pexels.com/api/ (free) | Pexels License |+| Pixabay | Stock media → Pixabay | `PIXABAY_API_KEY` | https://pixabay.com/api/docs/ (free) | Pixabay Content License |++**v0.16.5 (A5): the keys are managed in the admin console** — the+AI & models page's **Stock media** card (Pexels & Pixabay), with+write-only key fields, a per-provider Test button and a Clear+button, exactly like the AI providers above it. A stored console+key **wins over** the env var; clearing it falls back to the env+key when one is set. Zero console work still works:```bash# .env — either key activates photo search (and the Videos rail)@@ -55,6 +57,11 @@ PEXELS_API_KEY=your-free-key# PIXABAY_API_KEY=your-free-key```+Optional base overrides exist for proxies and test rigs:+`PEXELS_API_BASE` (default `https://api.pexels.com`) and+`PIXABAY_API_BASE` (default `https://pixabay.com/api`) — the same+overrides the Videos rail uses.+Both connectors are plain REST/JSON over `fetch`. **Zero newruntime dependencies** (the house rule).@@ -103,10 +110,18 @@ can never become a credit link.## Admin surface+- **The Stock media card (v0.16.5 A5)** on the AI & models page+ manages the two keys: write-only fields (stored keys echo as+ masks only), a per-provider **Test** button — one minimal+ one-result search through the provider's real endpoint, so a+ pass there is a pass in the Photos panel — and a per-provider+ Clear that restores the env fallback. Saving takes effect+ immediately, no redeploy (the key store rides `AppConfig` with+ the config module's 10 s in-process cache).- The **AI & models** page shows four slots and a banner stating- where photo search lives (the stock keys) and whether they are- set — the operator is never sent hunting for a slot that no- longer exists.+ where photo search lives (the stock media card) and which keys+ are active — the operator is never sent hunting for a slot that+ no longer exists.- The **photoSearch feature switch** still works: switched off,`/api/stock-photo/search` answers `503 FEATURE_DISABLED` — samesemantics as every AI feature.diff --git a/docs/STOCK-VIDEO.md b/docs/STOCK-VIDEO.mdindex d6ece09..de438ad 100644--- a/docs/STOCK-VIDEO.md+++ b/docs/STOCK-VIDEO.md@@ -11,21 +11,29 @@ and everything else in the editor keeps working.## Providers-| Provider | Env key | Where to get it | License |-|---|---|---|---|-| Pexels | `PEXELS_API_KEY` | https://www.pexels.com/api/ (free) | Pexels License |-| Pixabay | `PIXABAY_API_KEY` | https://pixabay.com/api/docs/ (free) | Pixabay Content License |--Optional base overrides exist for proxies and test rigs:-`PEXELS_API_BASE` (default `https://api.pexels.com`) and-`PIXABAY_API_BASE` (default `https://pixabay.com/api`).+| Provider | Console card | Env fallback | Where to get it | License |+|---|---|---|---|---|+| Pexels | Stock media → Pexels | `PEXELS_API_KEY` | https://www.pexels.com/api/ (free) | Pexels License |+| Pixabay | Stock media → Pixabay | `PIXABAY_API_KEY` | https://pixabay.com/api/docs/ (free) | Pixabay Content License |++**v0.16.5 (A5): the keys are managed in the admin console** — the+AI & models page's **Stock media** card, shared with the Photos+rail (the same two keys activate both). Write-only fields,+per-provider Test (a real one-result search) and Clear (env+fallback restored). A stored console key wins over the env var;+saving takes effect immediately, no redeploy. Zero console work+still works:```bash-# .env — either key activates the Videos rail+# .env — either key activates the Videos rail (and photo search)PEXELS_API_KEY=your-free-key# PIXABAY_API_KEY=your-free-key```+Optional base overrides exist for proxies and test rigs:+`PEXELS_API_BASE` (default `https://api.pexels.com`) and+`PIXABAY_API_BASE` (default `https://pixabay.com/api`).+Both connectors are plain REST/JSON over `fetch`.## How an insert works (and what it costs you)diff --git a/package.json b/package.jsonindex ef2c209..5877f9c 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "canvix",- "version": "0.16.4",+ "version": "0.16.5","private": false,"description": "Canvix \u2014 free & open-source graphic design tool. A community-built Canva alternative.","scripts": {diff --git a/src/app/api/admin/config/route.ts b/src/app/api/admin/config/route.tsindex 9d06241..aee6aa0 100644--- a/src/app/api/admin/config/route.ts+++ b/src/app/api/admin/config/route.ts@@ -20,12 +20,17 @@ import {validateSettings,validateProviderList,validateSlots,+ validateStockKeys,+ setStockKeys,+ getStockKeys,+ effectiveStockKeys,+ STOCK_ENV_KEYS,maskApiKey,type StoredProviderEntry,type AiSlot,+ type StockProviderName,} from '@/lib/admin/config'import { resolveProvider, resolveSlot, type ResolvedSlot } from '@/lib/ai/provider'-import { stockPhotoProviders } from '@/lib/stock-photo'import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'import { withLogging } from '@/lib/observability'@@ -48,6 +53,10 @@ export const dynamic = 'force-dynamic'// v0.16.4 (A4): imageSearch is retired — four model slots remain;// photo search runs on the stock-provider keys (surfaced below)+//+// v0.16.5 (A5) adds the stock section: { pexels?, pixabay? } keys+// for the Photos AND Videos search rails — write-only, null clears,+// env vars as fallback (the same precedence as every credential).const SLOT_ORDER: AiSlot[] = ['text', 'vision', 'image', 'imageEdit']function slotView(resolved: ResolvedSlot | null) {@@ -61,14 +70,27 @@ function slotView(resolved: ResolvedSlot | null) {}}+/** One connector's sanitized state: masked stored key, which layer+ * answers, never the key itself (A5). */+function stockProviderView(name: StockProviderName, stored: string | undefined) {+ const envSet = Boolean((process.env[STOCK_ENV_KEYS[name]] ?? '').trim())+ return {+ set: Boolean(stored) || envSet,+ source: stored ? ('db' as const) : envSet ? ('env' as const) : null,+ keyMasked: stored ? maskApiKey(stored) : null,+ }+}+async function sanitizedView() {- const [provider, stored, providers, models, features, settings] = await Promise.all([+ const [provider, stored, providers, models, features, settings, stockKeys, stockEffective] = await Promise.all([resolveProvider(),getProviderOverride(),getProviders(),getModels(),getFeatures(),getSettings(),+ getStockKeys(),+ effectiveStockKeys(),])// per-slot resolution (multi table → legacy chain) for the slots cardconst resolved = {} as Record<AiSlot, ReturnType<typeof slotView>>@@ -101,12 +123,15 @@ async function sanitizedView() {models,features,settings,- // v0.16.4 (A4): photo search left the AI table — the console shows- // where it lives now (stock keys, shared with the Videos rail) and- // whether those keys are set. Secret-free: names only, never keys.- stockPhotos: {- available: stockPhotoProviders().length > 0,- providers: stockPhotoProviders(),+ // v0.16.5 (A5): the stock-media card's data — per-connector mask+ // + which layer answers (console key vs env var), plus whether the+ // rails are live at all. Secret-free: masks and names only, never keys.+ stock: {+ available: Boolean(stockEffective.pexels || stockEffective.pixabay),+ providers: {+ pexels: stockProviderView('pexels', stockKeys.pexels),+ pixabay: stockProviderView('pixabay', stockKeys.pixabay),+ },},}}@@ -211,6 +236,21 @@ async function __canvix_put(req: NextRequest) {await setSettings({ ...(await getSettings()), ...check.value })}+ // ── stock section (stock-media keys, v0.16.5 A5) ───────────+ // Partial merge per connector: { pexels?: key | null, pixabay?:+ // key | null } — a string sets the stored key (write-only, never+ // displayed again), null clears it (env fallback restored),+ // omitted/empty leaves it untouched. The SAME two keys power the+ // Photos and Videos search rails.+ if (body.stock !== undefined) {+ if (typeof body.stock !== 'object' || body.stock === null || Array.isArray(body.stock)) {+ return NextResponse.json({ error: 'stock must be an object ({ pexels?, pixabay? }).' }, { status: 400 })+ }+ const check = validateStockKeys(body.stock)+ if (!check.ok) return NextResponse.json({ error: check.error }, { status: 400 })+ await setStockKeys(check.value)+ }+return NextResponse.json(await sanitizedView())} catch (error) {console.error('PUT /api/admin/config failed', error)diff --git a/src/app/api/admin/config/stock-test/route.test.ts b/src/app/api/admin/config/stock-test/route.test.tsnew file mode 100644index 0000000..26df82a--- /dev/null+++ b/src/app/api/admin/config/stock-test/route.test.ts@@ -0,0 +1,151 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import { NextRequest } from 'next/server'++// Route tests for the A5 stock-key probe. No network, no Postgres.+// The db is mocked (sessions for the admin guard, AppConfig for the+// stored keys); the global fetch is stubbed per test — the probe is+// the one place the route actually goes out, and these tests pin+// both the verdict mapping and the never-leak-the-key invariants+// (Pixabay's key rides the request URL; provider bodies may echo it).++const dbMock = vi.hoisted(() => ({+ session: { findUnique: vi.fn() },+ appConfig: { findMany: vi.fn(), upsert: vi.fn() },+}))+vi.mock('@/lib/db', () => ({ db: dbMock }))++import { POST as stockTest } from './route'+import { invalidateAdminConfig } from '@/lib/admin/config'++// provider.ts's rateLimit (the one this route uses) keeps its own+// bucket store with no reset hook — give every request a unique+// x-forwarded-for so each test gets a fresh bucket instead of+// tripping the 1-per-10s cap meant for real operators.++const ADMIN_SESSION = {+ id: 'sess-admin',+ expiresAt: new Date(Date.now() + 86_400_000),+ user: { id: 'u-admin', username: 'root', role: 'admin', createdAt: new Date('2026-01-01T00:00:00Z') },+}++function req(url: string, init: { body?: unknown; cookie?: string | null; origin?: string } = {}) {+ const headers: Record<string, string> = {+ 'content-type': 'application/json',+ 'x-forwarded-for': `10.${Math.floor(Math.random() * 250)}.${Math.floor(Math.random() * 250)}.${Math.floor(Math.random() * 250)}`,+ }+ if (init.cookie !== null) headers.cookie = init.cookie ?? 'canvix_session=tok'+ if (init.origin) headers.origin = init.origin+ return new NextRequest(url, {+ method: 'POST',+ headers,+ ...(init.body !== undefined ? { body: JSON.stringify(init.body) } : {}),+ })+}++const fetchMock = vi.fn()++beforeEach(() => {+ vi.clearAllMocks()+ invalidateAdminConfig()+ dbMock.session.findUnique.mockResolvedValue(ADMIN_SESSION)+ dbMock.appConfig.findMany.mockResolvedValue([])+ vi.stubGlobal('fetch', fetchMock)+})++afterEach(() => {+ vi.unstubAllGlobals()+ vi.unstubAllEnvs()+})++describe('POST /api/admin/config/stock-test (v0.16.5 A5)', () => {+ it('non-admins never probe (fail-closed guard)', async () => {+ // sticky (not Once): clearAllMocks drains calls, not the once-queue+ dbMock.session.findUnique.mockResolvedValue(null)+ const res = await stockTest(req('http://localhost/api/admin/config/stock-test', { body: { provider: 'pexels' }, cookie: null }))+ expect(res.status).toBe(401)+ expect(fetchMock).not.toHaveBeenCalled()+ })++ it('cross-origin mutation → CSRF 403 before any provider work', async () => {+ const res = await stockTest(+ req('http://localhost/api/admin/config/stock-test', { body: { provider: 'pexels' }, origin: 'https://evil.io' })+ )+ expect(res.status).toBe(403)+ expect(fetchMock).not.toHaveBeenCalled()+ })++ it('unknown provider → 400', async () => {+ const res = await stockTest(req('http://localhost/api/admin/config/stock-test', { body: { provider: 'unsplash' } }))+ expect(res.status).toBe(400)+ })++ it('no key stored and no env var → 400 naming the env fallback', async () => {+ const res = await stockTest(req('http://localhost/api/admin/config/stock-test', { body: { provider: 'pexels' } }))+ expect(res.status).toBe(400)+ const body = (await res.json()) as { error: string }+ expect(body.error).toContain('PEXELS_API_KEY')+ expect(fetchMock).not.toHaveBeenCalled()+ })++ it('pexels: 200 with results → ok, message sanitized, key never echoed', async () => {+ vi.stubEnv('PEXELS_API_KEY', 'env-pexels-key-1234')+ fetchMock.mockResolvedValueOnce(+ new Response(JSON.stringify({ total_results: 1234, photos: [] }), { status: 200 })+ )+ const res = await stockTest(req('http://localhost/api/admin/config/stock-test', { body: { provider: 'pexels' } }))+ expect(res.status).toBe(200)+ const body = (await res.json()) as { ok: boolean; message: string }+ expect(body.ok).toBe(true)+ expect(body.message).toContain('key valid')+ // the probe went out with the env key in the Authorization header…+ const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit]+ expect(url).toContain('/v1/search')+ expect((init.headers as Record<string, string>).Authorization).toBe('env-pexels-key-1234')+ // …but the answer never carries it+ expect(JSON.stringify(body)).not.toContain('env-pexels-key-1234')+ })++ it('pexels: 401 → the verdict says the key was rejected, nothing else', async () => {+ vi.stubEnv('PEXELS_API_KEY', 'env-pexels-key-1234')+ fetchMock.mockResolvedValueOnce(new Response('{"error":"invalid key env-pexels-key-1234"}', { status: 401 }))+ const res = await stockTest(req('http://localhost/api/admin/config/stock-test', { body: { provider: 'pexels' } }))+ const body = (await res.json()) as { ok: boolean; message: string }+ expect(body.ok).toBe(false)+ expect(body.message).toContain('rejected')+ expect(JSON.stringify(body)).not.toContain('env-pexels-key-1234')+ })++ it('pixabay: a stored console key wins over the env var', async () => {+ vi.stubEnv('PIXABAY_API_KEY', 'env-pixabay-key')+ dbMock.appConfig.findMany.mockResolvedValue([{ key: 'stock.providers', value: { pixabay: 'db-pixabay-key' } }])+ fetchMock.mockResolvedValueOnce(new Response(JSON.stringify({ total: 99, hits: [] }), { status: 200 }))+ const res = await stockTest(req('http://localhost/api/admin/config/stock-test', { body: { provider: 'pixabay' } }))+ const body = (await res.json()) as { ok: boolean; message: string }+ expect(body.ok).toBe(true)+ const [url] = fetchMock.mock.calls[0] as [string]+ expect(url).toContain('key=db-pixabay-key') // the REQUEST carries the db key…+ expect(JSON.stringify(body)).not.toContain('db-pixabay-key') // …the verdict never does+ })++ it('pixabay: a 200-with-error-object body → rejected verdict, body never echoed', async () => {+ vi.stubEnv('PIXABAY_API_KEY', 'env-pixabay-key')+ fetchMock.mockResolvedValueOnce(+ new Response(JSON.stringify({ error: { code: 400, message: 'key env-pixabay-key invalid' } }), { status: 200 })+ )+ const res = await stockTest(req('http://localhost/api/admin/config/stock-test', { body: { provider: 'pixabay' } }))+ const body = (await res.json()) as { ok: boolean; message: string }+ expect(body.ok).toBe(false)+ expect(body.message).toContain('rejected')+ expect(JSON.stringify(body)).not.toContain('env-pixabay-key')+ })++ it('network failure → a generic verdict (the error text may embed the URL)', async () => {+ vi.stubEnv('PEXELS_API_KEY', 'env-pexels-key-1234')+ fetchMock.mockRejectedValueOnce(new TypeError('fetch failed https://api.pexels.com?key=env-pexels-key-1234'))+ const res = await stockTest(req('http://localhost/api/admin/config/stock-test', { body: { provider: 'pexels' } }))+ const body = (await res.json()) as { ok: boolean; message: string }+ expect(body.ok).toBe(false)+ expect(body.message).toContain('Could not reach')+ expect(JSON.stringify(body)).not.toContain('env-pexels-key-1234')+ })+})diff --git a/src/app/api/admin/config/stock-test/route.ts b/src/app/api/admin/config/stock-test/route.tsnew file mode 100644index 0000000..80e904b--- /dev/null+++ b/src/app/api/admin/config/stock-test/route.ts@@ -0,0 +1,125 @@+import { NextRequest, NextResponse } from 'next/server'+import { requireAdmin } from '@/lib/admin/guard'+import { effectiveStockKeys, STOCK_ENV_KEYS, type StockProviderName } from '@/lib/admin/config'+import { rateLimit } from '@/lib/ai/provider'+import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'+import { withLogging } from '@/lib/observability'++export const runtime = 'nodejs'+export const dynamic = 'force-dynamic'++// POST /api/admin/config/stock-test — "does the stock key actually+// answer?" (v0.16.5 A5). One minimal one-result search against the+// provider's real search endpoint — the same call the Photos rail+// makes, so a pass here is a pass there (and the Videos rail rides+// the same key). Admin-only and rate-limited to one probe per 10 s:+// like the AI test connection, it is one of the only console actions+// that spends real provider quota.+//+// Body: { provider: 'pexels' | 'pixabay' } — required. The key+// resolves through the same chain as search: stored console key+// first, PEXELS_API_KEY / PIXABAY_API_KEY fallback.+//+// Sanitization (the house rule, same as the search routes): the+// verdict NEVER echoes the provider's body, the request URL+// (Pixabay's key lives in the query string) or the key itself —+// our own words over the HTTP status only.++const TEST_TIMEOUT_MS = 10_000++async function __canvix_post(req: NextRequest) {+ if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })+ const guard = await requireAdmin(req)+ if (!guard.ok) return guard.res++ const rl = rateLimit('admin:stock-test', req, 1, 10)+ if (!rl.ok) {+ return NextResponse.json(+ { ok: false, error: `Wait ${rl.retryAfterSec}s between stock key tests.` },+ { status: 429, headers: { 'Retry-After': String(rl.retryAfterSec) } }+ )+ }++ const body = (await req.json().catch(() => ({}))) as Record<string, unknown>+ const provider = typeof body.provider === 'string' ? body.provider.trim() : ''+ if (provider !== 'pexels' && provider !== 'pixabay') {+ return NextResponse.json({ ok: false, error: 'provider must be "pexels" or "pixabay".' }, { status: 400 })+ }+ const name = provider as StockProviderName++ const keys = await effectiveStockKeys()+ const key = keys[name]+ if (!key) {+ return NextResponse.json(+ {+ ok: false,+ error: `No ${name} key stored and ${STOCK_ENV_KEYS[name]} is not set — save a key first.`,+ },+ { status: 400 }+ )+ }++ let url: string+ let init: RequestInit+ if (name === 'pexels') {+ const base = (process.env.PEXELS_API_BASE ?? 'https://api.pexels.com').replace(/\/+$/, '')+ url = `${base}/v1/search?query=nature&per_page=1&orientation=landscape`+ init = { headers: { Authorization: key } }+ } else {+ const base = (process.env.PIXABAY_API_BASE ?? 'https://pixabay.com/api').replace(/\/+$/, '')+ url = `${base}/?key=${encodeURIComponent(key)}&q=nature&image_type=photo&per_page=3&safesearch=true`+ init = {}+ }++ try {+ const res = await fetch(url, { ...init, signal: AbortSignal.timeout(TEST_TIMEOUT_MS) })+ if (!res.ok) {+ // status-only verdicts — the body may echo the request+ const message =+ res.status === 401 || res.status === 403+ ? `${name} rejected the key (HTTP ${res.status}) — check it and save again.`+ : res.status === 429+ ? `${name} rate-limited the probe (HTTP 429) — the key was recognized; retry in a moment.`+ : `${name} answered HTTP ${res.status}.`+ return NextResponse.json({ ok: false, provider: name, httpStatus: res.status, message })+ }+ const payload = (await res.json().catch(() => null)) as Record<string, unknown> | null+ // Pixabay occasionally answers 200 with an error object for a bad+ // key — detect the shape, never echo it.+ if (payload && typeof payload === 'object' && 'error' in payload && !('hits' in payload)) {+ return NextResponse.json({+ ok: false,+ provider: name,+ httpStatus: 200,+ message: `${name} rejected the key — check it and save again.`,+ })+ }+ const total =+ name === 'pexels'+ ? Number((payload as { total_results?: unknown } | null)?.total_results)+ : Number((payload as { total?: unknown } | null)?.total)+ return NextResponse.json({+ ok: true,+ provider: name,+ httpStatus: 200,+ message:+ Number.isFinite(total) && total > 0+ ? `${name} answered — key valid (${total.toLocaleString('en-US')}+ results for "nature").`+ : `${name} answered — key valid.`,+ })+ } catch (error) {+ // network/timeout errors can embed the request URL — never echo+ // them raw (Pixabay's key rides it). Our words only.+ const timedOut = error instanceof Error && error.name === 'TimeoutError'+ return NextResponse.json({+ ok: false,+ provider: name,+ httpStatus: 0,+ message: timedOut+ ? `${name} timed out after ${TEST_TIMEOUT_MS / 1000} s.`+ : `Could not reach ${name} (network error).`,+ })+ }+}++export const POST = withLogging('POST /api/admin/config/stock-test', __canvix_post)diff --git a/src/app/api/ai/capabilities/route.ts b/src/app/api/ai/capabilities/route.tsindex 8646b44..679453b 100644--- a/src/app/api/ai/capabilities/route.ts+++ b/src/app/api/ai/capabilities/route.ts@@ -27,7 +27,7 @@ async function __canvix_get() {hasProviderForSlot('vision'),hasProviderForSlot('image'),hasProviderForSlot('imageEdit'),- Promise.resolve(stockPhotoAvailable()),+ stockPhotoAvailable(), // async since A5 — keys resolve console-first])const configured = text || vision || image || imageEditconst flags = await getFeatures()diff --git a/src/app/api/stock-photo/available/route.ts b/src/app/api/stock-photo/available/route.tsindex d56eea4..63c54a8 100644--- a/src/app/api/stock-photo/available/route.ts+++ b/src/app/api/stock-photo/available/route.ts@@ -13,9 +13,12 @@ export const dynamic = 'force-dynamic'* Exposes WHICH connectors are keyed, never the keys themselves.*/async function __canvix_get() {+ // A5: keys resolve console-first (stored → env), so this reads the+ // AppConfig cache — one findMany per 10 s per instance at most.+ const providers = await stockPhotoProviders()return NextResponse.json({- available: stockPhotoProviders().length > 0,- providers: stockPhotoProviders(),+ available: providers.length > 0,+ providers,})}diff --git a/src/app/api/stock-photo/search/route.ts b/src/app/api/stock-photo/search/route.tsindex 1a064ec..e39db50 100644--- a/src/app/api/stock-photo/search/route.ts+++ b/src/app/api/stock-photo/search/route.ts@@ -39,13 +39,13 @@ async function __canvix_post(req: NextRequest) {const limit = checkRateLimit(req, 'stockphoto:search')if (!limit.ok) return rateLimitResponse(limit)- const providers = stockPhotoProviders()+ const providers = await stockPhotoProviders()if (providers.length === 0) {return NextResponse.json({error: 'Photo search needs a stock provider key on the server.',code: 'NO_PROVIDER',- hint: 'Set PEXELS_API_KEY or PIXABAY_API_KEY — free keys from each provider (docs/STOCK-PHOTO.md). The same keys also enable the Videos rail.',+ hint: 'Store a Pexels or Pixabay key on the admin AI & models page (stock media card), or set PEXELS_API_KEY / PIXABAY_API_KEY — free keys from each provider (docs/STOCK-PHOTO.md). The same keys also enable the Videos rail.',},{ status: 503 },)diff --git a/src/app/api/stock-video/available/route.ts b/src/app/api/stock-video/available/route.tsindex 8e41d3c..386089c 100644--- a/src/app/api/stock-video/available/route.ts+++ b/src/app/api/stock-video/available/route.ts@@ -14,9 +14,11 @@ export const dynamic = 'force-dynamic'* never the keys themselves.*/async function __canvix_get() {+ // A5: keys resolve console-first (stored → env), same as photos.+ const providers = await stockVideoProviders()return NextResponse.json({- available: stockVideoProviders().length > 0,- providers: stockVideoProviders(),+ available: providers.length > 0,+ providers,})}diff --git a/src/app/api/stock-video/search/route.ts b/src/app/api/stock-video/search/route.tsindex 32e707c..c515bd9 100644--- a/src/app/api/stock-video/search/route.ts+++ b/src/app/api/stock-video/search/route.ts@@ -28,7 +28,7 @@ async function __canvix_post(req: NextRequest) {const limit = checkRateLimit(req, 'stockvideo:search')if (!limit.ok) return rateLimitResponse(limit)- const providers = stockVideoProviders()+ const providers = await stockVideoProviders()if (providers.length === 0) {return NextResponse.json({diff --git a/src/components/admin/ai-config.tsx b/src/components/admin/ai-config.tsxindex aa4bcc1..b09e068 100644--- a/src/components/admin/ai-config.tsx+++ b/src/components/admin/ai-config.tsx@@ -1,18 +1,22 @@'use client'-// AI configuration (v0.16 A1 → v0.16.2 A2 rework).+// AI configuration (v0.16 A1 → v0.16.2 A2 rework → v0.16.5 A5).//-// Four surfaces:+// Five surfaces:// 1. Providers — the multi-provider table: add any OpenAI-compatible// endpoint (NVIDIA NIM, OpenRouter, Z.ai, Groq, …), one key each,// write-only credentials, per-provider Test button.// 2. Model slots — pin each capability (text / vision / image /// imageEdit) to a provider + model id, so different features can// run on different vendors. (v0.16.4 A4: imageSearch is retired —-// photo search runs on the stock-provider keys, see the banner.)+// photo search runs on the stock-media keys, see the banner.)// 3. Legacy fallback — the v0.16 A1 single-provider override and model// ids, used only by slots that don't resolve through the table.// 4. Feature kill switches.+// 5. Stock media (v0.16.5 A5) — the Pexels/Pixabay keys behind the+// Photos and Videos search rails: write-only, per-provider Test+// button, env vars as fallback. Not AI providers — library+// catalogs with free keys (the A4 decision, made manageable).import { useEffect, useState } from 'react'import { Zap, Plus, Trash2, Import } from 'lucide-react'@@ -53,8 +57,11 @@ interface ConfigView {models: { text?: string; vision?: string; image?: string }features: Record<string, boolean>settings: { signupsOpen: boolean; anonymousEditing: boolean }- /** v0.16.4 (A4): where photo search lives now (stock keys) */- stockPhotos: { available: boolean; providers: string[] }+ /** v0.16.5 (A5): the stock-media keys — masks + which layer answers */+ stock: {+ available: boolean+ providers: Record<string, { set: boolean; source: 'db' | 'env' | null; keyMasked: string | null }>+ }}/** Local editing state for one provider row. New rows get a client-generated@@ -110,6 +117,14 @@ interface SlotTestState {busy?: boolean}+/** Stock-key probe result (A5) — same verdict posture as the slot probe. */+interface StockTestState {+ provider: string+ ok: boolean+ message: string+ busy?: boolean+}+/** The endpoint each slot exercises — shown next to the slot so the* provider-fit question ("can NVIDIA generate images?") answers itself. */const SLOT_ENDPOINT: Record<string, string> = {@@ -119,6 +134,25 @@ const SLOT_ENDPOINT: Record<string, string> = {imageEdit: 'images/generations/edit',}+/** The stock-media connectors (A5) — a fixed set, one free key each,+ * shared by the Photos and Videos search rails. */+const STOCK_PROVIDERS = [+ {+ key: 'pexels',+ label: 'Pexels',+ hint: 'Photos + Videos search · free key at pexels.com/api',+ env: 'PEXELS_API_KEY',+ placeholder: 'free Pexels key',+ },+ {+ key: 'pixabay',+ label: 'Pixabay',+ hint: 'Photos + Videos search · free key at pixabay.com/api/docs',+ env: 'PIXABAY_API_KEY',+ placeholder: 'free Pixabay key',+ },+] as const+export function AdminAiConfig() {const [view, setView] = useState<ConfigView | null>(null)const [error, setError] = useState<string | null>(null)@@ -156,6 +190,9 @@ export function AdminAiConfig() {image: data.models.image ?? '',})setFeatures(data.features)+ // write-only credentials: never prefilled, cleared after every save+ setStockPexels('')+ setStockPixabay('')}async function put(body: unknown, message: string) {@@ -216,6 +253,11 @@ export function AdminAiConfig() {const [slotTest, setSlotTest] = useState<SlotTestState | null>(null)+ // ── stock media (A5): Pexels/Pixabay keys, write-only like providers ──+ const [stockPexels, setStockPexels] = useState('')+ const [stockPixabay, setStockPixabay] = useState('')+ const [stockTest, setStockTest] = useState<StockTestState | null>(null)+/** Probe the ENDPOINT the slot actually uses (A3) — a chat-only* provider passes the text test but cannot generate images. */async function testSlot(slot: string) {@@ -236,6 +278,39 @@ export function AdminAiConfig() {}}+ /** Save the stock-media keys — only the fields the operator typed;+ * empty keeps the stored credential (the write-only posture). */+ async function saveStockKeys() {+ const stock: Record<string, string> = {}+ if (stockPexels.trim()) stock.pexels = stockPexels.trim()+ if (stockPixabay.trim()) stock.pixabay = stockPixabay.trim()+ await put({ stock }, 'Stock keys saved — the Photos and Videos rails pick them up immediately.')+ }++ /** Remove one stored key (explicit null) — env fallback restored. */+ async function clearStockKey(name: 'pexels' | 'pixabay') {+ await put({ stock: { [name]: null } }, `Stored ${name} key cleared.`)+ }++ /** Probe the provider's real search endpoint with the effective key. */+ async function testStockKey(name: 'pexels' | 'pixabay') {+ setStockTest({ provider: name, ok: true, busy: true, message: 'probing…' })+ const res = await sendJson<{ ok: boolean; message?: string; error?: string }>(+ '/api/admin/config/stock-test',+ 'POST',+ { provider: name }+ )+ if (res.ok && res.data.ok) {+ setStockTest({ provider: name, ok: true, message: res.data.message ?? 'Key valid.' })+ } else {+ setStockTest({+ provider: name,+ ok: false,+ message: res.data.message ?? res.data.error ?? `Test failed (${res.status}).`,+ })+ }+ }+useEffect(() => {getJson<ConfigView>('/api/admin/config').then((res) => {if (res.ok) {@@ -261,6 +336,7 @@ export function AdminAiConfig() {const providerSectionReady = Boolean(baseUrl.trim()) === Boolean(apiKey.trim()) || (!baseUrl && !apiKey)const legacyStored = view.provider.stored !== nullconst tableEmpty = rows.length === 0+ const stockKeyedCount = Object.values(view.stock.providers).filter((p) => p.set).lengthreturn (<>@@ -408,20 +484,21 @@ export function AdminAiConfig() {every feature can run on a different vendor.</p>{/* v0.16.4 (A4): photo search LEFT the AI table — it runs on the- free stock-provider keys (same keys as the Videos rail), not on- a model slot. State where it lives and whether the keys are set,- so the operator is never sent hunting for a slot that no longer- exists. */}+ free stock-media keys (same keys as the Videos rail), not on a+ model slot. v0.16.5 (A5): those keys are managed in the Stock+ media card below. State where they live so the operator is+ never sent hunting for a slot that no longer exists. */}<div className="mb-4 rounded-xl border border-cyan-500/30 bg-cyan-500/10 p-3 text-sm"><p>- Photo search is no longer a model slot — it runs on free stock-provider keys (Pexels / Pixabay), the same- keys as the Videos rail:{' '}- <code className="rounded bg-muted px-1">PEXELS_API_KEY</code> /{' '}- <code className="rounded bg-muted px-1">PIXABAY_API_KEY</code> (docs/STOCK-PHOTO.md).+ Photo search is not a model slot — it runs on the free stock-media keys (Pexels / Pixabay) managed in the{' '}+ <strong>Stock media</strong> card below, shared with the Videos rail (docs/STOCK-PHOTO.md).</p><p className="mt-1 text-xs text-muted-foreground">- {view.stockPhotos.available- ? `Active — keyed: ${view.stockPhotos.providers.join(', ')}.`+ {view.stock.available+ ? `Active — keyed: ${Object.entries(view.stock.providers)+ .filter(([, p]) => p.set)+ .map(([n, p]) => `${n}${p.source === 'db' ? ' (console)' : ' (env)'}`)+ .join(' · ')}.`: 'No stock key set — the Photos panel keeps only its bundled library.'}</p></div>@@ -493,6 +570,107 @@ export function AdminAiConfig() {</button></Card>+ {/* v0.16.5 (A5): the stock-media card — Pexels/Pixabay keys for the+ Photos + Videos search rails, managed like the AI providers:+ write-only credentials, masked placeholders, per-provider Test+ (a real one-result search through the effective key) and Clear+ (env fallback restored). NOT model slots — the A4 decision. */}+ <Card+ title="Stock media — Pexels & Pixabay"+ right={<Chip tone={stockKeyedCount > 0 ? 'good' : 'neutral'}>{stockKeyedCount > 0 ? `${stockKeyedCount} keyed` : 'no keys'}</Chip>}+ >+ <p className="mb-4 text-sm text-muted-foreground">+ The same two free keys power the Photos and Videos search rails — no AI provider involved. Get a free key at{' '}+ <a href="https://www.pexels.com/api/" target="_blank" rel="noreferrer" className="underline">+ pexels.com/api+ </a>{' '}+ and{' '}+ <a href="https://pixabay.com/api/docs/" target="_blank" rel="noreferrer" className="underline">+ pixabay.com/api/docs+ </a>+ . Keys are write-only — stored, never displayed again; leave a field empty to keep the stored one. A stored+ key wins over the <code className="rounded bg-muted px-1">PEXELS_API_KEY</code> /{' '}+ <code className="rounded bg-muted px-1">PIXABAY_API_KEY</code> environment variables; clearing a stored key+ falls back to the env key when one is set.+ </p>+ <div className="space-y-3">+ {STOCK_PROVIDERS.map((s) => {+ const state = view.stock.providers[s.key]+ const savedHere = state?.source === 'db'+ const testHere = stockTest?.provider === s.key ? stockTest : null+ return (+ <div key={s.key} className="rounded-xl border p-3">+ <div className="grid gap-2 sm:grid-cols-[1.1fr_1.6fr_auto]">+ <div>+ <p className="text-sm font-medium">{s.label}</p>+ <p className="text-xs text-muted-foreground">{s.hint}</p>+ <p className="mt-0.5 text-[11px] text-muted-foreground">+ {state?.set ? `active · ${savedHere ? 'console key' : `env ${s.env}`}` : 'not keyed'}+ </p>+ </div>+ <label className="text-xs">+ <span className="mb-1 block font-medium">API key</span>+ <input+ type="password"+ value={s.key === 'pexels' ? stockPexels : stockPixabay}+ onChange={(e) =>+ s.key === 'pexels' ? setStockPexels(e.target.value) : setStockPixabay(e.target.value)+ }+ placeholder={+ state?.keyMasked+ ? `stored: ${state.keyMasked}`+ : state?.source === 'env'+ ? 'env key active — store one to override'+ : s.placeholder+ }+ autoComplete="off"+ className="h-9 w-full rounded-lg border bg-background px-3 font-mono text-xs outline-none focus:ring-2 focus:ring-ring"+ />+ </label>+ <div className="flex items-end gap-1.5">+ <button+ onClick={() => void testStockKey(s.key)}+ disabled={busy || stockTest?.busy === true || !state?.set}+ title={state?.set ? `One minimal real search through ${s.label}` : 'Save a key first, then test'}+ className="inline-flex h-9 items-center gap-1.5 rounded-lg border px-3 text-sm font-medium transition-colors hover:bg-muted disabled:opacity-50"+ >+ <Zap size={14} /> Test+ </button>+ <button+ onClick={() => void clearStockKey(s.key)}+ disabled={busy || !savedHere}+ title={savedHere ? 'Remove the stored key (env fallback restored)' : 'Nothing stored — env or unset'}+ className="inline-flex h-9 items-center rounded-lg border px-2.5 text-muted-foreground transition-colors hover:bg-destructive/10 hover:text-destructive disabled:opacity-50"+ >+ <Trash2 size={14} />+ </button>+ </div>+ </div>+ {testHere && !testHere.busy && (+ <p className={`mt-2 text-sm ${testHere.ok ? 'text-emerald-600' : 'text-destructive'}`}>+ {testHere.message}+ </p>+ )}+ </div>+ )+ })}+ </div>+ <div className="mt-3 flex flex-wrap items-center gap-3">+ <button+ onClick={() => void saveStockKeys()}+ disabled={busy || (!stockPexels.trim() && !stockPixabay.trim())}+ className="rounded-lg bg-primary px-3.5 py-1.5 text-sm font-medium text-primary-foreground disabled:opacity-50"+ >+ Save stock keys+ </button>+ <span className="text-xs text-muted-foreground">+ {view.stock.available+ ? 'Search active — the Photos web-results section and the Videos rail answer now.'+ : 'No stock key set — Photos keeps its bundled library and the Videos rail stays hidden.'}+ </span>+ </div>+ </Card>+<Cardtitle="Fallback — single provider & default models"right={diff --git a/src/lib/admin/config.test.ts b/src/lib/admin/config.test.tsindex 2c16374..2512bd8 100644--- a/src/lib/admin/config.test.ts+++ b/src/lib/admin/config.test.ts@@ -27,6 +27,10 @@ import {clearProvider,importLegacyProvider,invalidateAdminConfig,+ validateStockKeys,+ getStockKeys,+ setStockKeys,+ effectiveStockKeys,DEFAULT_FEATURES,type StoredProviderEntry,} from './config'@@ -350,3 +354,49 @@ describe('importLegacyProvider (v0.16.2 A2)', () => {expect(out.ok).toBe(false)})})++describe('stock keys (v0.16.5 A5)', () => {+ it('validateStockKeys: set, clear, keep — unknown keys dropped', () => {+ expect(validateStockKeys({ pexels: ' k1 ' })).toEqual({ ok: true, value: { pexels: 'k1' } })+ expect(validateStockKeys({ pixabay: null })).toEqual({ ok: true, value: { pixabay: null } })+ expect(validateStockKeys({ pexels: ' ' })).toEqual({ ok: true, value: {} }) // empty = keep+ const mixed = validateStockKeys({ pexels: 'k', junk: 'x' })+ expect(mixed.ok && mixed.value).toEqual({ pexels: 'k' })+ expect(validateStockKeys({ pixabay: 'x'.repeat(4097) }).ok).toBe(false)+ expect(validateStockKeys('nope').ok).toBe(false)+ expect(validateStockKeys({ pexels: 42 }).ok).toBe(false)+ })++ it('getStockKeys reads only well-formed stored keys (corrupt entries skipped)', async () => {+ findMany.mockResolvedValue([{ key: 'stock.providers', value: { pexels: ' db-key ', pixabay: 7, junk: 'x' } }])+ expect(await getStockKeys()).toEqual({ pexels: 'db-key' })+ })++ it('setStockKeys merges the patch over the stored state — null clears', async () => {+ findMany.mockResolvedValue([{ key: 'stock.providers', value: { pexels: 'old', pixabay: 'keep' } }])+ upsert.mockResolvedValue({})+ await setStockKeys({ pexels: 'new', pixabay: null })+ expect(upsert).toHaveBeenCalledWith(+ expect.objectContaining({+ where: { key: 'stock.providers' },+ create: { key: 'stock.providers', value: { pexels: 'new' } },+ })+ )+ })++ it('effectiveStockKeys: the console key wins, env fills the rest', async () => {+ vi.stubEnv('PEXELS_API_KEY', 'env-pexels')+ vi.stubEnv('PIXABAY_API_KEY', 'env-pixabay')+ findMany.mockResolvedValue([{ key: 'stock.providers', value: { pexels: 'db-pexels' } }])+ expect(await effectiveStockKeys()).toEqual({ pexels: 'db-pexels', pixabay: 'env-pixabay' })+ vi.unstubAllEnvs()+ })++ it('effectiveStockKeys with nothing anywhere → empty strings, never a throw', async () => {+ vi.stubEnv('PEXELS_API_KEY', '')+ vi.stubEnv('PIXABAY_API_KEY', ' ')+ findMany.mockResolvedValue([])+ expect(await effectiveStockKeys()).toEqual({ pexels: '', pixabay: '' })+ vi.unstubAllEnvs()+ })+})diff --git a/src/lib/admin/config.ts b/src/lib/admin/config.tsindex e304843..5e3d851 100644--- a/src/lib/admin/config.ts+++ b/src/lib/admin/config.ts@@ -1,6 +1,6 @@// ─────────────────────────────────────────────────────────────-// Instance configuration (v0.16 A1, extended in v0.16.2 A2) —-// the store behind /admin's AI + settings pages.+// Instance configuration (v0.16 A1, extended in v0.16.2 A2,+// v0.16.5 A5) — the store behind /admin's AI + settings pages.//// AppConfig rows (key → JSON):// ai.provider { baseUrl, apiKey } — legacy single override (v0.16 A1)@@ -8,6 +8,7 @@// ai.models { text?, vision?, image? } — legacy model ids (A1)// ai.features { magicWrite, … } — per-feature kill switches// app.settings { signupsOpen, anonymousEditing }+// stock.providers { pexels?, pixabay? } — stock-media keys (A5)//// Design decisions (documented in docs/ADMIN.md):// • Precedence per capability slot: multi-provider table (ai.providers)@@ -41,6 +42,7 @@ export const CONFIG_KEYS = {models: 'ai.models',features: 'ai.features',settings: 'app.settings',+ stock: 'stock.providers',} as constexport const AI_FEATURES = [@@ -114,6 +116,18 @@ export const DEFAULT_SETTINGS: StoredSettings = {anonymousEditing: true,}+// ── stock-media keys (v0.16.5 A5) ─────────────────────────────++/** The two stock-media connectors — photos + videos share each key. */+export type StockProviderName = 'pexels' | 'pixabay'+/** Stored stock keys (AppConfig `stock.providers`) — write-only like every credential here. */+export type StoredStockKeys = Partial<Record<StockProviderName, string>>+/** The pre-A5 way to key stock search — still the fallback when nothing is stored. */+export const STOCK_ENV_KEYS: Record<StockProviderName, string> = {+ pexels: 'PEXELS_API_KEY',+ pixabay: 'PIXABAY_API_KEY',+}+const BASEURL_MAX = 2048const APIKEY_MAX = 4096// Model ids: letters, digits, ._:+- plus "/" (NVIDIA NIM + HuggingFace@@ -210,6 +224,42 @@ export function validateSettings(input: unknown): Check<Partial<StoredSettings>>return { ok: true, value: out }}+/**+ * Validate a stock-keys PATCH (v0.16.5 A5). Per connector:+ * a non-empty string (trimmed, ≤ APIKEY_MAX) sets the stored key,+ * null explicitly clears it (env fallback restored),+ * omitted OR an empty string leaves it untouched — the same+ * write-only posture as the providers table, applied to a fixed+ * two-provider set (editing one key never demands the other).+ */+export function validateStockKeys(+ input: unknown,+): Check<Partial<Record<StockProviderName, string | null>>> {+ if (typeof input !== 'object' || input === null || Array.isArray(input)) {+ return { ok: false, error: 'stock must be an object.' }+ }+ const raw = input as Record<string, unknown>+ const out: Partial<Record<StockProviderName, string | null>> = {}+ for (const name of ['pexels', 'pixabay'] as const) {+ const v = raw[name]+ if (v === undefined) continue+ if (v === null) {+ out[name] = null // explicit clear+ continue+ }+ if (typeof v !== 'string') {+ return { ok: false, error: `stock.${name} must be a key string or null (to clear).` }+ }+ const key = v.trim()+ if (!key) continue // empty = keep the stored key (write-only editing)+ if (key.length > APIKEY_MAX) {+ return { ok: false, error: `stock.${name} must be at most ${APIKEY_MAX} characters.` }+ }+ out[name] = key+ }+ return { ok: true, value: out }+}+// ── multi-provider table validation (v0.16.2 A2) ─────────────/**@@ -499,3 +549,44 @@ export async function setFeatures(value: StoredFeatures): Promise<void> {export async function setSettings(value: StoredSettings): Promise<void> {await writeRow(CONFIG_KEYS.settings, value as unknown as Prisma.InputJsonValue)}++// ── stock-media keys: read / merge-write / resolve (A5) ───────++/** The console-stored stock keys only (no env) — corrupt entries are skipped, never fatal. */+export async function getStockKeys(): Promise<StoredStockKeys> {+ const rows = await readRows()+ const raw = asRecord(rows.get(CONFIG_KEYS.stock))+ const out: StoredStockKeys = {}+ for (const name of ['pexels', 'pixabay'] as const) {+ const v = raw[name]+ if (typeof v === 'string' && v.trim()) out[name] = v.trim()+ }+ return out+}++/** Merge a validated patch over the stored keys and write the full state. */+export async function setStockKeys(patch: Partial<Record<StockProviderName, string | null>>): Promise<void> {+ const next: StoredStockKeys = { ...(await getStockKeys()) }+ for (const name of ['pexels', 'pixabay'] as const) {+ const v = patch[name]+ if (v === null) delete next[name]+ else if (typeof v === 'string' && v) next[name] = v+ }+ await writeRow(CONFIG_KEYS.stock, next as unknown as Prisma.InputJsonValue)+}++/**+ * The keys the stock connectors actually use (A5): a stored console+ * key wins, else the env var, else '' (unset) — the same precedence+ * direction as every AI credential here: the console overrides the+ * environment, it never loses to it. Clearing a stored key restores+ * the env fallback.+ */+export async function effectiveStockKeys(): Promise<Record<StockProviderName, string>> {+ const stored = await getStockKeys()+ const out = { pexels: '', pixabay: '' }+ for (const name of ['pexels', 'pixabay'] as const) {+ out[name] = stored[name] ?? (process.env[STOCK_ENV_KEYS[name]] ?? '').trim()+ }+ return out+}diff --git a/src/lib/admin/routes.test.ts b/src/lib/admin/routes.test.tsindex 952f3ac..750fe08 100644--- a/src/lib/admin/routes.test.ts+++ b/src/lib/admin/routes.test.ts@@ -311,3 +311,58 @@ describe('POST /api/auth/register × signups switch (v0.16 A1)', () => {expect(((await res.json()) as { code?: string }).code).toBeUndefined()})})++describe('GET/PUT /api/admin/config × stock section (v0.16.5 A5)', () => {+ it('GET shows per-connector masks, sources and availability — never keys', async () => {+ dbMock.session.findUnique.mockResolvedValue(ADMIN_SESSION)+ dbMock.appConfig.findMany.mockResolvedValue([{ key: 'stock.providers', value: { pexels: 'sk-pexels-secret-1234' } }])+ const res = await configGet(req('http://localhost/api/admin/config'))+ expect(res.status).toBe(200)+ const body = (await res.json()) as {+ stock: { available: boolean; providers: Record<string, { set: boolean; source: string | null; keyMasked: string | null }> }+ }+ expect(body.stock.available).toBe(true)+ expect(body.stock.providers.pexels).toEqual({ set: true, source: 'db', keyMasked: 'sk-p…1234' })+ expect(JSON.stringify(body)).not.toContain('sk-pexels-secret-1234')+ })++ it('PUT stock saves write-only and keeps an untouched connector', async () => {+ dbMock.session.findUnique.mockResolvedValue(ADMIN_SESSION)+ // the mock db "persists": upserts land in the row store findMany+ // reads, so the sanitized echo reflects the just-saved state+ const rows = new Map<string, unknown>([['stock.providers', { pixabay: 'keep-me' }]])+ dbMock.appConfig.findMany.mockImplementation(async () => [...rows.entries()].map(([key, value]) => ({ key, value })))+ dbMock.appConfig.upsert.mockImplementation(async (args: { where: { key: string }; create: { value: unknown } }) => {+ rows.set(args.where.key, args.create.value)+ return {}+ })+ const res = await configPut(req('http://localhost/api/admin/config', { method: 'PUT', body: { stock: { pexels: 'new-pexels-key-1234' } } }))+ expect(res.status).toBe(200)+ expect(dbMock.appConfig.upsert).toHaveBeenCalledWith(+ expect.objectContaining({ where: { key: 'stock.providers' }, create: { key: 'stock.providers', value: { pexels: 'new-pexels-key-1234', pixabay: 'keep-me' } } })+ )+ const body = (await res.json()) as { stock: { providers: { pexels: { keyMasked: string } } } }+ expect(body.stock.providers.pexels.keyMasked).toBe('new-…1234')+ })++ it('PUT stock null clears one connector (env fallback restored)', async () => {+ dbMock.session.findUnique.mockResolvedValue(ADMIN_SESSION)+ dbMock.appConfig.findMany.mockResolvedValue([{ key: 'stock.providers', value: { pexels: 'old', pixabay: 'keep' } }])+ const res = await configPut(req('http://localhost/api/admin/config', { method: 'PUT', body: { stock: { pexels: null } } }))+ expect(res.status).toBe(200)+ expect(dbMock.appConfig.upsert).toHaveBeenCalledWith(+ expect.objectContaining({ create: { key: 'stock.providers', value: { pixabay: 'keep' } } })+ )+ })++ it('PUT stock rejects garbage (wrong types, oversize)', async () => {+ dbMock.session.findUnique.mockResolvedValue(ADMIN_SESSION)+ const bad1 = await configPut(req('http://localhost/api/admin/config', { method: 'PUT', body: { stock: { pexels: 42 } } }))+ expect(bad1.status).toBe(400)+ const bad2 = await configPut(req('http://localhost/api/admin/config', { method: 'PUT', body: { stock: 'nope' } }))+ expect(bad2.status).toBe(400)+ const bad3 = await configPut(req('http://localhost/api/admin/config', { method: 'PUT', body: { stock: { pixabay: 'x'.repeat(4097) } } }))+ expect(bad3.status).toBe(400)+ expect(dbMock.appConfig.upsert).not.toHaveBeenCalled()+ })+})diff --git a/src/lib/stock-photo.test.ts b/src/lib/stock-photo.test.tsindex 61377cb..2e478f5 100644--- a/src/lib/stock-photo.test.ts+++ b/src/lib/stock-photo.test.ts@@ -1,4 +1,11 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++// A5: availability resolves console-first through the admin config —+// mock the db (empty AppConfig by default) so the env path is the+// default and stock.providers rows can be injected per test.+const findMany = vi.hoisted(() => vi.fn())+vi.mock('@/lib/db', () => ({ db: { appConfig: { findMany } } }))+import {choosePhotoRenditions,resetStockPhotoCache,@@ -7,6 +14,7 @@ import {stockPhotoProviders,type StockPhotoResult,} from './stock-photo'+import { invalidateAdminConfig } from '@/lib/admin/config'// ── recorded provider response shapes ─────────────────────────// The Pexels Photo resource + the Pixabay photo hit, exactly as@@ -92,6 +100,8 @@ function jsonRes(body: unknown, status = 200): Response {beforeEach(() => {resetStockPhotoCache()+ findMany.mockResolvedValue([])+ invalidateAdminConfig()vi.stubEnv('PEXELS_API_KEY', 'test-pexels-key')vi.stubEnv('PIXABAY_API_KEY', 'test-pixabay-key')delete process.env.PEXELS_API_BASE@@ -101,23 +111,41 @@ beforeEach(() => {afterEach(() => {vi.unstubAllEnvs()vi.restoreAllMocks()+ // a test may warm the config cache with injected rows — never leak it+ invalidateAdminConfig()})describe('availability — self-hoster keys gate the feature', () => {- it('no keys → no providers, not available', () => {+ it('no keys → no providers, not available', async () => {vi.stubEnv('PEXELS_API_KEY', '')vi.stubEnv('PIXABAY_API_KEY', '')- expect(stockPhotoProviders()).toEqual([])- expect(stockPhotoAvailable()).toBe(false)+ await expect(stockPhotoProviders()).resolves.toEqual([])+ await expect(stockPhotoAvailable()).resolves.toBe(false)})- it('either key enables its provider only', () => {+ it('either key enables its provider only', async () => {vi.stubEnv('PIXABAY_API_KEY', '')- expect(stockPhotoProviders()).toEqual(['pexels'])+ await expect(stockPhotoProviders()).resolves.toEqual(['pexels'])vi.stubEnv('PEXELS_API_KEY', '')vi.stubEnv('PIXABAY_API_KEY', 'k2')- expect(stockPhotoProviders()).toEqual(['pixabay'])- expect(stockPhotoAvailable()).toBe(true)+ await expect(stockPhotoProviders()).resolves.toEqual(['pixabay'])+ await expect(stockPhotoAvailable()).resolves.toBe(true)+ })++ it('A5: a console-stored key activates the rail with no env var', async () => {+ vi.stubEnv('PEXELS_API_KEY', '')+ vi.stubEnv('PIXABAY_API_KEY', '')+ findMany.mockResolvedValue([{ key: 'stock.providers', value: { pixabay: 'db-key' } }])+ await expect(stockPhotoProviders()).resolves.toEqual(['pixabay'])+ await expect(stockPhotoAvailable()).resolves.toBe(true)+ })++ it('A5: a corrupt stock row is ignored, never fatal', async () => {+ vi.stubEnv('PEXELS_API_KEY', '')+ vi.stubEnv('PIXABAY_API_KEY', '')+ findMany.mockResolvedValue([{ key: 'stock.providers', value: { pexels: 42, junk: 'x' } }])+ await expect(stockPhotoProviders()).resolves.toEqual([])+ await expect(stockPhotoAvailable()).resolves.toBe(false)})})@@ -279,6 +307,15 @@ describe('gating + failure modes', () => {await expect(searchStockPhotos('x', 10, { noCache: true })).rejects.toThrow('NO_PROVIDER')})+ it('A5: a stored console key wins over the env var (the request carries it)', async () => {+ findMany.mockResolvedValue([{ key: 'stock.providers', value: { pexels: 'db-pexels-key' } }])+ const fetchImpl = vi.fn().mockResolvedValue(jsonRes({ photos: [] }))+ await searchStockPhotos('x', 5, { fetchImpl, noCache: true })+ const [url, init] = fetchImpl.mock.calls[0] as [string, RequestInit]+ expect(url.startsWith('https://api.pexels.com/v1/search')).toBe(true)+ expect((init.headers as Record<string, string>).Authorization).toBe('db-pexels-key')+ })+it('provider error → sanitized message, never the request URL or body', async () => {const fetchImpl = vi.fn()diff --git a/src/lib/stock-photo.ts b/src/lib/stock-photo.tsindex 8f3a267..be4c6e3 100644--- a/src/lib/stock-photo.ts+++ b/src/lib/stock-photo.ts@@ -9,9 +9,15 @@// images/search route — the standing 404 behind the A3 incident.// The slot is retired; photos now ride the SAME self-hoster-key// architecture as stock video (v0.15 R6): Pexels + Pixabay,-// plain REST, one free key each — and the SAME two env keys+// plain REST, one free key each — and the SAME two keys// (PEXELS_API_KEY / PIXABAY_API_KEY) activate both rails.//+// v0.16.5 (A5): those keys are console-manageable. They resolve+// through src/lib/admin/config.ts — a key stored on the AI & models+// page (stock.providers row) wins over the env var, so /admin can+// activate or rotate stock search without a redeploy; the env var+// remains the zero-console fallback.+//// No provider key configured ⇒ the Photos panel keeps its// bundled library, web results answer 503 NO_PROVIDER with the// operator hint, and everything else keeps working (the F2b@@ -49,6 +55,8 @@// suite (tests/e2e/stock-photo-gated.spec.ts).// ─────────────────────────────────────────────────────────────+import { effectiveStockKeys } from '@/lib/admin/config'+export type StockPhotoProvider = 'pexels' | 'pixabay'/** Sanitized attribution block — also the shape stored on ImageElement.credit. */@@ -78,16 +86,21 @@ export interface StockPhotoResult {}// ── availability (secret-free — never expose the keys) ────────+// Async since A5: the keys resolve console-first (stored key → env+// var), which means one AppConfig read (cached 10 s in-process by+// the config module — the same cost profile as aiFeatureEnabled,+// which already sits on this route).-export function stockPhotoProviders(): StockPhotoProvider[] {+export async function stockPhotoProviders(): Promise<StockPhotoProvider[]> {+ const keys = await effectiveStockKeys()const out: StockPhotoProvider[] = []- if ((process.env.PEXELS_API_KEY ?? '').trim()) out.push('pexels')- if ((process.env.PIXABAY_API_KEY ?? '').trim()) out.push('pixabay')+ if (keys.pexels) out.push('pexels')+ if (keys.pixabay) out.push('pixabay')return out}-export function stockPhotoAvailable(): boolean {- return stockPhotoProviders().length > 0+export async function stockPhotoAvailable(): Promise<boolean> {+ return (await stockPhotoProviders()).length > 0}// ── shared helpers ────────────────────────────────────────────@@ -322,7 +335,10 @@ export async function searchStockPhotos(count: number,opts: SearchStockPhotosOptions = {},): Promise<StockPhotoResult[]> {- const providers = stockPhotoProviders()+ const keys = await effectiveStockKeys()+ const providers: StockPhotoProvider[] = []+ if (keys.pexels) providers.push('pexels')+ if (keys.pixabay) providers.push('pixabay')const provider = opts.provider && providers.includes(opts.provider) ? opts.provider : providers[0]if (!provider) throw new Error('NO_PROVIDER')@@ -342,7 +358,7 @@ export async function searchStockPhotos(const base = (process.env.PEXELS_API_BASE ?? 'https://api.pexels.com').replace(/\/+$/, '')const url = `${base}/v1/search?query=${encodeURIComponent(q)}&per_page=${n}&orientation=landscape`const res = await doFetch(url, {- headers: { Authorization: (process.env.PEXELS_API_KEY ?? '').trim() },+ headers: { Authorization: keys.pexels },signal: AbortSignal.timeout(PROVIDER_FETCH_TIMEOUT_MS),})if (!res.ok) {@@ -354,7 +370,7 @@ export async function searchStockPhotos(body = await res.json()} else {const base = (process.env.PIXABAY_API_BASE ?? 'https://pixabay.com/api').replace(/\/+$/, '')- const key = encodeURIComponent((process.env.PIXABAY_API_KEY ?? '').trim())+ const key = encodeURIComponent(keys.pixabay)const url = `${base}/?key=${key}&q=${encodeURIComponent(q)}&image_type=photo&per_page=${n}&safesearch=true`const res = await doFetch(url, {signal: AbortSignal.timeout(PROVIDER_FETCH_TIMEOUT_MS),diff --git a/src/lib/stock-video.test.ts b/src/lib/stock-video.test.tsindex e21850a..73d4cf3 100644--- a/src/lib/stock-video.test.ts+++ b/src/lib/stock-video.test.ts@@ -1,4 +1,11 @@import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++// A5: availability resolves console-first through the admin config —+// mock the db (empty AppConfig by default) so the env path is the+// default and stock.providers rows can be injected per test.+const findMany = vi.hoisted(() => vi.fn())+vi.mock('@/lib/db', () => ({ db: { appConfig: { findMany } } }))+import { invalidateAdminConfig } from '@/lib/admin/config'import {chooseRenditions,resetStockVideoCache,@@ -137,6 +144,8 @@ function jsonRes(body: unknown, status = 200): Response {beforeEach(() => {resetStockVideoCache()+ findMany.mockResolvedValue([])+ invalidateAdminConfig()vi.stubEnv('PEXELS_API_KEY', 'test-pexels-key')vi.stubEnv('PIXABAY_API_KEY', 'test-pixabay-key')delete process.env.PEXELS_API_BASE@@ -146,22 +155,32 @@ beforeEach(() => {afterEach(() => {vi.unstubAllEnvs()vi.restoreAllMocks()+ // a test may warm the config cache with injected rows — never leak it+ invalidateAdminConfig()})describe('availability — self-hoster keys gate the feature', () => {- it('no keys → no providers, not available', () => {+ it('no keys → no providers, not available', async () => {vi.stubEnv('PEXELS_API_KEY', '')vi.stubEnv('PIXABAY_API_KEY', ' ')- expect(stockVideoProviders()).toEqual([])- expect(stockVideoAvailable()).toBe(false)+ await expect(stockVideoProviders()).resolves.toEqual([])+ await expect(stockVideoAvailable()).resolves.toBe(false)})- it('either key enables its provider only', () => {+ it('either key enables its provider only', async () => {vi.stubEnv('PEXELS_API_KEY', '')- expect(stockVideoProviders()).toEqual(['pixabay'])+ await expect(stockVideoProviders()).resolves.toEqual(['pixabay'])vi.stubEnv('PEXELS_API_KEY', 'k')vi.stubEnv('PIXABAY_API_KEY', '')- expect(stockVideoProviders()).toEqual(['pexels'])+ await expect(stockVideoProviders()).resolves.toEqual(['pexels'])+ })++ it('A5: a console-stored key activates the rail with no env var', async () => {+ vi.stubEnv('PEXELS_API_KEY', '')+ vi.stubEnv('PIXABAY_API_KEY', '')+ findMany.mockResolvedValue([{ key: 'stock.providers', value: { pexels: 'db-key' } }])+ await expect(stockVideoProviders()).resolves.toEqual(['pexels'])+ await expect(stockVideoAvailable()).resolves.toBe(true)})})diff --git a/src/lib/stock-video.ts b/src/lib/stock-video.tsindex 58c08b6..855682b 100644--- a/src/lib/stock-video.ts+++ b/src/lib/stock-video.ts@@ -8,6 +8,12 @@// NO_PROVIDER — everything else in the editor keeps working (the// F2b fail-closed pattern; research §5.4 R6).//+// v0.16.5 (A5): the keys are console-manageable. They resolve+// through src/lib/admin/config.ts — a key stored on the AI & models+// page (stock.providers row) wins over the env var, so /admin can+// activate or rotate the Videos rail without a redeploy; the env+// var remains the zero-console fallback. Photos share the keys.+//// Dependency decision (the house rule): ZERO new runtime// dependencies — both providers are JSON-over-GET with one auth// value; the whole connector is plain fetch. Recorded in@@ -38,6 +44,8 @@// no-provider states are e2e-asserted on the default suite.// ─────────────────────────────────────────────────────────────+import { effectiveStockKeys } from '@/lib/admin/config'+export type StockVideoProvider = 'pexels' | 'pixabay'/** Sanitized attribution block — also the shape stored on VideoElement.credit. */@@ -70,16 +78,19 @@ export interface StockVideoResult {}// ── availability (secret-free — never expose the keys) ────────+// Async since A5: the keys resolve console-first (stored key → env+// var) through src/lib/admin/config.ts (cached 10 s in-process).-export function stockVideoProviders(): StockVideoProvider[] {+export async function stockVideoProviders(): Promise<StockVideoProvider[]> {+ const keys = await effectiveStockKeys()const out: StockVideoProvider[] = []- if ((process.env.PEXELS_API_KEY ?? '').trim()) out.push('pexels')- if ((process.env.PIXABAY_API_KEY ?? '').trim()) out.push('pixabay')+ if (keys.pexels) out.push('pexels')+ if (keys.pixabay) out.push('pixabay')return out}-export function stockVideoAvailable(): boolean {- return stockVideoProviders().length > 0+export async function stockVideoAvailable(): Promise<boolean> {+ return (await stockVideoProviders()).length > 0}// ── shared helpers ────────────────────────────────────────────@@ -318,7 +329,10 @@ export async function searchStockVideos(count: number,opts: SearchStockVideosOptions = {},): Promise<StockVideoResult[]> {- const providers = stockVideoProviders()+ const keys = await effectiveStockKeys()+ const providers: StockVideoProvider[] = []+ if (keys.pexels) providers.push('pexels')+ if (keys.pixabay) providers.push('pixabay')const provider = opts.provider && providers.includes(opts.provider) ? opts.provider : providers[0]if (!provider) throw new Error('NO_PROVIDER')@@ -338,7 +352,7 @@ export async function searchStockVideos(const base = (process.env.PEXELS_API_BASE ?? 'https://api.pexels.com').replace(/\/+$/, '')const url = `${base}/videos/search?query=${encodeURIComponent(q)}&per_page=${n}&orientation=landscape`const res = await doFetch(url, {- headers: { Authorization: (process.env.PEXELS_API_KEY ?? '').trim() },+ headers: { Authorization: keys.pexels },signal: AbortSignal.timeout(PROVIDER_FETCH_TIMEOUT_MS),})if (!res.ok) {@@ -350,7 +364,7 @@ export async function searchStockVideos(body = await res.json()} else {const base = (process.env.PIXABAY_API_BASE ?? 'https://pixabay.com/api').replace(/\/+$/, '')- const key = encodeURIComponent((process.env.PIXABAY_API_KEY ?? '').trim())+ const key = encodeURIComponent(keys.pixabay)const url = `${base}/videos/?key=${key}&q=${encodeURIComponent(q)}&per_page=${n}&safesearch=true`const res = await doFetch(url, {signal: AbortSignal.timeout(PROVIDER_FETCH_TIMEOUT_MS),