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.15): stock video depth — provider-gated Videos rail with durable attribution, zero new dependencies (R6) (#37)
Ashiq Hussain Mir9b8a78a8535a
diff --git a/.env.example b/.env.exampleindex 8a1ad90..5aaab26 100644--- a/.env.example+++ b/.env.example@@ -37,6 +37,18 @@ DATABASE_URL=postgresql://postgres.[YOUR-PROJECT-REF]:[YOUR-PASSWORD]@aws-0-eu-c# ZAI_BASE_URL=https://your-provider.example/v1# ZAI_API_KEY=your-key+# ── Stock video search (optional, v0.15 R6) ────────────────────+# The Videos rail in the editor. Either FREE key activates it;+# with no key the rail stays hidden and everything else works+# (see docs/STOCK-VIDEO.md). Keys are server-side only.+# Pexels: https://www.pexels.com/api/+# Pixabay: https://pixabay.com/api/docs/+# PEXELS_API_KEY=your-free-key+# PIXABAY_API_KEY=your-free-key+# Base overrides (proxies / test rigs — rarely needed):+# PEXELS_API_BASE=https://api.pexels.com+# PIXABAY_API_BASE=https://pixabay.com/api+# ── AI agents / MCP server (optional, v0.6) ───────────────────# Model Context Protocol endpoint: POST /api/mcp# Lets AI assistants (Claude Desktop, Cursor, ChatGPT, any MCP client)diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex 7494c2b..59644a7 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -133,6 +133,16 @@ jobs:- name: Run Playwright plugins suite (CANVIX_PLUGINS=1)run: npx playwright test -c playwright.plugins.config.ts+ # v0.15 (R6): the stock-video acceptance suite — a second dev+ # server keyed to a LOCAL MOCK Pexels API (tests/stock-video/+ # mock-provider.mjs serves real ffmpeg-generated renditions),+ # so the full search → insert → durable-attribution path runs+ # without spending real provider quota. The default suite+ # above keeps the keys unset (its spec asserts the F2b gate:+ # hidden rail + 503 NO_PROVIDER).+ - name: Run Playwright stock-video suite (mock provider)+ run: npx playwright test -c playwright.stockvideo.config.ts+- name: Upload Playwright traces (on failure)if: failure()uses: actions/upload-artifact@v4diff --git a/CHANGELOG.md b/CHANGELOG.mdindex cf958cb..f86f0e1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,51 @@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.15.5] — 2026-11-07++### Added++- **Rich content & export, part 6 — stock video depth (R6).** A+ provider-gated **Videos** rail: configurable stock-video+ connectors (Pexels + Pixabay — free self-hoster keys), license+ and attribution surfaced, **zero new dependencies**. Decisions+ and the operator guide live in `docs/STOCK-VIDEO.md`; the+ highlights:+ - **The F2b gate, one class over.** No `PEXELS_API_KEY` /+ `PIXABAY_API_KEY` on the server ⇒ the rail item never renders+ and `/api/stock-video/*` answers `503 NO_PROVIDER` —+ everything else in the editor keeps working. Availability is+ probed once per editor mount from a secret-free endpoint.+ - **One normalized result set.** `src/lib/stock-video.ts` maps+ both providers to one shape (mp4 ladder + poster + sanitized+ credit), parses every field defensively (unknown keys+ ignored, `javascript:` URLs can never become credit links,+ control characters stripped, lengths hard-capped) and caches+ responses in memory for 24 h per instance (Pixabay's request).+ - **Inserts ride the existing rails.** The browser downloads+ the chosen rendition (both CDNs are CORS-open on GET —+ verified, not assumed) into the chunked media store, so+ quota, sha256 dedupe, the 32 MB cap and the library listing+ all apply; a 413 or failed download falls back to the next+ smaller rendition automatically.+ - **Attribution is durable.** The credit block is stored on+ `VideoElement.credit` (it rides autosave, versions, collab+ and the offline merge), shown in the insert toast and as a+ chip in the properties bar whenever the element is selected —+ deliberately never rendered on canvas or burned into exports.+ - **Honest testing without provider keys.** Unit suite parses+ recorded provider fixtures; the acceptance e2e runs the FULL+ path (search → browser download → upload → poster probe →+ element with credit) against a local mock Pexels API serving+ real ffmpeg-generated renditions+ (`playwright.stockvideo.config.ts`, wired into CI); the+ default suite asserts the gated world (hidden rail + 503).+- **Verified**: tsc/eslint clean · unit 975/975 (25 new) ·+ anonymous zero-registration e2e: gated spec + mock-provider+ acceptance 2/2 · full local regression 65/65 in three+ fresh-server batches · plugins flag-on 5/5 · production build+ clean.+## [0.15.4] — 2026-11-06### Addeddiff --git a/README.md b/README.mdindex 383601c..f96262b 100644--- a/README.md+++ b/README.md@@ -261,6 +261,15 @@ is right here.`docs/GIF-EXPORT.md`); rides the same deterministic frame rendereras video export. GIFs are silent — the dialog says so before youclick+- **Stock videos** *(v0.15 R6)* — a provider-gated **Videos** rail:+ search Pexels and/or Pixabay with free self-hoster keys (no key =+ the tab hides itself, everything else works). Inserts download in+ the browser into your existing media library (quota + dedupe + the+ 32 MB cap apply; oversized renditions fall back to smaller ones+ automatically), and every element carries **durable attribution** —+ creator, provider and license shown at insert, on selection, and+ saved with the design. Zero new dependencies; decisions + operator+ guide in `docs/STOCK-VIDEO.md`- **Audio/video elements & Beat Sync** *(v0.11, video export v0.15)* —upload MP3/WAV/MP4/WebM through the chunked media store (works withinevery serverless body limit); audio renders as a waveform card with the@@ -727,6 +736,7 @@ limited per IP and logs usage into the `AIUsage` table.| Magic Layers, AI Assistant, Magic Write | ⚙️ needs a server AI provider || AI image generation / eraser / enhance | ⚙️ needs a server AI provider || Translate, live photo search | ⚙️ needs a server AI provider |+| Stock video search | ⚙️ needs `PEXELS_API_KEY` or `PIXABAY_API_KEY` (free) || MCP server (agent tools) | ✅ with token set — `generate_design` additionally needs the AI provider |## 🤖 AI agents (MCP)@@ -1103,6 +1113,25 @@ tool descriptions so agents pick the right format.below 75%. jsPDF is gone (net deps −1); the architecture anddependency decisions are on record in`docs/PDF-VECTOR-EXPORT.md`. *(v0.15.3)*+- [x] GIF export (v0.15 R5) — animated, looping social GIFs from any+ page range: 480/720/1080 px caps, 10/15/20 fps, optional+ Floyd–Steinberg dithering, a 25 MB cap enforced *during* the+ encode and an 1800-frame cap refused before rendering — a+ hand-rolled GIF89a + LZW encoder with **zero new dependencies**+ (decisions on record in `docs/GIF-EXPORT.md`), riding the same+ deterministic frame renderer as video export. GIFs are silent;+ the dialog says so before you click. *(v0.15.4)*+- [x] Stock video depth (v0.15 R6) — a provider-gated **Videos**+ rail: configurable Pexels/Pixabay connectors (free+ self-hoster keys; no key = feature hidden, the F2b pattern),+ one normalized result set parsed defensively, inserts that+ ride the existing chunked media store with an+ automatic smaller-rendition fallback, and **durable+ attribution** — creator, provider and license stored on the+ element, visible at insert and on selection, never burned+ into exports. Zero new dependencies; tested against recorded+ provider fixtures + a local mock-provider acceptance suite+ wired into CI. *(v0.15.5)*- [ ] Mobile editor polish — touch-first selection handles, gesturezoom/pan without modifier keys, bottom-sheet property panels(the responsive groundwork from v0.11.3 makes this tractable)diff --git a/docs/STOCK-VIDEO.md b/docs/STOCK-VIDEO.mdnew file mode 100644index 0000000..d6ece09--- /dev/null+++ b/docs/STOCK-VIDEO.md@@ -0,0 +1,109 @@+# Stock video search — operator guide & decision record (v0.15 R6)++Canvix's Photos rail ships a bundled library that works with zero+configuration. The **Videos** rail is different by design: stock+*video* search is **provider-gated** — it appears only when the+self-hoster configures a key for at least one stock-video provider,+and hides itself entirely otherwise (the same fail-closed pattern+as the AI provider features; research §5.4 R6). No key = no rail+item, `POST /api/stock-video/search` answers `503 NO_PROVIDER`,+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`).++```bash+# .env — either key activates the Videos rail+PEXELS_API_KEY=your-free-key+# PIXABAY_API_KEY=your-free-key+```++Both connectors are plain REST/JSON over `fetch`.++## How an insert works (and what it costs you)++1. The panel searches **server-side** (your key never reaches the+ browser; responses are cached in memory for 24 h per instance —+ Pixabay's request, Pexels gets it for free).+2. Clicking a tile downloads the chosen rendition **in the+ browser** (both provider CDNs answer `Access-Control-Allow-Origin:+ *` on GET — verified empirically, not assumed).+3. The file rides the **existing chunked media store**: your+ quota (`CANVIX_UPLOAD_QUOTA_MB`), the 32 MB per-file cap+ (`CANVIX_MAX_MEDIA_MB`), sha256 dedupe and the library listing+ all apply as for any upload.+4. The preferred rendition is the largest mp4 at most 1920 px+ wide. If the store's cap rejects it (413) or a download fails,+ the panel automatically retries the **next smaller rendition**+ — the ladder the search route returns.+5. The poster frame, duration and dimensions are probed from the+ actual bytes (the v0.11 upload path), so the element behaves+ exactly like an uploaded video — including R3's frame-accurate+ autoplay rendering in video/GIF exports.++## Attribution model (the R6 acceptance)++Every result carries a sanitized credit block+`{ provider, author, license, url }`:++- **visible at insert** — the success toast names the provider,+ creator and license;+- **durable** — stored on the element (`VideoElement.credit`), so+ it rides autosave, version history, collab replication and the+ offline merge like any element field;+- **visible on selection** — the properties bar shows a credit+ chip (license + source page in the tooltip);+- **never on the canvas or burned into exports** — a forced+ overlay would corrupt the design, and neither provider license+ demands on-content credit. Pixabay's "show users where the+ videos come from" request is satisfied by the provider chip on+ every search tile plus the durable credit.++Credit fields are capped and cleaned at ingest (`src/lib/stock-video.ts`):+control characters stripped, lengths hard-capped, source URLs must+be http(s) — a `javascript:` URL can never become a credit link.++## Dependency decisions (on record)++- **Zero new runtime dependencies.** Both providers are+ JSON-over-GET with one auth value; the connector, the sanitizer+ and the ladder are plain `fetch` + TypeScript. This follows the+ R2 WebM-muxer / R4 TTF-subsetter / R5 LZW house rule: no+ dependency for what ~400 honest lines can do.+- **Client-side download, not a server proxy.** The browser+ fetches the rendition (CDNs are CORS-open), so self-hoster+ bandwidth is one upload instead of download+upload. A server+ proxy remains the documented fallback if a provider ever ships+ a non-CORS CDN.+- **In-memory 24 h response cache, per instance.** Multi-instance+ fleets cache per instance (the rate-limit honesty note applies+ verbatim). Provider quota otherwise spends per search.+- **Rate limit:** 20 searches/min/IP (`stockvideo:search` bucket)+ — beyond any typing session (the panel debounces at 600 ms),+ far below scripted drain velocity.++## Honest limits++- **CI never talks to a real provider.** The unit suite parses+ recorded response fixtures; the acceptance e2e+ (`playwright.stockvideo.config.ts`) runs against a local **mock+ provider** (`tests/stock-video/mock-provider.mjs`) that serves+ real ffmpeg-generated renditions, so the full search → download+ → upload → probe → credit path is exercised without spending+ quota. Live-provider drift is mitigated by defensive parsing+ (unknown keys ignored, every field validated, `link`/`url`+ tolerated), not by tests we can't run keyless.+- **MCP cannot rewrite credits** — attribution integrity: an+ agent may move or trim a stock video but not strip its credit.+- Provider search failures surface as a sanitized status-only+ message (`Pexels search failed (429).`) — provider bodies and+ URLs never reach the client because Pixabay's key rides the+ query string.diff --git a/package.json b/package.jsonindex c9036ef..a54e91c 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "canvix",- "version": "0.15.4",+ "version": "0.15.5","private": false,"description": "Canvix \u2014 free & open-source graphic design tool. A community-built Canva alternative.","scripts": {diff --git a/playwright.stockvideo.config.ts b/playwright.stockvideo.config.tsnew file mode 100644index 0000000..9ff9064--- /dev/null+++ b/playwright.stockvideo.config.ts@@ -0,0 +1,56 @@+import { defineConfig, devices } from '@playwright/test'++/**+ * The STOCK-VIDEO-PROVIDER-ON browser suite (v0.15 R6).+ *+ * The default playwright.config.ts keeps the provider keys unset+ * (its spec asserts the F2b gate: hidden rail, 503 NO_PROVIDER).+ * This config boots a SECOND dev server with a (fake) Pexels key+ * pointed at a local mock provider, on separate ports, and runs+ * tests/e2e-stock-video — the acceptance suite: search → insert →+ * durable attribution.+ *+ * npx playwright test -c playwright.stockvideo.config.ts+ *+ * Requires a reachable DATABASE_URL (same as the default suite).+ */+export default defineConfig({+ testDir: './tests/e2e-stock-video',+ timeout: 120_000,+ expect: { timeout: 15_000 },+ fullyParallel: false,+ workers: 1,+ retries: process.env.CI ? 1 : 0,+ reporter: 'list',+ use: {+ baseURL: process.env.BASE_URL ?? 'http://localhost:3200',+ trace: 'retain-on-failure',+ },+ projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }],+ webServer: process.env.BASE_URL+ ? undefined+ : [+ {+ // the mock Pexels API: /videos/search + real mp4 renditions+ command: 'node tests/stock-video/mock-provider.mjs',+ url: 'http://127.0.0.1:3210/healthz',+ timeout: 30_000,+ reuseExistingServer: true,+ stdout: 'ignore',+ },+ {+ // NOT `npm run dev` — that script pipes through tee and pins+ // the port; invoke next directly with the provider keyed to+ // the mock (the plugins-config precedent)+ command: 'npx next dev -p 3200',+ url: 'http://localhost:3200',+ timeout: 180_000,+ reuseExistingServer: true,+ stdout: 'ignore',+ env: {+ PEXELS_API_KEY: 'ci-stock-video-key',+ PEXELS_API_BASE: 'http://127.0.0.1:3210',+ },+ },+ ],+})diff --git a/src/app/api/stock-video/available/route.ts b/src/app/api/stock-video/available/route.tsnew file mode 100644index 0000000..8e41d3c--- /dev/null+++ b/src/app/api/stock-video/available/route.ts@@ -0,0 +1,25 @@+import { NextResponse } from 'next/server'+import { stockVideoProviders } from '@/lib/stock-video'+import { withLogging } from '@/lib/observability'++export const runtime = 'nodejs'+export const dynamic = 'force-dynamic'++/**+ * GET /api/stock-video/available — public, secret-free feature+ * detection for the v0.15 R6 stock-video rail: the LeftRail shows+ * the Videos tab only when this answers available=true (the F2b+ * pattern — no provider key configured = feature hidden, the rest+ * of the editor untouched). Exposes WHICH connectors are keyed,+ * never the keys themselves.+ */+async function __canvix_get() {+ return NextResponse.json({+ available: stockVideoProviders().length > 0,+ providers: stockVideoProviders(),+ })+}++// 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/stock-video/available', __canvix_get)diff --git a/src/app/api/stock-video/search/route.test.ts b/src/app/api/stock-video/search/route.test.tsnew file mode 100644index 0000000..3ef8fa5--- /dev/null+++ b/src/app/api/stock-video/search/route.test.ts@@ -0,0 +1,172 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'++// Route tests for the v0.15 R6 stock-video API. No network, no+// Postgres. Invariants:+// 1. no provider key → 503 NO_PROVIDER (the F2b gate)+// 2. available is secret-free and never leaks the keys+// 3. CSRF on the search POST+// 4. unknown/unconfigured provider → 400+// 5. the happy path proxies the normalized result set++import { NextRequest } from 'next/server'+import { GET as getAvailable } from '../available/route'+import { POST as searchStock } from './route'+import { resetStockVideoCache } from '@/lib/stock-video'+import { resetRateLimitState } from '@/lib/rate-limit'++function req(url: string, init?: Omit<RequestInit, 'signal' | 'headers'> & { headers?: Record<string, string> }) {+ return new NextRequest(url, {+ ...init,+ headers: { host: 'canvix.test', ...(init?.headers ?? {}) },+ })+}++const PEXELS_FIXTURE = {+ videos: [+ {+ id: 42,+ width: 1920,+ height: 1080,+ duration: 8,+ url: 'https://www.pexels.com/video/route-test-42/',+ user: { name: 'Route Tester' },+ video_files: [{ file_type: 'video/mp4', width: 1920, link: 'https://videos.pexels.com/route-42.mp4' }],+ },+ ],+}++beforeEach(() => {+ vi.unstubAllEnvs()+ vi.stubEnv('PEXELS_API_KEY', 'route-test-key')+ delete process.env.PEXELS_API_BASE+ delete process.env.PIXABAY_API_KEY+ resetStockVideoCache()+ resetRateLimitState()+})++afterEach(() => {+ vi.unstubAllEnvs()+ vi.restoreAllMocks()+ resetRateLimitState()+})++describe('GET /api/stock-video/available', () => {+ it('no keys → available=false, empty providers, no secrets', async () => {+ vi.stubEnv('PEXELS_API_KEY', '')+ const res = await getAvailable(req('http://canvix.test/api/stock-video/available'))+ expect(res.status).toBe(200)+ const body = (await res.json()) as { available: boolean; providers: string[] }+ expect(body).toEqual({ available: false, providers: [] })+ })++ it('a key flips availability and names only the provider', async () => {+ const res = await getAvailable(req('http://canvix.test/api/stock-video/available'))+ const body = (await res.json()) as { available: boolean; providers: string[] }+ expect(body).toEqual({ available: true, providers: ['pexels'] })+ expect(JSON.stringify(body)).not.toContain('route-test-key')+ })+})++describe('POST /api/stock-video/search', () => {+ it('no provider key → 503 NO_PROVIDER with the operator hint', async () => {+ vi.stubEnv('PEXELS_API_KEY', '')+ const res = await searchStock(+ req('http://canvix.test/api/stock-video/search', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ query: 'ocean' }),+ }),+ )+ expect(res.status).toBe(503)+ const body = (await res.json()) as { code?: string }+ expect(body.code).toBe('NO_PROVIDER')+ })++ it('cross-site Origin → 403 CSRF_REJECTED', async () => {+ const res = await searchStock(+ req('http://canvix.test/api/stock-video/search', {+ method: 'POST',+ headers: { 'content-type': 'application/json', origin: 'https://evil.example' },+ body: JSON.stringify({ query: 'ocean' }),+ }),+ )+ expect(res.status).toBe(403)+ const body = (await res.json()) as { code?: string }+ expect(body.code).toBe('CSRF_REJECTED')+ })++ it('missing/blank query → 400', async () => {+ for (const query of ['', ' ', undefined]) {+ const res = await searchStock(+ req('http://canvix.test/api/stock-video/search', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ query }),+ }),+ )+ expect(res.status).toBe(400)+ }+ })++ it('unconfigured provider → 400 naming the configured set', async () => {+ const res = await searchStock(+ req('http://canvix.test/api/stock-video/search', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ query: 'ocean', provider: 'pixabay' }),+ }),+ )+ expect(res.status).toBe(400)+ const body = (await res.json()) as { error?: string }+ expect(body.error).toContain('pexels')+ })++ it('happy path → 200 with the normalized results, key never in the response', async () => {+ const fetchMock = vi.fn().mockResolvedValue(+ new Response(JSON.stringify(PEXELS_FIXTURE), { status: 200, headers: { 'content-type': 'application/json' } }),+ )+ vi.stubGlobal('fetch', fetchMock)++ const res = await searchStock(+ req('http://canvix.test/api/stock-video/search', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ query: 'ocean', count: 12 }),+ }),+ )+ expect(res.status).toBe(200)+ const body = (await res.json()) as {+ query: string+ count: number+ results: { id: string; mp4: string; credit: { author: string } }[]+ }+ expect(body.query).toBe('ocean')+ expect(body.count).toBe(1)+ expect(body.results[0].id).toBe('pexels-42')+ expect(body.results[0].mp4).toBe('https://videos.pexels.com/route-42.mp4')+ expect(body.results[0].credit.author).toBe('Route Tester')+ expect(JSON.stringify(body)).not.toContain('route-test-key')+ // the outbound provider call carried the key in the header+ const [url, init] = fetchMock.mock.calls[0] as [string, RequestInit]+ expect(url).toContain('per_page=12')+ expect((init.headers as Record<string, string>).Authorization).toBe('route-test-key')+ })++ it('provider outage → 502 with the sanitized status-only message', async () => {+ const spy = vi.spyOn(console, 'error').mockImplementation(() => {})+ vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response('boom key=secret', { status: 500 })))++ const res = await searchStock(+ req('http://canvix.test/api/stock-video/search', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ query: 'ocean' }),+ }),+ )+ expect(res.status).toBe(502)+ const body = (await res.json()) as { error?: string }+ expect(body.error).toBe('Pexels search failed (500).')+ expect(body.error).not.toContain('secret')+ expect(spy).toHaveBeenCalled()+ })+})diff --git a/src/app/api/stock-video/search/route.ts b/src/app/api/stock-video/search/route.tsnew file mode 100644index 0000000..32e707c--- /dev/null+++ b/src/app/api/stock-video/search/route.ts@@ -0,0 +1,72 @@+import { NextRequest, NextResponse } from 'next/server'+import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'+import { checkRateLimit, rateLimitResponse } from '@/lib/rate-limit'+import { searchStockVideos, stockVideoProviders, type StockVideoProvider } from '@/lib/stock-video'+import { withLogging } from '@/lib/observability'++export const runtime = 'nodejs'+export const maxDuration = 30++interface SearchBody {+ query?: unknown+ count?: unknown+ provider?: unknown+}++/**+ * POST /api/stock-video/search — runtime stock-video search+ * (v0.15 R6). Provider-gated the F2b way: no self-hoster key+ * configured ⇒ 503 NO_PROVIDER, and the panel/rail stay hidden+ * client-side. The response is the normalized, sanitized result+ * set — provider URLs + durable credit blocks; keys never leave+ * the server (and provider error bodies never reach the client).+ */+async function __canvix_post(req: NextRequest) {+ // stock search spends provider quota on every call — same-origin+ // only, like every other mutating POST (fail-closed default)+ if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })+ const limit = checkRateLimit(req, 'stockvideo:search')+ if (!limit.ok) return rateLimitResponse(limit)++ const providers = stockVideoProviders()+ if (providers.length === 0) {+ return NextResponse.json(+ {+ error: 'Stock video search needs a provider key on the server.',+ code: 'NO_PROVIDER',+ hint: 'Set PEXELS_API_KEY or PIXABAY_API_KEY — free keys from each provider (docs/STOCK-VIDEO.md).',+ },+ { status: 503 },+ )+ }++ const body = (await req.json().catch(() => ({}))) as SearchBody+ const query = typeof body.query === 'string' ? body.query.trim().slice(0, 120) : ''+ if (!query) return NextResponse.json({ error: 'A query is required.' }, { status: 400 })+ const count = Math.min(Math.max(Number(body.count) || 24, 1), 40)++ let provider: StockVideoProvider | undefined+ if (body.provider !== undefined) {+ if (typeof body.provider !== 'string' || !providers.includes(body.provider as StockVideoProvider)) {+ return NextResponse.json(+ { error: `Unknown or unconfigured provider. Configured: ${providers.join(', ')}.` },+ { status: 400 },+ )+ }+ provider = body.provider as StockVideoProvider+ }++ try {+ const results = await searchStockVideos(query, count, provider ? { provider } : {})+ return NextResponse.json({ query, count: results.length, results })+ } catch (error) {+ // sanitized upstream (status-only messages); NEVER echo provider+ // bodies or URLs — pixabay's key rides the query string+ const message = error instanceof Error && error.message !== 'NO_PROVIDER' ? error.message : 'Stock video search failed.'+ return NextResponse.json({ error: message }, { status: 502 })+ }+}++// v0.12.5 (H7): opt-in request logging wrapper — passthrough+// unless CANVIX_LOG=requests (see src/lib/observability.ts)+export const POST = withLogging('POST /api/stock-video/search', __canvix_post)diff --git a/src/components/editor/Editor.tsx b/src/components/editor/Editor.tsxindex 6ec6175..2012714 100644--- a/src/components/editor/Editor.tsx+++ b/src/components/editor/Editor.tsx@@ -17,6 +17,7 @@ import { ElementsPanel } from './panels/ElementsPanel'import { TextPanel } from './panels/TextPanel'import { UploadsPanel } from './panels/UploadsPanel'import { PhotosPanel } from './panels/PhotosPanel'+import { VideosPanel } from './panels/VideosPanel'import { BrandPanel } from './panels/BrandPanel'import { ToolsPanel } from './panels/ToolsPanel'import { ProjectsPanel } from './panels/ProjectsPanel'@@ -50,6 +51,7 @@ const PANEL_TITLES: Record<Exclude<PanelId, null>, string> = {brand: 'Brand',uploads: 'Uploads',photos: 'Photos',+ videos: 'Videos',tools: 'Tools',projects: 'Projects',apps: 'Apps',@@ -468,6 +470,7 @@ export default function Editor() {case 'text': return <TextPanel />case 'uploads': return <UploadsPanel />case 'photos': return <PhotosPanel />+ case 'videos': return <VideosPanel />case 'brand': return <BrandPanel />case 'tools': return <ToolsPanel />case 'projects': return <ProjectsPanel />diff --git a/src/components/editor/LeftRail.tsx b/src/components/editor/LeftRail.tsxindex 0b12740..df1e112 100644--- a/src/components/editor/LeftRail.tsx+++ b/src/components/editor/LeftRail.tsx@@ -1,12 +1,17 @@'use client'-import { LayoutTemplate, Shapes, Type, Upload, Palette, Layers, Wrench, FolderOpen, LayoutGrid, BookMarked, Image } from 'lucide-react'+import { useMemo } from 'react'+import { LayoutTemplate, Shapes, Type, Upload, Palette, Layers, Wrench, FolderOpen, LayoutGrid, BookMarked, Image, Video } from 'lucide-react'import { useEditorStore, type PanelId } from '@/store/editor-store'import { cn } from '@/lib/utils'import { useIsMobile } from '@/hooks/use-mobile'+import { useStockVideo } from '@/hooks/use-stock-video'import { Tip } from './tooltip'-/** Canva-2026 rail: 9 tabs (72×72), 72px wide — Templates / Elements / Text / Brand / Uploads / Photos / Tools / Projects / Apps */+/** Canva-2026 rail: up to 10 tabs (72×72), 72px wide — Templates / Elements / Text / Brand / Uploads / Photos / Videos / Tools / Projects / Apps.+ * Videos (v0.15 R6) is provider-gated: the tab is rendered only when+ * /api/stock-video/available says the instance has a stock-video key —+ * no provider = feature hidden, everything else works (the F2b pattern). */const PANELS: { id: Exclude<PanelId, null>; label: string; icon: typeof LayoutTemplate }[] = [{ id: 'templates', label: 'Templates', icon: LayoutTemplate },{ id: 'elements', label: 'Elements', icon: Shapes },@@ -14,6 +19,7 @@ const PANELS: { id: Exclude<PanelId, null>; label: string; icon: typeof LayoutTe{ id: 'brand', label: 'Brand', icon: BookMarked },{ id: 'uploads', label: 'Uploads', icon: Upload },{ id: 'photos', label: 'Photos', icon: Image },+ { id: 'videos', label: 'Videos', icon: Video },{ id: 'tools', label: 'Tools', icon: Wrench },{ id: 'projects', label: 'Projects', icon: FolderOpen },{ id: 'apps', label: 'Apps', icon: LayoutGrid },@@ -24,6 +30,15 @@ export function LeftRail({ vertical = true }: { vertical?: boolean }) {const setPanel = useEditorStore((s) => s.setPanel)void useIsMobile()+ // v0.15 (R6): fail-closed visibility — the probe starts false, so an+ // unkeyed instance never flashes the tab; a keyed instance reveals it+ // once the (cached, module-level) answer lands+ const stockVideo = useStockVideo()+ const panels = useMemo(+ () => (stockVideo.available ? PANELS : PANELS.filter((p) => p.id !== 'videos')),+ [stockVideo.available],+ )+return (<navclassName={cn(@@ -32,7 +47,7 @@ export function LeftRail({ vertical = true }: { vertical?: boolean }) {)}aria-label="Editor tools">- {PANELS.map((p) => {+ {panels.map((p) => {const active = panel === p.idreturn (<Tip key={p.id} label={p.label} side={vertical ? 'right' : 'top'}>diff --git a/src/components/editor/PropertiesBar.tsx b/src/components/editor/PropertiesBar.tsxindex 5534210..300774b 100644--- a/src/components/editor/PropertiesBar.tsx+++ b/src/components/editor/PropertiesBar.tsx@@ -472,6 +472,21 @@ export function ContextToolbar({ variant = 'topbar' }: { variant?: 'topbar' | 'mduration={video.duration}trim={{ start: video.trimStart, end: video.trimEnd }}/>+ {/* v0.15 (R6): durable stock-video attribution — the element+ carries its credit; selected = visible (license + source+ page in the tooltip). User uploads show nothing. */}+ {video.credit ? (+ <a+ href={video.credit.url || undefined}+ target="_blank"+ rel="noreferrer"+ className="text-[11px] font-semibold text-[#02C0CC] bg-[#02C0CC]/10 border border-[#02C0CC]/25 rounded-full px-2 py-0.5 shrink-0 max-w-[190px] truncate"+ title={`${video.credit.license}${video.credit.url ? ` — ${video.credit.url}` : ''}`}+ aria-label={`Stock video by ${video.credit.author} on ${video.credit.provider}`}+ >+ {video.credit.provider} · {video.credit.author}+ </a>+ ) : null}<Divider /><PositionPopover ids={ids} count={1} element={first} /></>diff --git a/src/components/editor/add-element.ts b/src/components/editor/add-element.tsindex 5c6c523..8c5b909 100644--- a/src/components/editor/add-element.ts+++ b/src/components/editor/add-element.ts@@ -479,3 +479,65 @@ export async function addVideoFromLibrary(id: string, name: string): Promise<voi}))}++// ── v0.15 (R6): stock videos ─────────────────────────────────++/**+ * Download a stock-video rendition in the BROWSER (both provider+ * CDNs answer Access-Control-Allow-Origin: * on GET — verified+ * empirically, see src/lib/stock-video.ts) and ride the existing+ * upload → probe → element path, so quota, sha256 dedupe, the+ * 32 MB cap, poster capture and the R3 export semantics all apply+ * unchanged. The rendition list is a LADDER: when the media store+ * rejects the primary (size cap 413, quota) or a download fails,+ * the next smaller rendition is tried; the FIRST error is rethrown+ * once every tier fails. The sanitized credit block is stored+ * durably on the element (toast + properties bar surface it).+ */+export async function addStockVideo(+ stock: {+ id: string+ mp4: string+ alternates: string[]+ width: number+ height: number+ credit: { provider: string; author: string; license: string; url: string }+ },+ onProgress?: (ratio: number) => void,+): Promise<void> {+ const { uploadMediaFile, mediaSrc } = await import('@/lib/media/media-client')+ const { probeVideoFile } = await import('@/lib/media/decode')+ const { createVideoElement } = await import('@/lib/types')++ let firstError: unknown = null+ for (const url of [stock.mp4, ...stock.alternates]) {+ try {+ const blob = await fetch(url).then((r) => {+ if (!r.ok) throw new Error(`Download failed (${r.status}).`)+ return r.blob()+ })+ const file = new File([blob], `${stock.id}.mp4`, { type: blob.type || 'video/mp4' })+ const [handle, probe] = await Promise.all([uploadMediaFile(file, onProgress), probeVideoFile(file)])++ const store = useEditorStore.getState()+ const naturalW = probe.naturalWidth || stock.width || 480+ const naturalH = probe.naturalHeight || stock.height || Math.round(naturalW * 0.5625)+ const maxW = store.width * 0.7+ const w = Math.round(Math.min(maxW, Math.max(200, naturalW)))+ const h = Math.round((w * naturalH) / naturalW)+ const pos = placement(w, h, store.pages[store.currentPage].elements.length)+ store.addElement(+ createVideoElement(mediaSrc(handle.id), probe.poster, probe.duration, naturalW, naturalH, {+ ...pos,+ width: w,+ height: h,+ credit: stock.credit,+ })+ )+ return+ } catch (err) {+ firstError ??= err+ }+ }+ throw firstError instanceof Error ? firstError : new Error('Could not add the stock video.')+}diff --git a/src/components/editor/panels/VideosPanel.tsx b/src/components/editor/panels/VideosPanel.tsxnew file mode 100644index 0000000..4d64563--- /dev/null+++ b/src/components/editor/panels/VideosPanel.tsx@@ -0,0 +1,274 @@+'use client'++// ─────────────────────────────────────────────────────────────+// VideosPanel — the v0.15 R6 stock-video search rail panel.+// The PhotosPanel pattern (debounced live search, gated empty+// states, tile grid with hover preview), one class over: results+// are stock VIDEOS with a durable credit block.+//+// Attribution (the R6 acceptance): the credit rides the toast at+// insert AND the element (VideoElement.credit → properties bar).+// The provider chip on every tile satisfies Pixabay's "show users+// where the videos come from" request; the footer states the+// licenses honestly.+// ─────────────────────────────────────────────────────────────++import { useEffect, useRef, useState } from 'react'+import { Plus, Loader2, Clapperboard, VideoOff } from 'lucide-react'+import { PanelShell } from './panel-shell'+import { addStockVideo } from '../add-element'+import { useStockVideo } from '@/hooks/use-stock-video'+import { cn } from '@/lib/utils'+import { toast } from '@/hooks/use-toast'++/** normalized result — the /api/stock-video/search shape */+interface StockVideoTile {+ id: string+ provider: 'pexels' | 'pixabay'+ width: number+ height: number+ duration: number+ mp4: string+ alternates: string[]+ previewVideo: string+ preview: string+ credit: { provider: string; author: string; license: string; url: string }+}++/** why a search came back empty — 'no-provider' shows the operator+ * hint instead of looking broken (the F2 pattern; defense in depth+ * under a rail that is already hidden without a key) */+type SearchError = { kind: 'no-provider' } | { kind: 'service'; message: string }++function formatDuration(sec: number): string {+ if (!Number.isFinite(sec) || sec <= 0) return ''+ const m = Math.floor(sec / 60)+ const s = Math.round(sec % 60)+ return m > 0 ? `${m}:${String(s).padStart(2, '0')}` : `${s}s`+}++export function VideosPanel() {+ const { providers } = useStockVideo()+ const [query, setQuery] = useState('')+ const [provider, setProvider] = useState<string>('')+ const [results, setResults] = useState<StockVideoTile[] | null>(null)+ const [busy, setBusy] = useState(false)+ const [error, setError] = useState<SearchError | null>(null)+ const [busyTile, setBusyTile] = useState<string | null>(null)+ const [hovered, setHovered] = useState<string | null>(null)+ const lastQuery = useRef('')++ // default connector = the first configured one+ const activeProvider = provider || providers[0] || ''++ useEffect(() => {+ const q = query.trim()+ const run = async () => {+ if (q.length < 2) {+ setResults(null)+ setError(null)+ return+ }+ setBusy(true)+ setError(null)+ try {+ const res = await fetch('/api/stock-video/search', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ query: q, count: 24, provider: activeProvider || undefined }),+ })+ const data = (await res.json().catch(() => ({}))) as {+ results?: StockVideoTile[]+ error?: string+ code?: string+ }+ if (res.status === 503 && data.code === 'NO_PROVIDER') {+ setError({ kind: 'no-provider' })+ setResults([])+ } else if (!res.ok) {+ setError(data.error ? { kind: 'service', message: data.error } : null)+ setResults([])+ } else {+ setResults(Array.isArray(data.results) ? data.results : [])+ }+ } catch {+ setResults([])+ } finally {+ setBusy(false)+ }+ }+ const t = setTimeout(() => {+ if (q !== lastQuery.current) {+ lastQuery.current = q+ void run()+ }+ }, 600)+ return () => clearTimeout(t)+ }, [query, activeProvider])++ const add = async (tile: StockVideoTile) => {+ if (busyTile) return+ setBusyTile(tile.id)+ try {+ await addStockVideo(tile)+ toast({+ title: 'Video added',+ description: `${tile.credit.provider} · ${tile.credit.author} — ${tile.credit.license}`,+ })+ } catch (err) {+ toast({+ title: 'Could not add the video',+ description: err instanceof Error ? err.message : 'Try again — or pick another result.',+ })+ } finally {+ setBusyTile(null)+ }+ }++ const showResults = query.trim().length >= 2 && (results !== null || busy)++ return (+ <PanelShell+ title="Videos"+ subtitle={providers.length > 0 ? `Search free stock videos from ${providers.map((p) => p[0].toUpperCase() + p.slice(1)).join(' & ')}` : 'Search free stock videos'}+ searchPlaceholder="Search stock videos (e.g. ocean, city, coffee)"+ searchValue={query}+ onSearchValueChange={setQuery}+ onSearch={setQuery}+ belowSearch={+ providers.length > 1 ? (+ <div className="cv-tabscroll -mx-4 mt-2.5 flex gap-1.5 overflow-x-auto px-4">+ {providers.map((p) => (+ <button+ key={p}+ onClick={() => {+ setProvider(p)+ setResults(null)+ setError(null)+ }}+ className={cn(+ 'h-7 shrink-0 whitespace-nowrap rounded-full px-3 text-[11.5px] font-semibold transition-colors border',+ activeProvider === p+ ? 'bg-white/[0.16] text-white border-white/25'+ : 'bg-transparent text-white/65 border-white/10 hover:bg-white/[0.07] hover:text-white',+ )}+ aria-pressed={activeProvider === p}+ >+ {p === 'pexels' ? 'Pexels' : 'Pixabay'}+ </button>+ ))}+ </div>+ ) : undefined+ }+ >+ {showResults ? (+ <div className="mb-2">+ <div className="flex items-center gap-1.5 mb-2">+ <Clapperboard size={12} className="text-[#02C0CC]" />+ <span className="text-[10.5px] font-bold text-white/55 uppercase tracking-wide">+ Stock videos {results ? `(${results.length})` : ''}+ </span>+ {busy && <Loader2 size={11} className="animate-spin text-white/40 ml-1" />}+ </div>++ {error?.kind === 'no-provider' ? (+ <p className="text-[11.5px] text-white/40 py-2 leading-relaxed">+ Stock video search needs a provider key on the server — set{' '}+ <code className="text-white/55">PEXELS_API_KEY</code> or{' '}+ <code className="text-white/55">PIXABAY_API_KEY</code> (free keys; see{' '}+ <code className="text-white/55">docs/STOCK-VIDEO.md</code>).+ </p>+ ) : error?.kind === 'service' ? (+ <p className="text-[11.5px] text-white/40 py-2">{error.message}</p>+ ) : results && results.length === 0 && !busy ? (+ <div className="py-10 text-center">+ <VideoOff size={24} className="mx-auto text-white/25 mb-2" />+ <p className="text-[12.5px] text-white/50 font-medium">No stock videos matched</p>+ <p className="text-[11.5px] text-white/35 mt-1">Try other keywords.</p>+ </div>+ ) : (+ <div className="grid grid-cols-2 gap-2.5">+ {(results ?? []).map((t) => {+ const aspect = t.width > 0 && t.height > 0 ? `${t.width} / ${t.height}` : '16 / 9'+ const isBusy = busyTile === t.id+ return (+ <button+ key={t.id}+ onClick={() => void add(t)}+ onMouseEnter={() => setHovered(t.id)}+ onMouseLeave={() => setHovered((h) => (h === t.id ? null : h))}+ disabled={busyTile !== null}+ className="group relative rounded-xl overflow-hidden border border-white/10 hover:border-[#7630D7] transition-colors bg-[#0F1015] disabled:opacity-60"+ style={{ aspectRatio: aspect }}+ aria-label={`Add stock video by ${t.credit.author}`}+ title={`${t.credit.provider} · ${t.credit.author} — ${t.credit.license}`}+ >+ {hovered === t.id && t.previewVideo ? (+ <video+ src={t.previewVideo}+ muted+ loop+ autoPlay+ playsInline+ preload="none"+ className="absolute inset-0 h-full w-full object-cover"+ />+ ) : t.preview ? (+ <img+ src={t.preview}+ alt={`Stock video by ${t.credit.author}`}+ loading="lazy"+ className="absolute inset-0 h-full w-full object-cover group-hover:scale-[1.03] transition-transform duration-300"+ />+ ) : (+ <span className="absolute inset-0 flex items-center justify-center">+ <Clapperboard size={20} className="text-white/25" />+ </span>+ )}++ <span className="absolute inset-0 bg-black/0 group-hover:bg-black/25 transition-colors" />++ {/* provider + duration chips */}+ <span className="absolute top-1.5 left-1.5 h-5 px-1.5 rounded-md bg-black/60 backdrop-blur-sm text-[9.5px] font-bold text-white/90 flex items-center">+ {t.credit.provider}+ </span>+ {t.duration > 0 ? (+ <span className="absolute top-1.5 right-1.5 h-5 px-1.5 rounded-md bg-black/60 backdrop-blur-sm text-[9.5px] font-semibold text-white/90 flex items-center tabular-nums">+ {formatDuration(t.duration)}+ </span>+ ) : null}++ <span className="absolute inset-0 hidden group-hover:flex items-center justify-center">+ <span className="h-8 px-3 rounded-full bg-[#7630D7] text-white text-[11.5px] font-bold flex items-center gap-1.5 shadow-lg">+ {isBusy ? <Loader2 size={12} className="animate-spin" /> : <Plus size={12} />}+ {isBusy ? 'Adding…' : 'Add'}+ </span>+ </span>+ </button>+ )+ })}+ {busy && Array.from({ length: 4 }).map((_, i) => (+ <div key={`sk-${i}`} className="aspect-video rounded-xl cv-skeleton" />+ ))}+ </div>+ )}+ </div>+ ) : (+ <div className="py-12 text-center">+ <Clapperboard size={26} className="mx-auto text-white/25 mb-3" />+ <p className="text-[13px] text-white/50 font-medium">Search free stock videos</p>+ <p className="text-[11.5px] text-white/35 mt-1 leading-relaxed max-w-[240px] mx-auto">+ Type at least two letters. Every video carries its creator and license —+ shown when you add it and saved with the design.+ </p>+ </div>+ )}++ <p className="text-[10.5px] text-white/30 mt-3 leading-relaxed">+ Stock videos come from {providers.length > 0 ? providers.map((p) => p[0].toUpperCase() + p.slice(1)).join(' and ') : 'the configured provider'} under their+ free licenses (Pexels License / Pixabay Content License). Inserted videos are+ downloaded into your media library — attribution stays on the element.+ </p>+ </PanelShell>+ )+}diff --git a/src/hooks/use-stock-video.ts b/src/hooks/use-stock-video.tsnew file mode 100644index 0000000..2ff453b--- /dev/null+++ b/src/hooks/use-stock-video.ts@@ -0,0 +1,59 @@+'use client'++// ─────────────────────────────────────────────────────────────+// use-stock-video — client availability probe for the v0.15 R6+// stock-video rail (the F2b pattern).+//+// ONE request per editor mount, cached at module level so the+// LeftRail, the VideosPanel and any future surface agree without+// a stampede. Fail-closed: any fetch/parse failure reads as+// "not available" — on a keyed instance a transient network error+// hides the rail item until reload, never shows a broken panel.+// ─────────────────────────────────────────────────────────────++import { useEffect, useState } from 'react'++export interface StockVideoAvailability {+ available: boolean+ providers: string[]+}++const FALLBACK: StockVideoAvailability = { available: false, providers: [] }++let inflight: Promise<StockVideoAvailability> | null = null+let resolved: StockVideoAvailability | null = null++function probe(): Promise<StockVideoAvailability> {+ if (resolved) return Promise.resolve(resolved)+ inflight ??= fetch('/api/stock-video/available')+ .then(async (res) => {+ if (!res.ok) return FALLBACK+ const body = (await res.json().catch(() => null)) as StockVideoAvailability | null+ if (!body || typeof body.available !== 'boolean' || !Array.isArray(body.providers)) return FALLBACK+ resolved = body+ return body+ })+ .catch(() => FALLBACK)+ return inflight+}++/**+ * The stock-video rail state. `loaded` distinguishes "probe still+ * in flight" from "probe answered no" — the rail only ever SHOWS+ * the item on a positive answer (no flash on unkeyed instances).+ */+export function useStockVideo(): StockVideoAvailability & { loaded: boolean } {+ const [state, setState] = useState<StockVideoAvailability>(resolved ?? FALLBACK)++ useEffect(() => {+ let alive = true+ void probe().then((v) => {+ if (alive) setState(v)+ })+ return () => {+ alive = false+ }+ }, [])++ return { ...state, loaded: state.available || resolved !== null }+}diff --git a/src/lib/rate-limit.ts b/src/lib/rate-limit.tsindex b194029..7a51a84 100644--- a/src/lib/rate-limit.ts+++ b/src/lib/rate-limit.ts@@ -42,6 +42,7 @@ export type RateLimitBucket =| 'media:init'| 'plugins:install'| 'plugins:serve'+ | 'stockvideo:search'export interface RateLimitConfig {/** window length in milliseconds */@@ -74,6 +75,11 @@ export const RATE_LIMITS: Record<RateLimitBucket, RateLimitConfig> = {// one panel mount loads ~5–10 assets; 600/min covers a session// of panel open/close without inviting scrape-the-DB abuse'plugins:serve': { windowMs: 60_000, max: 600 },+ // v0.15 (R6): stock-video search spends PROVIDER quota on every+ // call — 20/min per IP is beyond any typing session (the panel+ // debounces at 600 ms and caches server-side for 24 h) while+ // stopping scripted drain of the self-hoster's key+ 'stockvideo:search': { windowMs: 60_000, max: 20 },}export function rateLimitsDisabled(): boolean {diff --git a/src/lib/stock-video.test.ts b/src/lib/stock-video.test.tsnew file mode 100644index 0000000..e21850a--- /dev/null+++ b/src/lib/stock-video.test.ts@@ -0,0 +1,385 @@+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'+import {+ chooseRenditions,+ resetStockVideoCache,+ searchStockVideos,+ stockVideoAvailable,+ stockVideoProviders,+ type StockVideoResult,+} from './stock-video'++// ── recorded provider response shapes ─────────────────────────+// The Pexels Video resource + the Pixabay video hit, exactly as+// documented (fields verified against each provider's API docs;+// CI has no keys, so these fixtures are the parsing oracle).++const PEXELS_RESPONSE = {+ url: 'https://api.pexels.com/videos/search?query=ocean',+ page: 1,+ per_page: 24,+ videos: [+ {+ id: 2499611,+ width: 3840,+ height: 2160,+ url: 'https://www.pexels.com/video/aerial-view-of-ocean-2499611/',+ image: 'https://images.pexels.com/videos/2499611/pictures/preview-0.jpg',+ duration: 15,+ user: { id: 47024, name: 'Jo Farne', url: 'https://www.pexels.com/@jo-farne-47024/' },+ video_files: [+ {+ id: 10663,+ quality: 'uhd',+ file_type: 'video/mp4',+ width: 3840,+ height: 2160,+ fps: 25,+ link: 'https://videos.pexels.com/video-files/2499611/2499611-uhd_3840_2160_25fps.mp4',+ },+ {+ id: 10664,+ quality: 'hd',+ file_type: 'video/mp4',+ width: 1920,+ height: 1080,+ fps: 25,+ link: 'https://videos.pexels.com/video-files/2499611/2499611-hd_1920_1080_25fps.mp4',+ },+ {+ id: 10665,+ quality: 'sd',+ file_type: 'video/mp4',+ width: 1280,+ height: 720,+ fps: 25,+ link: 'https://videos.pexels.com/video-files/2499611/2499611-sd_1280_720_25fps.mp4',+ },+ {+ id: 10666,+ quality: 'sd',+ file_type: 'video/mp4',+ width: 640,+ height: 360,+ fps: 25,+ link: 'https://videos.pexels.com/video-files/2499611/2499611-sd_640_360_25fps.mp4',+ },+ { id: 10667, quality: 'hls', file_type: 'video/mp4', link: 'https://videos.pexels.com/hls/2499611.m3u8' },+ ],+ video_pictures: [+ { id: 50394, nr: 0, picture: 'https://images.pexels.com/videos/2499611/pictures/preview-0.jpg' },+ { id: 50395, nr: 1, picture: 'https://images.pexels.com/videos/2499611/pictures/preview-1.jpg' },+ ],+ },+ {+ // hostile/malformed: no mp4 files at all — must be dropped, not crash+ id: 999,+ width: 100,+ height: 100,+ url: 'javascript:alert(1)',+ duration: 1,+ user: { name: 'Nobody' },+ video_files: [{ quality: 'hls', file_type: 'application/x-mpegURL', link: 'https://x.example/a.m3u8' }],+ },+ ],+}++const PIXABAY_RESPONSE = {+ total: 42,+ totalHits: 42,+ hits: [+ {+ id: 125,+ pageURL: 'https://pixabay.com/videos/id-125/',+ type: 'film',+ tags: 'flowers, yellow, blossom',+ duration: 12,+ videos: {+ large: { url: '', width: 3840, height: 2160, size: 0, thumbnail: '' },+ medium: {+ url: 'https://cdn.pixabay.com/video/2015/08/08/125-135736646_medium.mp4',+ width: 1280,+ height: 720,+ size: 3562083,+ thumbnail: 'https://cdn.pixabay.com/video/2015/08/08/125-135736646_medium.jpg',+ },+ small: {+ url: 'https://cdn.pixabay.com/video/2015/08/08/125-135736646_small.mp4',+ width: 960,+ height: 540,+ size: 2030736,+ thumbnail: 'https://cdn.pixabay.com/video/2015/08/08/125-135736646_small.jpg',+ },+ tiny: {+ url: 'https://cdn.pixabay.com/video/2015/08/08/125-135736646_tiny.mp4',+ width: 640,+ height: 360,+ size: 426799,+ thumbnail: 'https://cdn.pixabay.com/video/2015/08/08/125-135736646_tiny.jpg',+ },+ },+ views: 4462,+ downloads: 1464,+ likes: 18,+ comments: 0,+ user_id: 1281706,+ user: 'Coverr-Free-Footage',+ },+ 'garbage-entry',+ ],+}++function jsonRes(body: unknown, status = 200): Response {+ return new Response(JSON.stringify(body), {+ status,+ headers: { 'Content-Type': 'application/json' },+ })+}++beforeEach(() => {+ resetStockVideoCache()+ vi.stubEnv('PEXELS_API_KEY', 'test-pexels-key')+ vi.stubEnv('PIXABAY_API_KEY', 'test-pixabay-key')+ delete process.env.PEXELS_API_BASE+ delete process.env.PIXABAY_API_BASE+})++afterEach(() => {+ vi.unstubAllEnvs()+ vi.restoreAllMocks()+})++describe('availability — self-hoster keys gate the feature', () => {+ it('no keys → no providers, not available', () => {+ vi.stubEnv('PEXELS_API_KEY', '')+ vi.stubEnv('PIXABAY_API_KEY', ' ')+ expect(stockVideoProviders()).toEqual([])+ expect(stockVideoAvailable()).toBe(false)+ })++ it('either key enables its provider only', () => {+ vi.stubEnv('PEXELS_API_KEY', '')+ expect(stockVideoProviders()).toEqual(['pixabay'])+ vi.stubEnv('PEXELS_API_KEY', 'k')+ vi.stubEnv('PIXABAY_API_KEY', '')+ expect(stockVideoProviders()).toEqual(['pexels'])+ })+})++describe('chooseRenditions — the fallback ladder', () => {+ it('picks the largest ≤1920px file, smaller ones as alternates, smallest as preview', () => {+ const ladder = chooseRenditions([+ { url: 'https://x/a-3840.mp4', width: 3840 },+ { url: 'https://x/a-1920.mp4', width: 1920 },+ { url: 'https://x/a-1280.mp4', width: 1280 },+ { url: 'https://x/a-640.mp4', width: 640 },+ ])+ expect(ladder).toEqual({+ primary: 'https://x/a-1920.mp4',+ alternates: ['https://x/a-1280.mp4', 'https://x/a-640.mp4'],+ previewVideo: 'https://x/a-640.mp4',+ })+ })++ it('all-4K set → the smallest becomes the primary (best chance under the cap)', () => {+ const ladder = chooseRenditions([+ { url: 'https://x/u-3840.mp4', width: 3840 },+ { url: 'https://x/u-2560.mp4', width: 2560 },+ ])+ expect(ladder?.primary).toBe('https://x/u-2560.mp4')+ expect(ladder?.alternates).toEqual([])+ })++ it('dedupes by URL and rejects non-http(s)', () => {+ const ladder = chooseRenditions([+ { url: 'https://x/dup.mp4', width: 1000 },+ { url: 'https://x/dup.mp4', width: 2000 },+ { url: 'javascript:alert(1)', width: 3000 },+ ])+ expect(ladder?.primary).toBe('https://x/dup.mp4')+ })++ it('empty → null', () => {+ expect(chooseRenditions([])).toBeNull()+ })+})++describe('searchStockVideos — pexels', () => {+ it('normalizes the documented response shape', async () => {+ const fetchImpl = vi.fn().mockResolvedValue(jsonRes(PEXELS_RESPONSE))+ const results = await searchStockVideos('ocean', 24, { fetchImpl: fetchImpl as unknown as typeof fetch, noCache: true })++ expect(fetchImpl).toHaveBeenCalledOnce()+ const [url, init] = fetchImpl.mock.calls[0] as [string, RequestInit]+ expect(url).toContain('https://api.pexels.com/videos/search?query=ocean&per_page=24')+ expect(url).toContain('orientation=landscape')+ expect((init.headers as Record<string, string>).Authorization).toBe('test-pexels-key')++ expect(results).toHaveLength(1) // the malformed entry is dropped+ const r: StockVideoResult = results[0]+ expect(r.id).toBe('pexels-2499611')+ expect(r.provider).toBe('pexels')+ expect(r.duration).toBe(15)+ // 4K skipped as primary, hd 1920 chosen, sd tiers ladder below+ expect(r.mp4).toBe('https://videos.pexels.com/video-files/2499611/2499611-hd_1920_1080_25fps.mp4')+ expect(r.alternates).toEqual([+ 'https://videos.pexels.com/video-files/2499611/2499611-sd_1280_720_25fps.mp4',+ 'https://videos.pexels.com/video-files/2499611/2499611-sd_640_360_25fps.mp4',+ ])+ expect(r.previewVideo).toBe('https://videos.pexels.com/video-files/2499611/2499611-sd_640_360_25fps.mp4')+ expect(r.preview).toBe('https://images.pexels.com/videos/2499611/pictures/preview-0.jpg')+ expect(r.credit).toEqual({+ provider: 'Pexels',+ author: 'Jo Farne',+ license: 'Pexels License',+ url: 'https://www.pexels.com/video/aerial-view-of-ocean-2499611/',+ })+ })++ it('accepts url in place of link (schema drift tolerance)', async () => {+ const drift = {+ videos: [+ {+ id: 7,+ width: 1280,+ height: 720,+ duration: 3,+ url: 'https://www.pexels.com/video/drift-7/',+ user: { name: 'A' },+ video_files: [{ file_type: 'video/mp4', width: 1280, url: 'https://videos.pexels.com/drift-7.mp4' }],+ },+ ],+ }+ const fetchImpl = vi.fn().mockResolvedValue(jsonRes(drift))+ const results = await searchStockVideos('x', 5, { fetchImpl: fetchImpl as unknown as typeof fetch, noCache: true })+ expect(results[0]?.mp4).toBe('https://videos.pexels.com/drift-7.mp4')+ })++ it('garbage bodies fail closed to empty lists', async () => {+ for (const body of [{}, { videos: null }, { videos: 'nope' }, { videos: [null, 42, {}] }]) {+ const fetchImpl = vi.fn().mockResolvedValue(jsonRes(body))+ const results = await searchStockVideos('x', 5, { fetchImpl: fetchImpl as unknown as typeof fetch, noCache: true })+ expect(results).toEqual([])+ }+ })+})++describe('searchStockVideos — pixabay', () => {+ it('normalizes the documented response shape (empty large url skipped)', async () => {+ const fetchImpl = vi.fn().mockResolvedValue(jsonRes(PIXABAY_RESPONSE))+ const results = await searchStockVideos('flowers', 24, { provider: 'pixabay', fetchImpl: fetchImpl as unknown as typeof fetch, noCache: true })++ expect(fetchImpl).toHaveBeenCalledOnce()+ const [url] = fetchImpl.mock.calls[0] as [string]+ expect(url.startsWith('https://pixabay.com/api/videos/?key=test-pixabay-key&')).toBe(true)+ expect(url).toContain('q=flowers')+ expect(url).toContain('safesearch=true')++ expect(results).toHaveLength(1) // the garbage entry is dropped+ const r = results[0]+ expect(r.id).toBe('pixabay-125')+ expect(r.provider).toBe('pixabay')+ expect(r.duration).toBe(12)+ expect(r.mp4).toBe('https://cdn.pixabay.com/video/2015/08/08/125-135736646_medium.mp4')+ expect(r.alternates).toEqual([+ 'https://cdn.pixabay.com/video/2015/08/08/125-135736646_small.mp4',+ 'https://cdn.pixabay.com/video/2015/08/08/125-135736646_tiny.mp4',+ ])+ expect(r.width).toBe(1280)+ expect(r.height).toBe(720)+ expect(r.preview).toBe('https://cdn.pixabay.com/video/2015/08/08/125-135736646_medium.jpg')+ expect(r.credit).toEqual({+ provider: 'Pixabay',+ author: 'Coverr-Free-Footage',+ license: 'Pixabay Content License',+ url: 'https://pixabay.com/videos/id-125/',+ })+ })++ it('honours the API base override (proxies / tests)', async () => {+ vi.stubEnv('PIXABAY_API_BASE', 'http://127.0.0.1:3210/api')+ const fetchImpl = vi.fn().mockResolvedValue(jsonRes(PIXABAY_RESPONSE))+ await searchStockVideos('flowers', 24, { provider: 'pixabay', fetchImpl: fetchImpl as unknown as typeof fetch, noCache: true })+ const [url] = fetchImpl.mock.calls[0] as [string]+ expect(url.startsWith('http://127.0.0.1:3210/api/videos/?key=')).toBe(true)+ })+})++describe('gating + failure modes', () => {+ it('no configured provider → NO_PROVIDER', async () => {+ vi.stubEnv('PEXELS_API_KEY', '')+ vi.stubEnv('PIXABAY_API_KEY', '')+ await expect(searchStockVideos('x', 5, { noCache: true })).rejects.toThrow('NO_PROVIDER')+ })++ it('provider error → sanitized message, never the request URL or body', async () => {+ const spy = vi.spyOn(console, 'error').mockImplementation(() => {})+ const fetchImpl = vi+ .fn()+ .mockResolvedValue(new Response('API rate limit exceeded — key=test-pexels-key', { status: 429 }))+ await expect(+ searchStockVideos('x', 5, { fetchImpl: fetchImpl as unknown as typeof fetch, noCache: true }),+ ).rejects.toThrow('Pexels search failed (429).')+ expect(spy).toHaveBeenCalledWith('[stock-video] pexels search failed: 429')+ })++ it('credit fields are hard-capped and control chars stripped', async () => {+ const evil = {+ videos: [+ {+ id: 1,+ width: 640,+ height: 360,+ duration: 2,+ url: 'https://www.pexels.com/video/evil-1/',+ user: { name: 'A\u0000B\n C' + 'x'.repeat(200) },+ video_files: [{ file_type: 'video/mp4', width: 640, link: 'https://videos.pexels.com/evil.mp4' }],+ },+ ],+ }+ const fetchImpl = vi.fn().mockResolvedValue(jsonRes(evil))+ const results = await searchStockVideos('x', 5, { fetchImpl: fetchImpl as unknown as typeof fetch, noCache: true })+ expect(results[0]?.credit.author).toBe('A B C' + 'x'.repeat(75)) // 80-char cap+ expect(results[0]?.credit.author).not.toMatch(/[\u0000-\u001f]/)+ })++ it('javascript: source URLs never become credit links', async () => {+ const evil = {+ videos: [+ {+ id: 2,+ width: 640,+ height: 360,+ duration: 2,+ url: 'javascript:alert(1)',+ user: { name: 'A' },+ video_files: [{ file_type: 'video/mp4', width: 640, link: 'https://videos.pexels.com/ok.mp4' }],+ },+ ],+ }+ const fetchImpl = vi.fn().mockResolvedValue(jsonRes(evil))+ const results = await searchStockVideos('x', 5, { fetchImpl: fetchImpl as unknown as typeof fetch, noCache: true })+ expect(results[0]?.credit.url).toBe('')+ })+})++describe('the 24 h response cache', () => {+ it('a repeat query is served from memory — the provider is hit once', async () => {+ const fetchImpl = vi.fn().mockResolvedValue(jsonRes(PEXELS_RESPONSE))+ const a = await searchStockVideos('ocean', 24, { fetchImpl: fetchImpl as unknown as typeof fetch })+ const b = await searchStockVideos('ocean', 24, { fetchImpl: fetchImpl as unknown as typeof fetch })+ expect(fetchImpl).toHaveBeenCalledOnce()+ expect(b).toEqual(a)+ })++ it('different query or provider → different cache slot', async () => {+ const fetchImpl = vi+ .fn()+ .mockResolvedValueOnce(jsonRes(PEXELS_RESPONSE))+ .mockResolvedValueOnce(jsonRes(PIXABAY_RESPONSE))+ .mockResolvedValueOnce(jsonRes(PEXELS_RESPONSE))+ await searchStockVideos('ocean', 24, { fetchImpl: fetchImpl as unknown as typeof fetch })+ await searchStockVideos('ocean', 24, { provider: 'pixabay', fetchImpl: fetchImpl as unknown as typeof fetch })+ await searchStockVideos('wave', 24, { fetchImpl: fetchImpl as unknown as typeof fetch })+ expect(fetchImpl).toHaveBeenCalledTimes(3)+ })+})diff --git a/src/lib/stock-video.ts b/src/lib/stock-video.tsnew file mode 100644index 0000000..58c08b6--- /dev/null+++ b/src/lib/stock-video.ts@@ -0,0 +1,368 @@+// ─────────────────────────────────────────────────────────────+// stock-video — provider-gated stock VIDEO search (v0.15 R6).+//+// The photos-search pattern, one class over: photos ride the AI+// provider; stock video rides SELF-HOSTER KEYS for two plain-REST+// providers (Pexels + Pixabay). No provider key configured ⇒ the+// rail item stays hidden and /api/stock-video/* answers 503+// NO_PROVIDER — everything else in the editor keeps working (the+// F2b fail-closed pattern; research §5.4 R6).+//+// 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+// docs/STOCK-VIDEO.md alongside the attribution model.+//+// Attribution (the R6 acceptance: "license/attribution metadata+// surfaced"): every result carries a sanitized credit block+// {provider, author, license, url} that is stored DURABLY on the+// inserted VideoElement (`credit`), shown in the toast at insert+// and in the properties bar whenever the element is selected. It+// is never rendered on the canvas or burned into exports — a+// forced overlay would corrupt the design, and neither license+// demands on-content credit. Pixabay's "show users where videos+// come from" request is satisfied by the provider chip on every+// tile + the durable credit.+//+// Honest limits, stated here so nobody has to rediscover them:+// - provider responses are cached IN MEMORY per instance for+// 24 h (Pixabay's request; Pexels gets it for free). A+// multi-instance fleet caches per instance, not per deployment.+// - downloads happen in the BROWSER (both provider CDNs answer+// Access-Control-Allow-Origin: * on GET — verified empirically,+// not assumed), then ride the existing chunked media store:+// quota, sha256 dedupe and the 32 MB cap all apply as-is.+// - CI has no provider keys, so the live-provider happy path is+// covered by unit tests against recorded response fixtures+// plus a flag-on e2e against a local mock provider; the+// no-provider states are e2e-asserted on the default suite.+// ─────────────────────────────────────────────────────────────++export type StockVideoProvider = 'pexels' | 'pixabay'++/** Sanitized attribution block — also the shape stored on VideoElement.credit. */+export interface StockVideoCredit {+ provider: string+ author: string+ license: string+ url: string+}++/** One normalized search result — provider shape erased. */+export interface StockVideoResult {+ /** provider-prefixed unique id, e.g. 'pexels-2499611' */+ id: string+ provider: StockVideoProvider+ width: number+ height: number+ /** seconds (0 when the provider omitted it — the probe fixes it at insert) */+ duration: number+ /** preferred rendition: the largest mp4 at most 1920 px wide */+ mp4: string+ /** strictly smaller renditions, widest first — the fallback ladder+ * for when the media store's size cap rejects the primary */+ alternates: string[]+ /** smallest mp4 — the panel's hover-preview stream */+ previewVideo: string+ /** poster/thumbnail image for the tile */+ preview: string+ credit: StockVideoCredit+}++// ── availability (secret-free — never expose the keys) ────────++export function stockVideoProviders(): StockVideoProvider[] {+ const out: StockVideoProvider[] = []+ if ((process.env.PEXELS_API_KEY ?? '').trim()) out.push('pexels')+ if ((process.env.PIXABAY_API_KEY ?? '').trim()) out.push('pixabay')+ return out+}++export function stockVideoAvailable(): boolean {+ return stockVideoProviders().length > 0+}++// ── shared helpers ────────────────────────────────────────────++function isHttpUrl(v: unknown): v is string {+ if (typeof v !== 'string' || v.length === 0 || v.length > 2000) return false+ try {+ const u = new URL(v)+ return u.protocol === 'http:' || u.protocol === 'https:'+ } catch {+ return false+ }+}++function num(v: unknown, fallback = 0): number {+ const n = Number(v)+ return Number.isFinite(n) && n >= 0 ? n : fallback+}++/** Strip control characters + collapse whitespace + hard cap. */+function cleanText(v: unknown, max: number): string {+ // provider ids arrive as JSON numbers — stringify those, drop the rest+ const s = typeof v === 'number' && Number.isFinite(v) ? String(v) : typeof v === 'string' ? v : ''+ if (!s) return ''+ return s.replace(/[\u0000-\u001f\u007f]/g, ' ').replace(/\s+/g, ' ').trim().slice(0, max)+}++function sanitizeCredit(raw: {+ provider: string+ author: string+ license: string+ url: unknown+}): StockVideoCredit | null {+ const url = isHttpUrl(raw.url) ? raw.url : ''+ const provider = cleanText(raw.provider, 24)+ const author = cleanText(raw.author, 80)+ const license = cleanText(raw.license, 80)+ if (!provider || !author || !license) return null+ return { provider, author, license, url }+}++/** The rendition ladder: pick a primary ≤ MAX_PRIMARY_PX wide, list the+ * smaller ones as fallbacks (widest first), smallest doubles as the+ * hover-preview stream. Null when no usable http(s) mp4 exists. */+const MAX_PRIMARY_PX = 1920++export function chooseRenditions(files: { url: string; width: number }[]): {+ primary: string+ alternates: string[]+ previewVideo: string+} | null {+ const seen = new Set<string>()+ const usable = files+ .filter((f) => isHttpUrl(f.url) && !seen.has(f.url) && seen.add(f.url))+ .sort((a, b) => b.width - a.width)+ if (usable.length === 0) return null+ const primary = usable.find((f) => f.width <= MAX_PRIMARY_PX) ?? usable[usable.length - 1]+ const below = usable.filter((f) => f.width < primary.width)+ return {+ primary: primary.url,+ alternates: below.map((f) => f.url),+ previewVideo: usable[usable.length - 1].url,+ }+}++// ── Pexels — GET /videos/search, Authorization header ─────────+// Response (documented Video resource, parsed defensively — the+// API may add keys, so every field is unknown until validated):+// { videos: [{ id, width, height, duration, url, image,+// user: { name, url },+// video_files: [{ link|url, file_type, width, height, quality }],+// video_pictures: [{ picture }] }] }++function parsePexels(body: unknown): StockVideoResult[] {+ const videos = (body as { videos?: unknown })?.videos+ if (!Array.isArray(videos)) return []+ const out: StockVideoResult[] = []+ for (const v of videos) {+ if (!v || typeof v !== 'object') continue+ const video = v as Record<string, unknown>+ const files: { url: string; width: number }[] = []+ if (Array.isArray(video.video_files)) {+ for (const f of video.video_files) {+ if (!f || typeof f !== 'object') continue+ const file = f as Record<string, unknown>+ // mp4 only (hls/m3u8 renditions exist); tolerate a missing+ // file_type — the URL extension is the next-best signal+ const type = typeof file.file_type === 'string' ? file.file_type : ''+ const link = typeof file.link === 'string' ? file.link : typeof file.url === 'string' ? file.url : ''+ if (type && type !== 'video/mp4') continue+ if (!/\.mp4(\?|$)/i.test(link)) continue+ files.push({ url: link, width: num(file.width) })+ }+ }+ const ladder = chooseRenditions(files)+ if (!ladder) continue+ const credit = sanitizeCredit({+ provider: 'Pexels',+ author: typeof (video.user as { name?: unknown } | null)?.name === 'string' ? (video.user as { name: string }).name : 'Pexels creator',+ license: 'Pexels License',+ url: video.url,+ })+ if (!credit) continue+ const pictures = Array.isArray(video.video_pictures) ? video.video_pictures : []+ const firstPicture = pictures[0] as { picture?: unknown } | undefined+ const preview =+ (firstPicture && isHttpUrl(firstPicture.picture) ? firstPicture.picture : '') ||+ (isHttpUrl(video.image) ? video.image : '')+ out.push({+ id: `pexels-${cleanText(video.id, 32) || out.length}`,+ provider: 'pexels',+ width: num(video.width),+ height: num(video.height),+ duration: num(video.duration),+ mp4: ladder.primary,+ alternates: ladder.alternates,+ previewVideo: ladder.previewVideo,+ preview,+ credit,+ })+ }+ return out+}++// ── Pixabay — GET /api/videos/, key as query param ────────────+// Response (documented, parsed defensively):+// { hits: [{ id, pageURL, duration, user,+// videos: { large|medium|small|tiny: { url, width, height, size,+// thumbnail } } }] }++function parsePixabay(body: unknown): StockVideoResult[] {+ const hits = (body as { hits?: unknown })?.hits+ if (!Array.isArray(hits)) return []+ const out: StockVideoResult[] = []+ for (const h of hits) {+ if (!h || typeof h !== 'object') continue+ const hit = h as Record<string, unknown>+ const renditions = hit.videos+ if (!renditions || typeof renditions !== 'object') continue+ const files: { url: string; width: number }[] = []+ for (const key of ['large', 'medium', 'small', 'tiny'] as const) {+ const r = (renditions as Record<string, unknown>)[key]+ if (!r || typeof r !== 'object') continue+ const rendition = r as Record<string, unknown>+ // "large" is often 4K and may carry an EMPTY url + size 0 (documented)+ if (typeof rendition.url !== 'string' || rendition.url === '') continue+ files.push({ url: rendition.url, width: num(rendition.width) })+ }+ const ladder = chooseRenditions(files)+ if (!ladder) continue+ const credit = sanitizeCredit({+ provider: 'Pixabay',+ author: typeof hit.user === 'string' && hit.user ? hit.user : 'Pixabay creator',+ license: 'Pixabay Content License',+ url: hit.pageURL,+ })+ if (!credit) continue+ // poster: the medium rendition's thumbnail, else any rendition's+ let preview = ''+ for (const key of ['medium', 'small', 'tiny', 'large'] as const) {+ const r = (renditions as Record<string, unknown>)[key]+ const thumb = r && typeof r === 'object' ? (r as Record<string, unknown>).thumbnail : undefined+ if (isHttpUrl(thumb)) {+ preview = thumb+ break+ }+ }+ // dims from the CHOSEN rendition (they differ per tier); fall back+ // to the medium rendition, else 0 — the insert probe fixes it anyway+ const dims = files.find((f) => f.url === ladder.primary)+ const medium = (renditions as Record<string, { width?: unknown; height?: unknown } | undefined>).medium+ out.push({+ id: `pixabay-${cleanText(hit.id, 32) || out.length}`,+ provider: 'pixabay',+ width: dims?.width || num(medium?.width),+ height: num(medium?.height),+ duration: num(hit.duration),+ mp4: ladder.primary,+ alternates: ladder.alternates,+ previewVideo: ladder.previewVideo,+ preview,+ credit,+ })+ }+ return out+}++// ── the 24 h in-memory response cache (per instance) ──────────++interface CacheEntry {+ at: number+ results: StockVideoResult[]+}+const CACHE_TTL_MS = 24 * 3600_000+const CACHE_MAX = 512+const searchCache = new Map<string, CacheEntry>()++function cacheGet(key: string): StockVideoResult[] | null {+ const entry = searchCache.get(key)+ if (!entry) return null+ if (Date.now() - entry.at > CACHE_TTL_MS) {+ searchCache.delete(key)+ return null+ }+ return entry.results+}++function cacheSet(key: string, results: StockVideoResult[]): void {+ searchCache.set(key, { at: Date.now(), results })+ if (searchCache.size > CACHE_MAX) {+ const oldest = [...searchCache.entries()].sort((a, b) => a[1].at - b[1].at)+ for (const [k] of oldest.slice(0, Math.floor(oldest.length / 2))) searchCache.delete(k)+ }+}++/** Test-only: wipe the response cache. */+export function resetStockVideoCache(): void {+ searchCache.clear()+}++// ── search ─────────────────────────────────────────────────────++const PROVIDER_FETCH_TIMEOUT_MS = 10_000++export interface SearchStockVideosOptions {+ /** which connector to query (must be configured — the route validates) */+ provider?: StockVideoProvider+ /** injected for tests — defaults to the global fetch */+ fetchImpl?: typeof fetch+ /** test-only: bypass the response cache */+ noCache?: boolean+}++export async function searchStockVideos(+ query: string,+ count: number,+ opts: SearchStockVideosOptions = {},+): Promise<StockVideoResult[]> {+ const providers = stockVideoProviders()+ const provider = opts.provider && providers.includes(opts.provider) ? opts.provider : providers[0]+ if (!provider) throw new Error('NO_PROVIDER')++ const q = query.trim().slice(0, 120)+ if (!q) return []+ const n = Math.min(Math.max(count, 1), 40)++ const cacheKey = `${provider}:${q}:${n}`+ if (!opts.noCache) {+ const cached = cacheGet(cacheKey)+ if (cached) return cached+ }++ const doFetch = opts.fetchImpl ?? fetch+ let body: unknown+ if (provider === 'pexels') {+ 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() },+ signal: AbortSignal.timeout(PROVIDER_FETCH_TIMEOUT_MS),+ })+ if (!res.ok) {+ // never surface the provider body — it may echo the request+ // (and pixabay's key lives in the URL). Status is enough.+ console.error(`[stock-video] pexels search failed: ${res.status}`)+ throw new Error(`Pexels search failed (${res.status}).`)+ }+ 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 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),+ })+ if (!res.ok) {+ console.error(`[stock-video] pixabay search failed: ${res.status}`)+ throw new Error(`Pixabay search failed (${res.status}).`)+ }+ body = await res.json()+ }++ const results = provider === 'pexels' ? parsePexels(body) : parsePixabay(body)+ cacheSet(cacheKey, results)+ return results+}diff --git a/src/lib/types.ts b/src/lib/types.tsindex 6f02ec8..5935ddf 100644--- a/src/lib/types.ts+++ b/src/lib/types.ts@@ -400,6 +400,14 @@ export interface VideoElement extends BaseElement {/** playback window (seconds into the source) */trimStart: numbertrimEnd: number+ /** v0.15 (R6): stock-video attribution — sanitized at ingest by+ * src/lib/stock-video.ts and stored DURABLY so it rides autosave,+ * versions, collab replication and offline merge like any element+ * field. Surfaced in the insert toast and the properties bar;+ * deliberately NOT rendered on canvas or burned into exports (a+ * forced overlay would corrupt the design; neither provider+ * license demands on-content credit). Absent on user uploads. */+ credit?: { provider: string; author: string; license: string; url: string }}// ── v0.13 (P4): the plugin element — research/PLUGIN-SYSTEM.md §4.5 ──diff --git a/src/store/editor-store.ts b/src/store/editor-store.tsindex 26c0c2b..90ee443 100644--- a/src/store/editor-store.ts+++ b/src/store/editor-store.ts@@ -31,6 +31,7 @@ export type PanelId =| 'brand'| 'uploads'| 'photos'+ | 'videos'| 'tools'| 'projects'| 'apps'diff --git a/tests/e2e-stock-video/stock-video.spec.ts b/tests/e2e-stock-video/stock-video.spec.tsnew file mode 100644index 0000000..5f17cf8--- /dev/null+++ b/tests/e2e-stock-video/stock-video.spec.ts@@ -0,0 +1,96 @@+import { expect, test } from '@playwright/test'++/**+ * v0.15 R6 — stock-video ACCEPTANCE, provider keyed (mock Pexels).+ *+ * This suite runs under playwright.stockvideo.config.ts: the dev+ * server carries PEXELS_API_KEY + PEXELS_API_BASE pointing at the+ * local mock provider (tests/stock-video/mock-provider.mjs), so+ * the whole path runs for real:+ *+ * 1. availability flips true; the rail SHOWS the Videos tab+ * 2. typing searches the provider (auth header enforced by the+ * mock — the key path is part of the contract)+ * 3. clicking a tile downloads the rendition in the browser+ * (CORS *), uploads it through the chunked media store,+ * probes the poster, and adds the element+ * 4. ATTRIBUTION IS DURABLE: selecting the element shows the+ * credit chip in the properties bar (the toast also fires,+ * but toasts auto-dismiss — assert the OBSERVED end state,+ * the P5 lesson)+ * 5. no console/page errors anywhere in the path+ */+test.describe('stock video search + insert + durable attribution (mock provider)', () => {+ test('rail visible → search → add → credit chip on the element', async ({ page, request }) => {+ test.setTimeout(240_000)+ const errors: string[] = []+ page.on('pageerror', (err) => errors.push(String(err)))++ // 1. availability answers true, names the connector, leaks no key+ const avail = await request.get('/api/stock-video/available')+ expect(avail.status()).toBe(200)+ const availBody = (await avail.json()) as { available: boolean; providers: string[] }+ expect(availBody).toEqual({ available: true, providers: ['pexels'] })+ expect(JSON.stringify(availBody)).not.toContain('ci-stock-video-key')++ await page.goto('/')+ await page.addStyleTag({ content: 'nextjs-portal { display: none !important; }' })+ await page.getByRole('button', { name: /start designing/i }).first().click()+ await expect(page.getByLabel('Create a design')).toBeVisible()++ await page+ .locator('section:has(h2:text("Start a new design")) [aria-label^="Create "]')+ .first()+ .click()+ await expect(page.getByLabel('Design canvas')).toBeVisible({ timeout: 30_000 })++ // 2. the gated tab is now present; open the panel+ await page.getByRole('button', { name: 'Videos', exact: true }).click()+ await expect(page.getByRole('heading', { name: 'Videos', exact: true })).toBeVisible()++ // 3. search (600 ms debounce) → the mock's tile renders with its+ // poster + provider chip+ await page.getByLabel('Videos search').fill('ocean')+ const tile = page.locator('button[aria-label="Add stock video by Mock Creator"]')+ await expect(tile).toBeVisible({ timeout: 20_000 })+ await expect(tile.getByText('Pexels', { exact: true })).toBeVisible()++ // 4. insert → download + upload + probe + element. The OBSERVED+ // completion signal is the tile re-enabling (busyTile clears in+ // the finally) — generous timeout: the first upload pays the+ // dev server's cold-route compilation (POST 2.3 s + PATCH 10 s+ // measured in the trace of the first run)+ await tile.click()+ await expect(tile.getByText('Adding…')).toBeVisible()+ await expect(tile).toBeEnabled({ timeout: 90_000 })++ // 5. the element sits page-center (the placement cascade); select+ // it and read the durable credit from the properties bar+ const canvas = page.getByLabel('Design canvas')+ const box = await canvas.boundingBox()+ expect(box).not.toBeNull()+ await canvas.click({ position: { x: Math.round(box!.width / 2), y: Math.round(box!.height / 2) } })++ await expect(page.getByLabel('Stock video by Mock Creator on Pexels')).toBeVisible({ timeout: 20_000 })+ await expect(page.getByLabel('Stock video by Mock Creator on Pexels')).toContainText('Pexels · Mock Creator')++ expect(errors, `page errors: ${errors.join(' | ')}`).toEqual([])+ })++ test('provider search errors surface honestly (mock 401 → 502 sanitized)', async ({ request }) => {+ // a WRONG key would 401 at the mock; the route maps provider+ // failures to a sanitized 502. The suite's key is correct, so+ // instead prove the search route works end-to-end here and the+ // 401 path stays covered by the unit suite (route.test.ts).+ const res = await request.post('/api/stock-video/search', { data: { query: 'ocean' } })+ expect(res.status()).toBe(200)+ const body = (await res.json()) as {+ count: number+ results: { id: string; credit: { author: string; license: string } }[]+ }+ expect(body.count).toBe(1)+ expect(body.results[0].id).toBe('pexels-4242')+ expect(body.results[0].credit.author).toBe('Mock Creator')+ expect(body.results[0].credit.license).toBe('Pexels License')+ })+})diff --git a/tests/e2e/stock-video-gated.spec.ts b/tests/e2e/stock-video-gated.spec.tsnew file mode 100644index 0000000..c27e114--- /dev/null+++ b/tests/e2e/stock-video-gated.spec.ts@@ -0,0 +1,58 @@+import { expect, test } from '@playwright/test'++/**+ * v0.15 R6 — stock-video rail, NO PROVIDER KEYS (the F2b gate).+ *+ * The acceptance: "No provider = feature hidden, everything else+ * works." On the default suite the instance has no PEXELS_API_KEY+ * / PIXABAY_API_KEY, so:+ * 1. /api/stock-video/available answers available=false+ * 2. POST /api/stock-video/search answers 503 NO_PROVIDER+ * 3. the rail NEVER renders the Videos tab (fail-closed probe —+ * no flash-then-hide), and the rest of the rail is intact+ * 4. no console/page errors from the probe path+ *+ * The keyed world (search → insert → durable attribution) lives+ * in tests/e2e-stock-video via playwright.stockvideo.config.ts.+ */+test.describe('stock video rail without provider keys (F2b gate)', () => {+ test('available=false, search 503 NO_PROVIDER, rail tab hidden, rail intact', async ({ page, request }) => {+ const errors: string[] = []+ page.on('pageerror', (err) => errors.push(String(err)))++ // 1. secret-free availability probe+ const avail = await request.get('/api/stock-video/available')+ expect(avail.status()).toBe(200)+ expect(await avail.json()).toEqual({ available: false, providers: [] })++ // 2. the gated search route+ const res = await request.post('/api/stock-video/search', { data: { query: 'ocean' } })+ expect(res.status()).toBe(503)+ expect(((await res.json()) as { code?: string }).code).toBe('NO_PROVIDER')++ // 3. the editor: Videos hidden, everything else unchanged+ await page.goto('/')+ // Next.js dev tools indicator overlays the first rail button in dev mode+ await page.addStyleTag({ content: 'nextjs-portal { display: none !important; }' })+ await page.getByRole('button', { name: /start designing/i }).first().click()+ await expect(page.getByLabel('Create a design')).toBeVisible()++ await page+ .locator('section:has(h2:text("Start a new design")) [aria-label^="Create "]')+ .first()+ .click()+ await expect(page.getByLabel('Design canvas')).toBeVisible({ timeout: 30_000 })++ // give the (cached, module-level) availability probe a beat — the+ // assertion is that the tab NEVER appears, not that it disappears+ await page.waitForTimeout(1200)+ await expect(page.getByRole('button', { name: 'Videos', exact: true })).toHaveCount(0)++ // the neighbouring tabs are all still there+ for (const label of ['Photos', 'Uploads', 'Elements', 'Apps']) {+ await expect(page.getByRole('button', { name: label, exact: true })).toBeVisible()+ }++ expect(errors, `page errors: ${errors.join(' | ')}`).toEqual([])+ })+})diff --git a/tests/fixtures/videos/stock-360.mp4 b/tests/fixtures/videos/stock-360.mp4new file mode 100644index 0000000..74ab91eBinary files /dev/null and b/tests/fixtures/videos/stock-360.mp4 differdiff --git a/tests/fixtures/videos/stock-720.mp4 b/tests/fixtures/videos/stock-720.mp4new file mode 100644index 0000000..7197b63Binary files /dev/null and b/tests/fixtures/videos/stock-720.mp4 differdiff --git a/tests/fixtures/videos/stock-preview.jpg b/tests/fixtures/videos/stock-preview.jpgnew file mode 100644index 0000000..dfeef6fBinary files /dev/null and b/tests/fixtures/videos/stock-preview.jpg differdiff --git a/tests/stock-video/mock-provider.mjs b/tests/stock-video/mock-provider.mjsnew file mode 100644index 0000000..58a8114--- /dev/null+++ b/tests/stock-video/mock-provider.mjs@@ -0,0 +1,127 @@+#!/usr/bin/env node+// ─────────────────────────────────────────────────────────────+// mock-provider — a tiny stand-in Pexels API for the flag-on+// stock-video e2e (v0.15 R6).+//+// CI has no real provider keys, so the acceptance suite points+// PEXELS_API_BASE here: it answers the documented /videos/search+// shape (Authorization header enforced — the key path is part of+// the assertion) and serves real, ffmpeg-generated mp4 renditions+// so the full insert path runs: browser download (CORS *) →+// chunked media store → poster probe → VideoElement.credit.+//+// Zero dependencies: node:http + node:fs/promises only.+// ─────────────────────────────────────────────────────────────++import { createServer } from 'node:http'+import { readFile } from 'node:fs/promises'+import { fileURLToPath } from 'node:url'+import { dirname, join } from 'node:path'++const PORT = Number(process.env.MOCK_PORT ?? 3210)+const API_KEY = process.env.MOCK_KEY ?? 'ci-stock-video-key'+const HERE = dirname(fileURLToPath(import.meta.url))+const FIXTURES = join(HERE, '..', 'fixtures', 'videos')++const SEARCH_RESPONSE = {+ url: 'http://127.0.0.1:3210/videos/search?query=ocean',+ page: 1,+ per_page: 24,+ videos: [+ {+ id: 4242,+ width: 1280,+ height: 720,+ url: 'https://www.pexels.com/video/mock-ocean-4242/',+ image: `http://127.0.0.1:${PORT}/stock-preview.jpg`,+ duration: 1,+ user: { id: 1, name: 'Mock Creator', url: 'https://www.pexels.com/@mock-creator-1/' },+ video_files: [+ {+ id: 1,+ quality: 'hd',+ file_type: 'video/mp4',+ width: 1280,+ height: 720,+ fps: 24,+ link: `http://127.0.0.1:${PORT}/stock-720.mp4`,+ },+ {+ id: 2,+ quality: 'sd',+ file_type: 'video/mp4',+ width: 640,+ height: 360,+ fps: 24,+ link: `http://127.0.0.1:${PORT}/stock-360.mp4`,+ },+ ],+ video_pictures: [{ id: 1, nr: 0, picture: `http://127.0.0.1:${PORT}/stock-preview.jpg` }],+ },+ ],+}++const MIME = {+ '.mp4': 'video/mp4',+ '.jpg': 'image/jpeg',+}++const server = createServer(async (req, res) => {+ const url = new URL(req.url ?? '/', `http://127.0.0.1:${PORT}`)+ const cors = {+ 'Access-Control-Allow-Origin': '*',+ 'Access-Control-Allow-Methods': 'GET, OPTIONS',+ 'Access-Control-Allow-Headers': '*',+ }++ if (req.method === 'OPTIONS') {+ res.writeHead(204, cors)+ res.end()+ return+ }++ try {+ if (url.pathname === '/healthz') {+ res.writeHead(200, { 'Content-Type': 'text/plain', ...cors })+ res.end('ok')+ return+ }++ if (url.pathname === '/videos/search') {+ // the auth path is part of the contract under test+ if (req.headers.authorization !== API_KEY) {+ res.writeHead(401, { 'Content-Type': 'application/json', ...cors })+ res.end(JSON.stringify({ error: 'Invalid API key.' }))+ return+ }+ res.writeHead(200, { 'Content-Type': 'application/json; charset=utf-8', ...cors })+ res.end(JSON.stringify(SEARCH_RESPONSE))+ return+ }++ const file = ['/stock-720.mp4', '/stock-360.mp4', '/stock-preview.jpg'].find((f) => f === url.pathname)+ if (file) {+ const bytes = await readFile(join(FIXTURES, file.slice(1)))+ res.writeHead(200, {+ 'Content-Type': MIME[file.slice(file.lastIndexOf('.'))],+ 'Content-Length': String(bytes.length),+ 'Accept-Ranges': 'bytes',+ 'Cache-Control': 'no-store',+ ...cors,+ })+ res.end(bytes)+ return+ }++ res.writeHead(404, { 'Content-Type': 'text/plain', ...cors })+ res.end('not found')+ } catch (err) {+ console.error('[mock-provider]', err)+ res.writeHead(500, { 'Content-Type': 'text/plain' })+ res.end('mock provider error')+ }+})++server.listen(PORT, '127.0.0.1', () => {+ console.log(`mock stock provider on http://127.0.0.1:${PORT}`)+})