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.

fix(v0.9.1): claim eligibility, CSRF enforcement & the pre-Phase-4 verification gate

Ashiq Hussain Mir9ce8d82465f6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 939e5ee..0346ef7 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,59 @@
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.9.1] — 2026-10-28
+
+The "never claim someone else's work" release: claim eligibility is now
+enforced, CSRF is closed out, and the verification report the roadmap
+called for exists as executable tests.
+
+### Claim eligibility (adopt-all made safe)
+- **Anonymous attribution** — the first anonymous design creation sets a
+ `canvix_anon` cookie (256-bit, HttpOnly, 1 year); the design row stores
+ sha256(token) in the new indexed `Design.anonKey` (migration
+ `0003_anon_attribution`, purely additive). A database leak never
+ contains usable attribution tokens.
+- **adopt-all is scoped** — `POST /api/designs/adopt-all` now claims only
+ ownerless designs whose `anonKey` matches the caller's own browser.
+ Another person's anonymous work and legacy (pre-attribution) rows are
+ structurally outside the UPDATE. A browser with no attribution cookie
+ claims nothing.
+- **Per-design adoption** — new `POST /api/designs/[id]/adopt` claims ONE
+ ownerless design deliberately: your own browser's designs and legacy
+ rows are claimable; a foreign browser's design answers
+ `403 NOT_ELIGIBLE`; races between two claimants are resolved atomically
+ by a conditional `updateMany` (`409` on loss).
+- **Dashboard** shows the honest claimable count ("Save my designs to
+ this account (N)") and a per-design "Save to my account" action; the
+ list API exposes a boolean `claimable` per design (never the hash).
+
+### CSRF protection for cookie-authenticated writes
+- Every mutating API route (`POST /api/designs`, `PUT`/`DELETE` on a
+ design, restore, adopt, adopt-all, register, login, logout) now
+ enforces same-origin: browsers always attach `Origin` (or `Referer`)
+ to cross-site requests; when present it must match the request's host
+ (`x-forwarded-host` honoured behind proxies). Non-browser clients
+ (curl, MCP, health probes) send neither header and pass — they carry
+ no ambient cookie authority. This is defence-in-depth on top of the
+ existing `SameSite=Lax` session cookie.
+
+### Verification (the pre-Phase-4 gate)
+- `scripts/auth-e2e.sh` now proves, against a real database: register →
+ me → owned create → owner save → anonymous 403 → logout → **revoked
+ token replay is dead** → wrong-password 401 → login → **cross-origin
+ PUT/POST rejected (CSRF)** → same-origin unaffected → **two anonymous
+ browsers: adopt-all claims only the caller's own design** → foreign
+ per-design adopt refused, legacy allowed → **cross-account isolation
+ (B cannot modify/delete/adopt C's design, opens it view-only)**.
+ All probe rows are removed afterwards.
+- New unit suites: session expiry/revocation/cookie hardening (mocked
+ DB), CSRF guard matrix, adopt-all eligibility (the WHERE-clause
+ invariant), per-design adopt matrix. SSRF suite extended with
+ DNS-flip regressions (between requests and mid-redirect-chain).
+ **152/152 tests green.**
+- `package-lock.json` version resynced with `package.json` (skew since
+ 0.8.1 — tolerated by npm but confusing for tooling).
+
## [0.9.0] — 2026-10-28
The "Your designs, yours" release: free accounts, per-design ownership,
diff --git a/README.md b/README.md
index 385a04f..1edf771 100644
--- a/README.md
+++ b/README.md
@@ -63,8 +63,18 @@ is right here.
anyone else. Share links still open — in view-only mode with an honest
banner in the editor.
- **Nothing breaks for existing setups** — ownerless designs keep the exact
- pre-v0.9 link-editable behaviour. One click (**“Save all designs to my
- account”**) migrates your existing library into your new account.
+ pre-v0.9 link-editable behaviour. One click (**“Save my designs to this
+ account”**) migrates the designs *this browser created* into your new
+ account — anonymous creations are attributed to the creating browser
+ (`canvix_anon` cookie, sha256-hashed in the DB), so **adopt-all can
+ never sweep up another person's work**. Legacy designs from before
+ attribution exist? Claim those one-by-one with the per-design
+ **“Save to my account”** action (a deliberate, visible action for
+ pre-accounts self-hosters).
+- **CSRF-safe writes** — every mutating API route enforces same-origin on
+ top of the SameSite=Lax session cookie; cross-site POST/PUT/DELETE
+ requests answer `403 CSRF_REJECTED`. Non-browser clients (curl, the MCP
+ endpoint) are unaffected.
- **Collab identity upgrade** — signed-in users appear under their real
username in presence, cursors and comments.
- **DNS-rebinding pinning (SSRF close-out)** — the MCP server's `safeFetch`
@@ -73,8 +83,10 @@ is right here.
so certificate validation is unaffected.
- **End-to-end CI verification** — the “Canvix Database Setup” workflow now
boots the built server against your real database and exercises the whole
- account + ownership flow (register → me → owned create → owner save →
- anonymous 403 → logout → login) before cleaning up after itself.
+ account + ownership + claim-safety + CSRF flow (register → me → owned
+ create → owner save → anonymous 403 → logout → revoked-token replay →
+ login → cross-origin rejection → two-browser adopt-all scoping →
+ cross-account isolation) before cleaning up after itself.
### v0.8.0 — Supabase-ready infrastructure & the 110-template library
@@ -619,6 +631,8 @@ tool descriptions so agents pick the right format.
- [x] 110-template library, Supabase-first migrations & self-diagnosing setup *(v0.8.0)*
- [x] Accounts & per-design ownership — free username/password accounts, private
designs, one-click migration of existing work, SSRF DNS pinning *(v0.9.0)*
+- [x] Claim eligibility (browser-attributed adopt-all, per-design adopt),
+ CSRF same-origin enforcement, pre-Phase-4 verification gate *(v0.9.1)*
- [ ] Yjs-grade offline merge for collaboration
- [ ] Audio/video elements & Beat Sync
- [ ] Plugin system (external, installable apps)
diff --git a/package-lock.json b/package-lock.json
index 7f47859..2915ca3 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -1,12 +1,12 @@
{
"name": "canvix",
- "version": "0.8.0",
+ "version": "0.9.1",
"lockfileVersion": 3,
"requires": true,
"packages": {
"": {
"name": "canvix",
- "version": "0.8.0",
+ "version": "0.9.1",
"dependencies": {
"@imgly/background-removal": "^1.7.0",
"@prisma/client": "^6.11.1",
@@ -3443,6 +3443,72 @@
"node": ">=14.0.0"
}
},
+ "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core": {
+ "version": "1.11.1",
+ "dev": true,
+ "inBundle": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "@emnapi/wasi-threads": "1.2.2",
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime": {
+ "version": "1.11.1",
+ "dev": true,
+ "inBundle": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads": {
+ "version": "1.2.2",
+ "dev": true,
+ "inBundle": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime": {
+ "version": "1.1.4",
+ "dev": true,
+ "inBundle": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "@tybys/wasm-util": "^0.10.1"
+ },
+ "funding": {
+ "type": "github",
+ "url": "https://github.com/sponsors/Brooooooklyn"
+ },
+ "peerDependencies": {
+ "@emnapi/core": "^1.7.1",
+ "@emnapi/runtime": "^1.7.1"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util": {
+ "version": "0.10.2",
+ "dev": true,
+ "inBundle": true,
+ "license": "MIT",
+ "optional": true,
+ "dependencies": {
+ "tslib": "^2.4.0"
+ }
+ },
+ "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib": {
+ "version": "2.8.1",
+ "dev": true,
+ "inBundle": true,
+ "license": "0BSD",
+ "optional": true
+ },
"node_modules/@tailwindcss/oxide-win32-arm64-msvc": {
"version": "4.3.3",
"resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.3.3.tgz",
diff --git a/package.json b/package.json
index b0260df..4eb08e1 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "canvix",
- "version": "0.9.0",
+ "version": "0.9.1",
"private": false,
"description": "Canvix \u2014 free & open-source graphic design tool. A community-built Canva alternative.",
"scripts": {
diff --git a/prisma/migrations/0003_anon_attribution/migration.sql b/prisma/migrations/0003_anon_attribution/migration.sql
new file mode 100644
index 0000000..403d530
--- /dev/null
+++ b/prisma/migrations/0003_anon_attribution/migration.sql
@@ -0,0 +1,12 @@
+-- v0.9.1 — anonymous attribution for ownerless designs.
+--
+-- POST /api/designs stamps every anonymous creation with the sha256 of a
+-- per-browser `canvix_anon` cookie, so "adopt all" can be scoped to the
+-- designs this browser actually created (never another person's work).
+-- Existing ownerless rows keep anonKey = NULL (legacy): they are excluded
+-- from bulk adoption and can only be claimed one-by-one, deliberately.
+
+ALTER TABLE "Design" ADD COLUMN "anonKey" TEXT;
+
+-- Adopt-all scans WHERE "ownerId" IS NULL AND "anonKey" = <caller hash>.
+CREATE INDEX "Design_anonKey_idx" ON "Design"("anonKey");
diff --git a/prisma/schema.prisma b/prisma/schema.prisma
index 602a765..6064da6 100644
--- a/prisma/schema.prisma
+++ b/prisma/schema.prisma
@@ -48,6 +48,13 @@ model Design {
// behaviour — anonymous editing keeps working for legacy + shared links).
ownerId String?
owner User? @relation("DesignOwner", fields: [ownerId], references: [id], onDelete: SetNull)
+ // v0.9.1: anonymous attribution — sha256 of the canvix_anon cookie that
+ // was set when an anonymous browser created this design. adopt-all only
+ // claims rows whose anonKey matches the caller's cookie, so one account
+ // can never sweep up another person's anonymous work. null = legacy
+ // design created before attribution existed (claimable only via the
+ // explicit per-design adopt endpoint).
+ anonKey String?
// soft delete (dashboard Trash) — null = live design
deletedAt DateTime?
versions DesignVersion[]
@@ -55,6 +62,7 @@ model Design {
updatedAt DateTime @updatedAt
@@index([ownerId])
+ @@index([anonKey])
}
// Server-side version snapshots for a design (Canva "Version history").
diff --git a/scripts/auth-e2e.sh b/scripts/auth-e2e.sh
index 35af9cd..a3e7c27 100755
--- a/scripts/auth-e2e.sh
+++ b/scripts/auth-e2e.sh
@@ -1,21 +1,31 @@
#!/bin/bash
-# scripts/auth-e2e.sh — end-to-end smoke test of the v0.9 account system
-# against a REAL database (Supabase/Neon/local). Builds the standalone
-# server, boots it, and exercises the full account + ownership flow via
-# plain curl:
+# scripts/auth-e2e.sh — end-to-end verification of the v0.9/v0.9.1 account,
+# ownership and claim-safety behaviour against a REAL database
+# (Supabase/Neon/local). Builds the standalone server, boots it, and
+# exercises the full flow via plain curl:
#
-# register → me → create (owned) → save as owner → 403 as anonymous
-# → login → logout → me(null) → cleanup
+# register → me → owned create → owner save → anonymous 403
+# → logout → revoked-token replay → me(null) → wrong password 401 → login
+# → CSRF: cross-origin PUT/POST rejected
+# → anonymous attribution: two browsers create ownerless designs
+# → adopt-all claims ONLY the caller's own browser's designs
+# → per-design adopt: foreign browser's design refused, legacy allowed
+# → cross-account isolation: B cannot modify/delete C's design
+# → cleanup (all probe rows removed)
#
-# Exits non-zero on the first failed expectation. Leaves no rows behind
-# (the test user + design are deleted at the end).
+# Exits non-zero on the first failed expectation. Leaves no rows behind.
set -u
cd "$(dirname "$0")/.."
PORT="${E2E_PORT:-3100}"
BASE="http://127.0.0.1:$PORT"
-JAR="$(mktemp)"
+JAR="$(mktemp)" # browser/account TS_USER
+JAR_A="$(mktemp)" # anonymous browser A
+JAR_B="$(mktemp)" # anonymous browser B → later account B
+JAR_C="$(mktemp)" # account C (isolation probe)
TS_USER="e2e_tester_$$_$(date +%s)"
+USER_B="e2e_b_$$_$(date +%s)"
+USER_C="e2e_c_$$_$(date +%s)"
TS_PASS='e2e-Tr0ub4dor-pass'
SERVER_PID=""
@@ -25,7 +35,7 @@ fail() { printf ' \033[1;31m✗ %s\033[0m\n' "$*"; exit 1; }
cleanup() {
[ -n "$SERVER_PID" ] && kill "$SERVER_PID" 2>/dev/null
- rm -f "$JAR"
+ rm -f "$JAR" "$JAR_A" "$JAR_B" "$JAR_C"
}
trap cleanup EXIT
@@ -78,7 +88,7 @@ STATUS=$(curl -s -o /dev/null -w '%{http_code}' -b "$JAR" \
[ "$STATUS" = "200" ] || fail "owner save expected 200, got $STATUS"
pass "owner PUT → 200"
-# ── 5. anonymous gets 403 (the ownership guard) ─────────────
+# ── 5. anonymous gets 403 (the ownership guard) ──────────────
STATUS=$(curl -s -o /tmp/e2e-r5.json -w '%{http_code}' \
-H 'Content-Type: application/json' \
-X PUT "$BASE/api/designs/$DESIGN_ID" \
@@ -87,10 +97,15 @@ STATUS=$(curl -s -o /tmp/e2e-r5.json -w '%{http_code}' \
grep -q "READ_ONLY_DESIGN" /tmp/e2e-r5.json || fail "403 body should carry READ_ONLY_DESIGN"
pass "anonymous PUT → 403 READ_ONLY_DESIGN (ownership enforced)"
-# ── 6. logout → me is null ──────────────────────────────────
+# ── 6. logout → me is null; REVOKED token replay is dead ────
+OLD_TOKEN=$(awk '$6=="canvix_session" {print $7}' "$JAR" | tail -1)
+[ -n "$OLD_TOKEN" ] || fail "could not capture the session token for the replay probe"
curl -sf -b "$JAR" -c "$JAR" -X POST "$BASE/api/auth/logout" >/dev/null || fail "logout failed"
curl -sf -b "$JAR" "$BASE/api/auth/me" | grep -q '"user":null' || fail "me should be null after logout"
pass "logout → me(null)"
+curl -sf -H "Cookie: canvix_session=$OLD_TOKEN" "$BASE/api/auth/me" | grep -q '"user":null' \
+ || fail "REPLAY of the logged-out token must be rejected server-side (revocation)"
+pass "revoked session token replay → me(null) (server-side revocation works)"
# ── 7. wrong password is refused ────────────────────────────
STATUS=$(curl -s -o /dev/null -w '%{http_code}' \
@@ -108,15 +123,131 @@ STATUS=$(curl -s -o /dev/null -w '%{http_code}' -c "$JAR" \
[ "$STATUS" = "200" ] || fail "login expected 200, got $STATUS"
pass "login → 200, session restored"
-# ── cleanup: remove the probe rows ───────────────────────────
+# ── 9. CSRF: cross-site mutations are rejected ───────────────
+STATUS=$(curl -s -o /tmp/e2e-r9.json -w '%{http_code}' -b "$JAR" \
+ -H 'Content-Type: application/json' \
+ -H 'Origin: https://evil.example' \
+ -X PUT "$BASE/api/designs/$DESIGN_ID" \
+ -d '{"name":"csrf attempt"}')
+[ "$STATUS" = "403" ] || fail "cross-origin PUT expected 403, got $STATUS"
+grep -q "CSRF_REJECTED" /tmp/e2e-r9.json || fail "CSRF 403 body should carry CSRF_REJECTED"
+pass "cross-origin PUT → 403 CSRF_REJECTED"
+STATUS=$(curl -s -o /dev/null -w '%{http_code}' \
+ -H 'Content-Type: application/json' \
+ -H 'Origin: https://evil.example' \
+ -X POST "$BASE/api/designs" \
+ -d '{"name":"csrf attempt"}')
+[ "$STATUS" = "403" ] || fail "cross-origin POST /api/designs expected 403, got $STATUS"
+pass "cross-origin POST → 403 CSRF_REJECTED"
+# same-origin mutations still work (Origin matches the host)
+STATUS=$(curl -s -o /dev/null -w '%{http_code}' -b "$JAR" \
+ -H 'Content-Type: application/json' \
+ -H "Origin: $BASE" \
+ -X PUT "$BASE/api/designs/$DESIGN_ID" \
+ -d '{"name":"same-origin save"}')
+[ "$STATUS" = "200" ] || fail "same-origin PUT expected 200, got $STATUS"
+pass "same-origin PUT → 200 (guard does not over-block)"
+
+# ── 10. anonymous attribution: two browsers, two designs ────
+STATUS=$(curl -s -o /tmp/e2e-xa.json -w '%{http_code}' -c "$JAR_A" \
+ -H 'Content-Type: application/json' \
+ -X POST "$BASE/api/designs" \
+ -d '{"name":"E2E browser A design","width":100,"height":100}')
+[ "$STATUS" = "201" ] || fail "browser A create expected 201, got $STATUS"
+DESIGN_A=$(node -e "console.log(JSON.parse(require('fs').readFileSync('/tmp/e2e-xa.json','utf8')).id)")
+awk '$6=="canvix_anon" {print $7}' "$JAR_A" | grep -q . || fail "anonymous create must set the canvix_anon attribution cookie"
+pass "browser A created ownerless design $DESIGN_A (attribution cookie set)"
+
+STATUS=$(curl -s -o /tmp/e2e-xb.json -w '%{http_code}' -c "$JAR_B" \
+ -H 'Content-Type: application/json' \
+ -X POST "$BASE/api/designs" \
+ -d '{"name":"E2E browser B design","width":100,"height":100}')
+[ "$STATUS" = "201" ] || fail "browser B create expected 201, got $STATUS"
+DESIGN_B=$(node -e "console.log(JSON.parse(require('fs').readFileSync('/tmp/e2e-xb.json','utf8')).id)")
+pass "browser B created ownerless design $DESIGN_B"
+
+# a LEGACY design (pre-attribution): inserted directly, anonKey NULL
+LEGACY_ID=$(DATABASE_URL="$DATABASE_URL" npx tsx -e "
+const { PrismaClient } = require('@prisma/client')
+const db = new PrismaClient()
+;(async () => {
+ const d = await db.design.create({ data: { name: 'E2E legacy (pre-accounts) design', width: 100, height: 100 } })
+ console.log(d.id)
+ await db.\$disconnect()
+})().catch(() => process.exit(1))
+") || fail "could not insert the legacy probe design"
+pass "legacy design inserted directly: $LEGACY_ID (anonKey NULL, ownerId NULL)"
+
+# ── 11. register account B from browser B's jar ─────────────
+STATUS=$(curl -s -o /dev/null -w '%{http_code}' -b "$JAR_B" -c "$JAR_B" \
+ -H 'Content-Type: application/json' \
+ -X POST "$BASE/api/auth/register" \
+ -d "{\"username\":\"$USER_B\",\"password\":\"$TS_PASS\"}")
+[ "$STATUS" = "201" ] || fail "register B expected 201, got $STATUS"
+pass "registered $USER_B (same browser/cookie context as design B)"
+
+# ── 12. adopt-all claims ONLY browser B's own design ─────────
+ADOPTED=$(curl -sf -b "$JAR_B" -X POST "$BASE/api/designs/adopt-all" | node -e "let s='';process.stdin.on('data',d=>s+=d).on('end',()=>console.log(JSON.parse(s).adopted))")
+[ "$ADOPTED" = "1" ] || fail "adopt-all must claim exactly browser B's 1 design, got $ADOPTED (eligibility scoping broken!)"
+pass "adopt-all → adopted exactly 1 (browser B's own design; A's, the legacy row and all other users' work untouched)"
+curl -sf "$BASE/api/designs/$DESIGN_A" | grep -q '"ownerId":null' || fail "browser A's design must still be ownerless after B's adopt-all"
+pass "browser A's design remains ownerless (no cross-browser theft)"
+curl -sf "$BASE/api/designs/$LEGACY_ID" | grep -q '"ownerId":null' || fail "the legacy design must NOT be bulk-claimed"
+pass "legacy design untouched by adopt-all (needs explicit per-design adoption)"
+
+# ── 13. per-design adopt: foreign refused, legacy allowed ────
+STATUS=$(curl -s -o /tmp/e2e-adopt-a.json -w '%{http_code}' -b "$JAR_B" \
+ -X POST "$BASE/api/designs/$DESIGN_A/adopt")
+[ "$STATUS" = "403" ] || fail "B adopting browser A's design expected 403, got $STATUS"
+grep -q "NOT_ELIGIBLE" /tmp/e2e-adopt-a.json || fail "per-design adopt refusal should carry NOT_ELIGIBLE"
+pass "per-design adopt of a foreign browser's design → 403 NOT_ELIGIBLE"
+STATUS=$(curl -s -o /dev/null -w '%{http_code}' -b "$JAR_B" \
+ -X POST "$BASE/api/designs/$LEGACY_ID/adopt")
+[ "$STATUS" = "200" ] || fail "deliberate per-design adoption of a legacy design expected 200, got $STATUS"
+pass "explicit per-design adoption of the legacy design → 200 (deliberate action)"
+
+# ── 14. cross-account isolation (B vs C) ─────────────────────
+STATUS=$(curl -s -o /dev/null -w '%{http_code}' -c "$JAR_C" \
+ -H 'Content-Type: application/json' \
+ -X POST "$BASE/api/auth/register" \
+ -d "{\"username\":\"$USER_C\",\"password\":\"$TS_PASS\"}")
+[ "$STATUS" = "201" ] || fail "register C expected 201, got $STATUS"
+STATUS=$(curl -s -o /tmp/e2e-w.json -w '%{http_code}' -b "$JAR_C" \
+ -H 'Content-Type: application/json' \
+ -X POST "$BASE/api/designs" \
+ -d '{"name":"E2E account C design","width":100,"height":100}')
+[ "$STATUS" = "201" ] || fail "C create expected 201, got $STATUS"
+DESIGN_W=$(node -e "console.log(JSON.parse(require('fs').readFileSync('/tmp/e2e-w.json','utf8')).id)")
+pass "registered $USER_C and created owned design $DESIGN_W"
+
+STATUS=$(curl -s -o /tmp/e2e-isol.json -w '%{http_code}' -b "$JAR_B" \
+ -H 'Content-Type: application/json' \
+ -X PUT "$BASE/api/designs/$DESIGN_W" \
+ -d '{"name":"B hijacking C"}')
+[ "$STATUS" = "403" ] || fail "B modifying C's design expected 403, got $STATUS"
+STATUS=$(curl -s -o /dev/null -w '%{http_code}' -b "$JAR_B" \
+ -X DELETE "$BASE/api/designs/$DESIGN_W")
+[ "$STATUS" = "403" ] || fail "B deleting C's design expected 403, got $STATUS"
+STATUS=$(curl -s -o /dev/null -w '%{http_code}' -b "$JAR_B" \
+ -X POST "$BASE/api/designs/$DESIGN_W/adopt")
+[ "$STATUS" = "403" ] || fail "B adopting C's design expected 403, got $STATUS"
+pass "account B cannot modify, delete or adopt account C's design (403 ×3)"
+curl -sf -b "$JAR_B" "$BASE/api/designs/$DESIGN_W" | grep -q '"readOnly":true' \
+ || fail "B's GET of C's design should report readOnly:true (view-only mode)"
+pass "B opens C's design in view-only mode (readOnly:true)"
+
+# ── cleanup: remove every probe row ──────────────────────────
DATABASE_URL="$DATABASE_URL" npx tsx -e "
const { PrismaClient } = require('@prisma/client')
const db = new PrismaClient()
;(async () => {
- await db.design.deleteMany({ where: { id: process.argv[1] } })
- await db.user.deleteMany({ where: { username: process.argv[2] } })
+ const ids = process.argv.slice(1, 6) // 5 design ids
+ const names = process.argv.slice(6) // 3 usernames
+ await db.design.deleteMany({ where: { id: { in: ids } } })
+ await db.user.deleteMany({ where: { username: { in: names } } })
await db.\$disconnect()
})().then(() => process.exit(0)).catch(() => process.exit(1))
-" "$DESIGN_ID" "$TS_USER" || fail "cleanup failed"
+" "$DESIGN_ID" "$DESIGN_A" "$DESIGN_B" "$LEGACY_ID" "$DESIGN_W" "$TS_USER" "$USER_B" "$USER_C" \
+ || fail "cleanup failed"
-say "all green — accounts, ownership and sessions verified end-to-end."
+say "all green — accounts, sessions, CSRF, claim eligibility and ownership verified end-to-end."
diff --git a/src/app/api/auth/login/route.ts b/src/app/api/auth/login/route.ts
index 77397d6..1571231 100644
--- a/src/app/api/auth/login/route.ts
+++ b/src/app/api/auth/login/route.ts
@@ -4,11 +4,14 @@ import { verifyPassword } from '@/lib/auth/passwords'
import { canonicalUsername, checkUsername } from '@/lib/auth/validate'
import { createSession } from '@/lib/auth/session'
import { rateLimit } from '@/lib/ai/provider'
+import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'
// POST /api/auth/login — exchange username + password for a session cookie.
// One deliberately generic error message: never reveal whether the
// username exists (account enumeration).
+// v0.9.1: same-origin enforced (blocks login CSRF / session fixation).
export async function POST(req: NextRequest) {
+ if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })
const rl = rateLimit('auth:login', req, 10, 600)
if (!rl.ok) {
return NextResponse.json(
diff --git a/src/app/api/auth/logout/route.ts b/src/app/api/auth/logout/route.ts
index 3af32c7..e33a07e 100644
--- a/src/app/api/auth/logout/route.ts
+++ b/src/app/api/auth/logout/route.ts
@@ -1,8 +1,12 @@
import { NextRequest, NextResponse } from 'next/server'
import { destroySession } from '@/lib/auth/session'
+import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'
// POST /api/auth/logout — revoke the current session + clear the cookie.
+// v0.9.1: same-origin enforced (a cross-site page must not be able to
+// log the visitor out — logout CSRF).
export async function POST(req: NextRequest) {
+ if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })
const res = NextResponse.json({ ok: true })
await destroySession(req, res)
return res
diff --git a/src/app/api/auth/register/route.ts b/src/app/api/auth/register/route.ts
index 3ca62c9..8de6c5f 100644
--- a/src/app/api/auth/register/route.ts
+++ b/src/app/api/auth/register/route.ts
@@ -4,11 +4,14 @@ import { hashPassword } from '@/lib/auth/passwords'
import { canonicalUsername, checkUsername, checkPassword } from '@/lib/auth/validate'
import { createSession } from '@/lib/auth/session'
import { rateLimit } from '@/lib/ai/provider'
+import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'
// POST /api/auth/register — create an account (username + password).
// Free forever: no email, no verification, no external provider — a
// self-hosted account system with zero moving parts beyond the DB.
+// v0.9.1: same-origin enforced (blocks cross-site forced sign-ups).
export async function POST(req: NextRequest) {
+ if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })
const rl = rateLimit('auth:register', req, 5, 3600)
if (!rl.ok) {
return NextResponse.json(
diff --git a/src/app/api/designs/[id]/adopt/adopt.test.ts b/src/app/api/designs/[id]/adopt/adopt.test.ts
new file mode 100644
index 0000000..957bc9b
--- /dev/null
+++ b/src/app/api/designs/[id]/adopt/adopt.test.ts
@@ -0,0 +1,126 @@
+// Unit tests for per-design adoption (v0.9.1) — the deliberate,
+// single-design claim path.
+//
+// Eligibility matrix:
+// owned by other → 403 READ_ONLY_DESIGN (never claimable)
+// owned by self → idempotent ok / adopted 0
+// ownerless + own hash → claimed
+// ownerless + legacy → claimed (explicit action, by design)
+// ownerless + foreign → 403 NOT_ELIGIBLE (someone else's work)
+// race (count 0) → 409
+
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+const dbMock = vi.hoisted(() => ({
+ design: {
+ findUnique: vi.fn(),
+ updateMany: vi.fn(),
+ },
+}))
+vi.mock('@/lib/db', () => ({ db: dbMock }))
+
+const getSessionUser = vi.hoisted(() => vi.fn())
+vi.mock('@/lib/auth/session', () => ({ getSessionUser }))
+
+import { NextRequest } from 'next/server'
+import { POST } from './route'
+import { ANON_COOKIE, anonKeyHash } from '@/lib/auth/anon'
+
+const USER = { id: 'user-1', username: 'ashiq', createdAt: new Date() }
+
+function post(id: string, opts: { cookie?: string; origin?: string } = {}) {
+ const headers: Record<string, string> = { host: 'canvix.test' }
+ if (opts.cookie) headers.cookie = opts.cookie
+ if (opts.origin) headers.origin = opts.origin
+ const req = new NextRequest(`http://canvix.test/api/designs/${id}/adopt`, { method: 'POST', headers })
+ return POST(req, { params: Promise.resolve({ id }) })
+}
+
+function designRow(overrides: Record<string, unknown> = {}) {
+ return { id: 'd1', ownerId: null, anonKey: null, ...overrides }
+}
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ getSessionUser.mockResolvedValue(USER)
+ dbMock.design.updateMany.mockResolvedValue({ count: 1 })
+})
+
+describe('POST /api/designs/[id]/adopt', () => {
+ it('requires a signed-in account', async () => {
+ getSessionUser.mockResolvedValue(null)
+ const res = await post('d1', { cookie: `${ANON_COOKIE}=t` })
+ expect(res.status).toBe(401)
+ expect(dbMock.design.updateMany).not.toHaveBeenCalled()
+ })
+
+ it('rejects cross-site requests (CSRF)', async () => {
+ const res = await post('d1', { origin: 'https://evil.example' })
+ expect(res.status).toBe(403)
+ expect(dbMock.design.updateMany).not.toHaveBeenCalled()
+ })
+
+ it('404s for unknown designs', async () => {
+ dbMock.design.findUnique.mockResolvedValue(null)
+ expect((await post('missing')).status).toBe(404)
+ })
+
+ it('NEVER claims a design owned by another account', async () => {
+ dbMock.design.findUnique.mockResolvedValue(designRow({ ownerId: 'user-2' }))
+ const res = await post('d1')
+ expect(res.status).toBe(403)
+ const body = await res.json()
+ expect(body.code).toBe('READ_ONLY_DESIGN')
+ expect(dbMock.design.updateMany).not.toHaveBeenCalled()
+ })
+
+ it('is idempotent for designs you already own', async () => {
+ dbMock.design.findUnique.mockResolvedValue(designRow({ ownerId: USER.id }))
+ const res = await post('d1')
+ expect(res.status).toBe(200)
+ expect(await res.json()).toEqual({ ok: true, adopted: 0 })
+ expect(dbMock.design.updateMany).not.toHaveBeenCalled()
+ })
+
+ it('refuses a foreign browser’s anonymous design (NOT_ELIGIBLE)', async () => {
+ dbMock.design.findUnique.mockResolvedValue(designRow({ anonKey: anonKeyHash('someone-elses-browser') }))
+ const res = await post('d1', { cookie: `${ANON_COOKIE}=my-browser` })
+ expect(res.status).toBe(403)
+ const body = await res.json()
+ expect(body.code).toBe('NOT_ELIGIBLE')
+ expect(dbMock.design.updateMany).not.toHaveBeenCalled()
+ })
+
+ it('refuses a foreign design even when the caller has no attribution cookie', async () => {
+ dbMock.design.findUnique.mockResolvedValue(designRow({ anonKey: anonKeyHash('someone-elses-browser') }))
+ const res = await post('d1')
+ expect(res.status).toBe(403)
+ expect((await res.json()).code).toBe('NOT_ELIGIBLE')
+ })
+
+ it('claims the caller’s own anonymous design', async () => {
+ const token = 'my-browser'
+ dbMock.design.findUnique.mockResolvedValue(designRow({ anonKey: anonKeyHash(token) }))
+ const res = await post('d1', { cookie: `${ANON_COOKIE}=${token}` })
+ expect(res.status).toBe(200)
+ expect(await res.json()).toEqual({ ok: true, adopted: 1 })
+ expect(dbMock.design.updateMany).toHaveBeenCalledWith({
+ where: { id: 'd1', ownerId: null }, // the guard re-checks ownerlessness atomically
+ data: { ownerId: USER.id },
+ })
+ })
+
+ it('claims a LEGACY design (pre-attribution, anonKey null) — deliberate single-design action', async () => {
+ dbMock.design.findUnique.mockResolvedValue(designRow({ anonKey: null }))
+ const res = await post('d1', { cookie: `${ANON_COOKIE}=my-browser` })
+ expect(res.status).toBe(200)
+ expect(await res.json()).toEqual({ ok: true, adopted: 1 })
+ })
+
+ it('reports 409 when a racing account wins the claim', async () => {
+ dbMock.design.findUnique.mockResolvedValue(designRow({ anonKey: null }))
+ dbMock.design.updateMany.mockResolvedValue({ count: 0 })
+ const res = await post('d1')
+ expect(res.status).toBe(409)
+ })
+})
diff --git a/src/app/api/designs/[id]/adopt/route.ts b/src/app/api/designs/[id]/adopt/route.ts
new file mode 100644
index 0000000..7fd438a
--- /dev/null
+++ b/src/app/api/designs/[id]/adopt/route.ts
@@ -0,0 +1,63 @@
+import { NextRequest, NextResponse } from 'next/server'
+import { db } from '@/lib/db'
+import { getSessionUser } from '@/lib/auth/session'
+import { anonHashFrom } from '@/lib/auth/anon'
+import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'
+import { NOT_YOUR_DESIGN } from '@/lib/auth/design-guard'
+
+// POST /api/designs/[id]/adopt — deliberately claim ONE ownerless
+// design into the signed-in account.
+//
+// Eligibility (v0.9.1):
+// • ownerless + attributed to THIS browser (anonKey matches) → claim
+// • ownerless + legacy (anonKey null, created before attribution) → claim
+// • ownerless + attributed to ANOTHER browser → 403 NOT_ELIGIBLE
+// • already owned by you → ok, adopted 0 (idempotent)
+// • owned by someone else → 403 (the regular ownership guard)
+//
+// The claim itself is a single conditional updateMany (WHERE ownerId IS
+// NULL), so two racing accounts can never both win.
+export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
+ if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })
+ const user = await getSessionUser(req)
+ if (!user) {
+ return NextResponse.json(
+ { error: 'Sign in first — adopting a design moves it into your account.' },
+ { status: 401 }
+ )
+ }
+ try {
+ const { id } = await params
+ const design = await db.design.findUnique({ where: { id } })
+ if (!design) return NextResponse.json({ error: 'Not found' }, { status: 404 })
+
+ if (design.ownerId !== null) {
+ if (design.ownerId === user.id) return NextResponse.json({ ok: true, adopted: 0 })
+ return NextResponse.json(NOT_YOUR_DESIGN, { status: 403 })
+ }
+
+ const anonHash = anonHashFrom(req)
+ if (design.anonKey !== null && design.anonKey !== anonHash) {
+ return NextResponse.json(
+ {
+ error: 'This design was created from another browser — it stays shared.',
+ code: 'NOT_ELIGIBLE',
+ },
+ { status: 403 }
+ )
+ }
+
+ const result = await db.design.updateMany({
+ where: { id, ownerId: null },
+ data: { ownerId: user.id },
+ })
+ if (result.count === 0) {
+ // Lost the race: someone claimed it between our read and write.
+ return NextResponse.json({ error: 'This design was just claimed by someone else.' }, { status: 409 })
+ }
+ return NextResponse.json({ ok: true, adopted: 1 })
+ } catch (error) {
+ console.error('POST /api/designs/[id]/adopt failed', error)
+ return NextResponse.json({ error: 'Failed to adopt design.' }, { status: 500 })
+ }
+}
diff --git a/src/app/api/designs/[id]/restore/route.ts b/src/app/api/designs/[id]/restore/route.ts
index 2a7d3af..b0b68ac 100644
--- a/src/app/api/designs/[id]/restore/route.ts
+++ b/src/app/api/designs/[id]/restore/route.ts
@@ -1,10 +1,13 @@
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'
// POST /api/designs/[id]/restore — restore a design from the Trash.
// v0.9: owner-only for owned designs (403 otherwise); ownerless unchanged.
+// v0.9.1: same-origin enforced (CSRF).
export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
+ if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })
try {
const { id } = await params
const access = await resolveDesignAccess(req, id)
diff --git a/src/app/api/designs/[id]/route.ts b/src/app/api/designs/[id]/route.ts
index ff8d1c3..dbeea2d 100644
--- a/src/app/api/designs/[id]/route.ts
+++ b/src/app/api/designs/[id]/route.ts
@@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from 'next/server'
import { Prisma } from '@prisma/client'
import { db } from '@/lib/db'
import { resolveDesignAccess, NOT_YOUR_DESIGN } from '@/lib/auth/design-guard'
+import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'
// Normalise incoming pages payload (accepts object or legacy JSON string)
// into a value suitable for the Postgres jsonb column.
@@ -31,8 +32,9 @@ export async function GET(req: NextRequest, { params }: { params: Promise<{ id:
// PUT /api/designs/[id] — save design (name / pages / thumbnail)
// v0.9: ownerless designs stay link-editable; owned designs only save
-// for their owner (403 otherwise).
+// for their owner (403 otherwise). v0.9.1: same-origin enforced (CSRF).
export async function PUT(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
+ if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })
try {
const { id } = await params
const access = await resolveDesignAccess(req, id)
@@ -59,8 +61,9 @@ export async function PUT(req: NextRequest, { params }: { params: Promise<{ id:
// DELETE /api/designs/[id] — move to Trash (soft delete).
// ?permanent=1 → delete permanently (also removes version snapshots).
// v0.9: ownerless designs stay link-editable; owned designs only delete
-// for their owner (403 otherwise).
+// for their owner (403 otherwise). v0.9.1: same-origin enforced (CSRF).
export async function DELETE(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
+ if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })
try {
const { id } = await params
const access = await resolveDesignAccess(req, id)
diff --git a/src/app/api/designs/adopt-all/adopt-all.test.ts b/src/app/api/designs/adopt-all/adopt-all.test.ts
new file mode 100644
index 0000000..4031ac9
--- /dev/null
+++ b/src/app/api/designs/adopt-all/adopt-all.test.ts
@@ -0,0 +1,74 @@
+// Unit tests for adopt-all eligibility (v0.9.1) — the "never claim
+// another person's work" guarantee.
+//
+// The invariant: the bulk claim's WHERE clause is constrained to the
+// caller's OWN attribution hash (and ownerId IS NULL). A browser that
+// never made anonymous designs claims nothing; foreign work and legacy
+// rows are structurally outside the update.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+const dbMock = vi.hoisted(() => ({
+ design: { updateMany: vi.fn() },
+}))
+vi.mock('@/lib/db', () => ({ db: dbMock }))
+
+const getSessionUser = vi.hoisted(() => vi.fn())
+vi.mock('@/lib/auth/session', () => ({ getSessionUser }))
+
+import { NextRequest } from 'next/server'
+import { POST } from './route'
+import { ANON_COOKIE, anonKeyHash } from '@/lib/auth/anon'
+
+const USER = { id: 'user-1', username: 'ashiq', createdAt: new Date() }
+
+function post(opts: { cookie?: string; origin?: string } = {}) {
+ const headers: Record<string, string> = { host: 'canvix.test' }
+ if (opts.cookie) headers.cookie = opts.cookie
+ if (opts.origin) headers.origin = opts.origin
+ const req = new NextRequest('http://canvix.test/api/designs/adopt-all', { method: 'POST', headers })
+ return POST(req)
+}
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ getSessionUser.mockResolvedValue(USER)
+})
+
+describe('POST /api/designs/adopt-all', () => {
+ it('requires a signed-in account', async () => {
+ getSessionUser.mockResolvedValue(null)
+ const res = await post({ cookie: `${ANON_COOKIE}=whatever` })
+ expect(res.status).toBe(401)
+ expect(dbMock.design.updateMany).not.toHaveBeenCalled()
+ })
+
+ it('rejects cross-site requests (CSRF)', async () => {
+ const res = await post({ origin: 'https://evil.example' })
+ expect(res.status).toBe(403)
+ expect(dbMock.design.updateMany).not.toHaveBeenCalled()
+ })
+
+ it('claims NOTHING when the browser has no attribution cookie', async () => {
+ const res = await post()
+ expect(res.status).toBe(200)
+ const body = await res.json()
+ expect(body).toEqual({ ok: true, adopted: 0 })
+ expect(dbMock.design.updateMany).not.toHaveBeenCalled()
+ })
+
+ it('scopes the bulk claim to THIS browser’s attribution hash only', async () => {
+ const token = 'browser-a-token'
+ dbMock.design.updateMany.mockResolvedValue({ count: 3 })
+ const res = await post({ cookie: `${ANON_COOKIE}=${token}` })
+ expect(res.status).toBe(200)
+ expect(await res.json()).toEqual({ ok: true, adopted: 3 })
+ // THE invariant: ownerId null AND anonKey = sha256(caller's cookie).
+ // Foreign anonymous designs (other hashes) and legacy rows (null)
+ // are outside this UPDATE by construction.
+ expect(dbMock.design.updateMany).toHaveBeenCalledWith({
+ where: { ownerId: null, anonKey: anonKeyHash(token) },
+ data: { ownerId: USER.id },
+ })
+ })
+})
diff --git a/src/app/api/designs/adopt-all/route.ts b/src/app/api/designs/adopt-all/route.ts
index b985f57..6c29b08 100644
--- a/src/app/api/designs/adopt-all/route.ts
+++ b/src/app/api/designs/adopt-all/route.ts
@@ -1,14 +1,19 @@
import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'
import { getSessionUser } from '@/lib/auth/session'
+import { anonHashFrom } from '@/lib/auth/anon'
+import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'
// POST /api/designs/adopt-all — one-click migration into an account.
//
-// For the user who self-hosted Canvix before accounts existed (or who
-// worked anonymously and just signed up): claims every ownerless design
-// so they become private to the signed-in account. Idempotent — designs
-// that already have an owner are never touched.
+// v0.9.1 SAFETY: claims ONLY the ownerless designs attributed to the
+// caller's own browser (Design.anonKey = sha256 of the canvix_anon
+// cookie). Another person's anonymous work and pre-attribution legacy
+// rows are never touched — the first need their author's own browser,
+// the second are claimed one-by-one via POST /api/designs/[id]/adopt.
+// Idempotent; already-owned designs are excluded by the query itself.
export async function POST(req: NextRequest) {
+ if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })
const user = await getSessionUser(req)
if (!user) {
return NextResponse.json(
@@ -17,8 +22,13 @@ export async function POST(req: NextRequest) {
)
}
try {
+ const anonHash = anonHashFrom(req)
+ if (!anonHash) {
+ // No attribution cookie → nothing this browser created → claim nothing.
+ return NextResponse.json({ ok: true, adopted: 0 })
+ }
const result = await db.design.updateMany({
- where: { ownerId: null },
+ where: { ownerId: null, anonKey: anonHash },
data: { ownerId: user.id },
})
return NextResponse.json({ ok: true, adopted: result.count })
diff --git a/src/app/api/designs/route.ts b/src/app/api/designs/route.ts
index ccffc6c..daf94d4 100644
--- a/src/app/api/designs/route.ts
+++ b/src/app/api/designs/route.ts
@@ -3,6 +3,8 @@ import { Prisma } from '@prisma/client'
import { db } from '@/lib/db'
import { dbErrorResponse } from '@/lib/db-errors'
import { getSessionUser } from '@/lib/auth/session'
+import { readAnonToken, newAnonToken, anonKeyHash, setAnonCookie, anonHashFrom } from '@/lib/auth/anon'
+import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'
// Normalise incoming pages payload (accepts object or legacy JSON string)
// into a value suitable for the Postgres jsonb column.
@@ -19,6 +21,11 @@ function toPages(value: unknown): Prisma.InputJsonValue {
// v0.9 scoping: signed-in users see their designs + ownerless (shared)
// designs; anonymous visitors see ownerless designs only. Owned designs
// are private to their account.
+//
+// v0.9.1: each ownerless row carries `claimable` — true when the signed-in
+// (or anonymous) caller's browser is the author of the design, or when the
+// design predates attribution (legacy). The anonKey hash itself is never
+// returned, only the boolean decision.
export async function GET(req: NextRequest) {
try {
const trash = req.nextUrl.searchParams.get('trash') === '1'
@@ -40,12 +47,18 @@ export async function GET(req: NextRequest) {
thumbnail: true,
source: true,
ownerId: true,
+ anonKey: true,
deletedAt: true,
createdAt: true,
updatedAt: true,
},
})
- return NextResponse.json(designs)
+ const myHash = anonHashFrom(req)
+ const out = designs.map(({ anonKey, ...d }) => ({
+ ...d,
+ claimable: d.ownerId === null && (anonKey === null || anonKey === myHash),
+ }))
+ return NextResponse.json(out)
} catch (error) {
return dbErrorResponse(error, 'GET /api/designs')
}
@@ -54,10 +67,32 @@ export async function GET(req: NextRequest) {
// POST /api/designs — create a new design.
// v0.9: when signed in, the design is owned by the account (private).
// Anonymous users keep the link-accessible ownerless mode.
+// v0.9.1: anonymous creations are attributed to the creating browser
+// (anonKey = sha256 of the canvix_anon cookie, minted on first use) so
+// adopt-all can never claim someone else's work.
export async function POST(req: NextRequest) {
+ if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })
try {
const user = await getSessionUser(req)
const body = await req.json()
+
+ if (user) {
+ const design = await db.design.create({
+ data: {
+ name: typeof body.name === 'string' && body.name.trim() ? body.name.trim() : 'Untitled design',
+ width: Number.isFinite(body.width) ? Math.round(body.width) : 1080,
+ height: Number.isFinite(body.height) ? Math.round(body.height) : 1080,
+ pages: toPages(body.pages),
+ source: typeof body.source === 'string' ? body.source.slice(0, 120) : 'blank',
+ thumbnail: typeof body.thumbnail === 'string' ? body.thumbnail : null,
+ ownerId: user.id,
+ },
+ })
+ return NextResponse.json(design, { status: 201 })
+ }
+
+ // Anonymous: mint/refresh this browser's attribution, stamp the row.
+ const token = readAnonToken(req) ?? newAnonToken()
const design = await db.design.create({
data: {
name: typeof body.name === 'string' && body.name.trim() ? body.name.trim() : 'Untitled design',
@@ -66,10 +101,12 @@ export async function POST(req: NextRequest) {
pages: toPages(body.pages),
source: typeof body.source === 'string' ? body.source.slice(0, 120) : 'blank',
thumbnail: typeof body.thumbnail === 'string' ? body.thumbnail : null,
- ...(user ? { ownerId: user.id } : {}),
+ anonKey: anonKeyHash(token),
},
})
- return NextResponse.json(design, { status: 201 })
+ const res = NextResponse.json(design, { status: 201 })
+ setAnonCookie(res, token)
+ return res
} catch (error) {
// v0.8: template-opening failures get a classified, actionable payload
// (DB_NOT_MIGRATED after a host switch etc.) instead of a bare 500.
diff --git a/src/components/dashboard/Dashboard.tsx b/src/components/dashboard/Dashboard.tsx
index 2065937..096f2c0 100644
--- a/src/components/dashboard/Dashboard.tsx
+++ b/src/components/dashboard/Dashboard.tsx
@@ -38,7 +38,7 @@ import { Input } from '@/components/ui/input'
import { DesignPreview } from '@/components/design-preview'
import { McpCard } from '@/components/dashboard/McpCard'
import { AuthDialog } from '@/components/auth/AuthDialog'
-import { useAuth, adoptAllDesigns } from '@/lib/auth/client'
+import { useAuth, adoptAllDesigns, adoptDesign } from '@/lib/auth/client'
import { TEMPLATES } from '@/lib/templates'
import { createPage, TEMPLATE_CATEGORIES, type TemplateRecord } from '@/lib/types'
import { PRESET_SIZES } from '@/lib/editor-utils'
@@ -120,7 +120,9 @@ export function Dashboard() {
const [authOpen, setAuthOpen] = useState(false)
const [authMode, setAuthMode] = useState<'login' | 'register'>('login')
const [adopting, setAdopting] = useState(false)
- const ownerlessCount = (designs ?? []).filter((d) => d.ownerId === null).length
+ // v0.9.1: only designs attributed to THIS browser (or legacy rows) are
+ // bulk-claimable — the server enforces the same rule, this is just the count.
+ const claimableCount = (designs ?? []).filter((d) => d.claimable === true).length
const [query, setQuery] = useState('')
const [category, setCategory] = useState<string>('all')
@@ -387,7 +389,7 @@ export function Dashboard() {
</div>
{user ? (
<>
- {ownerlessCount > 0 && (
+ {claimableCount > 0 && (
<DropdownMenuItem
className="gap-2"
disabled={adopting}
@@ -404,7 +406,7 @@ export function Dashboard() {
}
}}
>
- <FolderInput size={14} /> {adopting ? 'Adopting…' : `Save all designs to my account (${ownerlessCount})`}
+ <FolderInput size={14} /> {adopting ? 'Adopting…' : `Save my designs to this account (${claimableCount})`}
</DropdownMenuItem>
)}
<DropdownMenuItem className="gap-2" onClick={() => void logout().then(() => refresh())}>
@@ -661,6 +663,21 @@ export function Dashboard() {
<DropdownMenuItem onClick={() => openDesign(d.id)}>
<Pencil size={14} className="mr-2" /> Open
</DropdownMenuItem>
+ {user && d.ownerId === null && d.claimable && (
+ <DropdownMenuItem
+ onClick={async () => {
+ const r = await adoptDesign(d.id)
+ if (r.ok) {
+ await refresh()
+ toast({ title: `“${d.name}” moved into your account` })
+ } else {
+ toast({ title: r.error ?? 'Could not save this design', variant: 'destructive' })
+ }
+ }}
+ >
+ <FolderInput size={14} className="mr-2" /> Save to my account
+ </DropdownMenuItem>
+ )}
<DropdownMenuItem onClick={() => { setRenameTarget({ id: d.id, name: d.name }); setRenameValue(d.name) }}>
<Pencil size={14} className="mr-2" /> Rename
</DropdownMenuItem>
diff --git a/src/components/dashboard/hooks.ts b/src/components/dashboard/hooks.ts
index aecdc67..78d848c 100644
--- a/src/components/dashboard/hooks.ts
+++ b/src/components/dashboard/hooks.ts
@@ -11,6 +11,10 @@ export interface DesignMeta {
thumbnail: string | null
source: string
ownerId: string | null
+ /** v0.9.1: ownerless + (this browser's attribution OR legacy) — i.e. the
+ * signed-in account may claim this design. Foreign anonymous designs
+ * are view/share-only and can never be claimed from here. */
+ claimable?: boolean
deletedAt: string | null
createdAt: string
updatedAt: string
diff --git a/src/lib/auth/anon.ts b/src/lib/auth/anon.ts
new file mode 100644
index 0000000..61aee67
--- /dev/null
+++ b/src/lib/auth/anon.ts
@@ -0,0 +1,74 @@
+// ─────────────────────────────────────────────────────────────
+// Anonymous attribution (v0.9.1) — who created an ownerless
+// design, without accounts.
+//
+// The first time a browser creates a design anonymously it receives a
+// `canvix_anon` cookie (32-byte random token, HttpOnly, 1 year). The
+// design row stores sha256(token) in `anonKey` — the same shape as
+// session ids, so a database leak never contains usable tokens.
+//
+// This is what makes claim eligibility enforceable:
+// • adopt-all claims only rows whose anonKey matches the caller's
+// cookie — never another browser's work, never legacy rows.
+// • per-design adopt additionally allows legacy rows (anonKey null),
+// as a deliberate single-design action.
+//
+// CONTRACT: server-only module (node:crypto).
+// ─────────────────────────────────────────────────────────────
+
+import { createHash, randomBytes } from 'node:crypto'
+import type { NextRequest, NextResponse } from 'next/server'
+
+export const ANON_COOKIE = 'canvix_anon'
+export const ANON_TTL_DAYS = 365
+
+/** New anonymous browser token (base64url, 256-bit). */
+export function newAnonToken(): string {
+ return randomBytes(32).toString('base64url')
+}
+
+/** Stored attribution for a token = sha256 hex (never the raw cookie). */
+export function anonKeyHash(token: string): string {
+ return createHash('sha256').update(token).digest('hex')
+}
+
+/**
+ * The caller's existing anon token, or null when absent/oversized.
+ * Read-only — never mints.
+ */
+export function readAnonToken(req: NextRequest): string | null {
+ const token = req.cookies.get(ANON_COOKIE)?.value
+ if (!token || token.length > 128) return null
+ return token
+}
+
+/** The caller's attribution hash, or null when the browser has none. */
+export function anonHashFrom(req: NextRequest): string | null {
+ const token = readAnonToken(req)
+ return token ? anonKeyHash(token) : null
+}
+
+/** (Re)attach the anon cookie to a response. */
+export function setAnonCookie(res: NextResponse, token: string): void {
+ res.cookies.set(ANON_COOKIE, token, {
+ httpOnly: true,
+ sameSite: 'lax' as const,
+ secure: process.env.NODE_ENV === 'production',
+ path: '/',
+ maxAge: ANON_TTL_DAYS * 24 * 60 * 60,
+ })
+}
+
+/**
+ * Resolve the caller's attribution, minting a token (and scheduling the
+ * cookie on `res`) when the browser has none. Used by design creation.
+ */
+export function ensureAnonAttribution(
+ req: NextRequest,
+ res: NextResponse
+): { token: string; hash: string } {
+ const existing = readAnonToken(req)
+ const token = existing ?? newAnonToken()
+ setAnonCookie(res, token)
+ return { token, hash: anonKeyHash(token) }
+}
diff --git a/src/lib/auth/client.ts b/src/lib/auth/client.ts
index 2ee0371..749237e 100644
--- a/src/lib/auth/client.ts
+++ b/src/lib/auth/client.ts
@@ -84,10 +84,30 @@ export function useAuth(): AuthState & {
return { ...state, refresh, login, register, logout }
}
-/** Claim every ownerless design for the signed-in account. */
+/**
+ * Claim the ownerless designs attributed to THIS browser for the signed-in
+ * account (v0.9.1: server-side scoped to the caller's canvix_anon cookie —
+ * another person's anonymous work is never touched).
+ */
export async function adoptAllDesigns(): Promise<number> {
const res = await fetch('/api/designs/adopt-all', { method: 'POST' })
if (!res.ok) throw new Error('adopt failed')
const data = (await res.json()) as { adopted?: number }
return data.adopted ?? 0
}
+
+/**
+ * Deliberately claim ONE ownerless design (your own anonymous work, or a
+ * legacy design from before accounts existed). Foreign-attributed designs
+ * are refused by the server with 403 NOT_ELIGIBLE.
+ */
+export async function adoptDesign(id: string): Promise<{ ok: boolean; status: number; error?: string }> {
+ const res = await fetch(`/api/designs/${id}/adopt`, { method: 'POST' })
+ let data: Record<string, unknown> = {}
+ try {
+ data = (await res.json()) as Record<string, unknown>
+ } catch {
+ /* empty body */
+ }
+ return { ok: res.ok, status: res.status, error: typeof data.error === 'string' ? data.error : undefined }
+}
diff --git a/src/lib/auth/csrf.test.ts b/src/lib/auth/csrf.test.ts
new file mode 100644
index 0000000..a1f52ba
--- /dev/null
+++ b/src/lib/auth/csrf.test.ts
@@ -0,0 +1,76 @@
+// Unit tests for the v0.9.1 CSRF guard (same-origin enforcement on
+// cookie-authenticated mutations).
+//
+// The contract: browsers ALWAYS attach Origin (or a Referer fallback) to
+// cross-site requests; when either header is present it must match the
+// request's own host. Non-browser clients send neither — allowed (no
+// ambient cookie authority to abuse).
+
+import { describe, it, expect } from 'vitest'
+import { NextRequest } from 'next/server'
+import { isSameOrigin } from './csrf'
+
+function req(headers: Record<string, string> = {}, url = 'http://canvix.test/api/designs'): NextRequest {
+ return new NextRequest(url, { method: 'POST', headers })
+}
+
+describe('isSameOrigin', () => {
+ it('allows requests with no Origin/Referer (curl, MCP, health probes)', () => {
+ expect(isSameOrigin(req())).toBe(true)
+ expect(isSameOrigin(req({ 'user-agent': 'curl/8.0' }))).toBe(true)
+ })
+
+ it('allows same-origin Origin headers (exact host match)', () => {
+ expect(isSameOrigin(req({ host: 'canvix.test', origin: 'http://canvix.test' }))).toBe(true)
+ expect(isSameOrigin(req({ host: 'canvix.test', origin: 'https://canvix.test/editor' }))).toBe(true)
+ })
+
+ it('allows the port to match via the URL host', () => {
+ expect(
+ isSameOrigin(req({ host: 'localhost:3000', origin: 'http://localhost:3000' }, 'http://localhost:3000/api/x'))
+ ).toBe(true)
+ })
+
+ it('rejects cross-origin Origin headers', () => {
+ expect(isSameOrigin(req({ host: 'canvix.test', origin: 'https://evil.example' }))).toBe(false)
+ expect(isSameOrigin(req({ host: 'canvix.test', origin: 'http://canvix.test.evil.com' }))).toBe(false)
+ expect(isSameOrigin(req({ host: 'canvix.test', origin: 'https://sub.canvix.test' }))).toBe(false)
+ })
+
+ it('rejects cross-origin Referer fallbacks', () => {
+ expect(
+ isSameOrigin(req({ host: 'canvix.test', referer: 'https://evil.example/attack.html' }))
+ ).toBe(false)
+ })
+
+ it('allows same-origin Referer fallbacks', () => {
+ expect(
+ isSameOrigin(req({ host: 'canvix.test', referer: 'https://canvix.test/dashboard' }))
+ ).toBe(true)
+ })
+
+ it('rejects malformed Origin headers rather than guessing', () => {
+ expect(isSameOrigin(req({ host: 'canvix.test', origin: 'not a url' }))).toBe(false)
+ expect(isSameOrigin(req({ host: 'canvix.test', origin: 'https://' }))).toBe(false)
+ })
+
+ it('treats an empty Origin value as absent (browsers never send it empty)', () => {
+ // Documented behaviour: `Origin: ` (empty) cannot be a browser fetch —
+ // real browsers either omit the header or send a valid URL. Non-browser
+ // clients have no ambient cookie authority, so this is safe to allow.
+ expect(isSameOrigin(req({ host: 'canvix.test', origin: '' }))).toBe(true)
+ })
+
+ it('honours x-forwarded-host behind a reverse proxy', () => {
+ expect(
+ isSameOrigin(req({ host: '127.0.0.1:3000', 'x-forwarded-host': 'canvix.example.com', origin: 'https://canvix.example.com' }))
+ ).toBe(true)
+ expect(
+ isSameOrigin(req({ host: '127.0.0.1:3000', 'x-forwarded-host': 'canvix.example.com', origin: 'https://evil.example' }))
+ ).toBe(false)
+ })
+
+ it('rejects when no host information exists at all', () => {
+ expect(isSameOrigin(req({ origin: 'https://evil.example' }))).toBe(false)
+ })
+})
diff --git a/src/lib/auth/csrf.ts b/src/lib/auth/csrf.ts
new file mode 100644
index 0000000..2fa79ee
--- /dev/null
+++ b/src/lib/auth/csrf.ts
@@ -0,0 +1,42 @@
+// ─────────────────────────────────────────────────────────────
+// CSRF protection (v0.9.1) — same-origin enforcement for every
+// cookie-authenticated mutating API route.
+//
+// Layer 1 (v0.9): the session cookie is SameSite=Lax, so modern
+// browsers already refuse to attach it to cross-site POST/PUT/DELETE.
+// Layer 2 (this module): browsers ALWAYS send an Origin header (with
+// Referer as a legacy fallback) on cross-site requests; when either is
+// present it must match the request's own host, otherwise the mutation
+// is rejected. Non-browser clients (curl, the MCP endpoint, health
+// checks) send neither header and pass — they carry no ambient cookie
+// authority to forge.
+// ─────────────────────────────────────────────────────────────
+
+import type { NextRequest } from 'next/server'
+
+/**
+ * True when the request is same-origin (or provably not from a browser
+ * navigation/fetch — no Origin/Referer headers at all).
+ */
+export function isSameOrigin(req: NextRequest): boolean {
+ const origin = req.headers.get('origin') ?? req.headers.get('referer')
+ if (!origin) return true // curl / MCP / server-to-server: no CSRF surface
+ let parsed: URL
+ try {
+ parsed = new URL(origin)
+ } catch {
+ return false // malformed header — reject rather than guess
+ }
+ const hosts = [
+ req.headers.get('host'),
+ req.headers.get('x-forwarded-host')?.split(',')[0]?.trim(),
+ ].filter((h): h is string => Boolean(h))
+ if (!hosts.length) return false
+ return hosts.includes(parsed.host)
+}
+
+/** Standard 403 body for a rejected cross-site mutation. */
+export const CSRF_REJECTED = {
+ error: 'Cross-site request rejected.',
+ code: 'CSRF_REJECTED',
+} as const
diff --git a/src/lib/auth/session.test.ts b/src/lib/auth/session.test.ts
new file mode 100644
index 0000000..ba1fe36
--- /dev/null
+++ b/src/lib/auth/session.test.ts
@@ -0,0 +1,137 @@
+// Unit tests for v0.9 session semantics — expiration, revocation and
+// cookie hardening — against a mocked Prisma client (no DB needed).
+//
+// Establishes the properties the Phase-3 report was missing:
+// • expired sessions are rejected AND swept server-side
+// • a logged-out (deleted) session token is dead on replay
+// • the cookie is HttpOnly + SameSite=Lax (+ Secure in production)
+// • the DB stores sha256(token), never the usable token itself
+
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+const dbMock = vi.hoisted(() => ({
+ session: {
+ create: vi.fn(),
+ findUnique: vi.fn(),
+ delete: vi.fn(),
+ deleteMany: vi.fn(),
+ },
+}))
+vi.mock('@/lib/db', () => ({ db: dbMock }))
+
+import { NextRequest, NextResponse } from 'next/server'
+import { createSession, destroySession, getSessionUser, SESSION_COOKIE, sessionIdFor } from './session'
+
+const USER = { id: 'user-1', username: 'ashiq', createdAt: new Date('2026-01-01T00:00:00Z') }
+
+function reqWithCookie(token?: string): NextRequest {
+ return new NextRequest('http://canvix.test/api/x', {
+ headers: token ? { cookie: `${SESSION_COOKIE}=${token}` } : {},
+ })
+}
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ // promise-returning defaults (the real client never returns undefined)
+ dbMock.session.create.mockResolvedValue({})
+ dbMock.session.delete.mockResolvedValue({})
+ dbMock.session.deleteMany.mockResolvedValue({ count: 0 })
+ dbMock.session.findUnique.mockResolvedValue(null)
+})
+
+describe('getSessionUser', () => {
+ it('returns null without a cookie (anonymous visitor)', async () => {
+ expect(await getSessionUser(reqWithCookie())).toBeNull()
+ expect(dbMock.session.findUnique).not.toHaveBeenCalled()
+ })
+
+ it('returns null for oversized tokens without touching the DB', async () => {
+ expect(await getSessionUser(reqWithCookie('x'.repeat(200)))).toBeNull()
+ expect(dbMock.session.findUnique).not.toHaveBeenCalled()
+ })
+
+ it('resolves the user for a valid, unexpired session', async () => {
+ dbMock.session.findUnique.mockResolvedValue({
+ id: 'row-1',
+ userId: USER.id,
+ expiresAt: new Date(Date.now() + 86_400_000),
+ user: USER,
+ })
+ expect(await getSessionUser(reqWithCookie('valid-token'))).toEqual(USER)
+ // looked up by sha256(token), never by the raw token
+ expect(dbMock.session.findUnique).toHaveBeenCalledWith(
+ expect.objectContaining({ where: { id: sessionIdFor('valid-token') } })
+ )
+ })
+
+ it('EXPIRED session: rejected and swept from the DB', async () => {
+ dbMock.session.findUnique.mockResolvedValue({
+ id: 'row-expired',
+ userId: USER.id,
+ expiresAt: new Date(Date.now() - 1000),
+ user: USER,
+ })
+ expect(await getSessionUser(reqWithCookie('expired-token'))).toBeNull()
+ expect(dbMock.session.delete).toHaveBeenCalledWith({ where: { id: 'row-expired' } })
+ })
+
+ it('REVOKED session (logged out elsewhere / row deleted): replay is dead', async () => {
+ dbMock.session.findUnique.mockResolvedValue(null)
+ expect(await getSessionUser(reqWithCookie('logged-out-token'))).toBeNull()
+ })
+
+ it('DB failure degrades to signed-out instead of crashing the route', async () => {
+ dbMock.session.findUnique.mockRejectedValue(new Error('connection refused'))
+ expect(await getSessionUser(reqWithCookie('any-token'))).toBeNull()
+ })
+})
+
+describe('createSession', () => {
+ it('stores sha256(token) and sets a hardened cookie', async () => {
+ const res = NextResponse.json({})
+ await createSession(USER.id, res)
+
+ const create = dbMock.session.create.mock.calls[0][0]
+ const storedId = create.data.id as string
+ expect(storedId).toMatch(/^[0-9a-f]{64}$/) // hash, not the raw token
+
+ const cookies = res.headers.getSetCookie()
+ const session = cookies.find((c) => c.startsWith(`${SESSION_COOKIE}=`))
+ expect(session).toBeDefined()
+ const flat = session!.toLowerCase()
+ expect(flat).toContain('httponly')
+ expect(flat).toContain('samesite=lax')
+ expect(flat).toContain('max-age=2592000') // 30 days
+ expect(flat).toContain('path=/')
+ // the cookie value must NOT be the stored row id (it must be the raw
+ // token whose sha256 is the row id)
+ expect(session).not.toContain(storedId)
+ const token = session!.split(';')[0].split('=')[1]
+ expect(sessionIdFor(token)).toBe(storedId)
+ })
+
+ it('sweeps expired sessions opportunistically', async () => {
+ const res = NextResponse.json({})
+ await createSession(USER.id, res)
+ expect(dbMock.session.deleteMany).toHaveBeenCalled()
+ })
+})
+
+describe('destroySession (logout = server-side revocation)', () => {
+ it('deletes the row by sha256(token) and clears the cookie', async () => {
+ const res = NextResponse.json({})
+ await destroySession(reqWithCookie('bye-token'), res)
+ expect(dbMock.session.deleteMany).toHaveBeenCalledWith({
+ where: { id: sessionIdFor('bye-token') },
+ })
+ const cookies = res.headers.getSetCookie()
+ const cleared = cookies.find((c) => c.startsWith(`${SESSION_COOKIE}=`))
+ expect(cleared).toContain('Max-Age=0')
+ })
+
+ it('is a no-op when there is no cookie', async () => {
+ const res = NextResponse.json({})
+ await destroySession(reqWithCookie(), res)
+ expect(dbMock.session.deleteMany).not.toHaveBeenCalled()
+ })
+})
diff --git a/src/lib/mcp/ssrf-guard.test.ts b/src/lib/mcp/ssrf-guard.test.ts
index ee66980..9fce49f 100644
--- a/src/lib/mcp/ssrf-guard.test.ts
+++ b/src/lib/mcp/ssrf-guard.test.ts
@@ -207,6 +207,15 @@ describe('assertPublicHost', () => {
await expect(assertPublicHost('nonexistent.example.invalid')).rejects.toThrow(/does not resolve/)
})
+ it('rejects hostnames that resolve to loopback / link-local / metadata addresses', async () => {
+ lookupMock.mockResolvedValue([{ address: '127.0.0.1', family: 4 }])
+ await expect(assertPublicHost('loop.example.com')).rejects.toThrow(/resolves to private/)
+ lookupMock.mockResolvedValue([{ address: '169.254.169.254', family: 4 }])
+ await expect(assertPublicHost('meta.example.com')).rejects.toThrow(/resolves to private/)
+ lookupMock.mockResolvedValue([{ address: '::1', family: 6 }])
+ await expect(assertPublicHost('v6loop.example.com')).rejects.toThrow(/resolves to private/)
+ })
+
it('allows hostnames that resolve only to public addresses', async () => {
lookupMock.mockResolvedValue([
{ address: '93.184.216.34', family: 4 },
@@ -314,6 +323,29 @@ describe('safeFetch', () => {
await safeFetch('https://rebind.example.net/x', { transport })
expect(transport.mock.calls[0][1]).toBe('203.0.114.10') // the pinned address
})
+
+ it('DNS CHANGES BETWEEN REQUESTS: a host that was public earlier is re-validated — and refused once it flips private', async () => {
+ // Request 1 succeeds against the then-public record…
+ lookupMock.mockResolvedValueOnce([{ address: '203.0.114.10', family: 4 }])
+ const transport = vi.fn().mockResolvedValue(res(200))
+ await safeFetch('https://flip.example.net/x', { transport })
+ expect(transport).toHaveBeenCalledTimes(1)
+ // …then DNS changes. The NEXT request must re-resolve and refuse —
+ // validation is per-request, never cached.
+ lookupMock.mockResolvedValueOnce([{ address: '10.0.0.9', family: 4 }])
+ await expect(safeFetch('https://flip.example.net/x', { transport })).rejects.toThrow(/resolves to private/)
+ expect(transport).toHaveBeenCalledTimes(1) // no second connection
+ })
+
+ it('DNS CHANGES MID-CHAIN: a redirect hop whose target has rebound to loopback is refused before connecting', async () => {
+ // initial host resolves public…
+ lookupMock.mockResolvedValueOnce([{ address: '93.184.216.34', family: 4 }])
+ const transport = vi.fn().mockResolvedValue(res(302, { location: 'https://hop2.example.net/x' }))
+ // …but the redirect target now resolves to loopback
+ lookupMock.mockResolvedValueOnce([{ address: '127.0.0.1', family: 4 }])
+ await expect(safeFetch('https://start.example.com/r', { transport })).rejects.toThrow(/resolves to private/)
+ expect(transport).toHaveBeenCalledTimes(1) // connected to hop 1 only, never to loopback
+ })
})
// ── pinnedFetch: the real transport, exercised end-to-end ─────