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.14): dashboard folders — private organization, account-following, unfile-on-delete (D6) (#27)
Ashiq Hussain Mire198280bc196
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 71c7643..ec7203f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,56 @@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.2] — 2026-11-04++### Added++- **Daily-driver depth, part 3 — dashboard folders (D6).** "Recent+ designs" was one flat grid; every project jostled every other. Now+ the caller organizes designs into folders — private, attribution-+ scoped, and account-following like everything else.+ - **`Folder` model + `Design.folderId`** (migration 0008, additive+ and nullable — zero folders = "All designs", byte-for-byte the+ pre-v0.14 view). Deleting a folder UNFILES its designs (FK `ON+ DELETE SET NULL`): a folder delete can never destroy work, live+ or trashed. Trashed designs keep their folder and return to it on+ restore.+ - **API**: `GET/POST /api/folders` (list with live design counts;+ create with name sanitize + 50-folder ceiling) and+ `PATCH/DELETE /api/folders/[id]` — all attribution-scoped+ (ownerId or the canvix_anon hash), foreign ids are a flat 404+ (no cross-account existence oracle), CSRF-guarded, rate-limited+ (`folders:create`/`folders:update` buckets). `GET /api/designs`+ gains `?folder=<id>` (caller-owned or 404) and returns+ `folderId`; `POST /api/designs` accepts `folderId` so designs can+ be born filed; `POST /api/designs/[id]/move` files/unfiles (edit+ access on the design + ownership of the target folder — never+ someone else's tree).+ - **Login/register claims this browser's anonymous folders**+ (`claim-folders.ts`, the D1 media pattern) — organization follows+ the account across devices.+ - **Dashboard UI**: folder chips between the section header and+ the grid ("All designs" + per-folder chips with counts + "New+ folder"), one dialog for create/rename, chip ⋯ menu (rename /+ delete with an honest confirm: "designs inside are NOT deleted"),+ design-card ⋯ menu gains a "Move to folder" submenu (with a check+ on the current folder + "Remove from folder"), the section title+ shows the open folder, and anything created while a folder is+ open is born inside it. Duplicates stay in their folder when it+ is one of the caller's own.+ - **Verification**: vitest 676/676 (32 new: folder list/create+ scoping + sanitize + ceiling, rename/delete flat-404 matrices,+ move-route authz incl. foreign-folder 404 + read-only 403,+ designs `?folder=` + create-folderId paths); e2e +2 specs+ (anonymous full lifecycle: create → file → filter → rename →+ delete → designs survive at the root, API-truth asserts; and+ cross-attribution isolation: a second browser cannot list,+ mutate, filter by, or create into the first one's folders);+ default suite 49 specs green locally (fresh-server batches —+ see worklog for the fuse-watcher caveat), flag-on plugins 5/5;+ tsc/eslint/build clean. Zero new registrations in the new specs+ (the PR #26 register budget).+## [0.14.1] — 2026-11-04### Addeddiff --git a/README.md b/README.mdindex e99be67..e436285 100644--- a/README.md+++ b/README.md@@ -413,7 +413,7 @@ is right here.- **Templates** — 11 starter templates: Instagram posts & stories, pitch decks,posters, logos, YouTube thumbnails- **Backgrounds** — solid colors, curated palettes and gradient presets-- **Uploads** — drag-and-drop your own images (kept locally in your session)+- **Uploads** — drag-and-drop your own images (a persistent library since v0.14: uploads survive reload and follow your account)- **Undo / redo** — full history stack with keyboard shortcuts- **Autosave** — designs persist to the database automatically- **Export** — PNG & JPG at 1× / 2× / 3× quality, current page or all pages,@@ -964,6 +964,18 @@ tool descriptions so agents pick the right format.depth/count caps, geometry clamps, prototype-pollution stripping)and every paste remaps element ids. Read-only designs neverpaste *(v0.14.1)*+- [x] Folders (v0.14 D6) — organize the dashboard: private,+ attribution-scoped folders (`Folder` model + nullable+ `Design.folderId`, migration 0008 — zero folders = "All+ designs" unchanged). Folder chips with counts, create/rename/+ delete (a confirm notes the designs survive), a "Move to+ folder" submenu on every design card, designs born inside the+ open folder, duplicates inherit it, and login/register claims+ anonymous folders so the tree follows the account. Deleting a+ folder unfiles its designs — never deletes them (FK+ `ON DELETE SET NULL`), and trashed designs return to their+ folder on restore. Foreign folder ids are flat 404s everywhere+ (no cross-account probe) *(v0.14.2)*- [ ] 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/package.json b/package.jsonindex e61696f..d900d52 100644--- a/package.json+++ b/package.json@@ -1,8 +1,8 @@{"name": "canvix",- "version": "0.14.1",+ "version": "0.14.2","private": false,- "description": "Canvix \u2014 free & open-source graphic design tool. A community-built Canva alternative.",+ "description": "Canvix — 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/0008_folders/migration.sql b/prisma/migrations/0008_folders/migration.sqlnew file mode 100644index 0000000..2da3101--- /dev/null+++ b/prisma/migrations/0008_folders/migration.sql@@ -0,0 +1,38 @@+-- v0.14 (D6): dashboard folders+-- A Folder is a named group of the caller's designs. Attribution+-- mirrors Design/Media (ownerId for accounts, anonKey for anonymous+-- browsers); folders are private organization. Designs gain a NULLABLE+-- folderId — null = "All designs" (the root), so every pre-existing+-- row and every caller without folders behaves exactly as before.+-- Deleting a folder unfiles its designs (ON DELETE SET NULL): a folder+-- delete never destroys work, live or trashed.++-- CreateTable+CREATE TABLE "Folder" (+ "id" TEXT NOT NULL,+ "name" TEXT NOT NULL,+ "ownerId" TEXT,+ "anonKey" TEXT,+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "updatedAt" TIMESTAMP(3) NOT NULL,++ CONSTRAINT "Folder_pkey" PRIMARY KEY ("id")+);++-- CreateIndex+CREATE INDEX "Folder_ownerId_idx" ON "Folder"("ownerId");++-- CreateIndex+CREATE INDEX "Folder_anonKey_idx" ON "Folder"("anonKey");++-- AddForeignKey+ALTER TABLE "Folder" ADD CONSTRAINT "Folder_ownerId_fkey" FOREIGN KEY ("ownerId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- AddColumn: Design.folderId (nullable — migration is a no-op for data)+ALTER TABLE "Design" ADD COLUMN "folderId" TEXT;++-- CreateIndex+CREATE INDEX "Design_folderId_idx" ON "Design"("folderId");++-- AddForeignKey: unfile on folder delete, never cascade-delete designs+ALTER TABLE "Design" ADD CONSTRAINT "Design_folderId_fkey" FOREIGN KEY ("folderId") REFERENCES "Folder"("id") ON DELETE SET NULL ON UPDATE CASCADE;diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex a9142ef..aff0d4e 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -38,6 +38,7 @@ model User {passwordHash StringcreatedAt DateTime @default(now())designs Design[] @relation("DesignOwner")+ folders Folder[] @relation("FolderOwner")sessions Session[]}@@ -75,12 +76,42 @@ model Design {// design created before attribution existed (claimable only via the// explicit per-design adopt endpoint).anonKey String?+ // v0.14 (D6): dashboard organization — the folder this design is+ // filed under. null = "All designs" (the root; unchanged pre-v0.14+ // behaviour). Deleting a folder unfiles its designs (SetNull) — a+ // folder delete never destroys work.+ folderId String?+ folder Folder? @relation("DesignFolder", fields: [folderId], references: [id], onDelete: SetNull)// soft delete (dashboard Trash) — null = live design- deletedAt DateTime?+ deletedAt DateTime?versions DesignVersion[]createdAt DateTime @default(now())updatedAt DateTime @updatedAt+ @@index([ownerId])+ @@index([anonKey])+ @@index([folderId])+}++// ── v0.14 (D6): dashboard folders ───────────────────────────+// A named group of the caller's designs. Attribution mirrors Design/+// Media exactly: signed-in → ownerId, anonymous → anonKey (the+// canvix_anon cookie hash). Folders are PRIVATE organization — the+// list endpoint only ever returns the caller's own rows — while the+// designs inside keep their own visibility (the anonymous commons+// stays shared). claim-on-login moves anon folders into the account+// (src/lib/auth/claim-folders.ts), so organization follows the user+// across devices just like uploads (D1).+model Folder {+ id String @id @default(cuid())+ name String+ ownerId String?+ owner User? @relation("FolderOwner", fields: [ownerId], references: [id], onDelete: Cascade)+ anonKey String?+ designs Design[] @relation("DesignFolder")+ createdAt DateTime @default(now())+ updatedAt DateTime @updatedAt+@@index([ownerId])@@index([anonKey])}diff --git a/src/app/api/auth/login/route.ts b/src/app/api/auth/login/route.tsindex 8ea5233..e258baa 100644--- a/src/app/api/auth/login/route.ts+++ b/src/app/api/auth/login/route.ts@@ -7,6 +7,7 @@ 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'+import { claimAnonFolders } from '@/lib/auth/claim-folders'// POST /api/auth/login — exchange username + password for a session cookie.// One deliberately generic error message: never reveal whether the@@ -38,6 +39,8 @@ async function __canvix_post(req: NextRequest) {// v0.14 (D1): this browser's anonymous uploads follow the accountawait claimAnonMedia(req, user.id)+ // v0.14 (D6): so does its folder organization+ await claimAnonFolders(req, user.id)const res = NextResponse.json({ user: { id: user.id, username: user.username, createdAt: user.createdAt } })await createSession(user.id, res)return resdiff --git a/src/app/api/auth/register/route.ts b/src/app/api/auth/register/route.tsindex bc33ce0..820d449 100644--- a/src/app/api/auth/register/route.ts+++ b/src/app/api/auth/register/route.ts@@ -7,6 +7,7 @@ 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'+import { claimAnonFolders } from '@/lib/auth/claim-folders'// POST /api/auth/register — create an account (username + password).// Free forever: no email, no verification, no external provider — a@@ -38,6 +39,8 @@ async function __canvix_post(req: NextRequest) {const res = NextResponse.json({ user }, { status: 201 })// v0.14 (D1): this browser's anonymous uploads follow the accountawait claimAnonMedia(req, user.id)+ // v0.14 (D6): so does its folder organization+ await claimAnonFolders(req, user.id)await createSession(user.id, res)return res} catch (error) {diff --git a/src/app/api/designs/[id]/move/move.test.ts b/src/app/api/designs/[id]/move/move.test.tsnew file mode 100644index 0000000..8156496--- /dev/null+++ b/src/app/api/designs/[id]/move/move.test.ts@@ -0,0 +1,130 @@+// Unit tests for POST /api/designs/[id]/move (v0.14, D6).+//+// Invariants under test:+// 1. the caller must be able to EDIT the design (the design-guard+// three-case rule: ownerless → anyone, owned → owner only)+// 2. the target folder must belong to the caller's attribution —+// foreign ids are a flat 404, so nobody can file designs into+// someone else's tree or probe which folders exist+// 3. folderId null = the root ("All designs"), always allowed+// 4. same-origin enforced (CSRF); bad payloads are a 400++import { describe, it, expect, vi, beforeEach } from 'vitest'++const designFindUnique = vi.hoisted(() => vi.fn())+const designUpdate = vi.hoisted(() => vi.fn())+const queryRaw = vi.hoisted(() => vi.fn())+const dbMock = vi.hoisted(() => ({+ design: { findUnique: designFindUnique, update: designUpdate },+ $queryRawUnsafe: queryRaw,+}))+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 { POST } from './route'++const USER_A = { id: 'user-a', username: 'alpha', createdAt: new Date() }++function moveReq(+ id: string,+ opts: { user?: unknown; anon?: string | null; body?: unknown; origin?: string } = {}+) {+ getSessionUser.mockResolvedValue(opts.user ?? null)+ readAnonToken.mockReturnValue(opts.anon === undefined ? null : opts.anon)+ const headers: Record<string, string> = { 'Content-Type': 'application/json' }+ if (opts.origin) headers.origin = opts.origin+ return new NextRequest(`http://localhost/api/designs/${id}/move`, {+ method: 'POST',+ headers,+ body: JSON.stringify(opts.body ?? {}),+ })+}++function designRow(ownerId: string | null) {+ return { id: 'd1', ownerId, anonKey: null, name: 'D', deletedAt: null }+}++beforeEach(() => {+ vi.clearAllMocks()+})++describe('POST /api/designs/[id]/move', () => {+ it('files an ownerless design into the caller own folder', async () => {+ designFindUnique.mockResolvedValueOnce(designRow(null))+ queryRaw.mockResolvedValueOnce([{ id: 'f1' }])+ designUpdate.mockResolvedValueOnce({ id: 'd1' })+ const res = await POST(moveReq('d1', { user: USER_A, body: { folderId: 'f1' } }), { params: Promise.resolve({ id: 'd1' }) })+ expect(res.status).toBe(200)+ expect(await res.json()).toEqual({ ok: true, folderId: 'f1' })+ // the folder ownership check scoped by the caller's attribution+ expect(queryRaw.mock.calls[0][0]).toContain('FROM "Folder"')+ expect(queryRaw.mock.calls[0][2]).toBe('user-a')+ expect(designUpdate).toHaveBeenCalledWith({ where: { id: 'd1' }, data: { folderId: 'f1' } })+ })++ it('scopes the folder check for anonymous callers by anonKey', async () => {+ designFindUnique.mockResolvedValueOnce(designRow(null))+ queryRaw.mockResolvedValueOnce([{ id: 'f1' }])+ designUpdate.mockResolvedValueOnce({ id: 'd1' })+ const res = await POST(moveReq('d1', { anon: 'tok-1', body: { folderId: 'f1' } }), { params: Promise.resolve({ id: 'd1' }) })+ expect(res.status).toBe(200)+ expect(queryRaw.mock.calls[0][2]).toBeNull()+ expect(queryRaw.mock.calls[0][3]).toBe('hash(tok-1)')+ })++ it('folderId null moves the design back to the root (no folder query)', async () => {+ designFindUnique.mockResolvedValueOnce(designRow(null))+ designUpdate.mockResolvedValueOnce({ id: 'd1' })+ const res = await POST(moveReq('d1', { user: USER_A, body: { folderId: null } }), { params: Promise.resolve({ id: 'd1' }) })+ expect(res.status).toBe(200)+ expect(await res.json()).toEqual({ ok: true, folderId: null })+ expect(queryRaw).not.toHaveBeenCalled()+ expect(designUpdate).toHaveBeenCalledWith({ where: { id: 'd1' }, data: { folderId: null } })+ })++ it('a foreign folder id is a flat 404 — no probe, no move', async () => {+ designFindUnique.mockResolvedValueOnce(designRow(null))+ queryRaw.mockResolvedValueOnce([]) // not the caller's folder+ const res = await POST(moveReq('d1', { user: USER_A, body: { folderId: 'f-foreign' } }), { params: Promise.resolve({ id: 'd1' }) })+ expect(res.status).toBe(404)+ expect(designUpdate).not.toHaveBeenCalled()+ })++ it("someone else's owned design is a 403 (read-only)", async () => {+ designFindUnique.mockResolvedValueOnce(designRow('user-b'))+ const res = await POST(moveReq('d1', { user: USER_A, body: { folderId: null } }), { params: Promise.resolve({ id: 'd1' }) })+ expect(res.status).toBe(403)+ expect(designUpdate).not.toHaveBeenCalled()+ })++ it('absent design is a 404', async () => {+ designFindUnique.mockResolvedValueOnce(null)+ const res = await POST(moveReq('missing', { user: USER_A, body: { folderId: null } }), { params: Promise.resolve({ id: 'missing' }) })+ expect(res.status).toBe(404)+ })++ it('a non-string folderId is a 400', async () => {+ designFindUnique.mockResolvedValueOnce(designRow(null))+ const res = await POST(moveReq('d1', { user: USER_A, body: { folderId: 42 } }), { params: Promise.resolve({ id: 'd1' }) })+ expect(res.status).toBe(400)+ })++ it('cross-origin move is rejected by the CSRF guard', async () => {+ const res = await POST(moveReq('d1', { user: USER_A, body: { folderId: null }, origin: 'https://evil.example' }), { params: Promise.resolve({ id: 'd1' }) })+ expect(res.status).toBe(403)+ expect(designFindUnique).not.toHaveBeenCalled()+ })+})diff --git a/src/app/api/designs/[id]/move/route.ts b/src/app/api/designs/[id]/move/route.tsnew file mode 100644index 0000000..b995433--- /dev/null+++ b/src/app/api/designs/[id]/move/route.ts@@ -0,0 +1,76 @@+import { NextRequest, NextResponse } from 'next/server'+import { db } from '@/lib/db'+import { resolveDesignAccess, NOT_YOUR_DESIGN } from '@/lib/auth/design-guard'+import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'+import { checkRateLimit, rateLimitResponse } from '@/lib/rate-limit'+import { getSessionUser } from '@/lib/auth/session'+import { anonKeyHash, readAnonToken } from '@/lib/auth/anon'+import { withLogging } from '@/lib/observability'++export const runtime = 'nodejs'++// ── v0.14 (D6): move a design into a folder (or back to the root) ──+// POST /api/designs/[id]/move { folderId: string | null }+//+// Two authorizations, both required:+// 1. the caller must be able to EDIT the design (the standard+// design guard — 404 absent, 403 foreign-owned);+// 2. the target folder must belong to the caller's attribution —+// a foreign folder id is a flat 404 (no existence oracle), so+// nobody can file designs into someone else's tree or probe it.+// folderId null = "All designs" (the root) — always allowed.+//+// Deliberately NOT part of PUT /api/designs/[id]: that route is the+// autosave path (name/pages/thumbnail, 300/min); filing is an explicit+// dashboard action and gets its own budget.++async function __canvix_post(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {+ if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })+ const limit = checkRateLimit(req, 'designs:update')+ if (!limit.ok) return rateLimitResponse(limit)+ try {+ const { id } = await params+ const access = await resolveDesignAccess(req, id)+ if (!access) return NextResponse.json({ error: 'Not found' }, { status: 404 })+ if (!access.canEdit) return NextResponse.json(NOT_YOUR_DESIGN, { status: 403 })++ const body = (await req.json().catch(() => ({}))) as { folderId?: unknown }++ if (body.folderId === null || body.folderId === undefined) {+ await db.design.update({ where: { id }, data: { folderId: null } })+ return NextResponse.json({ ok: true, folderId: null })+ }++ if (typeof body.folderId !== 'string' || !body.folderId) {+ return NextResponse.json({ error: 'folderId must be a folder id or null.' }, { status: 400 })+ }++ // the target folder must be the caller's own+ 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 owned = await db.$queryRawUnsafe<{ id: string }[]>(+ `SELECT id FROM "Folder"+ WHERE id = $1 AND (+ ("ownerId" = $2 AND $2 IS NOT NULL) OR ("anonKey" = $3 AND $3 IS NOT NULL))`,+ body.folderId,+ ownerId,+ anonKey,+ )+ if (owned.length === 0) return NextResponse.json({ error: 'Folder not found' }, { status: 404 })++ await db.design.update({ where: { id }, data: { folderId: body.folderId } })+ return NextResponse.json({ ok: true, folderId: body.folderId })+ } catch (error) {+ console.error('POST /api/designs/[id]/move failed', error)+ return NextResponse.json({ error: 'Failed to move the design' }, { status: 500 })+ }+}++// 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/designs/[id]/move', __canvix_post)diff --git a/src/app/api/designs/designs.test.ts b/src/app/api/designs/designs.test.tsindex 9e16d79..5544e31 100644--- a/src/app/api/designs/designs.test.ts+++ b/src/app/api/designs/designs.test.ts@@ -12,15 +12,25 @@import { describe, it, expect, vi, beforeEach } from 'vitest'const dbMock = vi.hoisted(() => ({- design: { findMany: vi.fn() },+ design: { findMany: vi.fn(), create: vi.fn() },+ $queryRawUnsafe: vi.fn(),}))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,+ newAnonToken: () => 'fresh-token',+ anonKeyHash: (t: string) => `hash(${t})`,+ setAnonCookie: vi.fn(),+ anonHashFrom: () => null,+}))+import { NextRequest } from 'next/server'-import { GET } from './route'+import { GET, POST } from './route'const USER_A = { id: 'user-a', username: 'alpha', createdAt: new Date() }@@ -127,3 +137,104 @@ describe('GET /api/designs (v0.9.2 pagination)', () => {])})})+++// ── v0.14 (D6): folder scoping on the list + create ────────────────+//+// ?folder=<id> must filter to one of the CALLER'S OWN folders; a+// foreign id is a flat 404 (folders are private organization, and+// probing must not reveal which exist). POST accepts folderId under+// the same rule — a design can be born filed.++function postReq(opts: { user?: unknown; body?: unknown; origin?: string } = {}) {+ getSessionUser.mockResolvedValue(opts.user ?? null)+ readAnonToken.mockReturnValue(null)+ const headers: Record<string, string> = { 'Content-Type': 'application/json', host: 'canvix.test' }+ if (opts.origin) headers.origin = opts.origin+ return new NextRequest('http://canvix.test/api/designs', {+ method: 'POST',+ headers,+ body: JSON.stringify(opts.body ?? {}),+ })+}++describe('GET /api/designs ?folder= (v0.14 D6)', () => {+ it("filters the list to the caller's own folder", async () => {+ dbMock.$queryRawUnsafe.mockResolvedValueOnce([{ id: 'f1' }])+ dbMock.design.findMany.mockResolvedValue([])+ const res = await get({+ user: USER_A,+ url: 'http://canvix.test/api/designs?folder=f1',+ })+ expect(res.status).toBe(200)+ // the ownership check scoped by the caller's attribution+ expect(dbMock.$queryRawUnsafe.mock.calls[0][0]).toContain('FROM "Folder"')+ expect(dbMock.$queryRawUnsafe.mock.calls[0][2]).toBe('user-a')+ // the list where carries the folder filter+ expect(dbMock.design.findMany.mock.calls[0][0].where.folderId).toBe('f1')+ })++ it('a foreign folder id is a flat 404 — the list never runs', async () => {+ dbMock.$queryRawUnsafe.mockResolvedValueOnce([]) // not the caller's+ const res = await get({+ user: USER_A,+ url: 'http://canvix.test/api/designs?folder=f-foreign',+ })+ expect(res.status).toBe(404)+ expect(dbMock.design.findMany).not.toHaveBeenCalled()+ })++ it('an empty folder param is a 400, not an empty list', async () => {+ const res = await get({ url: 'http://canvix.test/api/designs?folder=' })+ expect(res.status).toBe(400)+ expect(dbMock.design.findMany).not.toHaveBeenCalled()+ })++ it('no folder param = All designs, no folder query at all', async () => {+ dbMock.design.findMany.mockResolvedValue([])+ await get()+ expect(dbMock.$queryRawUnsafe).not.toHaveBeenCalled()+ expect(dbMock.design.findMany.mock.calls[0][0].where.folderId).toBeUndefined()+ })++ it("scopes the folder check for anonymous callers by anonKey", async () => {+ readAnonToken.mockReturnValue('tok-1')+ dbMock.$queryRawUnsafe.mockResolvedValueOnce([{ id: 'f1' }])+ dbMock.design.findMany.mockResolvedValue([])+ const res = await get({ url: 'http://canvix.test/api/designs?folder=f1' })+ expect(res.status).toBe(200)+ expect(dbMock.$queryRawUnsafe.mock.calls[0][2]).toBeNull()+ expect(dbMock.$queryRawUnsafe.mock.calls[0][3]).toBe('hash(tok-1)')+ })+})++describe('POST /api/designs folderId (v0.14 D6)', () => {+ it('creates the design filed into the caller own folder', async () => {+ dbMock.$queryRawUnsafe.mockResolvedValueOnce([{ id: 'f1' }])+ dbMock.design.create.mockResolvedValueOnce({ id: 'd-new' })+ const res = await POST(postReq({+ user: USER_A,+ body: { name: 'Filed', width: 800, height: 600, folderId: 'f1' },+ }))+ expect(res.status).toBe(201)+ expect(dbMock.design.create.mock.calls[0][0].data.folderId).toBe('f1')+ })++ it('a foreign folderId is a flat 404 — nothing is created', async () => {+ dbMock.$queryRawUnsafe.mockResolvedValueOnce([])+ const res = await POST(postReq({+ user: USER_A,+ body: { name: 'Nope', folderId: 'f-foreign' },+ }))+ expect(res.status).toBe(404)+ expect(dbMock.design.create).not.toHaveBeenCalled()+ })++ it('no folderId creates at the root (unchanged pre-v0.14 behaviour)', async () => {+ dbMock.design.create.mockResolvedValueOnce({ id: 'd-root' })+ const res = await POST(postReq({ user: USER_A, body: { name: 'Root' } }))+ expect(res.status).toBe(201)+ expect(dbMock.$queryRawUnsafe).not.toHaveBeenCalled()+ expect(dbMock.design.create.mock.calls[0][0].data.folderId).toBeNull()+ })+})diff --git a/src/app/api/designs/route.ts b/src/app/api/designs/route.tsindex 7f392a6..241fb7d 100644--- a/src/app/api/designs/route.ts+++ b/src/app/api/designs/route.ts@@ -8,6 +8,36 @@ import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'import { checkRateLimit, rateLimitResponse } from '@/lib/rate-limit'import { withLogging } from '@/lib/observability'+/** v0.14 (D6): resolve a ?folder= id / POST folderId to a folder the+ * CALLER owns, or null. Foreign and absent ids are indistinguishable+ * (flat 404 upstream) — folders are private organization, so probing+ * ids must not reveal which exist. Returns:+ * { ok: true, folderId } — mine, use it+ * { ok: false, status: 400|404 } — reject the request+ */+async function resolveOwnFolder(+ req: NextRequest,+ ownerId: string | null,+ rawFolderId: unknown+): Promise<{ ok: true; folderId: string | null } | { ok: false; status: 400 | 404 }> {+ if (rawFolderId === undefined || rawFolderId === null) return { ok: true, folderId: null }+ if (typeof rawFolderId !== 'string' || !rawFolderId) {+ return { ok: false, status: 400 }+ }+ const token = readAnonToken(req)+ const anonKey = ownerId ? null : token ? anonKeyHash(token) : null+ if (!ownerId && !anonKey) return { ok: false, status: 404 }+ const owned = await db.$queryRawUnsafe<{ id: string }[]>(+ `SELECT id FROM "Folder" WHERE id = $1 AND (+ ("ownerId" = $2 AND $2 IS NOT NULL) OR ("anonKey" = $3 AND $3 IS NOT NULL))`,+ rawFolderId,+ ownerId,+ anonKey,+ )+ if (owned.length === 0) return { ok: false, status: 404 }+ return { ok: true, folderId: rawFolderId }+}+// Normalise incoming pages payload (accepts object or legacy JSON string)// into a value suitable for the Postgres jsonb column.function toPages(value: unknown): Prisma.InputJsonValue {@@ -46,6 +76,15 @@ async function __canvix_get(req: NextRequest) {const cursorId = req.nextUrl.searchParams.get('id')const user = await getSessionUser(req)+ // v0.14 (D6): ?folder=<id> — one of the caller's own folders, or a+ // flat 404. Absent param = "All designs" (unchanged behaviour).+ let folderFilter: string | null = null+ if (req.nextUrl.searchParams.has('folder')) {+ const resolved = await resolveOwnFolder(req, user?.id ?? null, req.nextUrl.searchParams.get('folder'))+ if (!resolved.ok) return NextResponse.json({ error: 'Folder not found' }, { status: resolved.status })+ folderFilter = resolved.folderId+ }+// Compose scoping + keyset via AND — never spread two `OR` keys into// the same object (the second would silently replace the first and// leak private designs to other accounts).@@ -66,6 +105,7 @@ async function __canvix_get(req: NextRequest) {deletedAt: trash ? { not: null } : null,AND: filters,}+ if (folderFilter) where.folderId = folderFilterconst designs = await db.design.findMany({where,orderBy: [{ updatedAt: 'desc' }, { id: 'desc' }],@@ -79,6 +119,7 @@ async function __canvix_get(req: NextRequest) {source: true,ownerId: true,anonKey: true,+ folderId: true,deletedAt: true,createdAt: true,updatedAt: true,@@ -121,6 +162,17 @@ async function __canvix_post(req: NextRequest) {const user = await getSessionUser(req)const body = await req.json()+ // v0.14 (D6): optional folderId — a design can be born filed into+ // one of the caller's folders ("create inside folder"). Foreign+ // ids are a flat 404, the same rule as the move route.+ const folderResolved = await resolveOwnFolder(req, user?.id ?? null, (body as { folderId?: unknown }).folderId)+ if (!folderResolved.ok) {+ return NextResponse.json(+ folderResolved.status === 404 ? { error: 'Folder not found' } : { error: 'folderId must be a folder id or null.' },+ { status: folderResolved.status },+ )+ }+if (user) {const design = await db.design.create({data: {@@ -131,12 +183,15 @@ async function __canvix_post(req: NextRequest) {source: typeof body.source === 'string' ? body.source.slice(0, 120) : 'blank',thumbnail: typeof body.thumbnail === 'string' ? body.thumbnail : null,ownerId: user.id,+ folderId: folderResolved.folderId,},})return NextResponse.json(design, { status: 201 })}// Anonymous: mint/refresh this browser's attribution, stamp the row.+ // The folder check above already ran against this browser's cookie —+ // a folder the anonymous caller does not own never gets here.const token = readAnonToken(req) ?? newAnonToken()const design = await db.design.create({data: {@@ -147,6 +202,7 @@ async function __canvix_post(req: NextRequest) {source: typeof body.source === 'string' ? body.source.slice(0, 120) : 'blank',thumbnail: typeof body.thumbnail === 'string' ? body.thumbnail : null,anonKey: anonKeyHash(token),+ folderId: folderResolved.folderId,},})const res = NextResponse.json(design, { status: 201 })diff --git a/src/app/api/folders/[id]/route.ts b/src/app/api/folders/[id]/route.tsnew file mode 100644index 0000000..102355c--- /dev/null+++ b/src/app/api/folders/[id]/route.ts@@ -0,0 +1,93 @@+import { NextRequest, NextResponse } from 'next/server'+import { db } from '@/lib/db'+import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'+import { checkRateLimit, rateLimitResponse } from '@/lib/rate-limit'+import { getSessionUser } from '@/lib/auth/session'+import { anonKeyHash, readAnonToken } from '@/lib/auth/anon'+import { withLogging } from '@/lib/observability'++export const runtime = 'nodejs'++// ── v0.14 (D6): folder item management ───────────────────────+// PATCH /api/folders/[id] { name } — rename+// DELETE /api/folders/[id] — delete the folder+//+// Ownership: the row's attribution (ownerId / anonKey) must match the+// caller's; anything else is a flat 404 (no cross-account existence+// oracle — the same rule as the uploads library). DELETE never touches+// designs: the FK's ON DELETE SET NULL unfiles them (live AND trashed)+// back into "All designs" — a folder delete can never destroy work.++const MAX_NAME = 60++function sanitizeName(raw: unknown): string | null {+ if (typeof raw !== 'string') return null+ const trimmed = raw.replace(/[\\/]|\.\./g, '').trim().slice(0, MAX_NAME)+ 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 limit = checkRateLimit(req, 'folders:update')+ if (!limit.ok) return rateLimitResponse(limit)+ 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 folder 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 "Folder" SET name = $3, "updatedAt" = now()+ WHERE id = $1 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('[api/folders] 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 limit = checkRateLimit(req, 'folders:update')+ if (!limit.ok) return rateLimitResponse(limit)+ 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 })++ // The designs' folderId goes NULL via the FK's ON DELETE SET NULL+ const deleted = await db.$executeRawUnsafe(+ `DELETE FROM "Folder" WHERE id = $1 AND (+ ("ownerId" = $2 AND $2 IS NOT NULL) OR ("anonKey" = $3 AND $3 IS NOT NULL))`,+ id,+ ownerId,+ anonKey,+ )+ if (deleted === 0) return NextResponse.json({ error: 'Not found.' }, { status: 404 })+ return NextResponse.json({ ok: true })+ } catch (error) {+ console.error('[api/folders] delete failed', error)+ return NextResponse.json({ error: 'Could not delete the folder.' }, { status: 500 })+ }+}++// v0.12.5 (H7): opt-in request logging wrapper — passthrough+// unless CANVIX_LOG=requests (see src/lib/observability.ts)+export const PATCH = withLogging('PATCH /api/folders/[id]', __canvix_patch)+export const DELETE = withLogging('DELETE /api/folders/[id]', __canvix_delete)diff --git a/src/app/api/folders/folders.test.ts b/src/app/api/folders/folders.test.tsnew file mode 100644index 0000000..b95e6b1--- /dev/null+++ b/src/app/api/folders/folders.test.ts@@ -0,0 +1,227 @@+// Unit tests for the v0.14 (D6) folder routes.+//+// Invariants under test:+// 1. GET lists ONLY the caller's attribution (ownerId or anonKey),+// never another account's rows — the scoping lives in the SQL+// 2. POST validates/caps names, enforces the per-attribution folder+// ceiling (409), and stamps attribution (user → ownerId,+// anonymous → anonKey + cookie)+// 3. PATCH/DELETE are attribution-scoped: a foreign id is a flat 404+// (no cross-account existence oracle)+// 4. DELETE removes the folder row only — the unfile-on-delete FK+// lives in the database (migration 0008), verified by the e2e++import { describe, it, expect, vi, beforeEach } from 'vitest'++const queryRaw = vi.hoisted(() => vi.fn())+const executeRaw = vi.hoisted(() => vi.fn())+const folderCount = vi.hoisted(() => vi.fn())+const folderCreate = vi.hoisted(() => vi.fn())+const dbMock = vi.hoisted(() => ({+ $queryRawUnsafe: queryRaw,+ $executeRawUnsafe: executeRaw,+ folder: { count: folderCount, create: folderCreate },+}))+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,+ newAnonToken: () => 'fresh-token',+ anonKeyHash: (t: string) => `hash(${t})`,+ setAnonCookie: vi.fn(),+}))++vi.mock('@/lib/observability', () => ({+ withLogging: (_name: string, fn: unknown) => fn,+}))++import { NextRequest } from 'next/server'+import { GET, POST } from './route'+import { PATCH, DELETE } from './[id]/route'++const USER_A = { id: 'user-a', username: 'alpha', 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/folders')+}++function idReq(+ id: string,+ opts: { user?: unknown; anon?: string | null; body?: unknown; method?: string; origin?: string } = {}+) {+ getSessionUser.mockResolvedValue(opts.user ?? null)+ readAnonToken.mockReturnValue(opts.anon === undefined ? null : opts.anon)+ const headers: Record<string, string> = { 'Content-Type': 'application/json' }+ if (opts.origin) headers.origin = opts.origin+ return new NextRequest(`http://localhost/api/folders/${id}`, {+ method: opts.method ?? 'PATCH',+ headers,+ body: JSON.stringify(opts.body ?? {}),+ })+}++function postReq(opts: { user?: unknown; anon?: string | null; body?: unknown; origin?: string } = {}) {+ getSessionUser.mockResolvedValue(opts.user ?? null)+ readAnonToken.mockReturnValue(opts.anon === undefined ? null : opts.anon)+ const headers: Record<string, string> = { 'Content-Type': 'application/json' }+ if (opts.origin) headers.origin = opts.origin+ return new NextRequest('http://localhost/api/folders', {+ method: 'POST',+ headers,+ body: JSON.stringify(opts.body ?? {}),+ })+}++beforeEach(() => {+ vi.clearAllMocks()+})++describe('GET /api/folders', () => {+ it('returns the caller scoping query with counts', async () => {+ queryRaw.mockResolvedValueOnce([+ { id: 'f1', name: 'Client work', createdAt: new Date('2026-11-01T00:00:00Z'), designCount: 2 },+ ])+ const res = await GET(getReq({ user: USER_A }))+ expect(res.status).toBe(200)+ const body = await res.json()+ expect(body.folders).toEqual([+ { id: 'f1', name: 'Client work', createdAt: '2026-11-01T00:00:00.000Z', designCount: 2 },+ ])+ // the SQL must scope by the ownerId, never the anonKey+ const sql = queryRaw.mock.calls[0][0] as string+ expect(sql).toContain('FROM "Folder" f')+ expect(sql).toContain('"ownerId" = $1')+ expect(queryRaw.mock.calls[0][1]).toBe('user-a')+ expect(queryRaw.mock.calls[0][2]).toBeNull()+ // the design-count join only counts LIVE designs+ expect(sql).toContain('d."deletedAt" IS NULL')+ })++ it('scopes anonymous callers by their anonKey', async () => {+ queryRaw.mockResolvedValueOnce([])+ const res = await GET(getReq({ anon: 'tok-1' }))+ expect(res.status).toBe(200)+ expect(await res.json()).toEqual({ folders: [] })+ expect(queryRaw.mock.calls[0][1]).toBeNull()+ expect(queryRaw.mock.calls[0][2]).toBe('hash(tok-1)')+ })++ it('attribution-less caller gets an honest empty tree, no SQL', async () => {+ const res = await GET(getReq())+ expect(res.status).toBe(200)+ expect(await res.json()).toEqual({ folders: [] })+ expect(queryRaw).not.toHaveBeenCalled()+ })+})++describe('POST /api/folders', () => {+ it('creates the folder for a signed-in caller', async () => {+ folderCount.mockResolvedValueOnce(0)+ folderCreate.mockResolvedValueOnce({ id: 'f2', name: 'Posters', createdAt: new Date('2026-11-02T00:00:00Z') })+ const res = await POST(postReq({ user: USER_A, body: { name: 'Posters' } }))+ expect(res.status).toBe(201)+ const body = await res.json()+ expect(body.folder).toMatchObject({ id: 'f2', name: 'Posters', designCount: 0 })+ expect(folderCreate).toHaveBeenCalledWith({+ data: { name: 'Posters', ownerId: 'user-a' },+ select: { id: true, name: true, createdAt: true },+ })+ })++ it('creates the folder for an anonymous caller with attribution', async () => {+ folderCount.mockResolvedValueOnce(0)+ folderCreate.mockResolvedValueOnce({ id: 'f3', name: 'Scratch', createdAt: new Date('2026-11-02T00:00:00Z') })+ const res = await POST(postReq({ anon: 'tok-9', body: { name: 'Scratch' } }))+ expect(res.status).toBe(201)+ expect(folderCreate).toHaveBeenCalledWith({+ data: { name: 'Scratch', anonKey: 'hash(tok-9)' },+ select: { id: true, name: true, createdAt: true },+ })+ })++ it('sanitizes the name: path fragments and traversal stripped, capped', async () => {+ folderCount.mockResolvedValueOnce(0)+ folderCreate.mockResolvedValueOnce({ id: 'f4', name: 'a.b', createdAt: new Date() })+ const res = await POST(postReq({ user: USER_A, body: { name: ' ../a/b\\c ' } }))+ expect(res.status).toBe(201)+ expect(folderCreate.mock.calls[0][0].data.name).toBe('abc')+ })++ it('empty name is a 400', async () => {+ const res = await POST(postReq({ user: USER_A, body: { name: ' ' } }))+ expect(res.status).toBe(400)+ expect(folderCreate).not.toHaveBeenCalled()+ })++ it('enforces the per-attribution folder ceiling (409)', async () => {+ folderCount.mockResolvedValueOnce(50)+ const res = await POST(postReq({ user: USER_A, body: { name: 'One too many' } }))+ expect(res.status).toBe(409)+ expect(folderCreate).not.toHaveBeenCalled()+ })++ it('cross-origin POST is rejected by the CSRF guard', async () => {+ const res = await POST(postReq({ user: USER_A, body: { name: 'X' }, origin: 'https://evil.example' }))+ expect(res.status).toBe(403)+ expect(folderCreate).not.toHaveBeenCalled()+ })+})++describe('PATCH /api/folders/[id] (rename)', () => {+ it('renames within the attribution', async () => {+ executeRaw.mockResolvedValueOnce(1)+ const res = await PATCH(idReq('f1', { user: USER_A, body: { name: 'Renamed' } }), { params: Promise.resolve({ id: 'f1' }) })+ expect(res.status).toBe(200)+ expect(await res.json()).toEqual({ ok: true, name: 'Renamed' })+ const sql = executeRaw.mock.calls[0][0] as string+ expect(sql).toContain('UPDATE "Folder"')+ expect(sql).toContain('"ownerId" = $2')+ })++ it('foreign id is a flat 404', async () => {+ executeRaw.mockResolvedValueOnce(0)+ const res = await PATCH(idReq('f-foreign', { user: USER_A, body: { name: 'Nope' } }), { params: Promise.resolve({ id: 'f-foreign' }) })+ expect(res.status).toBe(404)+ })++ it('attribution-less caller is a flat 404', async () => {+ const res = await PATCH(idReq('f1', { body: { name: 'Nope' } }), { params: Promise.resolve({ id: 'f1' }) })+ expect(res.status).toBe(404)+ expect(executeRaw).not.toHaveBeenCalled()+ })++ it('cross-origin PATCH is rejected by the CSRF guard', async () => {+ const res = await PATCH(idReq('f1', { user: USER_A, body: { name: 'X' }, origin: 'https://evil.example' }), { params: Promise.resolve({ id: 'f1' }) })+ expect(res.status).toBe(403)+ })+})++describe('DELETE /api/folders/[id]', () => {+ it('deletes the folder row (designs unfile via the FK, not here)', async () => {+ executeRaw.mockResolvedValueOnce(1)+ const res = await DELETE(idReq('f1', { user: USER_A, method: 'DELETE' }), { params: Promise.resolve({ id: 'f1' }) })+ expect(res.status).toBe(200)+ expect(await res.json()).toEqual({ ok: true })+ const sql = executeRaw.mock.calls[0][0] as string+ expect(sql).toContain('DELETE FROM "Folder"')+ })++ it('foreign id is a flat 404', async () => {+ executeRaw.mockResolvedValueOnce(0)+ const res = await DELETE(idReq('f-foreign', { user: USER_A, method: 'DELETE' }), { params: Promise.resolve({ id: 'f-foreign' }) })+ expect(res.status).toBe(404)+ })++ it('anonymous caller scopes by anonKey', async () => {+ executeRaw.mockResolvedValueOnce(1)+ const res = await DELETE(idReq('f1', { anon: 'tok-1', method: 'DELETE' }), { params: Promise.resolve({ id: 'f1' }) })+ expect(res.status).toBe(200)+ expect(executeRaw.mock.calls[0][3]).toBe('hash(tok-1)')+ })+})diff --git a/src/app/api/folders/route.ts b/src/app/api/folders/route.tsnew file mode 100644index 0000000..f662c78--- /dev/null+++ b/src/app/api/folders/route.ts@@ -0,0 +1,135 @@+import { NextRequest, NextResponse } from 'next/server'+import { db } from '@/lib/db'+import { getSessionUser } from '@/lib/auth/session'+import {+ readAnonToken,+ newAnonToken,+ anonKeyHash,+ setAnonCookie,+} from '@/lib/auth/anon'+import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'+import { checkRateLimit, rateLimitResponse } from '@/lib/rate-limit'+import { withLogging } from '@/lib/observability'++export const runtime = 'nodejs'++// ── v0.14 (D6): dashboard folders ────────────────────────────+// GET /api/folders — the caller's folders, with live design counts+// POST /api/folders { name } — create a folder+//+// Folders are PRIVATE organization: attribution mirrors the rest of+// the app (signed-in → ownerId, else the canvix_anon cookie →+// anonKey), and every query is scoped to exactly one attribution.+// The designs inside keep their own visibility — an ownerless design+// stays in the anonymous commons; the folder is just the caller's+// grouping of it. Signing in claims anonymous folders (claim-folders),+// so the tree follows the account across devices.++const FOLDERS_LIMIT = 200 // rows returned by the list+const MAX_FOLDERS = 50 // per attribution — junk ceiling+const MAX_NAME = 60++function sanitizeName(raw: unknown): string | null {+ if (typeof raw !== 'string') return null+ const trimmed = raw.replace(/[\\/]|\.\./g, '').trim().slice(0, MAX_NAME)+ return trimmed || null+}++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) — an honest empty tree+ return NextResponse.json({ folders: [] })+ }++ // LEFT JOIN counts only LIVE designs (trashed rows still belong to+ // their folder and return on restore, but they are not clutter for+ // the count). Attribution scoping is in the WHERE, never the join.+ const rows = await db.$queryRawUnsafe<+ { id: string; name: string; createdAt: Date; designCount: number }[]+ >(+ `SELECT f.id, f.name, f."createdAt", COUNT(d.id)::int AS "designCount"+ FROM "Folder" f+ LEFT JOIN "Design" d ON d."folderId" = f.id AND d."deletedAt" IS NULL+ WHERE (f."ownerId" = $1 AND $1 IS NOT NULL) OR (f."anonKey" = $2 AND $2 IS NOT NULL)+ GROUP BY f.id, f.name, f."createdAt"+ ORDER BY f."createdAt" ASC+ LIMIT ${FOLDERS_LIMIT}`,+ ownerId,+ anonKey,+ )+ return NextResponse.json({+ folders: rows.map((f) => ({+ id: f.id,+ name: f.name,+ createdAt: f.createdAt,+ designCount: f.designCount,+ })),+ })+ } catch (error) {+ console.error('[api/folders] list failed', error)+ return NextResponse.json({ error: 'Could not load folders.' }, { status: 500 })+ }+}++async function __canvix_post(req: NextRequest) {+ if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })+ const limit = checkRateLimit(req, 'folders:create')+ if (!limit.ok) return rateLimitResponse(limit)+ try {+ const body = (await req.json().catch(() => ({}))) as { name?: unknown }+ const name = sanitizeName(body.name)+ if (!name) return NextResponse.json({ error: 'A folder name is required.' }, { status: 400 })++ const user = await getSessionUser(req)++ if (user) {+ const existing = await db.folder.count({+ where: { ownerId: user.id },+ })+ if (existing >= MAX_FOLDERS) {+ return NextResponse.json(+ { error: `Folder limit reached (${MAX_FOLDERS}). Delete one first.` },+ { status: 409 },+ )+ }+ const folder = await db.folder.create({+ data: { name, ownerId: user.id },+ select: { id: true, name: true, createdAt: true },+ })+ return NextResponse.json({ folder: { ...folder, designCount: 0 } }, { status: 201 })+ }++ // Anonymous: mint/refresh this browser's attribution, stamp the row+ const token = readAnonToken(req) ?? newAnonToken()+ const existing = await db.folder.count({+ where: { anonKey: anonKeyHash(token) },+ })+ if (existing >= MAX_FOLDERS) {+ return NextResponse.json(+ { error: `Folder limit reached (${MAX_FOLDERS}). Delete one first.` },+ { status: 409 },+ )+ }+ const folder = await db.folder.create({+ data: { name, anonKey: anonKeyHash(token) },+ select: { id: true, name: true, createdAt: true },+ })+ const res = NextResponse.json({ folder: { ...folder, designCount: 0 } }, { status: 201 })+ setAnonCookie(res, token)+ return res+ } catch (error) {+ console.error('[api/folders] create failed', error)+ return NextResponse.json({ error: 'Could not create the folder.' }, { status: 500 })+ }+}++// v0.12.5 (H7): opt-in request logging wrapper — passthrough+// unless CANVIX_LOG=requests (see src/lib/observability.ts)+export const GET = withLogging('GET /api/folders', __canvix_get)+export const POST = withLogging('POST /api/folders', __canvix_post)diff --git a/src/components/dashboard/Dashboard.tsx b/src/components/dashboard/Dashboard.tsxindex d4d15e9..fa45552 100644--- a/src/components/dashboard/Dashboard.tsx+++ b/src/components/dashboard/Dashboard.tsx@@ -29,6 +29,10 @@ import {LogIn,LogOut,FolderInput,+ Folder,+ FolderPlus,+ FolderMinus,+ Check,} from 'lucide-react'import { useAppStore } from '@/store/app-store'import { useEditorStore } from '@/store/editor-store'@@ -46,15 +50,20 @@ import { cn } from '@/lib/utils'import {ApiError,createDesign,+ createFolder,deleteDesign,deleteDesignForever,+ deleteFolder,duplicateDesign,fetchDesign,listTrash,+ moveDesignToFolder,renameDesign,+ renameFolder,restoreDesign,timeAgo,useDesigns,+ useFolders,type DesignMeta,} from './hooks'import {@@ -69,6 +78,10 @@ import {DropdownMenu,DropdownMenuContent,DropdownMenuItem,+ DropdownMenuSeparator,+ DropdownMenuSub,+ DropdownMenuSubContent,+ DropdownMenuSubTrigger,DropdownMenuTrigger,} from '@/components/ui/dropdown-menu'import { toast } from '@/hooks/use-toast'@@ -111,7 +124,11 @@ export function Dashboard() {const goLanding = useAppStore((s) => s.goLanding)const openEditor = useAppStore((s) => s.openEditor)const loadEditorDesign = useEditorStore((s) => s.loadDesign)- const { designs, loading, refresh, dbIssue, hasMore, loadMore } = useDesigns()+ // v0.14 (D6): folder organization — activeFolder null = "All designs"+ // (the root, the pre-v0.14 view). The designs hook refetches on switch.+ const [activeFolder, setActiveFolder] = useState<string | null>(null)+ const { designs, loading, refresh, dbIssue, hasMore, loadMore } = useDesigns(activeFolder)+ const { folders, refresh: refreshFolders } = useFolders()const isMobile = useIsMobile()const [helpOpen, setHelpOpen] = useState(false)@@ -139,6 +156,11 @@ export function Dashboard() {const [trashOpen, setTrashOpen] = useState(false)const [trash, setTrash] = useState<DesignMeta[] | null>(null)const [sort, setSort] = useState<'recent' | 'name'>('recent')+ // v0.14 (D6): the create/rename folder dialog (one dialog, two modes)+ const [folderDialog, setFolderDialog] = useState<+ { mode: 'create' } | { mode: 'rename'; id: string; name: string } | null+ >(null)+ const [folderValue, setFolderValue] = useState('')const refreshTrash = useCallback(async () => {try {@@ -201,6 +223,8 @@ export function Dashboard() {)// ── actions ─────────────────────────────────────────────────+ // v0.14 (D6): anything created from this dashboard is born inside the+ // folder the user is currently viewing (null = the root)const startBlank = async (w: number, h: number, name?: string) => {setCreating(true)try {@@ -209,6 +233,7 @@ export function Dashboard() {width: w,height: h,pages: newBlankPages(),+ folderId: activeFolder,})openEditor(record)loadEditorDesign(record)@@ -228,6 +253,7 @@ export function Dashboard() {height: t.height,pages: t.pages,source: `template:${t.slug}`,+ folderId: activeFolder,})openEditor(record)loadEditorDesign(record)@@ -250,10 +276,14 @@ export function Dashboard() {}}- const doDuplicate = async (id: string) => {+ const doDuplicate = async (d: DesignMeta) => {try {- await duplicateDesign(id)- await refresh()+ // v0.14 (D6): the copy stays in the design's folder — but only when+ // that folder is one of the caller's own (foreign folders 404)+ const mineFolder =+ d.folderId && (folders ?? []).some((f) => f.id === d.folderId) ? d.folderId : null+ await duplicateDesign(d.id, mineFolder)+ await Promise.all([refresh(), refreshFolders()])toast({ title: 'Design duplicated' })} catch {toast({ title: 'Could not duplicate', variant: 'destructive' })@@ -284,6 +314,67 @@ export function Dashboard() {}}+ // ── v0.14 (D6): folder actions ──────────────────────────────+ const openCreateFolder = () => {+ setFolderValue('')+ setFolderDialog({ mode: 'create' })+ }++ const openRenameFolder = (id: string, name: string) => {+ setFolderValue(name)+ setFolderDialog({ mode: 'rename', id, name })+ }++ const doFolderSubmit = async () => {+ if (!folderDialog) return+ const dialog = folderDialog+ const name = folderValue.trim()+ setFolderDialog(null)+ if (!name) return+ try {+ if (dialog.mode === 'create') {+ const folder = await createFolder(name)+ await refreshFolders()+ toast({ title: `Folder “${folder.name}” created` })+ } else {+ await renameFolder(dialog.id, name)+ await refreshFolders()+ toast({ title: 'Folder renamed' })+ }+ } catch (error) {+ apiErrorToast(error, 'Could not save the folder')+ }+ }++ const doDeleteFolder = async (id: string, name: string) => {+ const ok = window.confirm(+ `Delete the folder “${name}”?\n\nThe designs inside are NOT deleted — they return to All designs.`,+ )+ if (!ok) return+ try {+ await deleteFolder(id)+ if (activeFolder === id) setActiveFolder(null)+ await Promise.all([refreshFolders(), refresh()])+ toast({ title: `Folder “${name}” deleted — its designs are in All designs` })+ } catch {+ toast({ title: 'Could not delete the folder', variant: 'destructive' })+ }+ }++ const doMoveDesign = async (id: string, folderId: string | null, name: string) => {+ try {+ await moveDesignToFolder(id, folderId)+ await Promise.all([refresh(), refreshFolders()])+ toast({+ title: folderId+ ? `“${name}” moved to “${(folders ?? []).find((f) => f.id === folderId)?.name ?? 'folder'}”`+ : `“${name}” moved to All designs`,+ })+ } catch (error) {+ apiErrorToast(error, 'Could not move the design')+ }+ }+return (<div className="min-h-screen flex bg-[#1F142E] text-[#EDEEF2]">{/* ── Canva-style left rail (desktop) ── */}@@ -622,7 +713,11 @@ export function Dashboard() {{/* ── Recent designs ── */}<section id="cv-recents" className="pt-12 scroll-mt-20"><div className="flex items-center justify-between flex-wrap gap-3">- <h2 className="text-xl font-bold">Recent designs</h2>+ <h2 className="text-xl font-bold">+ {activeFolder+ ? (folders ?? []).find((f) => f.id === activeFolder)?.name ?? 'Folder'+ : 'Recent designs'}+ </h2>{/* v0.4: canva-style sort control */}<div className="flex items-center gap-1 rounded-full border border-white/10 p-0.5" role="group" aria-label="Sort designs">{(['recent', 'name'] as const).map((mode) => (@@ -640,6 +735,70 @@ export function Dashboard() {))}</div></div>++ {/* v0.14 (D6): folder chips — All designs + the caller's folders. */}+ <div className="mt-3 flex items-center gap-2 flex-wrap" role="group" aria-label="Design folders">+ <button+ onClick={() => setActiveFolder(null)}+ className={cn(+ 'inline-flex items-center gap-1.5 rounded-full px-3.5 py-1.5 text-sm font-medium border transition-colors',+ activeFolder === null+ ? 'bg-[#7630D7] text-white border-transparent'+ : 'bg-transparent border-white/12 text-white/60 hover:border-white/30 hover:text-white'+ )}+ aria-pressed={activeFolder === null}+ >+ <LayoutGrid size={14} /> All designs+ </button>+ {(folders ?? []).map((f) => (+ <span+ key={f.id}+ className={cn(+ 'inline-flex items-center rounded-full border transition-colors',+ activeFolder === f.id+ ? 'bg-[#7630D7] text-white border-transparent'+ : 'bg-transparent border-white/12 text-white/60 hover:border-white/30',+ )}+ >+ <button+ onClick={() => setActiveFolder(f.id)}+ className="inline-flex items-center gap-1.5 rounded-l-full pl-3.5 py-1.5 pr-1.5 text-sm font-medium hover:text-white transition-colors"+ aria-pressed={activeFolder === f.id}+ aria-label={`Open folder ${f.name}`}+ >+ <Folder size={14} /> {f.name}+ <span className="text-xs text-white/40">{f.designCount}</span>+ </button>+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <Button+ variant="ghost"+ size="icon"+ className="h-6 w-6 rounded-r-full text-white/50 hover:bg-white/10 hover:text-white"+ aria-label={`Options for folder ${f.name}`}+ >+ <MoreHorizontal size={13} />+ </Button>+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" className="w-40 bg-[#16181D] border-white/10 text-white">+ <DropdownMenuItem onClick={() => openRenameFolder(f.id, f.name)}>+ <Pencil size={14} className="mr-2" /> Rename+ </DropdownMenuItem>+ <DropdownMenuItem className="text-red-600 focus:text-red-600" onClick={() => void doDeleteFolder(f.id, f.name)}>+ <Trash2 size={14} className="mr-2" /> Delete folder+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ </span>+ ))}+ <button+ onClick={openCreateFolder}+ className="inline-flex items-center gap-1.5 rounded-full px-3 py-1.5 text-sm font-medium border border-dashed border-white/20 text-white/50 hover:border-white/40 hover:text-white transition-colors"+ aria-label="New folder"+ >+ <FolderPlus size={14} /> New folder+ </button>+ </div>{loading ? (<div className="mt-4 grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-4">{Array.from({ length: 5 }).map((_, i) => (@@ -653,10 +812,14 @@ export function Dashboard() {) : filteredDesigns.length === 0 ? (<div className="mt-6 rounded-2xl border-2 border-dashed border-white/12 p-10 text-center"><div className="mx-auto h-14 w-14 rounded-2xl bg-brand-gradient-soft flex items-center justify-center text-[#A78BFA]">- <Plus size={24} />+ {activeFolder ? <Folder size={24} /> : <Plus size={24} />}</div>- <p className="mt-4 font-semibold">No designs yet</p>- <p className="mt-1 text-sm text-white/45">Pick a preset or template above to get started.</p>+ <p className="mt-4 font-semibold">{activeFolder ? 'This folder is empty' : 'No designs yet'}</p>+ <p className="mt-1 text-sm text-white/45">+ {activeFolder+ ? 'Open a design’s ⋯ menu and “Move to folder”, or create something new — it lands here.'+ : 'Pick a preset or template above to get started.'}+ </p></div>) : (<div className="mt-4 grid grid-cols-2 sm:grid-cols-3 lg:grid-cols-5 gap-4">@@ -709,9 +872,44 @@ export function Dashboard() {<DropdownMenuItem onClick={() => { setRenameTarget({ id: d.id, name: d.name }); setRenameValue(d.name) }}><Pencil size={14} className="mr-2" /> Rename</DropdownMenuItem>- <DropdownMenuItem onClick={() => doDuplicate(d.id)}>+ <DropdownMenuItem onClick={() => void doDuplicate(d)}><Copy size={14} className="mr-2" /> Duplicate</DropdownMenuItem>+ <DropdownMenuSub>+ <DropdownMenuSubTrigger className="gap-2">+ <Folder size={14} /> Move to folder+ </DropdownMenuSubTrigger>+ <DropdownMenuSubContent className="w-44 bg-[#16181D] border-white/10 text-white">+ {(folders ?? []).length === 0 ? (+ <DropdownMenuItem disabled>+ Create a folder first — “New folder” above+ </DropdownMenuItem>+ ) : (+ (folders ?? []).map((f) => (+ <DropdownMenuItem+ key={f.id}+ onClick={() => void doMoveDesign(d.id, f.id, d.name)}+ className="gap-2"+ >+ {d.folderId === f.id ? (+ <Check size={14} className="text-[#A78BFA]" />+ ) : (+ <span className="w-[14px]" />+ )}+ <span className="truncate">{f.name}</span>+ </DropdownMenuItem>+ ))+ )}+ {d.folderId && (+ <>+ <DropdownMenuSeparator className="bg-white/10" />+ <DropdownMenuItem onClick={() => void doMoveDesign(d.id, null, d.name)}>+ <FolderMinus size={14} className="mr-2" /> Remove from folder+ </DropdownMenuItem>+ </>+ )}+ </DropdownMenuSubContent>+ </DropdownMenuSub><DropdownMenuItem className="text-red-600 focus:text-red-600" onClick={() => setDeleteTarget(d.id)}><Trash2 size={14} className="mr-2" /> Delete</DropdownMenuItem>@@ -976,6 +1174,36 @@ export function Dashboard() {</DialogContent></Dialog>+ {/* ── v0.14 (D6): create / rename folder dialog ── */}+ <Dialog open={!!folderDialog} onOpenChange={(open) => !open && setFolderDialog(null)}>+ <DialogContent className="rounded-[28px] sm:max-w-sm bg-[#16181D] border-white/10 text-white">+ <DialogHeader>+ <DialogTitle>{folderDialog?.mode === 'rename' ? 'Rename folder' : 'New folder'}</DialogTitle>+ {folderDialog?.mode === 'create' && (+ <DialogDescription className="text-white/55">+ Folders organize your designs — deleting one never deletes the designs inside.+ </DialogDescription>+ )}+ </DialogHeader>+ <Input+ value={folderValue}+ onChange={(e) => setFolderValue(e.target.value)}+ autoFocus+ maxLength={60}+ placeholder="Folder name"+ onKeyDown={(e) => e.key === 'Enter' && void doFolderSubmit()}+ className="bg-white/[0.06] border-white/10 text-white"+ aria-label="Folder name"+ />+ <DialogFooter>+ <Button variant="outline" className="border-white/15 bg-transparent text-white hover:bg-white/10 hover:text-white" onClick={() => setFolderDialog(null)}>Cancel</Button>+ <Button className="btn-cv" onClick={() => void doFolderSubmit()}>+ {folderDialog?.mode === 'rename' ? 'Save' : 'Create'}+ </Button>+ </DialogFooter>+ </DialogContent>+ </Dialog>+{/* ── v0.9: account sign-in / sign-up ── */}<AuthDialogopen={authOpen}@@ -983,8 +1211,10 @@ export function Dashboard() {initialMode={authMode}onAuthed={() => {// the session changed — re-read auth state AND the dashboard scope+ // (v0.14 D6: folders were claimed into the account on login)void refreshAuth()void refresh()+ void refreshFolders()}}/></div>diff --git a/src/components/dashboard/hooks.ts b/src/components/dashboard/hooks.tsindex 8eda644..0ebf58e 100644--- a/src/components/dashboard/hooks.ts+++ b/src/components/dashboard/hooks.ts@@ -18,11 +18,21 @@ export interface DesignMeta {/** v0.9.1: ownerless AND attributed to this exact browser — the only rows* the bulk "Save my designs" action will claim. */mine?: boolean+ /** v0.14 (D6): the folder this design is filed under (null = root). */+ folderId?: string | nulldeletedAt: string | nullcreatedAt: stringupdatedAt: string}+/** v0.14 (D6): one dashboard folder — the caller's own, always. */+export interface FolderMeta {+ id: string+ name: string+ createdAt: string+ designCount: number+}+function toRecord(row: Record<string, unknown>): DesignRecord {const pages = typeof row.pages === 'string' ? JSON.parse(row.pages || '[]') : (row.pages ?? [])return { ...(row as unknown as DesignRecord), pages: pages as PageData[] }@@ -56,9 +66,19 @@ interface DesignsPage {nextCursor: { cursor: string; id: string } | null}-async function fetchDesignsPage(cursor?: { cursor: string; id: string } | null): Promise<DesignsPage> {- const qs = cursor ? `?cursor=${encodeURIComponent(cursor.cursor)}&id=${encodeURIComponent(cursor.id)}` : ''- const res = await fetch(`/api/designs${qs}`, { cache: 'no-store' })+async function fetchDesignsPage(+ cursor?: { cursor: string; id: string } | null,+ folderId?: string | null+): Promise<DesignsPage> {+ const params = new URLSearchParams()+ if (cursor) {+ params.set('cursor', cursor.cursor)+ params.set('id', cursor.id)+ }+ // v0.14 (D6): a folder filter scopes the list to that folder+ if (folderId) params.set('folder', folderId)+ const qs = params.toString()+ const res = await fetch(`/api/designs${qs ? `?${qs}` : ''}`, { cache: 'no-store' })if (!res.ok) {const err = await readApiError(res)throw new ApiError(err.message, err.code, err.fix)@@ -67,9 +87,13 @@ async function fetchDesignsPage(cursor?: { cursor: string; id: string } | null):return { designs: body.designs ?? [], nextCursor: body.nextCursor ?? null }}-export function useDesigns() {+export function useDesigns(folderId?: string | null) {const [designs, setDesigns] = useState<DesignMeta[] | null>(null)- const [loading, setLoading] = useState(true)+ // v0.14 (D6): the folder the held `designs` page belongs to. When it+ // differs from `folderId` the hook is (re)loading a new view — the+ // DERIVED `loading` below flips true synchronously on the switch,+ // without any setState inside the effect (react-hooks rule).+ const [loadedFor, setLoadedFor] = useState<string | null>(null)// v0.8: null = healthy; otherwise an error code/message from the APIconst [dbIssue, setDbIssue] = useState<string | null>(null)// v0.9.2: pagination state — true when the server says there is another page@@ -79,7 +103,7 @@ export function useDesigns() {const refresh = useCallback(async () => {try {- const page = await fetchDesignsPage()+ const page = await fetchDesignsPage(null, folderId)setDesigns(page.designs)setHasMore(page.nextCursor !== null)nextCursorRef.current = page.nextCursor@@ -90,16 +114,16 @@ export function useDesigns() {setHasMore(false)nextCursorRef.current = null} finally {- setLoading(false)+ setLoadedFor(folderId ?? null)}- }, [])+ }, [folderId])/** v0.9.2: append the next page (guard against double-clicks/stale calls). */const loadMore = useCallback(async () => {if (loadingMoreRef.current || !nextCursorRef.current) returnloadingMoreRef.current = truetry {- const page = await fetchDesignsPage(nextCursorRef.current)+ const page = await fetchDesignsPage(nextCursorRef.current, folderId)nextCursorRef.current = page.nextCursorsetHasMore(page.nextCursor !== null)setDesigns((prev) => (prev ? [...prev, ...page.designs] : page.designs))@@ -108,24 +132,96 @@ export function useDesigns() {} finally {loadingMoreRef.current = false}- }, [])+ }, [folderId])useEffect(() => {// kick the fetch off in a microtask so the effect body itself never// calls setState synchronously (react-hooks/set-state-in-effect);// refresh() only sets state after its awaits resolve anyway.+ // v0.14 (D6): switching folders re-runs this because refresh is+ // keyed on folderId.void Promise.resolve().then(() => refresh())}, [refresh])+ // loading = nothing loaded yet, OR the held page belongs to a+ // different folder than the one being viewed (mid-switch skeletons)+ const loading = designs === null || loadedFor !== (folderId ?? null)+return { designs, loading, refresh, dbIssue, clearDbIssue: () => setDbIssue(null), hasMore, loadMore }}+// ── v0.14 (D6): folders ─────────────────────────────────────++export function useFolders() {+ const [folders, setFolders] = useState<FolderMeta[] | null>(null)++ const refresh = useCallback(async () => {+ try {+ const res = await fetch('/api/folders', { cache: 'no-store' })+ if (!res.ok) throw new Error('failed')+ const body = (await res.json()) as { folders?: FolderMeta[] }+ setFolders(body.folders ?? [])+ } catch {+ setFolders([]) // honest empty tree — folders are never critical-path+ }+ }, [])++ useEffect(() => {+ void Promise.resolve().then(() => refresh())+ }, [refresh])++ return { folders, refresh }+}++export async function createFolder(name: string): Promise<FolderMeta> {+ const res = await fetch('/api/folders', {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ name }),+ })+ if (!res.ok) {+ const err = await readApiError(res)+ throw new ApiError(err.message, err.code, err.fix)+ }+ const body = (await res.json()) as { folder: FolderMeta }+ return body.folder+}++export async function renameFolder(id: string, name: string): Promise<void> {+ const res = await fetch(`/api/folders/${id}`, {+ method: 'PATCH',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ name }),+ })+ if (!res.ok) throw new Error('Failed to rename folder')+}++export async function deleteFolder(id: string): Promise<void> {+ const res = await fetch(`/api/folders/${id}`, { method: 'DELETE' })+ if (!res.ok) throw new Error('Failed to delete folder')+}++/** File a design into one of the caller's folders (null = the root). */+export async function moveDesignToFolder(id: string, folderId: string | null): Promise<void> {+ const res = await fetch(`/api/designs/${id}/move`, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ folderId }),+ })+ if (!res.ok) {+ const err = await readApiError(res)+ throw new ApiError(err.message, err.code, err.fix)+ }+}+export async function createDesign(opts: {name: stringwidth: numberheight: numberpages: PageData[]source?: string+ /** v0.14 (D6): create directly inside one of the caller's folders. */+ folderId?: string | null}): Promise<DesignRecord> {const res = await fetch('/api/designs', {method: 'POST',@@ -136,6 +232,7 @@ export async function createDesign(opts: {height: opts.height,pages: opts.pages,source: opts.source ?? 'blank',+ folderId: opts.folderId ?? null,}),})if (!res.ok) {@@ -154,14 +251,18 @@ export async function fetchDesign(id: string): Promise<DesignRecord> {return toRecord(await res.json())}-export async function duplicateDesign(id: string): Promise<DesignRecord> {+export async function duplicateDesign(id: string, folderId?: string | null): Promise<DesignRecord> {const source = await fetchDesign(id)+ // v0.14 (D6): a duplicate stays in its folder when the caller asks+ // for it (the dashboard passes the design's folder only when it is+ // one of the caller's own — foreign folders 404 at the API).return createDesign({name: `${source.name} copy`,width: source.width,height: source.height,pages: source.pages,source: `duplicate:${id}`,+ folderId: folderId ?? null,})}diff --git a/src/lib/auth/claim-folders.ts b/src/lib/auth/claim-folders.tsnew file mode 100644index 0000000..db77538--- /dev/null+++ b/src/lib/auth/claim-folders.ts@@ -0,0 +1,31 @@+// ─────────────────────────────────────────────────────────────+// claim-folders — anonymous folders follow the account (v0.14, D6).+//+// Folders stamp attribution exactly like designs and media: signed-out+// creations carry the canvix_anon cookie hash. Signing in (or+// registering) claims those rows into the account, so the folder tree+// is visible from every device after login — the same D1 acceptance+// criterion, applied to organization.+//+// Designs keep pointing at the same folder ids through the claim (the+// rows are re-attributed in place), so nothing else needs to move.+// Failures are swallowed (best-effort — unclaimed folders stay+// anonymous and still work in that browser).+// ─────────────────────────────────────────────────────────────++import type { NextRequest } from 'next/server'+import { db } from '@/lib/db'+import { anonKeyHash, readAnonToken } from '@/lib/auth/anon'++export async function claimAnonFolders(req: NextRequest, userId: string): Promise<void> {+ try {+ const token = readAnonToken(req)+ if (!token) return+ await db.folder.updateMany({+ where: { ownerId: null, anonKey: anonKeyHash(token) },+ data: { ownerId: userId, anonKey: null },+ })+ } catch {+ // best-effort: unclaimed folders stay anonymous and still work+ }+}diff --git a/src/lib/rate-limit.ts b/src/lib/rate-limit.tsindex ebefb12..b194029 100644--- a/src/lib/rate-limit.ts+++ b/src/lib/rate-limit.ts@@ -34,6 +34,8 @@ export type RateLimitBucket =| 'designs:create'| 'designs:update'| 'designs:delete'+ | 'folders:create'+ | 'folders:update'| 'collab:events'| 'collab:presence'| 'comments:create'@@ -55,6 +57,11 @@ export const RATE_LIMITS: Record<RateLimitBucket, RateLimitConfig> = {// room for multi-tab + collaboration saves before it ever bites'designs:update': { windowMs: 60_000, max: 300 },'designs:delete': { windowMs: 60_000, max: 60 },+ // v0.14 (D6): folder CRUD is cheap but should never be scriptable+ // at scale — 30 creates / 60 renames+deletes per minute per IP is+ // far beyond any organizing session, well under abuse velocity+ 'folders:create': { windowMs: 60_000, max: 30 },+ 'folders:update': { windowMs: 60_000, max: 60 },// collab flush cadence is 400 ms per active client → 150/min'collab:events': { windowMs: 60_000, max: 600 },// presence heartbeats every 15 s → 4/min per clientdiff --git a/tests/e2e/folders.spec.ts b/tests/e2e/folders.spec.tsnew file mode 100644index 0000000..d360ea0--- /dev/null+++ b/tests/e2e/folders.spec.ts@@ -0,0 +1,193 @@+import { test, expect, type Page } from '@playwright/test'++/**+ * v0.14 (D6): dashboard folders — acceptance.+ *+ * 1. folder lifecycle: create a folder from the dashboard, file a+ * design into it (card ⋯ menu), the folder view shows ONLY that+ * design while All designs keeps everything, rename the folder,+ * delete it — the designs survive, back at the root (API truth)+ * 2. folders are PRIVATE organization: a different browser's+ * attribution cannot list, mutate, filter by, or create into+ * someone else's folders (flat 404s, no existence oracle)+ *+ * Both tests are fully ANONYMOUS — zero account registrations (the+ * suite-wide register budget is 5/h/IP, see the PR #26 fix).+ */++const ts = Date.now().toString(36)++async function openDashboard(page: Page) {+ await page.goto('/')+ await page.getByRole('button', { name: /start designing/i }).first().click()+ await expect(page.getByLabel('Create a design')).toBeVisible({ timeout: 60_000 })+}++async function createDesign(page: Page, name: string): Promise<string> {+ const res = await page.request.post('/api/designs', {+ data: {+ name,+ width: 800,+ height: 600,+ pages: [{ id: 'p1', background: { type: 'solid', color: '#FFFFFF' }, elements: [] }],+ },+ })+ expect(res.status(), `create design ${name}: ${await res.text()}`).toBeLessThan(300)+ return ((await res.json()) as { id: string }).id+}++test.setTimeout(120_000)++test.describe('Folders (v0.14 D6)', () => {+ test('create → file a design in → filter → rename → delete → designs survive at the root', async ({ page }) => {+ await openDashboard(page)++ // ── create the folder from the chips row ──+ await page.getByRole('button', { name: 'New folder' }).click()+ const dialog = page.getByRole('dialog')+ await expect(dialog).toBeVisible()+ await dialog.getByLabel('Folder name').fill(`Client work ${ts}`)+ await dialog.getByRole('button', { name: 'Create', exact: true }).click()+ await expect(dialog).toBeHidden()++ const chip = page.getByRole('button', { name: `Open folder Client work ${ts}` })+ await expect(chip).toBeVisible({ timeout: 45_000 })+ await expect(chip).toContainText('0') // empty folder count++ // two anonymous designs: one to file, one to leave at the root+ const filedName = `cvx_d6_filed_${ts}`+ const rootedName = `cvx_d6_rooted_${ts}`+ const filedId = await createDesign(page, filedName)+ await createDesign(page, rootedName)++ // reload the dashboard — both designs are in All designs+ await openDashboard(page)+ const filedCard = page.getByRole('button', { name: `Open ${filedName}` })+ const rootedCard = page.getByRole('button', { name: `Open ${rootedName}` })+ await expect(filedCard).toBeVisible({ timeout: 45_000 })+ await expect(rootedCard).toBeVisible()++ // ── file the design through the card's ⋯ menu ──+ await page.getByRole('button', { name: `Options for ${filedName}` }).click()+ await page.getByRole('menuitem', { name: 'Move to folder' }).click()+ await page.getByRole('menuitem', { name: `Client work ${ts}` }).click()++ // the chip count went up (UI truth)…+ await expect(chip).toContainText('1')++ // …and the API agrees+ const foldersRes = await page.request.get('/api/folders')+ expect(foldersRes.status()).toBe(200)+ const foldersBody = (await foldersRes.json()) as {+ folders: { id: string; name: string; designCount: number }[]+ }+ const folder = foldersBody.folders.find((f) => f.name === `Client work ${ts}`)+ expect(folder?.designCount).toBe(1)+ const listRes = await page.request.get(`/api/designs?folder=${folder?.id}`)+ expect(listRes.status()).toBe(200)+ const listed = (await listRes.json()) as { designs: { id: string }[] }+ expect(listed.designs.map((d) => d.id)).toContain(filedId)++ // ── the folder view shows ONLY the filed design ──+ await chip.click()+ await expect(page.getByRole('heading', { name: `Client work ${ts}` })).toBeVisible()+ await expect(filedCard).toBeVisible()+ await expect(rootedCard).toBeHidden()++ // ── All designs still shows everything ──+ await page.getByRole('button', { name: 'All designs' }).click()+ await expect(page.getByRole('heading', { name: 'Recent designs' })).toBeVisible()+ await expect(filedCard).toBeVisible()+ await expect(rootedCard).toBeVisible()++ // ── rename the folder from the chip's ⋯ menu ──+ await page.getByRole('button', { name: `Options for folder Client work ${ts}` }).click()+ await page.getByRole('menuitem', { name: 'Rename' }).click()+ const renameDialog = page.getByRole('dialog')+ await expect(renameDialog).toBeVisible()+ await renameDialog.getByLabel('Folder name').fill(`Client work 2026 ${ts}`)+ await renameDialog.getByRole('button', { name: 'Save', exact: true }).click()+ await expect(renameDialog).toBeHidden()+ const renamedChip = page.getByRole('button', { name: `Open folder Client work 2026 ${ts}` })+ await expect(renamedChip).toBeVisible({ timeout: 45_000 })++ // ── delete the folder: the confirm guard accepts ──+ page.on('dialog', (d) => void d.accept())+ await page.getByRole('button', { name: `Options for folder Client work 2026 ${ts}` }).click()+ await page.getByRole('menuitem', { name: 'Delete folder' }).click()++ // the chip is gone, the view falls back to All designs…+ await expect(renamedChip).toBeHidden({ timeout: 45_000 })+ await expect(page.getByRole('heading', { name: 'Recent designs' })).toBeVisible()+ // …and BOTH designs survived (API truth: unfiled, not deleted)+ const after = (await (await page.request.get(`/api/designs/${filedId}`)).json()) as {+ folderId: string | null+ deletedAt: string | null+ }+ expect(after.folderId).toBeNull()+ expect(after.deletedAt).toBeNull()+ await expect(filedCard).toBeVisible()+ await expect(rootedCard).toBeVisible()++ // the folder tree is empty again+ const treeRes = await page.request.get('/api/folders')+ const tree = (await treeRes.json()) as { folders: { name: string }[] }+ expect(tree.folders.some((f) => f.name.includes(ts))).toBe(false)+ })++ test('folders are private to their attribution — foreign ids are flat 404s', async ({ browser }) => {+ // browser A (with the folder) — API only, no dashboard needed+ const ctxA = await browser.newContext()+ const pageA = await ctxA.newPage()+ await pageA.goto('/')+ const createRes = await pageA.request.post('/api/folders', {+ data: { name: `Secret A ${ts}` },+ })+ expect(createRes.status(), await createRes.text()).toBeLessThan(300)+ const { folder } = (await createRes.json()) as { folder: { id: string } }+ expect(folder.id).toBeTruthy()++ // browser B (different attribution): the folder does not exist to it+ const ctxB = await browser.newContext()+ const pageB = await ctxB.newPage()+ await pageB.goto('/')++ const listRes = await pageB.request.get('/api/folders')+ expect(listRes.status()).toBe(200)+ const body = (await listRes.json()) as { folders: { id: string }[] }+ expect(body.folders.some((f) => f.id === folder.id)).toBe(false)++ // no mutation, no filtering, no creating-into, no existence oracle+ const patch = await pageB.request.patch(`/api/folders/${folder.id}`, {+ data: { name: 'Hijacked' },+ })+ expect(patch.status()).toBe(404)+ const del = await pageB.request.delete(`/api/folders/${folder.id}`)+ expect(del.status()).toBe(404)+ const filtered = await pageB.request.get(`/api/designs?folder=${folder.id}`)+ expect(filtered.status()).toBe(404)+ const createInto = await pageB.request.post('/api/designs', {+ data: { name: 'Intruder', width: 800, height: 600, folderId: folder.id },+ })+ expect(createInto.status()).toBe(404)++ // the move route rejects a foreign folder too (ownerless design,+ // editable by B — but the TARGET folder is not B's)+ const designRes = await pageA.request.post('/api/designs', {+ data: {+ name: `cvx_d6_iso_${ts}`,+ width: 800,+ height: 600,+ pages: [{ id: 'p1', background: { type: 'solid', color: '#FFFFFF' }, elements: [] }],+ },+ })+ const designId = ((await designRes.json()) as { id: string }).id+ const move = await pageB.request.post(`/api/designs/${designId}/move`, {+ data: { folderId: folder.id },+ })+ expect(move.status()).toBe(404)++ await ctxA.close()+ await ctxB.close()+ })+})