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.9.0): Phase 3 — accounts & per-design ownership, SSRF DNS pinning
Ashiq Hussain Mira280944d7ba8
diff --git a/.github/workflows/db-setup.yml b/.github/workflows/db-setup.ymlindex 74954a5..77b353a 100644--- a/.github/workflows/db-setup.yml+++ b/.github/workflows/db-setup.yml@@ -10,7 +10,7 @@ permissions:jobs:setup:runs-on: ubuntu-latest- timeout-minutes: 10+ timeout-minutes: 15steps:- name: Checkout repository@@ -29,3 +29,11 @@ jobs:run: npm run db:setupenv:DATABASE_URL: ${{ secrets.DATABASE_URL }}++ # v0.9: verify accounts + per-design ownership against the live DB+ # (boots the built server, exercises register/login/me/adopt/403,+ # removes its own probe rows afterwards).+ - name: Smoke-test accounts & ownership+ run: bash scripts/auth-e2e.sh+ env:+ DATABASE_URL: ${{ secrets.DATABASE_URL }}diff --git a/CHANGELOG.md b/CHANGELOG.mdindex e04d529..939e5ee 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -3,6 +3,85 @@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.0] — 2026-10-28++The "Your designs, yours" release: free accounts, per-design ownership,+and the SSRF DNS-pinning close-out promised in the Phase 3 plan.++### Accounts — free forever, zero dependencies+- **Username + password accounts** with scrypt hashing straight from+ `node:crypto` (N=16384, r=8, p=1, per-hash random salt, parameters+ stored alongside the hash for future cost upgrades) — no bcrypt/argon2+ native builds, no external provider, no email. A self-hoster runs the+ whole account system for $0.+- **Opaque DB-backed sessions** — the cookie carries a 256-bit random+ token; the `Session` row id is sha256(token), so a database leak never+ contains usable session tokens. 30-day expiry, HttpOnly + SameSite=Lax+ (+ Secure in production), server-side revocation on logout, and a+ best-effort expiry sweep on every new session.+- **Input rules** (NIST SP 800-63B-flavoured): usernames 3–32 chars of+ `[a-z0-9_-]` canonicalised to lowercase; passwords 8–200 with a tiny+ top-password blocklist. Login answers one generic error (no account+ enumeration) and is rate-limited (10/10min/IP); register 5/hour/IP —+ reusing the existing sliding-window limiter.++### Per-design ownership+- `Design.ownerId` (nullable FK → `User`, `SetNull` on user deletion,+ indexed). Migration `0002_accounts` is purely additive.+- **Three access cases, one helper** (`src/lib/auth/design-guard.ts`):+ ownerless designs stay link-editable (the exact pre-v0.9 behaviour —+ existing setups and intentionally shared designs keep working); the+ owner has full edit; everyone else gets view-only.+- Enforced at every mutating API — save (PUT), delete (DELETE), restore,+ version snapshots — with a structured `403 READ_ONLY_DESIGN` body.+ `GET /api/designs/[id]` still serves share links but now carries a+ `readOnly` flag.+- **Dashboard scoping** — signed-in users see their designs plus shared+ (ownerless) ones; anonymous visitors see ownerless designs only.+ New designs created while signed in are automatically owned.+- **One-click migration** — "Save all designs to my account" adopts every+ ownerless design into the signed-in account (`POST /api/designs/adopt-all`,+ idempotent, never touches already-owned designs).+- **Editor view-only mode** — autosave is disabled and an amber banner+ explains why, instead of silently failing saves.++### Collab identity+- Signed-in users automatically appear under their real username in+ presence, cursors and comments (the local participant identity is+ upgraded on login; anonymous users keep the generated names).++### Security — SSRF DNS-rebinding pinning (the v0.6.1 residual, closed)+- `safeFetch` no longer uses `fetch()` for the exchange: it connects via+ `node:http(s)` with a **custom DNS lookup pinned to the validated+ address**. The guard resolves and range-checks every address, hands the+ connection exactly that IP, and there is no second resolution — a+ rebinding attack between validation and connect is now impossible.+ TLS keeps the real hostname for SNI/Host, so certificate validation is+ unaffected. The transport is injectable for tests; the suite now asserts+ the pinned IP on every hop (including the rebinding scenario) and+ exercises the real transport end-to-end against a local server.++### Verification+- 115 unit tests (10 new: scrypt round-trip/salting/tamper-resistance,+ username/password rules, token derivation; SSRF suite upgraded to+ assert pinning). `tsc --noEmit` clean, production build clean.+- **`scripts/auth-e2e.sh`** — boots the built standalone server against a+ real database and drives the whole flow with curl: register → me →+ owned create → owner save → anonymous `403 READ_ONLY_DESIGN` → logout →+ me(null) → wrong-password `401` → login → cleanup. Wired into the+ "Canvix Database Setup" workflow, so every re-run of the workflow now+ proves accounts + ownership against *your* live database before it+ reports success.+- `/api/health` now also checks for the `User` and `Session` tables and+ tells you to re-run `npm run db:setup` after upgrading.++### Upgrade notes+- Run `npm run db:setup` once after pulling (applies `0002_accounts`).+ Existing designs are untouched: they stay link-editable until you+ choose "Save all designs to my account" while signed in.+- Nothing else changes — anonymous/local editing works exactly as before+ for anyone who never creates an account.+## [0.8.0] — 2026-10-28The "Supabase-ready & 110 Templates" release: switching your database todiff --git a/README.md b/README.mdindex 55b585f..385a04f 100644--- a/README.md+++ b/README.md@@ -24,8 +24,9 @@ Free & open-source graphic design tool — a community-built [Canva](https://canCanvix is a browser-based design tool that lets anyone create social media posts,presentations, posters, logos and thumbnails — with a drag-and-drop editor, a-60-template library and one-click export. It runs entirely on your own infrastructure, stores designs-in your own database, and exports files locally in your browser. No accounts, no+110-template library and one-click export. It runs entirely on your own infrastructure, stores designs+in your own database, and exports files locally in your browser. Free accounts+keep your designs yours; anonymous link-editing keeps working too. Nowatermarks, no paywalls.## 🆓 Free forever — the promise@@ -39,6 +40,8 @@ is a design tool that never asks you for a credit card:- All **exports** (PNG, JPG, SVG, PDF, video) are free and unwatermarked- All **AI features** (magic edit, magic write, background removal, translate)run against your own API keys, so there is nothing for us to meter+- **Accounts are free** — username + password, no email, no verification,+ no external provider; a self-hoster runs the whole thing for $0- **Self-hosting** is first-class: your server, your database, your rules- The license is **MIT** — you can even fork it and build a business on it@@ -47,6 +50,32 @@ is right here.## 🎨 Features+### v0.9.0 — Accounts & per-design ownership++- **Free accounts, zero dependencies** — username + password with scrypt+ hashing from `node:crypto` and opaque DB-backed sessions (HttpOnly,+ SameSite=Lax cookies; the DB stores only sha256(token) so a leak never+ yields usable sessions). No email, no OAuth, no external provider —+ deliberately self-contained so self-hosting stays free forever.+- **Per-design ownership** — designs you create while signed in are private+ to your account: the dashboard scopes to “yours + shared”, and every+ mutating API (save, delete, restore, version snapshot) answers 403 for+ 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.+- **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`+ now connects via a custom lookup pinned to the validated IP, closing the+ TOCTOU window documented in v0.6.1. TLS keeps the real hostname for SNI,+ 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.+### v0.8.0 — Supabase-ready infrastructure & the 110-template library- **Supabase-first database support** — switching hosts (Neon → Supabase,@@ -588,7 +617,8 @@ tool descriptions so agents pick the right format.- [x] MCP server (20 agent tools), tables, frames, curved text, embed cards *(v0.6.0)*- [x] Rendering performance (structural sharing, memoized nodes, O(1) undo) & the premium collection *(v0.7.0)*- [x] 110-template library, Supabase-first migrations & self-diagnosing setup *(v0.8.0)*-- [ ] Accounts & per-design ownership (identity layer groundwork shipped in v0.5)+- [x] Accounts & per-design ownership — free username/password accounts, private+ designs, one-click migration of existing work, SSRF DNS pinning *(v0.9.0)*- [ ] Yjs-grade offline merge for collaboration- [ ] Audio/video elements & Beat Sync- [ ] Plugin system (external, installable apps)diff --git a/package.json b/package.jsonindex 586c098..b0260df 100644--- a/package.json+++ b/package.json@@ -1,6 +1,6 @@{"name": "canvix",- "version": "0.8.2",+ "version": "0.9.0","private": false,"description": "Canvix \u2014 free & open-source graphic design tool. A community-built Canva alternative.","scripts": {diff --git a/prisma/migrations/0002_accounts/migration.sql b/prisma/migrations/0002_accounts/migration.sqlnew file mode 100644index 0000000..5de12e1--- /dev/null+++ b/prisma/migrations/0002_accounts/migration.sql@@ -0,0 +1,41 @@+-- v0.9.0: accounts & per-design ownership+-- User + Session tables, Design.ownerId column.+-- Deliberately additive: ownerless designs (ownerId NULL) keep the+-- pre-accounts link-accessible behaviour.++-- CreateTable+CREATE TABLE "User" (+ "id" TEXT NOT NULL,+ "username" TEXT NOT NULL,+ "passwordHash" TEXT NOT NULL,+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,++ CONSTRAINT "User_pkey" PRIMARY KEY ("id")+);++-- CreateTable+CREATE TABLE "Session" (+ "id" TEXT NOT NULL,+ "userId" TEXT NOT NULL,+ "createdAt" TIMESTAMP(3) NOT NULL DEFAULT CURRENT_TIMESTAMP,+ "expiresAt" TIMESTAMP(3) NOT NULL,++ CONSTRAINT "Session_pkey" PRIMARY KEY ("id")+);++-- AlterTable+ALTER TABLE "Design" ADD COLUMN "ownerId" TEXT;++-- CreateIndex+CREATE UNIQUE INDEX "User_username_key" ON "User"("username");++-- CreateIndex+CREATE INDEX "Session_userId_idx" ON "Session"("userId");+CREATE INDEX "Session_expiresAt_idx" ON "Session"("expiresAt");+CREATE INDEX "Design_ownerId_idx" ON "Design"("ownerId");++-- AddForeignKey+ALTER TABLE "Session" ADD CONSTRAINT "Session_userId_fkey" FOREIGN KEY ("userId") REFERENCES "User"("id") ON DELETE CASCADE ON UPDATE CASCADE;++-- AddForeignKey+ALTER TABLE "Design" ADD CONSTRAINT "Design_ownerId_fkey" FOREIGN KEY ("ownerId") REFERENCES "User"("id") ON DELETE SET NULL ON UPDATE CASCADE;diff --git a/prisma/schema.prisma b/prisma/schema.prismaindex bf04849..602a765 100644--- a/prisma/schema.prisma+++ b/prisma/schema.prisma@@ -7,6 +7,33 @@ datasource db {url = env("DATABASE_URL")}+// ── v0.9.0: accounts ─────────────────────────────────────────+// Username/password accounts — deliberately self-contained (no email,+// no OAuth, no external provider) so self-hosting stays free forever.+// Passwords are scrypt hashes from node:crypto (see src/lib/auth/passwords.ts).+model User {+ id String @id @default(cuid())+ // lowercase, 3–32 chars, [a-z0-9_-] (enforced in src/lib/auth/validate.ts)+ username String @unique+ passwordHash String+ createdAt DateTime @default(now())+ designs Design[] @relation("DesignOwner")+ sessions Session[]+}++// Opaque server-side sessions. The cookie carries the raw token; the row+// id is sha256(token) — a DB leak never yields usable tokens.+model Session {+ id String @id // sha256(token) hex+ userId String+ user User @relation(fields: [userId], references: [id], onDelete: Cascade)+ createdAt DateTime @default(now())+ expiresAt DateTime++ @@index([userId])+ @@index([expiresAt])+}+// A user design / project — the core artifact of Canvix.model Design {id String @id @default(cuid())@@ -17,11 +44,17 @@ model Design {pages Json @default("[]")thumbnail String? // small dataURL previewsource String @default("blank") // blank | template:<id> | duplicate:<id> | resize:<id>+ // v0.9: owning account. null = link-accessible design (pre-accounts+ // behaviour — anonymous editing keeps working for legacy + shared links).+ ownerId String?+ owner User? @relation("DesignOwner", fields: [ownerId], references: [id], onDelete: SetNull)// soft delete (dashboard Trash) — null = live designdeletedAt DateTime?versions DesignVersion[]createdAt DateTime @default(now())updatedAt DateTime @updatedAt++ @@index([ownerId])}// Server-side version snapshots for a design (Canva "Version history").diff --git a/scripts/auth-e2e.sh b/scripts/auth-e2e.shnew file mode 100755index 0000000..35af9cd--- /dev/null+++ b/scripts/auth-e2e.sh@@ -0,0 +1,122 @@+#!/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:+#+# register → me → create (owned) → save as owner → 403 as anonymous+# → login → logout → me(null) → cleanup+#+# Exits non-zero on the first failed expectation. Leaves no rows behind+# (the test user + design are deleted at the end).+set -u+cd "$(dirname "$0")/.."++PORT="${E2E_PORT:-3100}"+BASE="http://127.0.0.1:$PORT"+JAR="$(mktemp)"+TS_USER="e2e_tester_$$_$(date +%s)"+TS_PASS='e2e-Tr0ub4dor-pass'+SERVER_PID=""++say() { printf ' \033[1;36m%s\033[0m\n' "$*"; }+pass() { printf ' \033[1;32m✓\033[0m %s\n' "$*"; }+fail() { printf ' \033[1;31m✗ %s\033[0m\n' "$*"; exit 1; }++cleanup() {+ [ -n "$SERVER_PID" ] && kill "$SERVER_PID" 2>/dev/null+ rm -f "$JAR"+}+trap cleanup EXIT++if [ -z "${DATABASE_URL:-}" ]; then+ echo "DATABASE_URL is not set — the smoke test needs a real database."+ exit 1+fi++say "building the standalone server…"+npm run build >/dev/null 2>&1 || fail "next build failed"++say "booting the server on :$PORT…"+PORT="$PORT" HOSTNAME=127.0.0.1 DATABASE_URL="$DATABASE_URL" \+ node .next/standalone/server.js >/tmp/canvix-e2e-server.log 2>&1 &+SERVER_PID=$!++for i in $(seq 1 60); do+ curl -sf "$BASE/api/health" >/dev/null 2>&1 && break+ sleep 1+done+curl -sf "$BASE/api/health" >/dev/null 2>&1 || fail "server did not become healthy (see /tmp/canvix-e2e-server.log)"++# ── 1. register ─────────────────────────────────────────────+STATUS=$(curl -s -o /tmp/e2e-r1.json -w '%{http_code}' -c "$JAR" \+ -H 'Content-Type: application/json' \+ -X POST "$BASE/api/auth/register" \+ -d "{\"username\":\"$TS_USER\",\"password\":\"$TS_PASS\"}")+[ "$STATUS" = "201" ] || fail "register expected 201, got $STATUS: $(cat /tmp/e2e-r1.json)"+pass "register → 201, session cookie set"++# ── 2. me (signed in) ───────────────────────────────────────+curl -sf -b "$JAR" "$BASE/api/auth/me" | grep -q "\"$TS_USER\"" || fail "me should report the signed-in user"+pass "me → signed in as $TS_USER"++# ── 3. create a design (should be owned) ────────────────────+STATUS=$(curl -s -o /tmp/e2e-r3.json -w '%{http_code}' -b "$JAR" \+ -H 'Content-Type: application/json' \+ -X POST "$BASE/api/designs" \+ -d '{"name":"E2E ownership probe","width":100,"height":100}')+[ "$STATUS" = "201" ] || fail "create expected 201, got $STATUS"+DESIGN_ID=$(node -e "console.log(JSON.parse(require('fs').readFileSync('/tmp/e2e-r3.json','utf8')).id)")+[ -n "$DESIGN_ID" ] || fail "no design id in create response"+pass "create → owned design $DESIGN_ID"++# ── 4. owner can save it ─────────────────────────────────────+STATUS=$(curl -s -o /dev/null -w '%{http_code}' -b "$JAR" \+ -H 'Content-Type: application/json' \+ -X PUT "$BASE/api/designs/$DESIGN_ID" \+ -d '{"name":"E2E ownership probe (saved)"}')+[ "$STATUS" = "200" ] || fail "owner save expected 200, got $STATUS"+pass "owner PUT → 200"++# ── 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" \+ -d '{"name":"hijack attempt"}')+[ "$STATUS" = "403" ] || fail "anonymous PUT on an owned design expected 403, got $STATUS"+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 ──────────────────────────────────+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)"++# ── 7. wrong password is refused ────────────────────────────+STATUS=$(curl -s -o /dev/null -w '%{http_code}' \+ -H 'Content-Type: application/json' \+ -X POST "$BASE/api/auth/login" \+ -d "{\"username\":\"$TS_USER\",\"password\":\"definitely-wrong\"}")+[ "$STATUS" = "401" ] || fail "wrong password expected 401, got $STATUS"+pass "wrong password → 401"++# ── 8. login works ──────────────────────────────────────────+STATUS=$(curl -s -o /dev/null -w '%{http_code}' -c "$JAR" \+ -H 'Content-Type: application/json' \+ -X POST "$BASE/api/auth/login" \+ -d "{\"username\":\"$TS_USER\",\"password\":\"$TS_PASS\"}")+[ "$STATUS" = "200" ] || fail "login expected 200, got $STATUS"+pass "login → 200, session restored"++# ── cleanup: remove the probe rows ───────────────────────────+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] } })+ await db.\$disconnect()+})().then(() => process.exit(0)).catch(() => process.exit(1))+" "$DESIGN_ID" "$TS_USER" || fail "cleanup failed"++say "all green — accounts, ownership and sessions verified end-to-end."diff --git a/src/app/api/auth/login/route.ts b/src/app/api/auth/login/route.tsnew file mode 100644index 0000000..77397d6--- /dev/null+++ b/src/app/api/auth/login/route.ts@@ -0,0 +1,41 @@+import { NextRequest, NextResponse } from 'next/server'+import { db } from '@/lib/db'+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'++// POST /api/auth/login — exchange username + password for a session cookie.+// One deliberately generic error message: never reveal whether the+// username exists (account enumeration).+export async function POST(req: NextRequest) {+ const rl = rateLimit('auth:login', req, 10, 600)+ if (!rl.ok) {+ return NextResponse.json(+ { error: `Too many sign-in attempts — try again in ${rl.retryAfterSec}s.` },+ { status: 429, headers: { 'Retry-After': String(rl.retryAfterSec) } }+ )+ }+ try {+ const body = await req.json().catch(() => ({}))+ const uname = checkUsername(body?.username)+ if (!uname.ok) return NextResponse.json({ error: 'Invalid username or password.' }, { status: 401 })+ if (typeof body?.password !== 'string' || !body.password) {+ return NextResponse.json({ error: 'Invalid username or password.' }, { status: 401 })+ }++ const username = canonicalUsername(body.username)+ const user = await db.user.findUnique({ where: { username } })+ const ok = user ? await verifyPassword(body.password, user.passwordHash) : false+ if (!user || !ok) {+ return NextResponse.json({ error: 'Invalid username or password.' }, { status: 401 })+ }++ const res = NextResponse.json({ user: { id: user.id, username: user.username, createdAt: user.createdAt } })+ await createSession(user.id, res)+ return res+ } catch (error) {+ console.error('POST /api/auth/login failed', error)+ return NextResponse.json({ error: 'Sign-in failed. Please try again.' }, { status: 500 })+ }+}diff --git a/src/app/api/auth/logout/route.ts b/src/app/api/auth/logout/route.tsnew file mode 100644index 0000000..3af32c7--- /dev/null+++ b/src/app/api/auth/logout/route.ts@@ -0,0 +1,9 @@+import { NextRequest, NextResponse } from 'next/server'+import { destroySession } from '@/lib/auth/session'++// POST /api/auth/logout — revoke the current session + clear the cookie.+export async function POST(req: NextRequest) {+ const res = NextResponse.json({ ok: true })+ await destroySession(req, res)+ return res+}diff --git a/src/app/api/auth/me/route.ts b/src/app/api/auth/me/route.tsnew file mode 100644index 0000000..76f0b04--- /dev/null+++ b/src/app/api/auth/me/route.ts@@ -0,0 +1,9 @@+import { NextRequest, NextResponse } from 'next/server'+import { getSessionUser } from '@/lib/auth/session'++// GET /api/auth/me — the signed-in user (or null). Public endpoint the+// dashboard/editor use to decide between account mode and anonymous mode.+export async function GET(req: NextRequest) {+ const user = await getSessionUser(req)+ return NextResponse.json({ user: user ? { id: user.id, username: user.username, createdAt: user.createdAt } : null })+}diff --git a/src/app/api/auth/register/route.ts b/src/app/api/auth/register/route.tsnew file mode 100644index 0000000..3ca62c9--- /dev/null+++ b/src/app/api/auth/register/route.ts@@ -0,0 +1,40 @@+import { NextRequest, NextResponse } from 'next/server'+import { db } from '@/lib/db'+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'++// 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.+export async function POST(req: NextRequest) {+ const rl = rateLimit('auth:register', req, 5, 3600)+ if (!rl.ok) {+ return NextResponse.json(+ { error: `Too many sign-up attempts — try again in ${rl.retryAfterSec}s.` },+ { status: 429, headers: { 'Retry-After': String(rl.retryAfterSec) } }+ )+ }+ try {+ const body = await req.json().catch(() => ({}))+ const uname = checkUsername(body?.username)+ if (!uname.ok) return NextResponse.json({ error: uname.error }, { status: 400 })+ const pword = checkPassword(body?.password)+ if (!pword.ok) return NextResponse.json({ error: pword.error }, { status: 400 })++ const username = canonicalUsername(body.username)+ const existing = await db.user.findUnique({ where: { username }, select: { id: true } })+ if (existing) return NextResponse.json({ error: 'That username is already taken.' }, { status: 409 })++ const passwordHash = await hashPassword(String(body.password))+ const user = await db.user.create({ data: { username, passwordHash }, select: { id: true, username: true, createdAt: true } })++ const res = NextResponse.json({ user }, { status: 201 })+ await createSession(user.id, res)+ return res+ } catch (error) {+ console.error('POST /api/auth/register failed', error)+ return NextResponse.json({ error: 'Could not create the account. Please try again.' }, { status: 500 })+ }+}diff --git a/src/app/api/designs/[id]/restore/route.ts b/src/app/api/designs/[id]/restore/route.tsindex 70d7747..2a7d3af 100644--- a/src/app/api/designs/[id]/restore/route.ts+++ b/src/app/api/designs/[id]/restore/route.ts@@ -1,10 +1,15 @@import { NextRequest, NextResponse } from 'next/server'import { db } from '@/lib/db'+import { resolveDesignAccess, NOT_YOUR_DESIGN } from '@/lib/auth/design-guard'-// POST /api/designs/[id]/restore — restore a design from the Trash-export async function POST(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {+// POST /api/designs/[id]/restore — restore a design from the Trash.+// v0.9: owner-only for owned designs (403 otherwise); ownerless unchanged.+export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {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 design = await db.design.update({where: { id },data: { deletedAt: null },diff --git a/src/app/api/designs/[id]/route.ts b/src/app/api/designs/[id]/route.tsindex 3ee136e..ff8d1c3 100644--- a/src/app/api/designs/[id]/route.ts+++ b/src/app/api/designs/[id]/route.ts@@ -1,6 +1,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'// Normalise incoming pages payload (accepts object or legacy JSON string)// into a value suitable for the Postgres jsonb column.@@ -11,13 +12,17 @@ function toPages(value: unknown): Prisma.InputJsonValue {return (value ?? []) as Prisma.InputJsonValue}-// GET /api/designs/[id] — full design incl. pages-export async function GET(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {+// GET /api/designs/[id] — full design incl. pages.+// v0.9: open to anyone with the link (share/view), but carries a+// `readOnly` flag when the design belongs to another account so the+// editor can switch to view-only mode.+export async function GET(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {try {const { id } = await params- const design = await db.design.findUnique({ where: { id } })- if (!design) return NextResponse.json({ error: 'Not found' }, { status: 404 })- return NextResponse.json({ ...design, pages: design.pages ?? [] })+ const access = await resolveDesignAccess(req, id)+ if (!access) return NextResponse.json({ error: 'Not found' }, { status: 404 })+ const design = access.design+ return NextResponse.json({ ...design, pages: design.pages ?? [], readOnly: !access.canEdit })} catch (error) {console.error('GET /api/designs/[id] failed', error)return NextResponse.json({ error: 'Failed to get design' }, { status: 500 })@@ -25,9 +30,15 @@ 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).export async function PUT(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {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()const data: Record<string, unknown> = {}if (typeof body.name === 'string' && body.name.trim()) data.name = body.name.trim().slice(0, 120)@@ -47,9 +58,15 @@ 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).export async function DELETE(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {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 })+if (req.nextUrl.searchParams.get('permanent') === '1') {await db.design.delete({ where: { id } })return NextResponse.json({ ok: true, permanent: true })diff --git a/src/app/api/designs/[id]/versions/route.ts b/src/app/api/designs/[id]/versions/route.tsindex f813863..c5c23fd 100644--- a/src/app/api/designs/[id]/versions/route.ts+++ b/src/app/api/designs/[id]/versions/route.ts@@ -1,6 +1,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'// GET /api/designs/[id]/versions — list server-side version snapshots (newest first)export async function GET(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {@@ -30,13 +31,15 @@ export async function GET(_req: NextRequest, { params }: { params: Promise<{ id:}// POST /api/designs/[id]/versions — save a new version snapshot+// v0.9: owner-only for owned designs (403 otherwise); ownerless unchanged.export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {try {const { id } = await params- const body = await req.json()+ const access = await resolveDesignAccess(req, id)+ if (!access) return NextResponse.json({ error: 'Design not found' }, { status: 404 })+ if (!access.canEdit) return NextResponse.json(NOT_YOUR_DESIGN, { status: 403 })- const exists = await db.design.findUnique({ where: { id }, select: { id: true } })- if (!exists) return NextResponse.json({ error: 'Design not found' }, { status: 404 })+ const body = await req.json()const version = await db.designVersion.create({data: {diff --git a/src/app/api/designs/adopt-all/route.ts b/src/app/api/designs/adopt-all/route.tsnew file mode 100644index 0000000..b985f57--- /dev/null+++ b/src/app/api/designs/adopt-all/route.ts@@ -0,0 +1,29 @@+import { NextRequest, NextResponse } from 'next/server'+import { db } from '@/lib/db'+import { getSessionUser } from '@/lib/auth/session'++// 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.+export async function POST(req: NextRequest) {+ const user = await getSessionUser(req)+ if (!user) {+ return NextResponse.json(+ { error: 'Sign in first — adopting designs moves them into your account.' },+ { status: 401 }+ )+ }+ try {+ const result = await db.design.updateMany({+ where: { ownerId: null },+ data: { ownerId: user.id },+ })+ return NextResponse.json({ ok: true, adopted: result.count })+ } catch (error) {+ console.error('POST /api/designs/adopt-all failed', error)+ return NextResponse.json({ error: 'Failed to adopt designs.' }, { status: 500 })+ }+}diff --git a/src/app/api/designs/route.ts b/src/app/api/designs/route.tsindex 4cd0447..ccffc6c 100644--- a/src/app/api/designs/route.ts+++ b/src/app/api/designs/route.ts@@ -2,6 +2,7 @@ import { NextRequest, NextResponse } from 'next/server'import { Prisma } from '@prisma/client'import { db } from '@/lib/db'import { dbErrorResponse } from '@/lib/db-errors'+import { getSessionUser } from '@/lib/auth/session'// Normalise incoming pages payload (accepts object or legacy JSON string)// into a value suitable for the Postgres jsonb column.@@ -14,11 +15,22 @@ function toPages(value: unknown): Prisma.InputJsonValue {// GET /api/designs — list designs (metadata only, newest first)// ?trash=1 → only soft-deleted designs; default → only live designs+//+// 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.export async function GET(req: NextRequest) {try {const trash = req.nextUrl.searchParams.get('trash') === '1'+ const user = await getSessionUser(req)+ const where: Prisma.DesignWhereInput = {+ deletedAt: trash ? { not: null } : null,+ ...(user+ ? { OR: [{ ownerId: null }, { ownerId: user.id }] }+ : { ownerId: null }),+ }const designs = await db.design.findMany({- where: { deletedAt: trash ? { not: null } : null },+ where,orderBy: { updatedAt: 'desc' },select: {id: true,@@ -27,6 +39,7 @@ export async function GET(req: NextRequest) {height: true,thumbnail: true,source: true,+ ownerId: true,deletedAt: true,createdAt: true,updatedAt: true,@@ -38,9 +51,12 @@ export async function GET(req: NextRequest) {}}-// POST /api/designs — create a new design+// 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.export async function POST(req: NextRequest) {try {+ const user = await getSessionUser(req)const body = await req.json()const design = await db.design.create({data: {@@ -50,6 +66,7 @@ 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 } : {}),},})return NextResponse.json(design, { status: 201 })diff --git a/src/app/api/health/route.ts b/src/app/api/health/route.tsindex 8e01f02..ec87faf 100644--- a/src/app/api/health/route.ts+++ b/src/app/api/health/route.ts@@ -16,6 +16,9 @@ const REQUIRED_TABLES = ['Presence','Comment','AIUsage',+ // v0.9: accounts+ 'User',+ 'Session',] as constexport async function GET() {diff --git a/src/components/auth/AuthDialog.tsx b/src/components/auth/AuthDialog.tsxnew file mode 100644index 0000000..f09b165--- /dev/null+++ b/src/components/auth/AuthDialog.tsx@@ -0,0 +1,166 @@+'use client'++// ─────────────────────────────────────────────────────────────+// AuthDialog (v0.9) — sign in / create an account.+//+// Username + password only: no email verification, no OAuth, no+// external provider — an account system a self-hoster can run for+// free forever. Matches the Canva-accurate dark theme.+// ─────────────────────────────────────────────────────────────++import { useEffect, useState } from 'react'+import { Eye, EyeOff } from 'lucide-react'+import {+ Dialog,+ DialogContent,+ DialogDescription,+ DialogHeader,+ DialogTitle,+} from '@/components/ui/dialog'+import { Button } from '@/components/ui/button'+import { Input } from '@/components/ui/input'+import { Logo } from '@/components/logo'+import { cn } from '@/lib/utils'+import { setDisplayName } from '@/lib/collab/identity'++export interface AuthDialogProps {+ open: boolean+ onOpenChange: (open: boolean) => void+ onAuthed: (username: string) => void+ initialMode?: 'login' | 'register'+}++export function AuthDialog({ open, onOpenChange, onAuthed, initialMode = 'login' }: AuthDialogProps) {+ const [mode, setMode] = useState<'login' | 'register'>(initialMode)+ const [username, setUsername] = useState('')+ const [password, setPassword] = useState('')+ const [showPassword, setShowPassword] = useState(false)+ const [error, setError] = useState<string | null>(null)+ const [busy, setBusy] = useState(false)++ useEffect(() => {+ if (open) {+ setMode(initialMode)+ setError(null)+ setUsername('')+ setPassword('')+ }+ }, [open, initialMode])++ const submit = async (e: React.FormEvent) => {+ e.preventDefault()+ if (busy) return+ setBusy(true)+ setError(null)+ try {+ const endpoint = mode === 'login' ? '/api/auth/login' : '/api/auth/register'+ const res = await fetch(endpoint, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify({ username: username.trim(), password }),+ })+ const data = (await res.json().catch(() => ({}))) as { user?: { username: string }; error?: string }+ if (!res.ok) {+ setError(typeof data.error === 'string' ? data.error : 'Something went wrong. Please try again.')+ return+ }+ // the collab identity now carries the real name+ if (data.user?.username) setDisplayName(data.user.username)+ onAuthed(data.user?.username ?? username.trim())+ onOpenChange(false)+ } catch {+ setError('Network error — please try again.')+ } finally {+ setBusy(false)+ }+ }++ return (+ <Dialog open={open} onOpenChange={onOpenChange}>+ <DialogContent className="sm:max-w-[400px] bg-[#16181D] border-white/10 text-white p-0 overflow-hidden">+ <div className="cv-topbar-gradient h-1.5 w-full" />+ <div className="p-6">+ <DialogHeader className="items-start space-y-2">+ <div className="flex items-center gap-2.5">+ <Logo size={24} />+ <DialogTitle className="text-lg font-semibold">+ {mode === 'login' ? 'Welcome back' : 'Create your free account'}+ </DialogTitle>+ </div>+ <DialogDescription className="text-white/50 text-[13px] leading-relaxed text-left">+ {mode === 'login'+ ? 'Sign in to keep your designs private to your account.'+ : 'Free forever — every feature, every template, no subscriptions. Accounts just keep your work yours.'}+ </DialogDescription>+ </DialogHeader>++ <form onSubmit={submit} className="mt-5 space-y-3.5">+ <div className="space-y-1.5">+ <label htmlFor="cv-auth-username" className="text-[12px] font-medium text-white/70">+ Username+ </label>+ <Input+ id="cv-auth-username"+ autoComplete="username"+ autoCapitalize="none"+ spellCheck={false}+ value={username}+ onChange={(e) => setUsername(e.target.value)}+ placeholder="e.g. ashiq_designs"+ className="h-10 bg-white/[0.06] border-white/10 text-white placeholder:text-white/30 focus-visible:ring-[#7630D7]/50"+ />+ </div>+ <div className="space-y-1.5">+ <label htmlFor="cv-auth-password" className="text-[12px] font-medium text-white/70">+ Password+ </label>+ <div className="relative">+ <Input+ id="cv-auth-password"+ type={showPassword ? 'text' : 'password'}+ autoComplete={mode === 'login' ? 'current-password' : 'new-password'}+ value={password}+ onChange={(e) => setPassword(e.target.value)}+ placeholder={mode === 'login' ? 'Your password' : 'At least 8 characters'}+ className="h-10 pr-10 bg-white/[0.06] border-white/10 text-white placeholder:text-white/30 focus-visible:ring-[#7630D7]/50"+ />+ <button+ type="button"+ onClick={() => setShowPassword((v) => !v)}+ className="absolute right-3 top-1/2 -translate-y-1/2 text-white/40 hover:text-white/70"+ aria-label={showPassword ? 'Hide password' : 'Show password'}+ >+ {showPassword ? <EyeOff size={15} /> : <Eye size={15} />}+ </button>+ </div>+ </div>++ {error && (+ <p className="text-[12.5px] text-[#FF6B81] bg-[#FF6B81]/10 border border-[#FF6B81]/20 rounded-lg px-3 py-2" role="alert">+ {error}+ </p>+ )}++ <Button type="submit" disabled={busy || !username.trim() || !password} className="btn-cv w-full h-10 rounded-full font-semibold">+ {busy ? (mode === 'login' ? 'Signing in…' : 'Creating account…') : mode === 'login' ? 'Sign in' : 'Create account'}+ </Button>+ </form>++ <p className="mt-4 text-center text-[12.5px] text-white/45">+ {mode === 'login' ? "Don't have an account? " : 'Already have an account? '}+ <button+ type="button"+ onClick={() => {+ setMode(mode === 'login' ? 'register' : 'login')+ setError(null)+ }}+ className={cn('font-semibold text-[#00C4CC] hover:text-[#00C4CC]/80 underline-offset-2 hover:underline')}+ >+ {mode === 'login' ? 'Create one — it’s free' : 'Sign in'}+ </button>+ </p>+ </div>+ </DialogContent>+ </Dialog>+ )+}diff --git a/src/components/dashboard/Dashboard.tsx b/src/components/dashboard/Dashboard.tsxindex cf396f6..2065937 100644--- a/src/components/dashboard/Dashboard.tsx+++ b/src/components/dashboard/Dashboard.tsx@@ -26,6 +26,9 @@ import {Info,Heart,AlertTriangle,+ LogIn,+ LogOut,+ FolderInput,} from 'lucide-react'import { useAppStore } from '@/store/app-store'import { useEditorStore } from '@/store/editor-store'@@ -34,6 +37,8 @@ import { Button } from '@/components/ui/button'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 { TEMPLATES } from '@/lib/templates'import { createPage, TEMPLATE_CATEGORIES, type TemplateRecord } from '@/lib/types'import { PRESET_SIZES } from '@/lib/editor-utils'@@ -110,6 +115,13 @@ export function Dashboard() {const isMobile = useIsMobile()const [helpOpen, setHelpOpen] = useState(false)+ // v0.9: accounts — free forever, username + password+ const { user, login, register, logout } = useAuth()+ 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+const [query, setQuery] = useState('')const [category, setCategory] = useState<string>('all')const [customOpen, setCustomOpen] = useState(false)@@ -348,22 +360,68 @@ export function Dashboard() {><Plus size={16} /> <span className="hidden sm:inline">Custom size</span></Button>- {/* ── account area (canva-style avatar menu) ── */}+ {/* ── account area (v0.9: real accounts, free forever) ── */}<DropdownMenu><DropdownMenuTrigger asChild><buttonclassName="h-10 w-10 rounded-full bg-gradient-to-br from-[#02C0CC] to-[#7630D7] text-white text-[13px] font-extrabold flex items-center justify-center shrink-0 hover:brightness-110 transition-all"aria-label="Account menu"- title="Account"+ title={user ? `Signed in as ${user.username}` : 'Sign in — free forever'}>- CV+ {user ? user.username.slice(0, 2).toUpperCase() : 'CV'}</button></DropdownMenuTrigger>- <DropdownMenuContent align="end" className="w-56 bg-[#16181D] border-white/10 text-white">+ <DropdownMenuContent align="end" className="w-64 bg-[#16181D] border-white/10 text-white"><div className="px-3 py-2.5 border-b border-white/[0.07]">- <div className="text-[13px] font-semibold">Canvix creator</div>- <div className="text-[11px] text-white/45">Free · open-source · local-first</div>+ {user ? (+ <>+ <div className="text-[13px] font-semibold text-[#00C4CC]">@{user.username}</div>+ <div className="text-[11px] text-white/45">Your designs are private to your account</div>+ </>+ ) : (+ <>+ <div className="text-[13px] font-semibold">You are browsing anonymously</div>+ <div className="text-[11px] text-white/45">Free account — keep your designs yours</div>+ </>+ )}</div>+ {user ? (+ <>+ {ownerlessCount > 0 && (+ <DropdownMenuItem+ className="gap-2"+ disabled={adopting}+ onClick={async () => {+ setAdopting(true)+ try {+ const adopted = await adoptAllDesigns()+ await refresh()+ toast({ title: `${adopted} design${adopted === 1 ? '' : 's'} moved into your account` })+ } catch {+ toast({ title: 'Could not adopt designs', variant: 'destructive' })+ } finally {+ setAdopting(false)+ }+ }}+ >+ <FolderInput size={14} /> {adopting ? 'Adopting…' : `Save all designs to my account (${ownerlessCount})`}+ </DropdownMenuItem>+ )}+ <DropdownMenuItem className="gap-2" onClick={() => void logout().then(() => refresh())}>+ <LogOut size={14} /> Sign out+ </DropdownMenuItem>+ </>+ ) : (+ <>+ <DropdownMenuItem className="gap-2" onClick={() => { setAuthMode('login'); setAuthOpen(true) }}>+ <LogIn size={14} /> Sign in+ </DropdownMenuItem>+ <DropdownMenuItem className="gap-2" onClick={() => { setAuthMode('register'); setAuthOpen(true) }}>+ <LogIn size={14} /> Create a free account+ </DropdownMenuItem>+ </>+ )}+ <div className="my-1 border-t border-white/[0.07]" /><DropdownMenuItem className="gap-2" onClick={() => setHelpOpen(true)}><CircleHelp size={14} /> Help & shortcuts</DropdownMenuItem>@@ -861,6 +919,17 @@ export function Dashboard() {</DialogFooter></DialogContent></Dialog>++ {/* ── v0.9: account sign-in / sign-up ── */}+ <AuthDialog+ open={authOpen}+ onOpenChange={setAuthOpen}+ initialMode={authMode}+ onAuthed={() => {+ // the dashboard scope changes with the session — reload it+ void refresh()+ }}+ /></div>)}diff --git a/src/components/dashboard/hooks.ts b/src/components/dashboard/hooks.tsindex 51d047f..aecdc67 100644--- a/src/components/dashboard/hooks.ts+++ b/src/components/dashboard/hooks.ts@@ -10,6 +10,7 @@ export interface DesignMeta {height: numberthumbnail: string | nullsource: string+ ownerId: string | nulldeletedAt: string | nullcreatedAt: stringupdatedAt: stringdiff --git a/src/components/editor/Editor.tsx b/src/components/editor/Editor.tsxindex b5bdaa9..4a69a19 100644--- a/src/components/editor/Editor.tsx+++ b/src/components/editor/Editor.tsx@@ -2,7 +2,7 @@import { useCallback, useEffect, useRef, useState } from 'react'import dynamic from 'next/dynamic'-import { X, Keyboard } from 'lucide-react'+import { X, Keyboard, Eye } from 'lucide-react'import { useAppStore } from '@/store/app-store'import { useEditorStore, type PanelId } from '@/store/editor-store'import { TopBar } from './TopBar'@@ -80,6 +80,7 @@ export default function Editor() {const goDashboard = useAppStore((s) => s.goDashboard)const loadDesign = useEditorStore((s) => s.loadDesign)const designId = useEditorStore((s) => s.designId)+ const readOnly = useEditorStore((s) => s.readOnly)const panel = useEditorStore((s) => s.panel)const setPanel = useEditorStore((s) => s.setPanel)const dirty = useEditorStore((s) => s.dirty)@@ -122,10 +123,13 @@ export default function Editor() {}, [])// ── autosave ───────────────────────────────────────────────+ // v0.9: view-only designs (owned by another account) never autosave —+ // the API would refuse with 403 anyway; skipping keeps the console+ // clean and the “saved” indicator honest.const save = useCallback(async (withThumbnail: boolean) => {const state = useEditorStore.getState()- if (!state.designId || state.saving) return+ if (!state.designId || state.saving || state.readOnly) returnstate.markSaving()try {let thumbnail: string | null = null@@ -360,6 +364,11 @@ export default function Editor() {return (<div className="h-screen w-full flex flex-col bg-[#0F1015] overflow-hidden"><TopBar onSave={() => save(true)} onShortcuts={() => setShortcutsOpen(true)} />+ {readOnly && (+ <div className="flex items-center justify-center gap-2 bg-[#3B2A00] border-b border-[#F59E0B]/25 px-4 py-1.5 text-[12px] text-[#FBBF24]" role="status">+ <Eye size={13} /> View-only — this design belongs to another account. Sign in as its owner to edit it.+ </div>+ )}<div className="flex flex-1 min-h-0">{/* desktop rail */}diff --git a/src/components/landing/Landing.tsx b/src/components/landing/Landing.tsxindex 5656851..b112a99 100644--- a/src/components/landing/Landing.tsx+++ b/src/components/landing/Landing.tsx@@ -24,6 +24,7 @@ import {import { useAppStore } from '@/store/app-store'import { Logo } from '@/components/logo'import { Button } from '@/components/ui/button'+import { useAuth } from '@/lib/auth/client'// ── Editor mockup (pure CSS, zero assets) ────────────────────@@ -136,6 +137,7 @@ const TEMPLATE_SHOWCASE = [export function Landing() {const goDashboard = useAppStore((s) => s.goDashboard)+ const { user } = useAuth()return (<div className="min-h-screen flex flex-col bg-white">@@ -156,8 +158,13 @@ export function Landing() {<Github size={16} /> <span className="hidden sm:inline">GitHub</span></Button></a>+ {user && (+ <span className="hidden sm:inline text-xs font-medium text-muted-foreground">+ @{user.username}+ </span>+ )}<Button size="sm" className="btn-brand-gradient rounded-full px-4" onClick={goDashboard}>- Start designing+ {user ? 'Back to your designs' : 'Start designing'}</Button></div></nav>diff --git a/src/lib/auth/auth.test.ts b/src/lib/auth/auth.test.tsnew file mode 100644index 0000000..4b22def--- /dev/null+++ b/src/lib/auth/auth.test.ts@@ -0,0 +1,84 @@+// Unit tests for the v0.9 account primitives — password hashing,+// input validation and session token derivation. All pure (or+// node:crypto-only): no DB, no network, fully hermetic.++import { describe, it, expect } from 'vitest'+import { hashPassword, verifyPassword } from './passwords'+import { checkUsername, checkPassword, canonicalUsername } from './validate'+import { newSessionToken, sessionIdFor } from './session'++describe('hashPassword / verifyPassword', () => {+ it('round-trips a password', async () => {+ const stored = await hashPassword('correct horse battery staple')+ expect(stored.startsWith('scrypt:')).toBe(true)+ await expect(verifyPassword('correct horse battery staple', stored)).resolves.toBe(true)+ })++ it('rejects a wrong password', async () => {+ const stored = await hashPassword('correct horse battery staple')+ await expect(verifyPassword('wrong password entirely!', stored)).resolves.toBe(false)+ })++ it('salts: the same password hashes differently every time', async () => {+ const a = await hashPassword('same password')+ const b = await hashPassword('same password')+ expect(a).not.toBe(b)+ await expect(verifyPassword('same password', a)).resolves.toBe(true)+ await expect(verifyPassword('same password', b)).resolves.toBe(true)+ })++ it('never throws on malformed stored hashes — just fails', async () => {+ for (const bad of ['', 'plaintext', 'bcrypt:$x:y:z', 'scrypt:1:2', 'scrypt:abc:def:ghi:jkl:mno', 'scrypt:999999999:1:1:AAAA:BBBB']) {+ await expect(verifyPassword('whatever', bad)).resolves.toBe(false)+ }+ })+})++describe('checkUsername / canonicalUsername', () => {+ it('accepts valid usernames and canonicalizes case/space', () => {+ expect(checkUsername('ashiq')).toEqual({ ok: true })+ expect(checkUsername(' Ashiq_Designs-01 ').ok).toBe(true)+ expect(canonicalUsername(' Ashiq_Designs-01 ')).toBe('ashiq_designs-01')+ })++ it('rejects short, long, empty and non-string input', () => {+ expect(checkUsername('ab').ok).toBe(false)+ expect(checkUsername('').ok).toBe(false)+ expect(checkUsername(null).ok).toBe(false)+ expect(checkUsername('a'.repeat(33)).ok).toBe(false)+ })++ it('rejects characters outside [a-z0-9_-] and leading -/_', () => {+ expect(checkUsername('has space').ok).toBe(false)+ expect(checkUsername('ünicode').ok).toBe(false)+ expect(checkUsername('dot.name').ok).toBe(false)+ expect(checkUsername('../etc/passwd').ok).toBe(false)+ expect(checkUsername('-leading').ok).toBe(false)+ expect(checkUsername('_leading').ok).toBe(false)+ })+})++describe('checkPassword', () => {+ it('accepts long-enough passwords, rejects short/long/guessable', () => {+ expect(checkPassword('12345678').ok).toBe(false) // in top-passwords list+ expect(checkPassword('tr0ub4dor&3days').ok).toBe(true)+ expect(checkPassword('short').ok).toBe(false)+ expect(checkPassword('a'.repeat(201)).ok).toBe(false)+ expect(checkPassword(12345678).ok).toBe(false)+ })+})++describe('session tokens', () => {+ it('mints 256-bit base64url tokens with no padding', () => {+ const t = newSessionToken()+ expect(t).toMatch(/^[A-Za-z0-9_-]{43}$/)+ })++ it('derives a stable sha256 row id, different from the token', () => {+ const t = newSessionToken()+ const id = sessionIdFor(t)+ expect(id).toMatch(/^[0-9a-f]{64}$/)+ expect(sessionIdFor(t)).toBe(id)+ expect(sessionIdFor(newSessionToken())).not.toBe(id)+ })+})diff --git a/src/lib/auth/client.ts b/src/lib/auth/client.tsnew file mode 100644index 0000000..2ee0371--- /dev/null+++ b/src/lib/auth/client.ts@@ -0,0 +1,93 @@+'use client'++// ─────────────────────────────────────────────────────────────+// Client-side auth (v0.9) — a tiny hook + fetch wrappers, no+// external state library. Accounts are free forever; this module+// only decides between account mode and anonymous (link) mode.+// ─────────────────────────────────────────────────────────────++import { useCallback, useEffect, useState } from 'react'++export interface AuthUser {+ id: string+ username: string+ createdAt: string+}++export interface AuthState {+ user: AuthUser | null+ loading: boolean+}++async function postJson(url: string, body: unknown): Promise<{ ok: boolean; status: number; data: Record<string, unknown> }> {+ const res = await fetch(url, {+ method: 'POST',+ headers: { 'Content-Type': 'application/json' },+ body: JSON.stringify(body),+ })+ let data: Record<string, unknown> = {}+ try {+ data = (await res.json()) as Record<string, unknown>+ } catch {+ /* empty body */+ }+ return { ok: res.ok, status: res.status, data }+}++/**+ * The app's auth state. `refresh()` re-reads /api/auth/me (e.g. after+ * the login dialog succeeds somewhere else in the tree).+ */+export function useAuth(): AuthState & {+ refresh: () => Promise<void>+ login: (username: string, password: string) => Promise<string | null>+ register: (username: string, password: string) => Promise<string | null>+ logout: () => Promise<void>+} {+ const [state, setState] = useState<AuthState>({ user: null, loading: true })++ const refresh = useCallback(async () => {+ try {+ const res = await fetch('/api/auth/me', { cache: 'no-store' })+ const data = (await res.json()) as { user: AuthUser | null }+ setState({ user: data?.user ?? null, loading: false })+ } catch {+ setState((s) => ({ ...s, loading: false }))+ }+ }, [])++ useEffect(() => {+ void refresh()+ }, [refresh])++ /** returns an error message, or null on success */+ const login = useCallback(async (username: string, password: string): Promise<string | null> => {+ const { ok, data } = await postJson('/api/auth/login', { username, password })+ if (!ok) return typeof data.error === 'string' ? data.error : 'Sign-in failed.'+ setState({ user: data.user as AuthUser, loading: false })+ return null+ }, [])++ /** returns an error message, or null on success */+ const register = useCallback(async (username: string, password: string): Promise<string | null> => {+ const { ok, data } = await postJson('/api/auth/register', { username, password })+ if (!ok) return typeof data.error === 'string' ? data.error : 'Could not create the account.'+ setState({ user: data.user as AuthUser, loading: false })+ return null+ }, [])++ const logout = useCallback(async () => {+ await postJson('/api/auth/logout', {}).catch(() => {})+ setState({ user: null, loading: false })+ }, [])++ return { ...state, refresh, login, register, logout }+}++/** Claim every ownerless design for the signed-in account. */+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+}diff --git a/src/lib/auth/design-guard.ts b/src/lib/auth/design-guard.tsnew file mode 100644index 0000000..9bee1b1--- /dev/null+++ b/src/lib/auth/design-guard.ts@@ -0,0 +1,49 @@+// ─────────────────────────────────────────────────────────────+// Design access rules (v0.9) — one place, three cases:+//+// 1. ownerless design (ownerId null) → link-accessible: anyone can+// edit. This is the pre-accounts behaviour; legacy designs and+// intentionally shared designs keep working exactly as before.+// 2. owner signed in → full edit access.+// 3. anyone else (anonymous or another → read-only: the design+// account) opens, but every mutating+// API answers 403 and the+// editor shows view-only.+//+// SERVER-ONLY helper shared by the design routes.+// ─────────────────────────────────────────────────────────────++import type { NextRequest } from 'next/server'+import { db } from '@/lib/db'+import { getSessionUser, type SessionUser } from '@/lib/auth/session'++export interface DesignAccess {+ design: { id: string; ownerId: string | null } & Record<string, unknown>+ user: SessionUser | null+ /** true unless the design is owned by someone else */+ canEdit: boolean+}++/**+ * Load a design + resolve the caller's access. Returns null when the+ * design does not exist. Never throws (DB errors bubble as usual so+ * dbErrorResponse can classify them).+ */+export async function resolveDesignAccess(+ req: NextRequest,+ id: string+): Promise<DesignAccess | null> {+ const [design, user] = await Promise.all([+ db.design.findUnique({ where: { id } }),+ getSessionUser(req),+ ])+ if (!design) return null+ const canEdit = design.ownerId === null || design.ownerId === user?.id+ return { design: design as DesignAccess['design'], user, canEdit }+}++/** Standard 403 body for mutating routes. */+export const NOT_YOUR_DESIGN = {+ error: 'This design belongs to another account — it is view-only for you.',+ code: 'READ_ONLY_DESIGN',+} as constdiff --git a/src/lib/auth/passwords.ts b/src/lib/auth/passwords.tsnew file mode 100644index 0000000..fba6eda--- /dev/null+++ b/src/lib/auth/passwords.ts@@ -0,0 +1,59 @@+// ─────────────────────────────────────────────────────────────+// Password hashing for Canvix accounts (v0.9).+//+// scrypt from node:crypto — deliberately zero external dependencies+// (no bcrypt/argon2 native builds) so self-hosting stays trivially+// free and portable. Parameters are Node's defaults (N=16384, r=8,+// p=1) with a 64-byte key and per-hash random salt.+//+// Format: scrypt:<N>:<r>:<p>:<saltB64>:<hashB64>+// The stored parameters make future cost upgrades verifiable+// against old hashes without invalidating them.+// ─────────────────────────────────────────────────────────────++import { randomBytes, scrypt as _scrypt, timingSafeEqual } from 'node:crypto'+import { promisify } from 'node:util'++const scrypt = promisify(_scrypt) as (+ password: string | Buffer,+ salt: string | Buffer,+ keylen: number,+ options: { N: number; r: number; p: number; maxmem?: number }+) => Promise<Buffer>++const N = 16384+const R = 8+const P = 1+const KEYLEN = 64++/** Hash a password → storable string (random 16-byte salt). */+export async function hashPassword(password: string): Promise<string> {+ const salt = randomBytes(16)+ const key = await scrypt(password, salt, KEYLEN, { N, r: R, p: P, maxmem: 64 * 1024 * 1024 })+ return `scrypt:${N}:${R}:${P}:${salt.toString('base64')}:${key.toString('base64')}`+}++/**+ * Verify a password against a stored hash. Constant-time on the derived+ * key comparison; malformed stored hashes simply fail (never throw).+ */+export async function verifyPassword(password: string, stored: string): Promise<boolean> {+ try {+ const parts = stored.split(':')+ if (parts.length !== 6 || parts[0] !== 'scrypt') return false+ const [, nStr, rStr, pStr, saltB64, hashB64] = parts+ const n = parseInt(nStr, 10)+ const r = parseInt(rStr, 10)+ const p = parseInt(pStr, 10)+ // sanity bounds — refuse absurd parameters from a tampered row+ if (!(n >= 1 && n <= 1 << 22) || !(r >= 1 && r <= 1024) || !(p >= 1 && p <= 1024)) return false+ const salt = Buffer.from(saltB64, 'base64')+ const expected = Buffer.from(hashB64, 'base64')+ if (salt.length < 8 || expected.length < 32) return false+ const actual = await scrypt(password, salt, expected.length, { N: n, r, p, maxmem: 64 * 1024 * 1024 })+ if (actual.length !== expected.length) return false+ return timingSafeEqual(actual, expected)+ } catch {+ return false+ }+}diff --git a/src/lib/auth/session.ts b/src/lib/auth/session.tsnew file mode 100644index 0000000..445a471--- /dev/null+++ b/src/lib/auth/session.ts@@ -0,0 +1,93 @@+// ─────────────────────────────────────────────────────────────+// Server-side session management (v0.9).+//+// Opaque token sessions: the cookie carries a 32-byte random token;+// the DB row id is sha256(token). A database leak therefore never+// contains usable session tokens, and sessions can be revoked+// server-side at any time (logout, expiry sweep).+//+// Cookie: `canvix_session`, HttpOnly + SameSite=Lax (+ Secure in+// production). 30-day absolute lifetime.+//+// CONTRACT: server-only module (node:crypto + Prisma).+// ─────────────────────────────────────────────────────────────++import { createHash, randomBytes } from 'node:crypto'+import { NextResponse, type NextRequest } from 'next/server'+import { db } from '@/lib/db'++export const SESSION_COOKIE = 'canvix_session'+export const SESSION_TTL_DAYS = 30++export interface SessionUser {+ id: string+ username: string+ createdAt: Date+}++/** New random session token (base64url, 256-bit). */+export function newSessionToken(): string {+ return randomBytes(32).toString('base64url')+}++/** DB row id for a token = sha256 hex. */+export function sessionIdFor(token: string): string {+ return createHash('sha256').update(token).digest('hex')+}++function cookieOptions() {+ const secure = process.env.NODE_ENV === 'production'+ return {+ httpOnly: true,+ sameSite: 'lax' as const,+ secure,+ path: '/',+ maxAge: SESSION_TTL_DAYS * 24 * 60 * 60,+ }+}++/**+ * Create a session for a user and attach the cookie to a response.+ * Opportunistically sweeps expired sessions (bounded, best-effort).+ */+export async function createSession(userId: string, res: NextResponse): Promise<void> {+ const token = newSessionToken()+ const expiresAt = new Date(Date.now() + SESSION_TTL_DAYS * 24 * 60 * 60 * 1000)+ await db.session.create({ data: { id: sessionIdFor(token), userId, expiresAt } })+ res.cookies.set(SESSION_COOKIE, token, cookieOptions())+ // best-effort sweep: drop expired sessions (single bounded DELETE)+ void db.session.deleteMany({ where: { expiresAt: { lt: new Date() } } }).catch(() => {})+}++/** Delete the current session (if any) and clear the cookie. */+export async function destroySession(req: NextRequest, res: NextResponse): Promise<void> {+ const token = req.cookies.get(SESSION_COOKIE)?.value+ if (token) {+ await db.session.deleteMany({ where: { id: sessionIdFor(token) } }).catch(() => {})+ }+ res.cookies.set(SESSION_COOKIE, '', { ...cookieOptions(), maxAge: 0 })+}++/**+ * Resolve the signed-in user from the request cookie.+ * Returns null when absent, expired, or dangling (user deleted).+ */+export async function getSessionUser(req: NextRequest): Promise<SessionUser | null> {+ const token = req.cookies.get(SESSION_COOKIE)?.value+ if (!token || token.length > 128) return null+ try {+ const row = await db.session.findUnique({+ where: { id: sessionIdFor(token) },+ include: { user: { select: { id: true, username: true, createdAt: true } } },+ })+ if (!row) return null+ if (row.expiresAt.getTime() < Date.now()) {+ void db.session.delete({ where: { id: row.id } }).catch(() => {})+ return null+ }+ return row.user+ } catch {+ // DB unavailable — treat as signed out, never crash a route over auth+ return null+ }+}diff --git a/src/lib/auth/validate.ts b/src/lib/auth/validate.tsnew file mode 100644index 0000000..a3d5dae--- /dev/null+++ b/src/lib/auth/validate.ts@@ -0,0 +1,56 @@+// ─────────────────────────────────────────────────────────────+// Account input validation (v0.9) — pure, unit-testable.+//+// Usernames: 3–32 chars of [a-z0-9_-], stored lowercase.+// Lowercasing is canonical (uniqueness is case-insensitive);+// the charset blocks lookalike spoofing and path/SQL games.+// Passwords: 8–200 chars. No composition rules — length wins+// (NIST SP 800-63B guidance), and we refuse the handful of+// passwords that are trivially guessable.+// ─────────────────────────────────────────────────────────────++export const USERNAME_MIN = 3+export const USERNAME_MAX = 32+export const PASSWORD_MIN = 8+export const PASSWORD_MAX = 200++const USERNAME_RE = /^[a-z0-9_-]+$/++const TOP_PASSWORDS = new Set([+ 'password', 'password1', 'password123', 'passw0rd', '12345678',+ '123456789', '1234567890', 'qwertyuiop', 'qwerty123', 'letmein123',+ 'iloveyou1', 'admin1234', 'welcome123', 'canvix123', 'changeme123',+])++export interface ValidationCheck {+ ok: boolean+ error?: string+}++/** Canonicalize + validate a username. */+export function checkUsername(raw: unknown): ValidationCheck {+ if (typeof raw !== 'string') return { ok: false, error: 'Username is required.' }+ const name = raw.trim().toLowerCase()+ if (name.length < USERNAME_MIN) return { ok: false, error: `Username must be at least ${USERNAME_MIN} characters.` }+ if (name.length > USERNAME_MAX) return { ok: false, error: `Username must be at most ${USERNAME_MAX} characters.` }+ if (!USERNAME_RE.test(name)) {+ return { ok: false, error: 'Username can only use letters, numbers, - and _.' }+ }+ if (name.startsWith('-') || name.startsWith('_')) return { ok: false, error: 'Username must start with a letter or number.' }+ return { ok: true }+}++/** The canonical stored/compared form of a username. */+export function canonicalUsername(raw: string): string {+ return raw.trim().toLowerCase()+}++export function checkPassword(raw: unknown): ValidationCheck {+ if (typeof raw !== 'string') return { ok: false, error: 'Password is required.' }+ if (raw.length < PASSWORD_MIN) return { ok: false, error: `Password must be at least ${PASSWORD_MIN} characters.` }+ if (raw.length > PASSWORD_MAX) return { ok: false, error: `Password must be at most ${PASSWORD_MAX} characters.` }+ if (TOP_PASSWORDS.has(raw.trim().toLowerCase())) {+ return { ok: false, error: 'That password is too common — choose something less guessable.' }+ }+ return { ok: true }+}diff --git a/src/lib/mcp/ssrf-guard.test.ts b/src/lib/mcp/ssrf-guard.test.tsindex 89d3c43..ee66980 100644--- a/src/lib/mcp/ssrf-guard.test.ts+++ b/src/lib/mcp/ssrf-guard.test.ts@@ -23,7 +23,10 @@ import {assertPublicHost,parseHttpUrl,safeFetch,+ pinnedFetch,+ type PinnedTransport,} from './ssrf-guard'+import { createServer, type Server } from 'node:http'const PUBLIC_DNS = [{ address: '93.184.216.34', family: 4 }]@@ -220,89 +223,136 @@ function res(status: number, headers: Record<string, string> = {}): Response {}describe('safeFetch', () => {- it('returns a normal 200 response after validating the host', async () => {- const fetchMock = vi.fn().mockResolvedValue(res(200, { 'content-type': 'image/png' }))- vi.stubGlobal('fetch', fetchMock)- const out = await safeFetch('https://cdn.example.com/img.png')+ it('returns a normal 200 response after validating the host, PINNED to the resolved IP', async () => {+ const transport = vi.fn().mockResolvedValue(res(200, { 'content-type': 'image/png' }))+ const out = await safeFetch('https://cdn.example.com/img.png', { transport })expect(out.status).toBe(200)- expect(fetchMock).toHaveBeenCalledTimes(1)- expect(String(fetchMock.mock.calls[0][0])).toBe('https://cdn.example.com/img.png')+ expect(transport).toHaveBeenCalledTimes(1)+ // v0.9: the connection address is the VALIDATED one from DNS+ expect(transport.mock.calls[0][1]).toBe('93.184.216.34')+ expect(transport.mock.calls[0][2]).toBe(4)+ expect(transport.mock.calls[0][0].href).toBe('https://cdn.example.com/img.png')})it('REDIRECT BYPASS (the v0.6 bug): a public URL that 302s to a private IP is refused', async () => {- const fetchMock = vi+ const transport = vi.fn().mockResolvedValue(res(302, { location: 'http://169.254.169.254/latest/meta-data/' }))- vi.stubGlobal('fetch', fetchMock)- await expect(safeFetch('https://evil.example.com/redirect')).rejects.toThrow(+ await expect(safeFetch('https://evil.example.com/redirect', { transport })).rejects.toThrow(/private|blocked/i,)- expect(fetchMock).toHaveBeenCalledTimes(1) // never connected to the metadata service+ expect(transport).toHaveBeenCalledTimes(1) // never connected to the metadata service})it('redirect to an internal hostname is refused', async () => {- const fetchMock = vi.fn().mockResolvedValue(res(301, { location: 'http://intranet.corp/secret' }))- vi.stubGlobal('fetch', fetchMock)- await expect(safeFetch('https://evil.example.com/r')).rejects.toThrow(/internal-looking|blocked/i)+ const transport = vi.fn().mockResolvedValue(res(301, { location: 'http://intranet.corp/secret' }))+ await expect(safeFetch('https://evil.example.com/r', { transport })).rejects.toThrow(/internal-looking|blocked/i)})it('redirect to a non-http protocol is refused', async () => {- const fetchMock = vi.fn().mockResolvedValue(res(302, { location: 'file:///etc/passwd' }))- vi.stubGlobal('fetch', fetchMock)- await expect(safeFetch('https://evil.example.com/r')).rejects.toThrow(+ const transport = vi.fn().mockResolvedValue(res(302, { location: 'file:///etc/passwd' }))+ await expect(safeFetch('https://evil.example.com/r', { transport })).rejects.toThrow(/non-http|only http\(s\)/i,)- expect(fetchMock).toHaveBeenCalledTimes(1)+ expect(transport).toHaveBeenCalledTimes(1)})- it('follows redirects to PUBLIC hosts and returns the final response', async () => {- const fetchMock = vi+ it('follows redirects to PUBLIC hosts — re-pinning on every hop', async () => {+ const transport = vi.fn().mockResolvedValueOnce(res(302, { location: 'https://mirror.example.org/real.png' })).mockResolvedValueOnce(res(200, { 'content-type': 'image/png' }))- vi.stubGlobal('fetch', fetchMock)- const out = await safeFetch('https://cdn.example.com/img.png')+ const out = await safeFetch('https://cdn.example.com/img.png', { transport })expect(out.status).toBe(200)- expect(fetchMock).toHaveBeenCalledTimes(2)- expect(String(fetchMock.mock.calls[1][0])).toBe('https://mirror.example.org/real.png')+ expect(transport).toHaveBeenCalledTimes(2)+ expect(transport.mock.calls[1][0].href).toBe('https://mirror.example.org/real.png')+ // each hop is pinned to ITS OWN validated address+ expect(transport.mock.calls[1][1]).toBe('93.184.216.34')})it('resolves RELATIVE redirect locations against the current URL', async () => {- const fetchMock = vi+ const transport = vi.fn().mockResolvedValueOnce(res(302, { location: '/deep/real.png' })).mockResolvedValueOnce(res(200))- vi.stubGlobal('fetch', fetchMock)- await safeFetch('https://cdn.example.com/a/b/img.png')- expect(String(fetchMock.mock.calls[1][0])).toBe('https://cdn.example.com/deep/real.png')+ await safeFetch('https://cdn.example.com/a/b/img.png', { transport })+ expect(transport.mock.calls[1][0].href).toBe('https://cdn.example.com/deep/real.png')})it('refuses after MAX_REDIRECTS hops', async () => {- const fetchMock = vi.fn().mockImplementation(async () => res(302, { location: 'https://loop.example.com/next' }))- vi.stubGlobal('fetch', fetchMock)- await expect(safeFetch('https://loop.example.com/start')).rejects.toThrow(/too many redirects/i)- expect(fetchMock.mock.calls.length).toBeLessThanOrEqual(6) // 5 hops + initial+ const transport = vi.fn().mockImplementation(async () => res(302, { location: 'https://loop.example.com/next' }))+ await expect(safeFetch('https://loop.example.com/start', { transport })).rejects.toThrow(/too many redirects/i)+ expect(transport.mock.calls.length).toBeLessThanOrEqual(6) // 5 hops + initial})it('refuses the initial URL itself when it is private', async () => {- const fetchMock = vi.fn()- vi.stubGlobal('fetch', fetchMock)- await expect(safeFetch('http://192.168.1.1/admin')).rejects.toThrow(/private/i)- expect(fetchMock).not.toHaveBeenCalled()+ const transport = vi.fn()+ await expect(safeFetch('http://192.168.1.1/admin', { transport })).rejects.toThrow(/private/i)+ expect(transport).not.toHaveBeenCalled()})it('refuses non-http initial URLs', async () => {- const fetchMock = vi.fn()- vi.stubGlobal('fetch', fetchMock)- await expect(safeFetch('file:///etc/passwd')).rejects.toThrow(/only http\(s\)/i)- expect(fetchMock).not.toHaveBeenCalled()+ const transport = vi.fn()+ await expect(safeFetch('file:///etc/passwd', { transport })).rejects.toThrow(/only http\(s\)/i)+ expect(transport).not.toHaveBeenCalled()})- it('never sends automatic redirects to fetch() (pinning is manual)', async () => {- const fetchMock = vi.fn().mockResolvedValue(res(200))- vi.stubGlobal('fetch', fetchMock)- await safeFetch('https://cdn.example.com/img.png')- const init = fetchMock.mock.calls[0][1] as RequestInit+ it('hands the transport a manual-redirect init (pinning is manual)', async () => {+ const transport = vi.fn().mockResolvedValue(res(200))+ await safeFetch('https://cdn.example.com/img.png', { transport })+ const init = transport.mock.calls[0][3] as RequestInitexpect(init.redirect).toBe('manual')})++ it('DNS REBINDING (the v0.6.1 residual): a name that flips to a private IP after validation cannot be reached', async () => {+ // The guard resolves the name (public) and hands the transport the+ // validated address. Even if real DNS rebound a moment later, the+ // connection still goes to the validated IP — there is no second+ // lookup. This test asserts the invariant the pin enforces.+ lookupMock.mockResolvedValue([{ address: '203.0.114.10', family: 4 }])+ const transport = vi.fn().mockResolvedValue(res(200))+ await safeFetch('https://rebind.example.net/x', { transport })+ expect(transport.mock.calls[0][1]).toBe('203.0.114.10') // the pinned address+ })+})++// ── pinnedFetch: the real transport, exercised end-to-end ─────++describe('pinnedFetch (default transport)', () => {+ let server: Server+ let port: number+ let sawHost: string | null = null++ beforeEach(async () => {+ sawHost = null+ server = createServer((req, res) => {+ sawHost = req.headers.host ?? null+ res.writeHead(200, { 'content-type': 'text/plain' })+ res.end('hello from pinned')+ })+ await new Promise<void>((r) => server.listen(0, '127.0.0.1', () => r()))+ port = (server.address() as { port: number }).port+ })++ afterEach(async () => {+ await new Promise<void>((r) => server.close(() => r()))+ })++ it('connects to the PINNED address while sending the real hostname', async () => {+ // example.test would normally resolve via DNS — but the pin forces the+ // connection to 127.0.0.1:port. If the lookup were not pinned, this+ // request would fail (NXDOMAIN / wrong host).+ const url = new URL(`http://pin-target.example.test:${port}/x`)+ const out = await pinnedFetch(url, '127.0.0.1', 4, {})+ expect(out.status).toBe(200)+ expect(await out.text()).toBe('hello from pinned')+ // the Host header still carries the ORIGINAL hostname, not the IP+ expect(sawHost).toBe(`pin-target.example.test:${port}`)+ })++ it('rejects when the pinned address is unreachable', async () => {+ // port 1 on loopback: nothing listens there — connection refused+ const url = new URL('http://pin-target.example.test:1/x')+ await expect(pinnedFetch(url, '127.0.0.1', 4, {})).rejects.toThrow()+ })})diff --git a/src/lib/mcp/ssrf-guard.ts b/src/lib/mcp/ssrf-guard.tsindex 48ae0b6..f5ece9c 100644--- a/src/lib/mcp/ssrf-guard.ts+++ b/src/lib/mcp/ssrf-guard.ts@@ -13,15 +13,19 @@// 3. hostnames are checked against an intranet blocklist and// must NOT be bare (dot-less) names// 4. DNS is resolved and EVERY resolved address must be public-//-// Known residual risk (documented, accepted for v0.6.1): a DNS-// rebinding TOCTOU — the guard resolves the name, then fetch()-// resolves it again. Pinning the connection IP would break TLS-// SNI for https targets; that is Phase 3 work alongside auth.+// 5. v0.9 (Phase 3 close-out): the connection is PINNED to the+// validated address — the transport uses a custom DNS lookup+// that only ever returns the already-validated IP, closing the+// DNS-rebinding TOCTOU window (guard resolves, fetch would+// re-resolve). TLS keeps the real hostname for SNI, so+// certificate validation is unaffected.// ─────────────────────────────────────────────────────────────import { lookup } from 'node:dns/promises'import { isIP } from 'node:net'+import { request as httpRequest } from 'node:http'+import { request as httpsRequest } from 'node:https'+import { Readable } from 'node:stream'export const MAX_REDIRECTS = 5@@ -123,17 +127,19 @@ export function isBlockedHostname(hostname: string): boolean {* hostname resolves to must be public, otherwise the request is refused.* This also defeats decimal/octal/hex IP encodings (e.g. http://2130706433/)* because the resolver normalizes them before the range check.+ *+ * v0.9: returns the validated address the connection will be PINNED to.*/-export async function assertPublicHost(hostname: string): Promise<void> {+export async function resolvePublicHost(hostname: string): Promise<{ address: string; family: number }> {const h = normalizeHost(hostname)const version = isIP(h)if (version === 4) {if (isPrivateV4(h)) throw new Error(`Blocked target ${h}: private/reserved IP address.`)- return+ return { address: h, family: 4 }}if (version === 6) {if (isPrivateV6(h)) throw new Error(`Blocked target ${h}: private/reserved IP address.`)- return+ return { address: h, family: 6 }}if (isBlockedHostname(h)) throw new Error(`Blocked hostname "${h}": internal-looking name.`)let addrs: Array<{ address: string; family: number }>@@ -147,6 +153,12 @@ export async function assertPublicHost(hostname: string): Promise<void> {const priv = family === 6 ? isPrivateV6(address) : isPrivateV4(address)if (priv) throw new Error(`Blocked target "${h}": resolves to private address ${address}.`)}+ return addrs[0]+}++/** Back-compat wrapper: validate without returning the pin. */+export async function assertPublicHost(hostname: string): Promise<void> {+ await resolvePublicHost(hostname)}// ── protocol + URL validation ────────────────────────────────@@ -166,25 +178,117 @@ export function parseHttpUrl(raw: string): URL {// ── the safe fetch ───────────────────────────────────────────+/** Connection-layer function: performs the HTTP(S) exchange against a+ * pre-validated IP while presenting `url`'s hostname (Host header + TLS SNI). */+export type PinnedTransport = (+ url: URL,+ ip: string,+ family: number,+ init: RequestInit+) => Promise<Response>+export interface SafeFetchOptions extends RequestInit {/** max redirect hops that will be followed (default 5) */maxRedirects?: number+ /** @internal transport override — used by the test suite to observe+ * the pinned address without real network I/O */+ transport?: PinnedTransport+}++function normalizeHeaders(h: HeadersInit | undefined): Record<string, string> {+ const out: Record<string, string> = {}+ if (!h) return out+ if (h instanceof Headers) {+ h.forEach((v, k) => {+ out[k] = v+ })+ } else if (Array.isArray(h)) {+ for (const [k, v] of h) out[k] = v+ } else {+ for (const [k, v] of Object.entries(h)) out[k] = String(v)+ }+ return out}+/** Default transport: node:http(s) with a DNS lookup pinned to the+ * validated address — the connection can never drift to a rebound+ * record between validation and connect. */+export const pinnedFetch: PinnedTransport = (url, ip, family, init) =>+ new Promise<Response>((resolve, reject) => {+ const lib = url.protocol === 'https:' ? httpsRequest : httpRequest+ let settled = false+ const fail = (err: unknown) => {+ if (!settled) {+ settled = true+ reject(err instanceof Error ? err : new Error(String(err)))+ }+ }+ let req: import('node:http').ClientRequest+ try {+ req = lib(url, {+ method: init.method ?? 'GET',+ headers: normalizeHeaders(init.headers),+ signal: init.signal ?? undefined,+ // THE PIN: net/tls ask this lookup for the address; it can only+ // ever answer with the address the SSRF validation approved.+ lookup: (+ _hostname: string,+ _opts: unknown,+ cb: (err: null, addresses: Array<{ address: string; family: number }>) => void+ ) => {+ cb(null, [{ address: ip, family }])+ },+ })+ } catch (err) {+ fail(err)+ return+ }+ req.on('error', fail)+ req.on('response', (res) => {+ const headers = new Headers()+ for (const [k, v] of Object.entries(res.headers)) {+ if (Array.isArray(v)) v.forEach((x) => headers.append(k, x))+ else if (v != null) headers.set(k, String(v))+ }+ settled = true+ resolve(+ new Response(Readable.toWeb(res) as unknown as ReadableStream, {+ status: res.statusCode ?? 200,+ statusText: res.statusMessage ?? '',+ headers,+ })+ )+ })+ if (init.body != null) {+ const b = init.body+ if (typeof b === 'string' || Buffer.isBuffer(b) || b instanceof Uint8Array || b instanceof ArrayBuffer) {+ req.write(b)+ } else {+ fail(new Error('safeFetch: unsupported body type for a pinned request.'))+ req.destroy()+ return+ }+ }+ req.end()+ })+/**- * fetch() with SSRF-hardened, manually-followed redirects. Every hop- * (initial URL included) passes assertPublicHost() BEFORE the connection- * is made. Non-http(s) redirect targets are refused. Callers may pass an- * AbortSignal in options — it spans the whole hop chain.+ * fetch() with SSRF-hardened, manually-followed redirects and a connection+ * pinned to the validated address. Every hop (initial URL included) passes+ * resolvePublicHost() BEFORE the connection is made, and the connection then+ * uses that exact address (no second DNS resolution — rebinding between the+ * check and the connect is no longer possible). Non-http(s) redirect targets+ * are refused. Callers may pass an AbortSignal in options — it spans the+ * whole hop chain.*/export async function safeFetch(url: string, options: SafeFetchOptions = {}): Promise<Response> {- const { maxRedirects = MAX_REDIRECTS, ...init } = options+ const { maxRedirects = MAX_REDIRECTS, transport = pinnedFetch, ...init } = optionslet current = parseHttpUrl(url)for (let hop = 0; ; hop++) {- await assertPublicHost(current.hostname)+ const { address, family } = await resolvePublicHost(current.hostname)- const res = await fetch(current, { ...init, redirect: 'manual' })+ const res = await transport(current, address, family, { ...init, redirect: 'manual' })if (res.status >= 300 && res.status < 400) {const location = res.headers.get('location')diff --git a/src/lib/types.ts b/src/lib/types.tsindex 3982aa9..64c0f83 100644--- a/src/lib/types.ts+++ b/src/lib/types.ts@@ -339,6 +339,9 @@ export interface DesignRecord extends DesignSnapshot {source: stringcreatedAt: stringupdatedAt: string+ /** v0.9: true when the design belongs to another account — the editor+ * switches to view-only (no saves; mutating APIs answer 403). */+ readOnly?: boolean}export interface TemplateRecord extends DesignSnapshot {diff --git a/src/store/editor-store.ts b/src/store/editor-store.tsindex 8f6a8dc..aebc805 100644--- a/src/store/editor-store.ts+++ b/src/store/editor-store.ts@@ -114,6 +114,10 @@ interface EditorState {openCrop: (id: string) => voidcloseCrop: () => void+ // v0.9: read-only mode — the open design belongs to another account;+ // autosave is disabled and the editor shows a view-only banner+ readOnly: boolean+// lifecycleloadDesign: (d: DesignRecord) => voidrename: (name: string) => void@@ -266,6 +270,7 @@ export const useEditorStore = create<EditorState>((set, get) => ({manualGuides: [],versions: [],cropTargetId: null,+ readOnly: false,loadDesign: (d) => {set({@@ -285,6 +290,7 @@ export const useEditorStore = create<EditorState>((set, get) => ({previewOpen: false,tool: 'select',cropTargetId: null,+ readOnly: d.readOnly === true,})// v0.4: load server-side versions (Postgres); local list is the offline fallbackconst local = loadVersions(d.id)