Skip to content

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

feat(v0.14): persistent uploads library — images join the media store, sha256 dedupe, quota, account-following library, portable SVG exports (D1) (#24)

Ashiq Hussain Mirdd866174b597
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4347702..4bca632 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,62 @@
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.14.0] — 2026-11-04
+
+### Added
+
+- **Daily-driver depth, part 1 of the v0.14 menu — the persistent
+ uploads library (D1).** Uploads used to live two half-lives: images
+ embedded as data URLs inside the document (bloated designs, no
+ reuse, no account), audio/video in the media store but invisible
+ after reload. Both now share one DB-backed library that survives
+ reload and follows the account — upload on device A, log in on
+ device B, insert from the Uploads panel.
+ - **Images join the media store**: the upload rail accepts
+ `image/*` alongside audio/video (same chunked protocol, same
+ 32 MB cap), with the original bytes kept server-side — no more
+ silent downscaling into the document.
+ - **sha256 dedupe at finalize**: identical bytes within the SAME
+ attribution (account or anon cookie — never across accounts, so
+ uploads can't be probed through someone else's library) collapse
+ to the existing row; the finalize response carries
+ `deduplicated: true` and the old id.
+ - **Quota, surfaced**: `CANVIX_UPLOAD_QUOTA_MB` (default 256 MB)
+ per attribution, enforced at upload-init (in-flight rows count
+ too, so parallel uploads can't sail past the cap together) and
+ shown in the panel footer ("42.3 MB of 256.0 MB").
+ - **Library API**: `GET /api/media/library` (projection-only —
+ never the bytes; attribution-scoped), `PATCH`/`DELETE
+ /api/media/library/[id]` (rename / remove). A foreign id is a
+ flat 404 — no cross-account existence oracle. Removing an item
+ clears `keepInLibrary` only: designs already referencing it keep
+ working; the orphan GC owns reaping unreferenced rows.
+ - **Anonymous uploads follow the account**: login/register claims
+ this browser's anon-attributed media rows (scoped by the
+ canvix_anon hash — the design-adopt lesson, with none of the
+ eligibility subtlety).
+ - **UploadsPanel reads the DB**: grid of your files (image
+ thumbnails from the serve route, audio/video rows with icons),
+ click-to-insert (images keep replace-mode, audio/video re-probe
+ their blobs for duration/peaks), inline rename, hover delete,
+ set-as-background, upload progress, and the quota line.
+ - **Portable SVG exports**: media-store images inline to data URLs
+ at export time (`inlineMediaImages`, deep-copy — the live
+ document is never mutated); `safeHref` accepts the first-party
+ `/api/media/` srcs. A fetch that fails degrades honestly: the
+ relative URL stays (a visibly broken image beats silently
+ losing content).
+ - **GC discipline**: the media orphan GC skips `keepInLibrary`
+ rows (a library item is kept on purpose, not orphaned);
+ `--prune-library` opts back in.
+ - **Verification**: 23 new unit tests (library scoping/authz/CSRF,
+ dedupe + attribution-scoping, claim-on-login, safeHref +
+ inlining + no-mutation) and a 3-spec e2e acceptance
+ (`tests/e2e/uploads-library.spec.ts`): upload → reload →
+ second-design insert → inlined SVG export; remove-never-breaks-
+ designs; anonymous upload claimed on register (checked from a
+ second browser context).
+
## [0.13.4] — 2026-11-03
### Added
diff --git a/README.md b/README.md
index 03fb35d..cc32dbc 100644
--- a/README.md
+++ b/README.md
@@ -941,6 +941,19 @@ tool descriptions so agents pick the right format.
[`docs/PLUGINS.md`](docs/PLUGINS.md) — quickstart, manifest
spec, RPC reference, renderer contract, hosting guide
*(v0.13.4)*
+- [x] Persistent uploads library (v0.14 D1) — one DB-backed library
+ for images AND audio/video: the media store now accepts `image/*`
+ (same chunked rail), finalizes with sha256 dedupe scoped to your
+ attribution (never across accounts), enforces + surfaces a
+ per-account quota (`CANVIX_UPLOAD_QUOTA_MB`, default 256 MB), and
+ lists everything in the Uploads panel — thumbnails, click-to-insert,
+ rename, delete. Uploads survive reload, and login/register claims
+ this browser's anonymous uploads, so the library follows the
+ account across devices. Removing an item never breaks designs
+ using it (rows survive while referenced; the orphan GC skips
+ library-kept rows unless `--prune-library`). SVG exports inline
+ media images to data URLs so files stay portable
+ *(v0.14.0)*
- [ ] Mobile editor polish — touch-first selection handles, gesture
zoom/pan without modifier keys, bottom-sheet property panels
(the responsive groundwork from v0.11.3 makes this tractable)
diff --git a/docs/PLUGINS.md b/docs/PLUGINS.md
index 51459e1..2db7719 100644
--- a/docs/PLUGINS.md
+++ b/docs/PLUGINS.md
@@ -57,7 +57,7 @@ hello/
"description": "Adds a greeting text box",
"version": "1.0.0",
"author": { "name": "Your Name" },
- "engines": { "canvix": ">=0.13.4 <0.14.0" },
+ "engines": { "canvix": ">=0.13.4 <0.15.0" },
"entry": { "panel": "panel.html" },
"permissions": ["design:write"],
"files": ["manifest.json", "panel.html", "panel.js"],
diff --git a/package.json b/package.json
index c907158..7af5711 100644
--- a/package.json
+++ b/package.json
@@ -1,8 +1,8 @@
{
"name": "canvix",
- "version": "0.13.4",
+ "version": "0.14.0",
"private": false,
- "description": "Canvix — free & open-source graphic design tool. A community-built Canva alternative.",
+ "description": "Canvix \u2014 free & open-source graphic design tool. A community-built Canva alternative.",
"scripts": {
"dev": "next dev -p 3000 2>&1 | tee dev.log",
"build": "node scripts/build.mjs",
diff --git a/prisma/migrations/0007_uploads_library/migration.sql b/prisma/migrations/0007_uploads_library/migration.sql
new file mode 100644
index 0000000..b2f2971
--- /dev/null
+++ b/prisma/migrations/0007_uploads_library/migration.sql
@@ -0,0 +1,18 @@
+-- v0.14 (D1): persistent uploads library
+-- Additive only: three nullable/defaulted columns on Media.
+-- contentHash — sha256 of the finalized bytes; finalize dedupes an
+-- upload against the owner's earlier identical upload
+-- (attribution-scoped: never across accounts)
+-- name — the original filename, surfaced in the library UI
+-- keepInLibrary — library membership; true for every upload finalized
+-- from v0.14 on. The media orphan GC skips these rows
+-- (they are *kept*, not orphaned); --prune-library
+-- opts back in. Legacy audio/video rows keep false and
+-- behave exactly as before.
+
+ALTER TABLE "Media" ADD COLUMN "contentHash" TEXT;
+ALTER TABLE "Media" ADD COLUMN "name" TEXT;
+ALTER TABLE "Media" ADD COLUMN "keepInLibrary" BOOLEAN NOT NULL DEFAULT false;
+
+CREATE INDEX "Media_contentHash_idx" ON "Media"("contentHash");
+CREATE INDEX "Media_ownerId_keepInLibrary_idx" ON "Media"("ownerId", "keepInLibrary");
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index 7225fb9..a9142ef 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -193,9 +193,16 @@ model Media {
finalizedAt DateTime?
createdAt DateTime @default(now())
+ // v0.14 (D1): the persistent uploads library
+ contentHash String? // sha256 of the finalized bytes — same-owner dedupe
+ name String? // original filename, surfaced in the library
+ keepInLibrary Boolean @default(false) // library membership; GC-protected
+
@@index([ownerId])
@@index([anonKey])
@@index([finalizedAt, createdAt])
+ @@index([contentHash])
+ @@index([ownerId, keepInLibrary])
}
// Provider accounting + abuse telemetry for AI routes.
diff --git a/public/plugins/wordcloud/manifest.json b/public/plugins/wordcloud/manifest.json
index 6b9b3f7..072cf14 100644
--- a/public/plugins/wordcloud/manifest.json
+++ b/public/plugins/wordcloud/manifest.json
@@ -3,27 +3,72 @@
"id": "com.canvix.wordcloud",
"name": "Word Cloud",
"description": "Turn any text into a seeded word-cloud graphic. Deterministic, offline, zero network.",
- "version": "1.0.0",
- "author": { "name": "Canvix team", "url": "https://github.com/mir-ashiq/canvix" },
- "engines": { "canvix": ">=0.13.4 <0.14.0" },
- "entry": { "panel": "panel.html", "service": "service.html" },
- "permissions": ["design:read", "design:write", "element:plugin", "storage"],
- "files": ["manifest.json", "panel.html", "panel.js", "service.html", "service.js", "wordcloud.js"],
+ "version": "1.0.1",
+ "author": {
+ "name": "Canvix team",
+ "url": "https://github.com/mir-ashiq/canvix"
+ },
+ "engines": {
+ "canvix": ">=0.13.4 <0.15.0"
+ },
+ "entry": {
+ "panel": "panel.html",
+ "service": "service.html"
+ },
+ "permissions": [
+ "design:read",
+ "design:write",
+ "element:plugin",
+ "storage"
+ ],
+ "files": [
+ "manifest.json",
+ "panel.html",
+ "panel.js",
+ "service.html",
+ "service.js",
+ "wordcloud.js"
+ ],
"elements": [
{
"kind": "cloud",
"label": "Word cloud",
- "initialData": { "words": [], "seed": 42, "density": 0.7, "mask": "rect", "palette": "canvix" },
+ "initialData": {
+ "words": [],
+ "seed": 42,
+ "density": 0.7,
+ "mask": "rect",
+ "palette": "canvix"
+ },
"schema": [
- { "key": "seed", "type": "number", "label": "Seed", "min": 1, "max": 9999 },
- { "key": "density", "type": "range", "label": "Density", "min": 0.1, "max": 1, "step": 0.05 },
+ {
+ "key": "seed",
+ "type": "number",
+ "label": "Seed",
+ "min": 1,
+ "max": 9999
+ },
+ {
+ "key": "density",
+ "type": "range",
+ "label": "Density",
+ "min": 0.1,
+ "max": 1,
+ "step": 0.05
+ },
{
"key": "mask",
"type": "select",
"label": "Shape",
"options": [
- { "value": "rect", "label": "Rectangle" },
- { "value": "circle", "label": "Circle" }
+ {
+ "value": "rect",
+ "label": "Rectangle"
+ },
+ {
+ "value": "circle",
+ "label": "Circle"
+ }
]
},
{
@@ -31,10 +76,22 @@
"type": "select",
"label": "Palette",
"options": [
- { "value": "canvix", "label": "Canvix" },
- { "value": "sunset", "label": "Sunset" },
- { "value": "ocean", "label": "Ocean" },
- { "value": "mono", "label": "Mono" }
+ {
+ "value": "canvix",
+ "label": "Canvix"
+ },
+ {
+ "value": "sunset",
+ "label": "Sunset"
+ },
+ {
+ "value": "ocean",
+ "label": "Ocean"
+ },
+ {
+ "value": "mono",
+ "label": "Mono"
+ }
]
}
]
diff --git a/scripts/media-gc.ts b/scripts/media-gc.ts
index e9a3fd3..39f2b72 100644
--- a/scripts/media-gc.ts
+++ b/scripts/media-gc.ts
@@ -9,7 +9,11 @@
// upload-init route applies lazily, applied deterministically
// 2. finalized uploads older than the grace period (default 14 d)
// whose id is not referenced by ANY live design's pages — an
-// element references its media as `/api/media/<id>` in src
+// element references its media as `/api/media/<id>` in src.
+// v0.14 (D1): rows kept in the uploads library
+// (keepInLibrary = true) are SKIPPED — a library item is kept
+// on purpose, not orphaned; --prune-library opts back in and
+// treats them like any unreferenced row.
//
// Default mode REPORTS only; --prune actually deletes. The grace
// period exists because a freshly uploaded file can legitimately be
@@ -17,14 +21,16 @@
// offline tab, or a design that was never saved at all).
//
// Usage:
-// DATABASE_URL=... npx tsx scripts/media-gc.ts # report
-// DATABASE_URL=... npx tsx scripts/media-gc.ts --prune # delete
-// GRACE_DAYS=30 npx tsx scripts/media-gc.ts --prune # custom grace
+// DATABASE_URL=... npx tsx scripts/media-gc.ts # report
+// DATABASE_URL=... npx tsx scripts/media-gc.ts --prune # delete
+// GRACE_DAYS=30 npx tsx scripts/media-gc.ts --prune # custom grace
+// DATABASE_URL=... npx tsx scripts/media-gc.ts --prune --prune-library # also library items
import { createScriptClient } from '../src/lib/db-script'
const db = createScriptClient()
const PRUNE = process.argv.includes('--prune')
+const PRUNE_LIBRARY = process.argv.includes('--prune-library')
const GRACE_DAYS = Math.max(1, Number(process.env.GRACE_DAYS ?? 14))
const ABANDON_MS = 24 * 3600 * 1000
const GRACE_MS = GRACE_DAYS * 24 * 3600 * 1000
@@ -74,14 +80,25 @@ async function main() {
}
// 2. finalized orphans past the grace period
+ // (v0.14 D1: library-kept rows only pruned with --prune-library)
const candidates = await db.media.findMany({
- where: { finalizedAt: { not: null }, createdAt: { lt: new Date(now - GRACE_MS) } },
- select: { id: true, size: true, createdAt: true },
+ where: {
+ finalizedAt: { not: null },
+ createdAt: { lt: new Date(now - GRACE_MS) },
+ ...(PRUNE_LIBRARY ? {} : { keepInLibrary: false }),
+ },
+ select: { id: true, size: true, createdAt: true, keepInLibrary: true },
+ })
+ const kept = await db.media.count({
+ where: { finalizedAt: { not: null }, keepInLibrary: true, createdAt: { lt: new Date(now - GRACE_MS) } },
})
console.log(
`\nfinalized uploads older than ${GRACE_DAYS} d: ${candidates.length}` +
` (${(candidates.reduce((n, m) => n + m.size, 0) / 1024 / 1024).toFixed(2)} MB)`,
)
+ if (kept > 0 && !PRUNE_LIBRARY) {
+ console.log(` (skipping ${kept} library-kept row${kept === 1 ? '' : 's'} — pass --prune-library to include them)`)
+ }
// referenced set — scan live (non-trashed) designs in batches
const referenced = new Set<string>()
diff --git a/src/app/api/auth/login/route.ts b/src/app/api/auth/login/route.ts
index 128ad26..8ea5233 100644
--- a/src/app/api/auth/login/route.ts
+++ b/src/app/api/auth/login/route.ts
@@ -6,6 +6,7 @@ import { createSession } from '@/lib/auth/session'
import { rateLimit } from '@/lib/ai/provider'
import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'
import { withLogging } from '@/lib/observability'
+import { claimAnonMedia } from '@/lib/auth/claim-media'
// POST /api/auth/login — exchange username + password for a session cookie.
// One deliberately generic error message: never reveal whether the
@@ -35,6 +36,8 @@ async function __canvix_post(req: NextRequest) {
return NextResponse.json({ error: 'Invalid username or password.' }, { status: 401 })
}
+ // v0.14 (D1): this browser's anonymous uploads follow the account
+ await claimAnonMedia(req, user.id)
const res = NextResponse.json({ user: { id: user.id, username: user.username, createdAt: user.createdAt } })
await createSession(user.id, res)
return res
diff --git a/src/app/api/auth/register/route.ts b/src/app/api/auth/register/route.ts
index cbcfd5a..bc33ce0 100644
--- a/src/app/api/auth/register/route.ts
+++ b/src/app/api/auth/register/route.ts
@@ -6,6 +6,7 @@ import { createSession } from '@/lib/auth/session'
import { rateLimit } from '@/lib/ai/provider'
import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'
import { withLogging } from '@/lib/observability'
+import { claimAnonMedia } from '@/lib/auth/claim-media'
// POST /api/auth/register — create an account (username + password).
// Free forever: no email, no verification, no external provider — a
@@ -35,6 +36,8 @@ async function __canvix_post(req: NextRequest) {
const user = await db.user.create({ data: { username, passwordHash }, select: { id: true, username: true, createdAt: true } })
const res = NextResponse.json({ user }, { status: 201 })
+ // v0.14 (D1): this browser's anonymous uploads follow the account
+ await claimAnonMedia(req, user.id)
await createSession(user.id, res)
return res
} catch (error) {
diff --git a/src/app/api/media/[id]/route.ts b/src/app/api/media/[id]/route.ts
index 16cf7e0..342d23d 100644
--- a/src/app/api/media/[id]/route.ts
+++ b/src/app/api/media/[id]/route.ts
@@ -1,3 +1,4 @@
+import { createHash } from 'node:crypto'
import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'
import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'
@@ -69,7 +70,39 @@ async function __canvix_put(req: NextRequest, { params }: { params: Promise<{ id
{ status: 409 },
)
}
- await db.media.update({ where: { id }, data: { finalizedAt: new Date() } })
+ // v0.14 (D1): finalize = hash the bytes, dedupe within the SAME
+ // attribution (account or anon cookie — never across accounts, so
+ // one user's uploads can't be probed through another's), then keep
+ // the row in the persistent uploads library.
+ const byteRows = await db.$queryRawUnsafe<{ bytes: Buffer; ownerId: string | null; anonKey: Buffer | null }[]>(
+ `SELECT bytes, "ownerId", "anonKey" FROM "Media" WHERE id = $1 AND "finalizedAt" IS NULL`,
+ id,
+ )
+ if (!byteRows.length) return NextResponse.json({ error: 'Not found or already finalized.' }, { status: 404 })
+ const { ownerId, anonKey } = byteRows[0]
+ const contentHash = createHash('sha256').update(byteRows[0].bytes).digest('hex')
+
+ const dupe = await db.$queryRawUnsafe<{ id: string }[]>(
+ `SELECT id FROM "Media"
+ WHERE "contentHash" = $1 AND "finalizedAt" IS NOT NULL AND id != $2 AND (
+ ("ownerId" = $3 AND $3 IS NOT NULL) OR ("anonKey" = $4 AND $4 IS NOT NULL))
+ ORDER BY "createdAt" ASC LIMIT 1`,
+ contentHash,
+ id,
+ ownerId,
+ anonKey,
+ )
+ if (dupe.length) {
+ // identical bytes already in this attribution's library — the new
+ // row is redundant: point the caller at the old id and drop it
+ await db.media.delete({ where: { id } }).catch(() => { /* already gone */ })
+ return NextResponse.json({ id: dupe[0].id, deduplicated: true })
+ }
+
+ await db.media.update({
+ where: { id },
+ data: { finalizedAt: new Date(), contentHash, keepInLibrary: true },
+ })
return NextResponse.json({ id })
} catch (error) {
console.error('[media/finalize] failed', error)
diff --git a/src/app/api/media/finalize-dedupe.test.ts b/src/app/api/media/finalize-dedupe.test.ts
new file mode 100644
index 0000000..b6710bb
--- /dev/null
+++ b/src/app/api/media/finalize-dedupe.test.ts
@@ -0,0 +1,94 @@
+// Unit tests for the v0.14 (D1) finalize path: sha256 dedupe within
+// the SAME attribution + keepInLibrary stamping.
+//
+// 1. identical bytes already in the caller's library → the new row
+// is deleted and the OLD id returned (deduplicated: true)
+// 2. no dupe → row finalized, hashed, and kept in the library
+// 3. dedupe NEVER matches across attributions (the SQL scopes by
+// ownerId/anonKey — asserted on the emitted statement)
+
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+const queryRaw = vi.hoisted(() => vi.fn())
+const mediaDelete = vi.hoisted(() => vi.fn())
+const mediaUpdate = vi.hoisted(() => vi.fn())
+const dbMock = vi.hoisted(() => ({
+ $queryRawUnsafe: queryRaw,
+ media: { delete: mediaDelete, update: mediaUpdate },
+}))
+vi.mock('@/lib/db', () => ({ db: dbMock }))
+
+vi.mock('@/lib/observability', () => ({
+ withLogging: (_name: string, fn: unknown) => fn,
+}))
+
+import { createHash } from 'node:crypto'
+import { NextRequest } from 'next/server'
+import { PUT } from './[id]/route'
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ mediaDelete.mockResolvedValue({ id: 'gone' })
+ mediaUpdate.mockResolvedValue({ id: 'kept' })
+})
+
+function putReq(id: string, expectedSize: number) {
+ return new NextRequest(`http://localhost/api/media/${id}`, {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ expectedSize }),
+ })
+}
+
+const OWNER = { ownerId: 'user-a', anonKey: null }
+const BYTES = Buffer.from('pngbytes')
+
+function mockFinalizeQueries(bytes: Buffer, owner: { ownerId: string | null; anonKey: Buffer | null }, dupe: { id: string }[]) {
+ queryRaw
+ .mockResolvedValueOnce([{ len: bytes.length }]) // length check
+ .mockResolvedValueOnce([{ bytes, ...owner }]) // bytes + attribution
+ .mockResolvedValueOnce(dupe) // dedupe lookup
+}
+
+describe('PUT /api/media/[id] finalize (v0.14 D1)', () => {
+ it('dedupes: returns the OLD id and deletes the redundant row', async () => {
+ mockFinalizeQueries(BYTES, OWNER, [{ id: 'm-old' }])
+ const res = await PUT(putReq('m-new', BYTES.length), { params: Promise.resolve({ id: 'm-new' }) })
+ expect(res.status).toBe(200)
+ expect(await res.json()).toEqual({ id: 'm-old', deduplicated: true })
+ expect(mediaDelete).toHaveBeenCalledWith({ where: { id: 'm-new' } })
+ expect(mediaUpdate).not.toHaveBeenCalled()
+ })
+
+ it('no dupe: finalizes with contentHash + keepInLibrary', async () => {
+ mockFinalizeQueries(BYTES, OWNER, [])
+ const res = await PUT(putReq('m-new', BYTES.length), { params: Promise.resolve({ id: 'm-new' }) })
+ expect(res.status).toBe(200)
+ expect(await res.json()).toEqual({ id: 'm-new' })
+ expect(mediaDelete).not.toHaveBeenCalled()
+ const arg = mediaUpdate.mock.calls[0][0]
+ expect(arg.where).toEqual({ id: 'm-new' })
+ expect(arg.data.keepInLibrary).toBe(true)
+ // sha256 of 'pngbytes' — proving the hash covers the actual bytes
+ expect(arg.data.contentHash).toBe(createHash('sha256').update(BYTES).digest('hex'))
+ })
+
+ it('the dedupe lookup is attribution-scoped (never across accounts)', async () => {
+ mockFinalizeQueries(BYTES, OWNER, [])
+ await PUT(putReq('m-new', BYTES.length), { params: Promise.resolve({ id: 'm-new' }) })
+ const dupeSql = queryRaw.mock.calls[2][0] as string
+ expect(dupeSql).toContain('"ownerId" = $3')
+ expect(dupeSql).toContain('"anonKey" = $4')
+ // anonymous attribution rides the anonKey, never a foreign owner
+ const args = queryRaw.mock.calls[2].slice(1)
+ expect(args[2]).toBe('user-a')
+ expect(args[3]).toBeNull()
+ })
+
+ it('length mismatch is a 409 before any dedupe work', async () => {
+ queryRaw.mockResolvedValueOnce([{ len: 3 }])
+ const res = await PUT(putReq('m-new', 999), { params: Promise.resolve({ id: 'm-new' }) })
+ expect(res.status).toBe(409)
+ expect(queryRaw).toHaveBeenCalledTimes(1)
+ })
+})
diff --git a/src/app/api/media/library/[id]/route.ts b/src/app/api/media/library/[id]/route.ts
new file mode 100644
index 0000000..7d11508
--- /dev/null
+++ b/src/app/api/media/library/[id]/route.ts
@@ -0,0 +1,83 @@
+import { NextRequest, NextResponse } from 'next/server'
+import { db } from '@/lib/db'
+import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'
+import { getSessionUser } from '@/lib/auth/session'
+import { anonKeyHash, readAnonToken } from '@/lib/auth/anon'
+import { withLogging } from '@/lib/observability'
+
+export const runtime = 'nodejs'
+
+// ── v0.14 (D1): uploads library item management ──────────────
+// PATCH /api/media/library/[id] { name } — rename
+// DELETE /api/media/library/[id] — remove from the library
+//
+// Ownership: the row's attribution (ownerId / anonKey) must match the
+// caller's; anything else is a flat 404 (no existence oracle across
+// accounts). DELETE only clears keepInLibrary — the bytes survive while
+// any design still references them (the orphan GC's referenced-check
+// protects them); unreferenced rows are reclaimed by the GC after its
+// grace period, exactly like a deleted design's media always was.
+
+function sanitizeName(raw: unknown): string | null {
+ if (typeof raw !== 'string') return null
+ const trimmed = raw.replace(/[\\/]|\.\./g, '').trim().slice(0, 200)
+ return trimmed || null
+}
+
+async function __canvix_patch(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
+ if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })
+ const { id } = await params
+ try {
+ const body = (await req.json().catch(() => ({}))) as { name?: unknown }
+ const name = sanitizeName(body.name)
+ if (!name) return NextResponse.json({ error: 'A name is required.' }, { status: 400 })
+
+ const user = await getSessionUser(req)
+ const token = readAnonToken(req)
+ const ownerId = user?.id ?? null
+ const anonKey = user ? null : token ? anonKeyHash(token) : null
+ if (!ownerId && !anonKey) return NextResponse.json({ error: 'Not found.' }, { status: 404 })
+
+ const updated = await db.$executeRawUnsafe(
+ `UPDATE "Media" SET name = $3 WHERE id = $1 AND "keepInLibrary" = true AND (
+ ("ownerId" = $2 AND $2 IS NOT NULL) OR ("anonKey" = $4 AND $4 IS NOT NULL))`,
+ id,
+ ownerId,
+ name,
+ anonKey,
+ )
+ if (updated === 0) return NextResponse.json({ error: 'Not found.' }, { status: 404 })
+ return NextResponse.json({ ok: true, name })
+ } catch (error) {
+ console.error('[media/library rename] failed', error)
+ return NextResponse.json({ error: 'Could not rename.' }, { status: 500 })
+ }
+}
+
+async function __canvix_delete(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
+ if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })
+ const { id } = await params
+ try {
+ const user = await getSessionUser(req)
+ const token = readAnonToken(req)
+ const ownerId = user?.id ?? null
+ const anonKey = user ? null : token ? anonKeyHash(token) : null
+ if (!ownerId && !anonKey) return NextResponse.json({ error: 'Not found.' }, { status: 404 })
+
+ const updated = await db.$executeRawUnsafe(
+ `UPDATE "Media" SET "keepInLibrary" = false WHERE id = $1 AND "keepInLibrary" = true AND (
+ ("ownerId" = $2 AND $2 IS NOT NULL) OR ("anonKey" = $3 AND $3 IS NOT NULL))`,
+ id,
+ ownerId,
+ anonKey,
+ )
+ if (updated === 0) return NextResponse.json({ error: 'Not found.' }, { status: 404 })
+ return NextResponse.json({ ok: true })
+ } catch (error) {
+ console.error('[media/library delete] failed', error)
+ return NextResponse.json({ error: 'Could not remove.' }, { status: 500 })
+ }
+}
+
+export const PATCH = withLogging('PATCH /api/media/library/[id]', __canvix_patch)
+export const DELETE = withLogging('DELETE /api/media/library/[id]', __canvix_delete)
diff --git a/src/app/api/media/library/library.test.ts b/src/app/api/media/library/library.test.ts
new file mode 100644
index 0000000..df88a8f
--- /dev/null
+++ b/src/app/api/media/library/library.test.ts
@@ -0,0 +1,179 @@
+// Unit tests for the v0.14 (D1) uploads-library routes.
+//
+// Invariants under test:
+// 1. GET lists ONLY the caller's attribution (ownerId or anonKey) —
+// never another account's rows, never the bytes
+// 2. PATCH rename is attribution-scoped: a foreign id is a flat 404
+// (no cross-account existence oracle)
+// 3. DELETE clears keepInLibrary (the row survives for referenced
+// designs) and is equally 404-scoped
+// 4. an attribution-less caller gets an honest empty library
+
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+const queryRaw = vi.hoisted(() => vi.fn())
+const executeRaw = vi.hoisted(() => vi.fn())
+const dbMock = vi.hoisted(() => ({
+ $queryRawUnsafe: queryRaw,
+ $executeRawUnsafe: executeRaw,
+}))
+vi.mock('@/lib/db', () => ({ db: dbMock }))
+
+const getSessionUser = vi.hoisted(() => vi.fn())
+vi.mock('@/lib/auth/session', () => ({ getSessionUser }))
+
+const readAnonToken = vi.hoisted(() => vi.fn())
+vi.mock('@/lib/auth/anon', () => ({
+ readAnonToken,
+ anonKeyHash: (t: string) => `hash(${t})`,
+}))
+
+vi.mock('@/lib/observability', () => ({
+ withLogging: (_name: string, fn: unknown) => fn,
+}))
+
+import { NextRequest } from 'next/server'
+import { GET } from './route'
+import { PATCH, DELETE } from './[id]/route'
+
+const USER_A = { id: 'user-a', username: 'alpha', createdAt: new Date() }
+const USER_B = { id: 'user-b', username: 'beta', createdAt: new Date() }
+
+function getReq(opts: { user?: unknown; anon?: string | null } = {}) {
+ getSessionUser.mockResolvedValue(opts.user ?? null)
+ readAnonToken.mockReturnValue(opts.anon === undefined ? null : opts.anon)
+ return new NextRequest('http://localhost/api/media/library')
+}
+
+function idReq(id: string, opts: { user?: unknown; anon?: string | null; body?: unknown; method?: string } = {}) {
+ getSessionUser.mockResolvedValue(opts.user ?? null)
+ readAnonToken.mockReturnValue(opts.anon === undefined ? null : opts.anon)
+ // no Origin header: a non-browser client per the CSRF guard's curl
+ // rule — the cross-origin REJECTION is covered by its own test below
+ return new NextRequest(`http://localhost/api/media/library/${id}`, {
+ method: opts.method ?? 'PATCH',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(opts.body ?? {}),
+ })
+}
+
+beforeEach(() => {
+ vi.clearAllMocks()
+})
+
+describe('GET /api/media/library', () => {
+ it('returns the owner scoping query results with quota', async () => {
+ queryRaw
+ .mockResolvedValueOnce([
+ { id: 'm1', mime: 'image/png', name: 'logo.png', size: 1000, createdAt: new Date('2026-11-01T00:00:00Z') },
+ ])
+ .mockResolvedValueOnce([{ used: 1000 }])
+ const res = await GET(getReq({ user: USER_A }))
+ expect(res.status).toBe(200)
+ const body = await res.json()
+ expect(body.items).toEqual([
+ { id: 'm1', mime: 'image/png', name: 'logo.png', size: 1000, createdAt: '2026-11-01T00:00:00.000Z' },
+ ])
+ expect(body.usedBytes).toBe(1000)
+ expect(body.quotaBytes).toBe(256 * 1024 * 1024)
+ // the SQL must carry the ownerId scoping, not the anonKey
+ const listSql = queryRaw.mock.calls[0][0] as string
+ expect(listSql).toContain('"ownerId" = $1')
+ expect(listSql).toContain('"keepInLibrary" = true')
+ })
+
+ it('scopes anonymous callers by their anonKey', async () => {
+ queryRaw.mockResolvedValue([]).mockResolvedValue([{ used: 0 }])
+ const res = await GET(getReq({ anon: 'tok-123' }))
+ expect(res.status).toBe(200)
+ const listSql = queryRaw.mock.calls[0][0] as string
+ expect(listSql).toContain('"anonKey" = $2')
+ })
+
+ it('attribution-less caller gets an honest empty library, no SQL', async () => {
+ const res = await GET(getReq({}))
+ expect(res.status).toBe(200)
+ const body = await res.json()
+ expect(body.items).toEqual([])
+ expect(body.usedBytes).toBe(0)
+ expect(queryRaw).not.toHaveBeenCalled()
+ })
+
+ it('never selects the bytes column', async () => {
+ queryRaw.mockResolvedValue([]).mockResolvedValue([{ used: 0 }])
+ await GET(getReq({ user: USER_A }))
+ const listSql = queryRaw.mock.calls[0][0] as string
+ expect(listSql).not.toContain('bytes')
+ })
+})
+
+describe('PATCH /api/media/library/[id] (rename)', () => {
+ it('renames within the attribution', async () => {
+ executeRaw.mockResolvedValueOnce(1)
+ const res = await PATCH(idReq('m1', { user: USER_A, body: { name: 'hero.png' } }), {
+ params: Promise.resolve({ id: 'm1' }),
+ })
+ expect(res.status).toBe(200)
+ const body = await res.json()
+ expect(body.name).toBe('hero.png')
+ expect(executeRaw.mock.calls[0][0]).toContain('SET name = $3')
+ })
+
+ it('foreign id is a flat 404', async () => {
+ executeRaw.mockResolvedValueOnce(0) // USER_A does not own m-foreign
+ const res = await PATCH(idReq('m-foreign', { user: USER_A, body: { name: 'x' } }), {
+ params: Promise.resolve({ id: 'm-foreign' }),
+ })
+ expect(res.status).toBe(404)
+ })
+
+ it('sanitizes the name: path fragments and traversal stripped', async () => {
+ executeRaw.mockResolvedValueOnce(1)
+ const res = await PATCH(
+ idReq('m1', { user: USER_A, body: { name: '../../etc/passwd' } }),
+ { params: Promise.resolve({ id: 'm1' }) },
+ )
+ expect(res.status).toBe(200)
+ expect((await res.json()).name).toBe('etcpasswd')
+ })
+
+ it('empty name is a 400', async () => {
+ const res = await PATCH(idReq('m1', { user: USER_A, body: { name: ' ' } }), {
+ params: Promise.resolve({ id: 'm1' }),
+ })
+ expect(res.status).toBe(400)
+ })
+
+ it('cross-origin PATCH is rejected by the CSRF guard', async () => {
+ getSessionUser.mockResolvedValue(USER_A)
+ readAnonToken.mockReturnValue(null)
+ const req = new NextRequest('http://localhost/api/media/library/m1', {
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json', Origin: 'http://evil.example' },
+ body: JSON.stringify({ name: 'x' }),
+ })
+ const res = await PATCH(req, { params: Promise.resolve({ id: 'm1' }) })
+ expect(res.status).toBe(403)
+ })
+})
+
+describe('DELETE /api/media/library/[id]', () => {
+ it('clears keepInLibrary (row survives for referenced designs)', async () => {
+ executeRaw.mockResolvedValueOnce(1)
+ const res = await DELETE(idReq('m1', { user: USER_A, method: 'DELETE' }), {
+ params: Promise.resolve({ id: 'm1' }),
+ })
+ expect(res.status).toBe(200)
+ const sql = executeRaw.mock.calls[0][0] as string
+ expect(sql).toContain('SET "keepInLibrary" = false')
+ expect(sql).not.toContain('DELETE FROM')
+ })
+
+ it('foreign id is a flat 404', async () => {
+ executeRaw.mockResolvedValueOnce(0)
+ const res = await DELETE(idReq('m-foreign', { user: USER_B, method: 'DELETE' }), {
+ params: Promise.resolve({ id: 'm-foreign' }),
+ })
+ expect(res.status).toBe(404)
+ })
+})
diff --git a/src/app/api/media/library/route.ts b/src/app/api/media/library/route.ts
new file mode 100644
index 0000000..ef29d9f
--- /dev/null
+++ b/src/app/api/media/library/route.ts
@@ -0,0 +1,71 @@
+import { NextRequest, NextResponse } from 'next/server'
+import { db } from '@/lib/db'
+import { getSessionUser } from '@/lib/auth/session'
+import { anonKeyHash, readAnonToken } from '@/lib/auth/anon'
+import { withLogging } from '@/lib/observability'
+
+export const runtime = 'nodejs'
+
+// ── v0.14 (D1): the persistent uploads library ───────────────
+// GET /api/media/library — the caller's kept uploads (images, audio,
+// video), projection only (never the bytes):
+//
+// { items: [{ id, mime, name, size, createdAt }], usedBytes, quotaBytes }
+//
+// Attribution mirrors the media store itself: signed-in → ownerId,
+// otherwise the canvix_anon cookie → anonKey. Anonymous visitors get
+// their own session library (uploads survive reloads in that browser);
+// signing in claims the rows (see src/lib/auth/claim-media.ts), so the
+// library follows the account across devices.
+
+const QUOTA_MB = Math.max(8, Number(process.env.CANVIX_UPLOAD_QUOTA_MB ?? 256))
+const LIST_LIMIT = 100
+
+async function __canvix_get(req: NextRequest) {
+ try {
+ const user = await getSessionUser(req)
+ const token = readAnonToken(req)
+ const ownerId = user?.id ?? null
+ const anonKey = user ? null : token ? anonKeyHash(token) : null
+
+ if (!ownerId && !anonKey) {
+ // no attribution at all (fresh browser, nothing uploaded yet) —
+ // an honest empty library rather than an error
+ return NextResponse.json({ items: [], usedBytes: 0, quotaBytes: QUOTA_MB * 1024 * 1024 })
+ }
+
+ const items = await db.$queryRawUnsafe<
+ { id: string; mime: string; name: string | null; size: number; createdAt: Date }[]
+ >(
+ `SELECT id, mime, name, size, "createdAt" FROM "Media"
+ WHERE "keepInLibrary" = true AND "finalizedAt" IS NOT NULL AND (
+ ("ownerId" = $1 AND $1 IS NOT NULL) OR ("anonKey" = $2 AND $2 IS NOT NULL))
+ ORDER BY "createdAt" DESC LIMIT ${LIST_LIMIT}`,
+ ownerId,
+ anonKey,
+ )
+ const usedRows = await db.$queryRawUnsafe<{ used: bigint | number }[]>(
+ `SELECT COALESCE(SUM(size), 0)::bigint AS used FROM "Media"
+ WHERE "keepInLibrary" = true AND "finalizedAt" IS NOT NULL AND (
+ ("ownerId" = $1 AND $1 IS NOT NULL) OR ("anonKey" = $2 AND $2 IS NOT NULL))`,
+ ownerId,
+ anonKey,
+ )
+ return NextResponse.json({
+ items: items.map((m) => ({
+ id: m.id,
+ mime: m.mime,
+ name: m.name,
+ size: m.size,
+ createdAt: m.createdAt,
+ })),
+ usedBytes: Number(usedRows[0]?.used ?? 0),
+ quotaBytes: QUOTA_MB * 1024 * 1024,
+ })
+ } catch (error) {
+ console.error('[media/library] failed', error)
+ return NextResponse.json({ error: 'Could not load the uploads library.' }, { status: 500 })
+ }
+}
+
+export const GET = withLogging('GET /api/media/library', __canvix_get)
diff --git a/src/app/api/media/route.ts b/src/app/api/media/route.ts
index e488e9d..f50a009 100644
--- a/src/app/api/media/route.ts
+++ b/src/app/api/media/route.ts
@@ -19,7 +19,16 @@ export const maxDuration = 30
/** default cap: 32 MB per file (audio usually ≤ 8 MB, video ≤ 32 MB) */
const MAX_MEDIA_MB = Math.max(1, Number(process.env.CANVIX_MAX_MEDIA_MB ?? 32))
-const ALLOWED_PREFIXES = ['audio/', 'video/']
+// v0.14 (D1): images join audio/video in the store — the uploads
+// library needs server-side bytes (survive reload, follow the account,
+// sha256-deduped). Document embedding (data URLs) remains available to
+// plugins/legacy designs; new uploads land here.
+const ALLOWED_PREFIXES = ['audio/', 'video/', 'image/']
+
+/** library quota — the bytes an attribution (account or anon cookie)
+ * may keep in the library. Self-hosters can raise it freely. */
+const QUOTA_MB = Math.max(8, Number(process.env.CANVIX_UPLOAD_QUOTA_MB ?? 256))
+const QUOTA_BYTES = QUOTA_MB * 1024 * 1024
async function __canvix_post(req: NextRequest) {
if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })
@@ -28,9 +37,12 @@ async function __canvix_post(req: NextRequest) {
const limit = checkRateLimit(req, 'media:init')
if (!limit.ok) return rateLimitResponse(limit)
try {
- const body = (await req.json().catch(() => ({}))) as { mime?: unknown; size?: unknown }
+ const body = (await req.json().catch(() => ({}))) as { mime?: unknown; size?: unknown; name?: unknown }
const mime = typeof body.mime === 'string' ? body.mime.slice(0, 100) : ''
const size = Number(body.size)
+ // v0.14 (D1): original filename for the library listing — strip
+ // path fragments browsers sometimes send, cap hard
+ const name = typeof body.name === 'string' ? body.name.split(/[\\/]/).pop()!.slice(0, 200) || null : null
if (!ALLOWED_PREFIXES.some((p) => mime.startsWith(p))) {
return NextResponse.json({ error: 'Only audio and video files are supported.' }, { status: 415 })
@@ -53,6 +65,28 @@ async function __canvix_post(req: NextRequest) {
.deleteMany({ where: { finalizedAt: null, createdAt: { lt: new Date(Date.now() - 86_400_000) } } })
.catch(() => { /* GC is best-effort */ })
+ // v0.14 (D1): quota — the attribution's kept-library bytes + this
+ // upload must fit. In-flight (not yet finalized) rows count too, so
+ // parallel uploads can't sail past the cap together.
+ const usedRows = await db.$queryRawUnsafe<{ used: bigint | number }[]>(
+ `SELECT COALESCE(SUM(size), 0)::bigint AS used FROM "Media"
+ WHERE ("keepInLibrary" = true OR "finalizedAt" IS NULL) AND (
+ ("ownerId" = $1 AND $1 IS NOT NULL) OR ("anonKey" = $2 AND $2 IS NOT NULL))`,
+ ownerId,
+ anonKey,
+ )
+ const used = Number(usedRows[0]?.used ?? 0)
+ if (used + Math.round(size) > QUOTA_BYTES) {
+ return NextResponse.json(
+ {
+ error: `Uploads library is full (${(used / 1024 / 1024).toFixed(0)} of ${QUOTA_MB} MB used). Remove files from Uploads to free space.`,
+ quotaBytes: QUOTA_BYTES,
+ usedBytes: used,
+ },
+ { status: 413 },
+ )
+ }
+
const media = await db.media.create({
data: {
mime,
@@ -60,6 +94,7 @@ async function __canvix_post(req: NextRequest) {
bytes: new Uint8Array(0),
ownerId,
anonKey,
+ name,
},
select: { id: true },
})
diff --git a/src/components/editor/ExportDialog.tsx b/src/components/editor/ExportDialog.tsx
index 63e7955..bdc976f 100644
--- a/src/components/editor/ExportDialog.tsx
+++ b/src/components/editor/ExportDialog.tsx
@@ -100,7 +100,11 @@ export function ExportDialog({ open, onOpenChange }: { open: boolean; onOpenChan
// embedded; missing plugins degrade to placeholder cards.
const pagesToExport = allPages ? pages : [pages[currentPage]]
await primePluginRenders(collectPluginElements(pagesToExport), 'export')
- const svgs = exportDesignToSVGs(pagesToExport, canvasBridge.pageWidth, canvasBridge.pageHeight)
+ // v0.14 (D1): media-store images inline to data URLs so the
+ // file is portable (deep-copy inside — the live pages untouched)
+ const { inlineMediaImages } = await import('@/lib/svg-export')
+ const inlined = await inlineMediaImages(pagesToExport)
+ const svgs = exportDesignToSVGs(inlined, canvasBridge.pageWidth, canvasBridge.pageHeight)
for (let k = 0; k < svgs.length; k++) {
const suffix = svgs.length > 1 ? `-page-${(allPages ? 0 : currentPage) + k + 1}` : ''
downloadSVG(svgs[k], `${base}${suffix}.svg`)
diff --git a/src/components/editor/add-element.ts b/src/components/editor/add-element.ts
index c9a43d1..b0737e5 100644
--- a/src/components/editor/add-element.ts
+++ b/src/components/editor/add-element.ts
@@ -383,3 +383,88 @@ export async function addVideoFromFile(
})
)
}
+
+// ── v0.14 (D1): the persistent uploads library ──────────────
+
+/**
+ * Upload an image through the media store (NOT document embedding):
+ * the original bytes land server-side — sha256-deduped within the
+ * account, quota-counted, and listed in the Uploads panel from the
+ * database. Returns the element-facing src + natural dimensions.
+ */
+export async function uploadImageToLibrary(
+ file: File,
+ onProgress?: (ratio: number) => void,
+): Promise<{ id: string; src: string; w: number; h: number }> {
+ if (!file.type.startsWith('image/')) throw new Error('Not an image')
+ const { uploadMediaFile, mediaSrc } = await import('@/lib/media/media-client')
+ const handle = await uploadMediaFile(file, onProgress)
+ const { w, h } = await probeImageSize(mediaSrc(handle.id))
+ return { id: handle.id, src: mediaSrc(handle.id), w, h }
+}
+
+/** natural dimensions of an image URL (same-origin media or data). */
+export function probeImageSize(src: string): Promise<{ w: number; h: number }> {
+ return new Promise((resolve) => {
+ const img = new window.Image()
+ img.onload = () => resolve({ w: img.naturalWidth || 500, h: img.naturalHeight || 500 })
+ img.onerror = () => resolve({ w: 500, h: 500 })
+ img.src = src
+ })
+}
+
+/** Insert an image that already lives in the media store (library). */
+export function addImageFromLibrary(id: string, w: number, h: number) {
+ addImageFromSrc(`/api/media/${id}`, w, h)
+}
+
+/**
+ * Insert audio that already lives in the media store — the element
+ * references the served URL; duration is probed from the fetched blob
+ * (the store keeps bytes, not metadata).
+ */
+export async function addAudioFromLibrary(id: string, name: string): Promise<void> {
+ const { analyzeAudioFile } = await import('@/lib/media/decode')
+ const { createAudioElement } = await import('@/lib/types')
+ const blob = await fetch(`/api/media/${id}`).then((r) => {
+ if (!r.ok) throw new Error('Media unavailable')
+ return r.blob()
+ })
+ const analysis = await analyzeAudioFile(new File([blob], name || 'audio', { type: blob.type }))
+ const store = useEditorStore.getState()
+ const w = Math.min(520, Math.max(360, store.width * 0.55))
+ const pos = placement(w, 96, store.pages[store.currentPage].elements.length)
+ store.addElement(
+ createAudioElement(`/api/media/${id}`, (name || 'Audio').replace(/\.[^.]+$/, '').slice(0, 60), analysis.duration, {
+ ...pos,
+ width: Math.round(w),
+ height: 96,
+ peaks: analysis.peaks,
+ bpm: analysis.bpm,
+ beats: analysis.beats,
+ })
+ )
+}
+
+/** Insert video that already lives in the media store (library). */
+export async function addVideoFromLibrary(id: string, name: string): Promise<void> {
+ const { probeVideoFile } = await import('@/lib/media/decode')
+ const { createVideoElement } = await import('@/lib/types')
+ const blob = await fetch(`/api/media/${id}`).then((r) => {
+ if (!r.ok) throw new Error('Media unavailable')
+ return r.blob()
+ })
+ const probe = await probeVideoFile(new File([blob], name || 'video', { type: blob.type }))
+ const store = useEditorStore.getState()
+ const maxW = store.width * 0.7
+ const w = Math.round(Math.min(maxW, Math.max(200, probe.naturalWidth || 480)))
+ const h = Math.round(probe.naturalWidth ? (w * probe.naturalHeight) / probe.naturalWidth : w * 0.5625)
+ const pos = placement(w, h, store.pages[store.currentPage].elements.length)
+ store.addElement(
+ createVideoElement(`/api/media/${id}`, probe.poster, probe.duration, probe.naturalWidth, probe.naturalHeight, {
+ ...pos,
+ width: w,
+ height: h,
+ })
+ )
+}
diff --git a/src/components/editor/panels/UploadsPanel.tsx b/src/components/editor/panels/UploadsPanel.tsx
index ecbf675..2071ce3 100644
--- a/src/components/editor/panels/UploadsPanel.tsx
+++ b/src/components/editor/panels/UploadsPanel.tsx
@@ -1,35 +1,36 @@
'use client'
-import { useRef, useState } from 'react'
-import { Upload, Trash2, ImageIcon, Replace, Wallpaper, Music, Film, Loader2 } from 'lucide-react'
-import { addImageFromFile, addImageFromSrc, readImageFile, replaceSelectedImage, addAudioFromFile, addVideoFromFile } from '../add-element'
+import { useCallback, useEffect, useRef, useState } from 'react'
+import { Upload, Trash2, ImageIcon, Replace, Wallpaper, Music, Film, Loader2, Pencil } from 'lucide-react'
+import { replaceSelectedImage, addImageFromSrc, addAudioFromLibrary, addVideoFromLibrary, uploadImageToLibrary, addAudioFromFile, addVideoFromFile, probeImageSize } from '../add-element'
import { createImageElement } from '@/lib/types'
import { useEditorStore } from '@/store/editor-store'
import { toast } from '@/hooks/use-toast'
import { cn } from '@/lib/utils'
+import { fetchLibrary, renameLibraryItem, removeLibraryItem, formatBytes, type LibraryItem } from '@/lib/media/library-client'
-// session-level upload gallery (per editor session, not persisted)
-interface UploadItem {
- src: string
- w: number
- h: number
-}
-
-const uploadGallery: { items: UploadItem[] } = { items: [] }
+// ── v0.14 (D1): the persistent uploads library ──────────────
+// The panel reads the media store (GET /api/media/library) — uploads
+// survive reload, follow the account (anon rows are claimed on login),
+// and are sha256-deduped server-side. Images insert by served URL;
+// audio/video keep their upload-time analysis by probing the blob.
+// Removing an item only clears keepInLibrary: designs already using
+// it keep working (the GC protects referenced rows).
-/** v0.11: in-flight media uploads (audio/video) shown with progress */
interface MediaUpload {
key: string
name: string
- kind: 'audio' | 'video'
+ kind: 'image' | 'audio' | 'video'
ratio: number
failed?: boolean
}
export function UploadsPanel() {
const fileRef = useRef<HTMLInputElement>(null)
- const [, force] = useState(0)
const [mediaUploads, setMediaUploads] = useState<MediaUpload[]>([])
+ const [items, setItems] = useState<LibraryItem[] | null>(null)
+ const [quota, setQuota] = useState<{ used: number; total: number } | null>(null)
+ const [renaming, setRenaming] = useState<{ id: string; value: string } | null>(null)
const selectedIds = useEditorStore((s) => s.selectedIds)
const pages = useEditorStore((s) => s.pages)
const currentPage = useEditorStore((s) => s.currentPage)
@@ -37,37 +38,68 @@ export function UploadsPanel() {
(e) => selectedIds.includes(e.id) && e.type === 'image'
)
+ const refresh = useCallback(async () => {
+ try {
+ const lib = await fetchLibrary()
+ setItems(lib.items)
+ setQuota({ used: lib.usedBytes, total: lib.quotaBytes })
+ } catch {
+ // offline / 5xx — keep whatever we had; the panel is non-critical
+ }
+ }, [])
+
+ useEffect(() => {
+ // async state updates live in the .then — never synchronously
+ // inside the effect body (react-hooks/set-state-in-effect)
+ let cancelled = false
+ void fetchLibrary()
+ .then((lib) => {
+ if (cancelled) return
+ setItems(lib.items)
+ setQuota({ used: lib.usedBytes, total: lib.quotaBytes })
+ })
+ .catch(() => {
+ // offline / 5xx — the panel shows its empty state
+ })
+ return () => {
+ cancelled = true
+ }
+ }, [])
+
const handleFiles = async (files: FileList | null) => {
if (!files?.length) return
- let ok = 0
- const media: File[] = []
for (const file of Array.from(files)) {
- if (file.type.startsWith('audio/') || file.type.startsWith('video/')) {
- media.push(file)
- continue
- }
- try {
- const { src, w, h } = await readImageFile(file)
- uploadGallery.items.unshift({ src, w, h })
- await addImageFromFile(file)
- ok += 1
- } catch {
- // ignore this file
- }
- }
- if (ok > 0) toast({ title: `${ok} image${ok > 1 ? 's' : ''} uploaded` })
-
- // v0.11: audio/video → media store (chunked) + analysis, with progress
- for (const file of media) {
- const kind: 'audio' | 'video' = file.type.startsWith('audio/') ? 'audio' : 'video'
+ const kind = file.type.startsWith('image/')
+ ? 'image'
+ : file.type.startsWith('audio/')
+ ? 'audio'
+ : file.type.startsWith('video/')
+ ? 'video'
+ : null
+ if (!kind) continue
const key = `${file.name}-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`
setMediaUploads((prev) => [...prev, { key, name: file.name, kind, ratio: 0 }])
try {
- const add = kind === 'audio' ? addAudioFromFile : addVideoFromFile
- await add(file, (ratio) => {
- setMediaUploads((prev) => prev.map((u) => (u.key === key ? { ...u, ratio } : u)))
- })
- toast({ title: kind === 'audio' ? 'Audio added — open Preview to play it' : 'Video added — open Preview to play it' })
+ if (kind === 'image') {
+ // v0.14 (D1): images go to the media store — server bytes,
+ // dedupe, quota, library persistence (not document embedding)
+ const { src, w, h } = await uploadImageToLibrary(file, (ratio) => {
+ setMediaUploads((prev) => prev.map((u) => (u.key === key ? { ...u, ratio } : u)))
+ })
+ if (hasImageSelected) {
+ replaceSelectedImage(src, w, h)
+ toast({ title: 'Image replaced' })
+ } else {
+ addImageFromSrc(src, w, h)
+ toast({ title: 'Image uploaded to your library' })
+ }
+ } else {
+ const add = kind === 'audio' ? addAudioFromFile : addVideoFromFile
+ await add(file, (ratio) => {
+ setMediaUploads((prev) => prev.map((u) => (u.key === key ? { ...u, ratio } : u)))
+ })
+ toast({ title: kind === 'audio' ? 'Audio added — open Preview to play it' : 'Video added — open Preview to play it' })
+ }
} catch (err) {
setMediaUploads((prev) => prev.map((u) => (u.key === key ? { ...u, failed: true } : u)))
toast({
@@ -79,32 +111,43 @@ export function UploadsPanel() {
setTimeout(() => setMediaUploads((prev) => prev.filter((u) => u.key !== key)), 30_000)
}
}
+ void refresh()
}
- const applyGalleryItem = (item: UploadItem) => {
- if (hasImageSelected) {
- replaceSelectedImage(item.src, item.w, item.h)
- toast({ title: 'Image replaced' })
- } else {
- addImageFromSrc(item.src, item.w, item.h)
+ const insertItem = async (item: LibraryItem) => {
+ try {
+ if (item.mime.startsWith('image/')) {
+ const { w, h } = await probeImageSize(`/api/media/${item.id}`)
+ if (hasImageSelected) {
+ replaceSelectedImage(`/api/media/${item.id}`, w, h)
+ toast({ title: 'Image replaced' })
+ } else {
+ addImageFromSrc(`/api/media/${item.id}`, w, h)
+ }
+ } else if (item.mime.startsWith('audio/')) {
+ await addAudioFromLibrary(item.id, item.name ?? 'Audio')
+ } else if (item.mime.startsWith('video/')) {
+ await addVideoFromLibrary(item.id, item.name ?? 'Video')
+ }
+ } catch {
+ toast({ title: 'Could not insert this file', variant: 'destructive' })
}
}
- const setAsBackground = (item: UploadItem) => {
- // full-bleed cover image via a page-sized image element locked behind everything
+ const setAsBackground = async (item: LibraryItem) => {
+ const { w, h } = await probeImageSize(`/api/media/${item.id}`)
const state = useEditorStore.getState()
- const ratio = Math.max(state.width / item.w, state.height / item.h)
- const w = Math.round(item.w * ratio)
- const h = Math.round(item.h * ratio)
+ const ratio = Math.max(state.width / w, state.height / h)
+ const bw = Math.round(w * ratio)
+ const bh = Math.round(h * ratio)
state.addElement(
- createImageElement(item.src, item.w, item.h, {
- x: Math.round((state.width - w) / 2),
- y: Math.round((state.height - h) / 2),
- width: w,
- height: h,
+ createImageElement(`/api/media/${item.id}`, w, h, {
+ x: Math.round((state.width - bw) / 2),
+ y: Math.round((state.height - bh) / 2),
+ width: bw,
+ height: bh,
})
)
- // send to back + lock — a canva background behaves non-interactive
const el = useEditorStore.getState().pages[useEditorStore.getState().currentPage].elements.at(-1)
if (el) {
state.moveLayer(el.id, 'back')
@@ -113,12 +156,46 @@ export function UploadsPanel() {
toast({ title: 'Set as background' })
}
+ const commitRename = async () => {
+ if (!renaming) return
+ const { id, value } = renaming
+ setRenaming(null)
+ const trimmed = value.trim().slice(0, 200)
+ if (!trimmed) return
+ const prev = items
+ setItems((cur) => (cur ?? []).map((i) => (i.id === id ? { ...i, name: trimmed } : i)))
+ try {
+ await renameLibraryItem(id, trimmed)
+ } catch {
+ setItems(prev)
+ toast({ title: 'Could not rename', variant: 'destructive' })
+ }
+ }
+
+ const removeItem = async (item: LibraryItem) => {
+ const prev = items
+ const prevQuota = quota
+ setItems((cur) => (cur ?? []).filter((i) => i.id !== item.id))
+ try {
+ await removeLibraryItem(item.id)
+ if (prevQuota) setQuota({ ...prevQuota, used: Math.max(0, prevQuota.used - item.size) })
+ toast({
+ title: 'Removed from your library',
+ description: 'Designs already using this file keep working.',
+ })
+ } catch {
+ setItems(prev)
+ setQuota(prevQuota)
+ toast({ title: 'Could not remove', variant: 'destructive' })
+ }
+ }
+
return (
<div className="flex flex-col h-full bg-[#16181D] text-[#EDEEF2]">
<div className="px-4 pt-4 pb-3 border-b border-white/[0.07] shrink-0">
<h3 className="font-bold text-sm">Uploads</h3>
<p className="text-xs text-white/50 mt-0.5">
- {hasImageSelected ? 'Click a file to replace the selected image.' : 'Images stay in this browser session.'}
+ {hasImageSelected ? 'Click a file to replace the selected image.' : 'Your files follow your account.'}
</p>
{hasImageSelected && (
<div className="mt-2 inline-flex items-center gap-1.5 text-[11px] font-semibold text-[#02C0CC] bg-[#02C0CC]/10 border border-[#02C0CC]/25 rounded-full px-2.5 py-1">
@@ -141,7 +218,7 @@ export function UploadsPanel() {
>
<Upload size={22} />
<span className="text-sm font-medium text-white/80">Click or drag files here</span>
- <span className="text-xs">PNG, JPG, SVG, GIF — plus MP3/WAV audio & MP4/WebM video</span>
+ <span className="text-xs">PNG, JPG, SVG, GIF — plus MP3/WAV audio &amp; MP4/WebM video</span>
</button>
<input
ref={fileRef}
@@ -158,7 +235,7 @@ export function UploadsPanel() {
{mediaUploads.length > 0 && (
<div className="mt-4 flex flex-col gap-2">
- <h4 className="text-xs font-semibold text-white/50">Media uploads</h4>
+ <h4 className="text-xs font-semibold text-white/50">Uploading</h4>
{mediaUploads.map((u) => (
<div
key={u.key}
@@ -190,57 +267,107 @@ export function UploadsPanel() {
{!u.failed && <span className="text-[10px] text-white/40 shrink-0 tabular-nums">{Math.round(u.ratio * 100)}%</span>}
</div>
))}
- <p className="text-[11px] text-white/35 leading-relaxed">
- Audio is analyzed for tempo &amp; beats (Beat Sync). Media plays in Preview / Present mode.
- </p>
</div>
)}
- {uploadGallery.items.length > 0 ? (
+ {items === null ? (
+ <div className="mt-6 flex flex-col items-center py-6 text-white/35">
+ <Loader2 size={22} className="animate-spin" />
+ <p className="text-xs mt-2.5">Loading your library…</p>
+ </div>
+ ) : items.length > 0 ? (
<>
<div className="flex items-center justify-between mt-6 mb-2">
- <h4 className="text-xs font-semibold text-white/50">Session uploads</h4>
- <button
- className="text-xs text-white/50 hover:text-red-400 inline-flex items-center gap-1"
- onClick={() => {
- uploadGallery.items = []
- force((n) => n + 1)
- }}
- >
- <Trash2 size={12} /> Clear
- </button>
+ <h4 className="text-xs font-semibold text-white/50">Your library</h4>
+ {quota && (
+ <span className="text-[10px] text-white/40 tabular-nums">
+ {formatBytes(quota.used)} of {formatBytes(quota.total)}
+ </span>
+ )}
</div>
<div className="grid grid-cols-3 gap-2">
- {uploadGallery.items.map((item, i) => (
- <div key={i} className="group relative">
- <button
- onClick={() => applyGalleryItem(item)}
- className={cn(
- 'w-full rounded-lg overflow-hidden border transition-all aspect-square bg-[#0F1015]',
- hasImageSelected
- ? 'border-[#02C0CC]/60 hover:border-[#02C0CC]'
- : 'border-white/10 hover:border-[#7630D7]'
+ {items.map((item) => {
+ const isImage = item.mime.startsWith('image/')
+ const isAudio = item.mime.startsWith('audio/')
+ return (
+ <div key={item.id} className="group relative">
+ {renaming?.id === item.id ? (
+ <input
+ autoFocus
+ value={renaming.value}
+ onChange={(e) => setRenaming({ id: item.id, value: e.target.value })}
+ onBlur={() => void commitRename()}
+ onKeyDown={(e) => {
+ if (e.key === 'Enter') void commitRename()
+ if (e.key === 'Escape') setRenaming(null)
+ }}
+ className="w-full rounded-lg border border-[#02C0CC]/60 bg-[#0F1015] px-2 py-1.5 text-xs text-white outline-none"
+ aria-label="Rename file"
+ />
+ ) : (
+ <button
+ onClick={() => void insertItem(item)}
+ className={cn(
+ 'w-full rounded-lg overflow-hidden border transition-all aspect-square bg-[#0F1015]',
+ hasImageSelected
+ ? 'border-[#02C0CC]/60 hover:border-[#02C0CC]'
+ : 'border-white/10 hover:border-[#7630D7]'
+ )}
+ title={item.name ?? undefined}
+ aria-label={hasImageSelected ? `Replace selected image with ${item.name ?? 'file'}` : `Add ${item.name ?? 'file'} to canvas`}
+ >
+ {isImage ? (
+ <img src={`/api/media/${item.id}`} alt={item.name ?? 'Uploaded'} className="w-full h-full object-cover" loading="lazy" />
+ ) : (
+ <span className="w-full h-full flex flex-col items-center justify-center gap-1.5 text-white/45">
+ {isAudio ? <Music size={20} strokeWidth={1.5} /> : <Film size={20} strokeWidth={1.5} />}
+ <span className="text-[9px] px-1 text-center leading-tight break-all line-clamp-2">
+ {(item.name ?? 'file').replace(/\.[^.]+$/, '')}
+ </span>
+ </span>
+ )}
+ </button>
)}
- aria-label={hasImageSelected ? 'Replace selected image' : 'Add uploaded image to canvas'}
- >
- <img src={item.src} alt="Uploaded" className="w-full h-full object-cover" />
- </button>
- <button
- onClick={() => setAsBackground(item)}
- className="absolute bottom-1 right-1 h-7 w-7 rounded-lg bg-black/60 backdrop-blur text-white/90 hidden group-hover:flex items-center justify-center hover:bg-black/80"
- title="Set image as background"
- aria-label="Set image as background"
- >
- <Wallpaper size={13} />
- </button>
- </div>
- ))}
+ <div className="absolute top-1 right-1 hidden group-hover:flex flex-col gap-1">
+ <button
+ onClick={() => setRenaming({ id: item.id, value: item.name ?? '' })}
+ className="h-6 w-6 rounded-lg bg-black/60 backdrop-blur text-white/90 items-center justify-center hover:bg-black/80 flex"
+ title="Rename"
+ aria-label={`Rename ${item.name ?? 'file'}`}
+ >
+ <Pencil size={11} />
+ </button>
+ <button
+ onClick={() => void removeItem(item)}
+ className="h-6 w-6 rounded-lg bg-black/60 backdrop-blur text-white/90 items-center justify-center hover:bg-red-600/80 flex"
+ title="Remove from library"
+ aria-label={`Remove ${item.name ?? 'file'} from library`}
+ >
+ <Trash2 size={11} />
+ </button>
+ </div>
+ {isImage && (
+ <button
+ onClick={() => void setAsBackground(item)}
+ className="absolute bottom-1 left-1 h-7 w-7 rounded-lg bg-black/60 backdrop-blur text-white/90 hidden group-hover:flex items-center justify-center hover:bg-black/80"
+ title="Set image as background"
+ aria-label="Set image as background"
+ >
+ <Wallpaper size={13} />
+ </button>
+ )}
+ </div>
+ )
+ })}
</div>
+ <p className="mt-3 text-[11px] text-white/35 leading-relaxed">
+ Files live in your account — insert them in any design. Removing a file never breaks designs using it.
+ </p>
</>
) : (
<div className="mt-6 flex flex-col items-center py-6 text-white/35">
<ImageIcon size={28} strokeWidth={1.4} />
- <p className="text-xs mt-2.5 text-center leading-relaxed">No uploads yet.<br />Your images will appear here.</p>
+ <p className="text-xs mt-2.5 text-center leading-relaxed">No uploads yet.<br />Your files will appear here.</p>
</div>
)}
</div>
diff --git a/src/lib/auth/claim-media.test.ts b/src/lib/auth/claim-media.test.ts
new file mode 100644
index 0000000..333ff12
--- /dev/null
+++ b/src/lib/auth/claim-media.test.ts
@@ -0,0 +1,49 @@
+// Unit tests for claimAnonMedia (v0.14 D1): anonymous uploads follow
+// the account on login/register. Scoping must be exact — ownerId IS
+// NULL (never re-claim another account's rows) AND anonKey = this
+// browser's hash. Failures are swallowed (best-effort).
+
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+const updateMany = vi.hoisted(() => vi.fn())
+const dbMock = vi.hoisted(() => ({ media: { updateMany } }))
+vi.mock('@/lib/db', () => ({ db: dbMock }))
+
+const readAnonToken = vi.hoisted(() => vi.fn())
+vi.mock('@/lib/auth/anon', () => ({
+ readAnonToken,
+ anonKeyHash: (t: string) => `hash(${t})`,
+}))
+
+import { NextRequest } from 'next/server'
+import { claimAnonMedia } from './claim-media'
+
+beforeEach(() => {
+ vi.clearAllMocks()
+})
+
+function req(anon: string | null) {
+ readAnonToken.mockReturnValue(anon)
+ return new NextRequest('http://localhost/api/auth/login')
+}
+
+describe('claimAnonMedia (v0.14 D1)', () => {
+ it('claims this browser\'s anon uploads into the account', async () => {
+ updateMany.mockResolvedValueOnce({ count: 3 })
+ await claimAnonMedia(req('tok-1'), 'user-9')
+ expect(updateMany).toHaveBeenCalledTimes(1)
+ const arg = updateMany.mock.calls[0][0]
+ expect(arg.where).toEqual({ ownerId: null, anonKey: 'hash(tok-1)' })
+ expect(arg.data).toEqual({ ownerId: 'user-9', anonKey: null })
+ })
+
+ it('no anon cookie → no-op', async () => {
+ await claimAnonMedia(req(null), 'user-9')
+ expect(updateMany).not.toHaveBeenCalled()
+ })
+
+ it('DB failure is swallowed (login must not fail)', async () => {
+ updateMany.mockRejectedValueOnce(new Error('db down'))
+ await expect(claimAnonMedia(req('tok-2'), 'user-9')).resolves.toBeUndefined()
+ })
+})
diff --git a/src/lib/auth/claim-media.ts b/src/lib/auth/claim-media.ts
new file mode 100644
index 0000000..84563ad
--- /dev/null
+++ b/src/lib/auth/claim-media.ts
@@ -0,0 +1,30 @@
+// ─────────────────────────────────────────────────────────────
+// claim-media — anonymous uploads follow the account (v0.14, D1).
+//
+// The media store stamps attribution exactly like designs: signed-out
+// uploads carry the canvix_anon cookie hash. Signing in (or registering)
+// claims those rows into the account, so the uploads library is visible
+// from every device after login — the D1 acceptance criterion.
+//
+// Unlike design adoption there is no eligibility subtlety: the anon key
+// is scoped to this browser, so claiming on login can never sweep
+// another person's uploads. Failures are swallowed (best-effort — the
+// rows simply stay anonymous, nothing breaks).
+// ─────────────────────────────────────────────────────────────
+
+import type { NextRequest } from 'next/server'
+import { db } from '@/lib/db'
+import { anonKeyHash, readAnonToken } from '@/lib/auth/anon'
+
+export async function claimAnonMedia(req: NextRequest, userId: string): Promise<void> {
+ try {
+ const token = readAnonToken(req)
+ if (!token) return
+ await db.media.updateMany({
+ where: { ownerId: null, anonKey: anonKeyHash(token) },
+ data: { ownerId: userId, anonKey: null },
+ })
+ } catch {
+ // best-effort: unclaimed media stays anonymous and still works
+ }
+}
diff --git a/src/lib/media/library-client.ts b/src/lib/media/library-client.ts
new file mode 100644
index 0000000..8f1191a
--- /dev/null
+++ b/src/lib/media/library-client.ts
@@ -0,0 +1,45 @@
+// ─────────────────────────────────────────────────────────────
+// library-client — the uploads library API surface (v0.14, D1).
+// Thin typed fetchers; the panel owns all state. Never touches the
+// bytes — listing is projection-only by design.
+// ─────────────────────────────────────────────────────────────
+
+export interface LibraryItem {
+ id: string
+ mime: string
+ name: string | null
+ size: number
+ createdAt: string
+}
+
+export interface LibraryResponse {
+ items: LibraryItem[]
+ usedBytes: number
+ quotaBytes: number
+}
+
+export async function fetchLibrary(): Promise<LibraryResponse> {
+ const res = await fetch('/api/media/library', { cache: 'no-store' })
+ if (!res.ok) throw new Error(`Library unavailable (${res.status})`)
+ return (await res.json()) as LibraryResponse
+}
+
+export async function renameLibraryItem(id: string, name: string): Promise<void> {
+ const res = await fetch(`/api/media/library/${encodeURIComponent(id)}`, {
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ name }),
+ })
+ if (!res.ok) throw new Error('Could not rename.')
+}
+
+export async function removeLibraryItem(id: string): Promise<void> {
+ const res = await fetch(`/api/media/library/${encodeURIComponent(id)}`, { method: 'DELETE' })
+ if (!res.ok) throw new Error('Could not remove.')
+}
+
+export function formatBytes(bytes: number): string {
+ if (bytes < 1024) return `${bytes} B`
+ if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`
+ return `${(bytes / 1024 / 1024).toFixed(1)} MB`
+}
diff --git a/src/lib/svg-export-media.test.ts b/src/lib/svg-export-media.test.ts
new file mode 100644
index 0000000..d170f89
--- /dev/null
+++ b/src/lib/svg-export-media.test.ts
@@ -0,0 +1,86 @@
+// Unit tests for the v0.14 (D1) media-image export path:
+// 1. safeHref accepts media-store URLs (first-party, same-origin)
+// 2. inlineMediaImages rewrites media srcs to data URLs on a COPY —
+// the live pages object is never mutated
+// 3. failed fetches degrade honestly: the relative src survives
+// (safeHref still accepts it; the exported file shows a broken
+// image rather than silently losing content)
+// 4. non-media srcs (data:, https:) pass through untouched
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+import { safeHref, inlineMediaImages } from './svg-export'
+
+function pageWith(elements: unknown[]): { elements: unknown[] } {
+ return { elements }
+}
+
+describe('safeHref (v0.14 D1)', () => {
+ it('accepts data, https and media-store srcs', () => {
+ expect(safeHref('data:image/png;base64,AAAA')).toBe('data:image/png;base64,AAAA')
+ expect(safeHref('https://example.com/a.png')).toBe('https://example.com/a.png')
+ expect(safeHref('/api/media/cm123')).toBe('/api/media/cm123')
+ })
+
+ it('rejects other protocols and relative paths', () => {
+ expect(safeHref('javascript:alert(1)')).toBeNull()
+ expect(safeHref('ftp://x/y.png')).toBeNull()
+ expect(safeHref('/static/other.png')).toBeNull()
+ expect(safeHref('blob:https://x')).toBeNull()
+ })
+})
+
+describe('inlineMediaImages (v0.14 D1)', () => {
+ const realFetch = globalThis.fetch
+ beforeEach(() => {
+ globalThis.fetch = vi.fn(async (input: string | URL | Request) => {
+ const url = String(input)
+ if (url === '/api/media/ok1') {
+ return new Response(new Uint8Array([1, 2, 3]), {
+ status: 200,
+ headers: { 'Content-Type': 'image/png' },
+ })
+ }
+ return new Response('nope', { status: 404 })
+ })
+ })
+ afterEach(() => {
+ globalThis.fetch = realFetch
+ })
+
+ it('rewrites media srcs to data URLs on a copy; never mutates the input', async () => {
+ const pages = [
+ pageWith([
+ { type: 'image', id: 'a', src: '/api/media/ok1' },
+ { type: 'image', id: 'b', src: 'https://cdn.example.com/x.png' },
+ { type: 'text', id: 'c', text: 'hello' },
+ ]),
+ ]
+ const out = await inlineMediaImages(pages)
+ expect(out).not.toBe(pages)
+ expect(out[0].elements[0]).toMatchObject({ id: 'a', src: 'data:image/png;base64,AQID' })
+ // https src untouched
+ expect(out[0].elements[1]).toMatchObject({ id: 'b', src: 'https://cdn.example.com/x.png' })
+ // live pages NEVER mutated (exports must not touch the document)
+ expect(pages[0].elements[0]).toMatchObject({ id: 'a', src: '/api/media/ok1' })
+ })
+
+ it('leaves failed fetches as relative srcs (honest degradation)', async () => {
+ const pages = [pageWith([{ type: 'image', id: 'x', src: '/api/media/gone' }])]
+ const out = await inlineMediaImages(pages)
+ expect(out[0].elements[0]).toMatchObject({ id: 'x', src: '/api/media/gone' })
+ })
+
+ it('handles nested groups and returns pages with no media srcs unchanged', async () => {
+ const plain = [pageWith([{ type: 'text', id: 't', text: 'hi' }])]
+ expect(await inlineMediaImages(plain)).toBe(plain)
+
+ const nested = [
+ pageWith([
+ { type: 'group', id: 'g', children: [{ type: 'image', id: 'i', src: '/api/media/ok1' }] },
+ ]),
+ ]
+ const out = await inlineMediaImages(nested)
+ const group = out[0].elements[0] as { children: { src: string }[] }
+ expect(group.children[0].src).toBe('data:image/png;base64,AQID')
+ })
+})
diff --git a/src/lib/svg-export.ts b/src/lib/svg-export.ts
index e586a4e..82f020c 100644
--- a/src/lib/svg-export.ts
+++ b/src/lib/svg-export.ts
@@ -42,12 +42,77 @@ function esc(s: string): string {
.replace(/'/g, '&apos;')
}
-function safeHref(src: string): string | null {
+export function safeHref(src: string): string | null {
if (src.startsWith('data:image/')) return src
if (/^https?:\/\//i.test(src)) return src
+ // v0.14 (D1): media-store images are first-party same-origin — the
+ // export inlines them to data URLs (inlineMediaImages) so files are
+ // portable; if inlining failed we still emit the relative URL (a
+ // visibly broken image beats silently losing content)
+ if (src.startsWith('/api/media/')) return src
return null
}
+// ── v0.14 (D1): inline media-store images for portable exports ──
+
+/** every image element src in these pages (media-store URLs only) */
+function collectMediaSrcs(pages: { elements: unknown[] }[]): Set<string> {
+ const srcs = new Set<string>()
+ const walk = (value: unknown): void => {
+ if (value && typeof value === 'object') {
+ const v = value as { src?: unknown; children?: unknown[]; elements?: unknown[] }
+ if (typeof v.src === 'string' && v.src.startsWith('/api/media/')) srcs.add(v.src)
+ for (const key of ['children', 'elements'] as const) {
+ if (Array.isArray(v[key])) v[key]!.forEach(walk)
+ }
+ }
+ }
+ for (const page of pages) walk(page)
+ return srcs
+}
+
+/**
+ * Rewrite every media-store image src in the pages to an inlined data
+ * URL, so the exported .svg is self-contained (opens anywhere, not
+ * just against the instance that served the bytes). Best-effort per
+ * image: a fetch that fails leaves the original relative src, which
+ * safeHref still accepts. Called by ExportDialog before serializing.
+ */
+export async function inlineMediaImages<T extends { elements: unknown[] }>(pages: T[]): Promise<T[]> {
+ const srcs = Array.from(collectMediaSrcs(pages))
+ if (!srcs.length) return pages
+ const dataUrl = new Map<string, string>()
+ await Promise.all(
+ srcs.map(async (src) => {
+ try {
+ const res = await fetch(src)
+ if (!res.ok) return
+ const blob = await res.blob()
+ if (blob.size > 8 * 1024 * 1024) return // cap inlined size
+ // Buffer-based data URL — no FileReader (node/worker safe)
+ const b64 = Buffer.from(await blob.arrayBuffer()).toString('base64')
+ dataUrl.set(src, `data:${blob.type || 'application/octet-stream'};base64,${b64}`)
+ } catch {
+ // leave the relative src — safeHref accepts it
+ }
+ }),
+ )
+ if (!dataUrl.size) return pages
+ const rewrite = (value: unknown): void => {
+ if (value && typeof value === 'object') {
+ const v = value as { src?: string; children?: unknown[]; elements?: unknown[] }
+ if (typeof v.src === 'string' && dataUrl.has(v.src)) v.src = dataUrl.get(v.src)!
+ for (const key of ['children', 'elements'] as const) {
+ if (Array.isArray(v[key])) v[key]!.forEach(rewrite)
+ }
+ }
+ }
+ // deep-copy so the live document is never mutated by an export
+ const copy: T[] = JSON.parse(JSON.stringify(pages))
+ for (const page of copy) rewrite(page)
+ return copy
+}
+
// ── id sanitization for url(#id) references ─────────────────
let refCounter = 0
diff --git a/tests/e2e/uploads-library.spec.ts b/tests/e2e/uploads-library.spec.ts
new file mode 100644
index 0000000..1a549c8
--- /dev/null
+++ b/tests/e2e/uploads-library.spec.ts
@@ -0,0 +1,193 @@
+import { test, expect, type Page } from '@playwright/test'
+import { writeFileSync } from 'node:fs'
+import { tmpdir } from 'node:os'
+import { join } from 'node:path'
+
+/**
+ * v0.14 (D1): the persistent uploads library — acceptance.
+ *
+ * 1. an uploaded image lands in the media store (not the document),
+ * is visible in the Uploads panel, and SURVIVES a reload
+ * 2. the same library item inserts into a SECOND design
+ * 3. the exported SVG inlines media-store images (portable file)
+ * 4. removing an item from the library never breaks designs that
+ * still reference it (the row survives; the GC owns reaping)
+ * 5. an anonymous upload is claimed into the account on register —
+ * the library follows the account (D1 acceptance criterion)
+ */
+
+// a real 8×8 PNG (base64 of a valid 95-byte file)
+const PNG_B64 =
+ 'iVBORw0KGgoAAAANSUhEUgAAAAgAAAAICAYAAADED76LAAAAFklEQVR4nGP8z8Dwn4EIwESMolGFI0chAG+bAR7/Og14AAAAAElFTkSuQmCC'
+
+function pngFixture(): string {
+ const p = join(tmpdir(), `canvix-d1-${Date.now()}.png`)
+ writeFileSync(p, Buffer.from(PNG_B64, 'base64'))
+ return p
+}
+
+async function register(page: Page, tag: string): Promise<string> {
+ const username = `d1_${tag}_${Date.now().toString(36)}`
+ const res = await page.request.post('/api/auth/register', {
+ data: { username, password: `D1-E2e-${username}-17!q` },
+ })
+ expect(res.status(), `register ${username}`).toBeLessThan(300)
+ return username
+}
+
+async function createBlankDesign(page: Page, name: string): Promise<string> {
+ const res = await page.request.post('/api/designs', {
+ data: { name, width: 1080, height: 720, pages: [{ id: 'p1', background: { type: 'solid', color: '#FFFFFF' }, elements: [] }] },
+ })
+ expect(res.status(), `create design: ${await res.text()}`).toBeLessThan(300)
+ return ((await res.json()) as { id: string }).id
+}
+
+async function openEditor(page: Page, designId: string) {
+ await page.goto(`/design/${designId}`)
+ await page.addStyleTag({ content: 'nextjs-portal { display: none !important; }' })
+ await expect(page.getByLabel('Design canvas')).toBeVisible({ timeout: 60_000 })
+}
+
+async function openUploadsPanel(page: Page) {
+ await page.getByRole('button', { name: 'Uploads', exact: true }).click()
+ await expect(page.getByRole('heading', { name: 'Uploads', exact: true })).toBeVisible()
+}
+
+async function designDoc(page: Page, id: string) {
+ const res = await page.request.get(`/api/designs/${id}`)
+ expect(res.status()).toBe(200)
+ return (await res.json()) as {
+ pages: { elements: { id: string; type: string; src?: string }[] }[]
+ }
+}
+
+test.describe('Uploads library (v0.14 D1)', () => {
+ test('upload → library persists across reload → second design inserts it → SVG export inlines it', async ({ page }) => {
+ const username = await register(page, 'main')
+ const designA = await createBlankDesign(page, `cvx_d1_a_${username}`)
+ await openEditor(page, designA)
+
+ // upload a PNG through the panel
+ await openUploadsPanel(page)
+ await page.setInputFiles('input[aria-label="File upload"]', pngFixture())
+
+ // the element lands on the canvas with a media-store src (API truth)
+ await expect
+ .poll(async () => {
+ const doc = await designDoc(page, designA)
+ return doc.pages[0].elements.filter((e) => e.type === 'image' && e.src?.startsWith('/api/media/')).length
+ }, { timeout: 20_000 })
+ .toBeGreaterThanOrEqual(1)
+
+ // the library lists the file with the quota line
+ await expect(page.getByRole('heading', { name: 'Your library' })).toBeVisible({ timeout: 15_000 })
+ await expect(page.getByText(/of 268\.4 MB|of 256\.0 MB/).first()).toBeVisible()
+
+ // the media serves
+ const docA = await designDoc(page, designA)
+ const mediaId = docA.pages[0].elements.find((e) => e.src?.startsWith('/api/media/'))!.src!.slice('/api/media/'.length)
+ expect((await page.request.get(`/api/media/${mediaId}`)).status()).toBe(200)
+
+ // reload the editor — the library survives (it is DB-backed)
+ await openEditor(page, designA)
+ await openUploadsPanel(page)
+ await expect(page.getByRole('heading', { name: 'Your library' })).toBeVisible({ timeout: 15_000 })
+ const firstItem = page.locator('div.grid > div').first()
+ await expect(firstItem.locator('img')).toBeVisible({ timeout: 15_000 })
+
+ // a SECOND design: insert the library item from the grid
+ const designB = await createBlankDesign(page, `cvx_d1_b_${username}`)
+ await openEditor(page, designB)
+ await openUploadsPanel(page)
+ await page.locator('div.grid button[aria-label^="Add "]').first().click()
+ await expect
+ .poll(async () => {
+ const doc = await designDoc(page, designB)
+ return doc.pages[0].elements.filter((e) => e.type === 'image' && e.src === `/api/media/${mediaId}`).length
+ }, { timeout: 20_000 })
+ .toBe(1)
+
+ // the SVG export inlines media images (portable, no /api/media refs)
+ await page.getByRole('button', { name: 'Download', exact: true }).click()
+ await page.getByRole('button', { name: /^SVG\b/ }).click()
+ const [download] = await Promise.all([
+ page.waitForEvent('download'),
+ page.getByRole('button', { name: /Download 1 SVG/i }).click(),
+ ])
+ const path = await download.path()
+ expect(path, 'download landed').toBeTruthy()
+ const { readFileSync } = await import('node:fs')
+ const svg = readFileSync(path!, 'utf8')
+ expect(svg).toContain('data:image/png;base64,')
+ expect(svg).not.toContain('/api/media/')
+ })
+
+ test('removing a library item never breaks designs using it', async ({ page }) => {
+ const username = await register(page, 'remove')
+ const design = await createBlankDesign(page, `cvx_d1_rm_${username}`)
+ await openEditor(page, design)
+ await openUploadsPanel(page)
+ await page.setInputFiles('input[aria-label="File upload"]', pngFixture())
+ await expect
+ .poll(async () => {
+ const doc = await designDoc(page, design)
+ return doc.pages[0].elements.filter((e) => e.type === 'image' && e.src?.startsWith('/api/media/')).length
+ }, { timeout: 20_000 })
+ .toBeGreaterThanOrEqual(1)
+
+ const doc = await designDoc(page, design)
+ const mediaId = doc.pages[0].elements.find((e) => e.src?.startsWith('/api/media/'))!.src!.slice('/api/media/'.length)
+
+ // remove from the library (trash button on hover) — assert the
+ // OBSERVED end state (panel empties), never toast timing (the P5
+ // lesson: toasts auto-dismiss and race any fixed expect)
+ await expect(page.getByRole('heading', { name: 'Your library' })).toBeVisible({ timeout: 15_000 })
+ await page.locator('div.grid > div').first().hover()
+ await page.getByRole('button', { name: /^Remove .* from library$/ }).first().click()
+ await expect(page.getByText('No uploads yet')).toBeVisible({ timeout: 10_000 })
+
+ // …but the design's element still serves (row survives while referenced)
+ expect((await page.request.get(`/api/media/${mediaId}`)).status()).toBe(200)
+ const after = await designDoc(page, design)
+ expect(after.pages[0].elements.some((e) => e.src === `/api/media/${mediaId}`)).toBe(true)
+ })
+
+ test('an anonymous upload is claimed into the account on register', async ({ page }) => {
+ // anonymous: upload inside a fresh design (the upload stamps the anon cookie)
+ const design = await createBlankDesign(page, 'cvx_d1_anon')
+ await openEditor(page, design)
+ await openUploadsPanel(page)
+ await page.setInputFiles('input[aria-label="File upload"]', pngFixture())
+ await expect
+ .poll(async () => {
+ const doc = await designDoc(page, design)
+ return doc.pages[0].elements.filter((e) => e.type === 'image' && e.src?.startsWith('/api/media/')).length
+ }, { timeout: 20_000 })
+ .toBeGreaterThanOrEqual(1)
+
+ // the anonymous library lists it…
+ await expect(page.getByRole('heading', { name: 'Your library' })).toBeVisible({ timeout: 15_000 })
+
+ // …then registering claims the rows into the account
+ const username = await register(page, 'claim')
+ // the API now attributes the library to the account
+ const lib = await page.request.get('/api/media/library')
+ expect(lib.status()).toBe(200)
+ const body = (await lib.json()) as { items: { id: string }[] }
+ expect(body.items.length).toBeGreaterThanOrEqual(1)
+
+ // and a brand-new context? — same account sees it after login (device B story)
+ const ctx = await page.context().browser()!.newContext()
+ const pageB = await ctx.newPage()
+ await pageB.goto('/')
+ const login = await pageB.request.post('/api/auth/login', {
+ data: { username, password: `D1-E2e-${username}-17!q` },
+ })
+ expect(login.status()).toBe(200)
+ const libB = await pageB.request.get('/api/media/library')
+ const bodyB = (await libB.json()) as { items: { id: string }[] }
+ expect(bodyB.items.map((i) => i.id).sort()).toEqual(body.items.map((i) => i.id).sort())
+ await ctx.close()
+ })
+})