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.11.8): collab rail enforces design ownership + CSRF (#8)

Ashiq Hussain Mira89e1d05e752
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 15ff80a..287c8ee 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,50 @@
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.11.8] — 2026-11-01
+
+### Security
+
+- **Collab rail now enforces design ownership (P0).**
+ `POST /api/collab/[designId]/events` verified the design existed but
+ never consulted the access rule the document rail
+ (`PUT /api/designs/[id]`) enforces — so anyone holding an *owned*
+ design's link could append collab ops (up to and including
+ `pages:replace`), mutating the owner's live session and riding the
+ owner's next autosave. The route now resolves the same three-case
+ rule (`canEditDesign`, extracted from `design-guard.ts` so the two
+ rails can never drift) with a lean column set — ownerless designs
+ stay link-editable for everyone, owned designs accept ops from their
+ owner only, everyone else gets 403 `READ_ONLY_DESIGN`. Found during
+ the v1.0 roadmap research (`research/V0118-ROADMAP-RESEARCH.md` §3.7).
+- **Same-origin (CSRF) enforcement on the collab routes** — `events`
+ and `presence` were the only mutating routes without it; a cross-site
+ page could previously drive an authenticated owner's session cookie
+ at the events endpoint.
+- **Presence writes are design-gated** — the presence route now 404s
+ for missing/trashed designs instead of upserting junk rows for
+ arbitrary ids. Heartbeats stay open to signed-out visitors and
+ read-only viewers on purpose (they are legitimate room members, and a
+ presence row carries no document authority — element ops go through
+ `/events`, which enforces ownership).
+
+### Fixed
+
+- **Read-only sessions no longer queue collab ops.** The op emitter
+ skips when the store is read-only, and `CollabSession` treats a 403
+ flush like 404/503 (drop the queue) instead of retrying every 400 ms —
+ a misbehaving read-only tab can no longer spin against the 403.
+
+### Added
+
+- `scripts/collab-guard-probe.sh` — live API probe, 8 assertions:
+ the anonymous/second-account/owner/cross-site flush matrix, the
+ ownerless flow, viewer presence, and the junk-row 404.
+- Unit coverage for both collab routes: `events.test.ts` (9 tests) +
+ `presence.test.ts` (5) — **316 unit** total; Playwright **28/28**
+ green (incl. the offline-sync and presence-latency specs, proving the
+ anonymous ownerless path is byte-for-byte unchanged).
+
## [0.11.7] — 2026-11-01
The three findings that stayed open after the v0.11.4–v0.11.6 QA sweep
diff --git a/README.md b/README.md
index def50bb..89e0e8e 100644
--- a/README.md
+++ b/README.md
@@ -759,6 +759,10 @@ tool descriptions so agents pick the right format.
“Cannot update a component while rendering” warning, root-caused to
stroke/marquee/guide commits — not Magic Layers), and the Share
dialog documents the real access model for self-hosters *(v0.11.7)*
+- [x] Collab-rail ownership enforcement — the events/presence routes now
+ apply the same design-guard rule as the document rail (owned designs
+ 403 non-owners; ownerless designs stay link-editable), plus
+ same-origin enforcement and design-gated presence writes *(v0.11.8)*
- [ ] Plugin system (external, installable apps) — sandboxed-iframe MVP
per `research/PLUGIN-SYSTEM.md`: manifest + permission model, iframe
sandbox with postMessage bridge, an “Apps” panel store, and 2–3
diff --git a/package.json b/package.json
index 068c0b4..2726f82 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "canvix",
- "version": "0.11.7",
+ "version": "0.11.8",
"private": false,
"description": "Canvix — free & open-source graphic design tool. A community-built Canva alternative.",
"scripts": {
diff --git a/scripts/collab-guard-probe.sh b/scripts/collab-guard-probe.sh
new file mode 100755
index 0000000..50cb5d5
--- /dev/null
+++ b/scripts/collab-guard-probe.sh
@@ -0,0 +1,99 @@
+#!/usr/bin/env bash
+# v0.11.8 live probe — collab-rail ownership enforcement.
+# Boots nothing itself; expects the dev server on :3000 (or BASE_URL).
+set -u
+BASE="${BASE_URL:-http://localhost:3000}"
+JAR_A="$(mktemp)"; JAR_B="$(mktemp)"; JAR_ANON="$(mktemp)"
+PASS=0; FAIL=0
+note() { printf '%s\n' "$1"; }
+expect() { # expect <desc> <want> <got>
+ if [ "$2" = "$3" ]; then PASS=$((PASS+1)); note " ok $1 → $3"
+ else FAIL=$((FAIL+1)); note " FAIL $1 → want $2, got $3"; fi
+}
+
+UA='curl-probe/0.1'
+
+# ── account A (owner) ──────────────────────────────────────────
+A_USER="probe_a_$RANDOM$RANDOM"
+code=$(curl -s -o /dev/null -w '%{http_code}' -c "$JAR_A" -A "$UA" \
+ -H 'content-type: application/json' -H "origin: $BASE" \
+ -d "{\"username\":\"$A_USER\",\"password\":\"probe-pass-123\"}" \
+ "$BASE/api/auth/register")
+expect "register account A" 201 "$code"
+
+# ── owned design ───────────────────────────────────────────────
+resp=$(curl -s -b "$JAR_A" -c "$JAR_A" -A "$UA" \
+ -H 'content-type: application/json' -H "origin: $BASE" \
+ -d '{"name":"probe-owned","width":800,"height":600}' \
+ "$BASE/api/designs")
+OWNED=$(printf '%s' "$resp" | node -e 'let d="";process.stdin.on("data",c=>d+=c).on("end",()=>console.log(JSON.parse(d).id))')
+note "owned design: $OWNED"
+
+# ── account B (second account) ─────────────────────────────────
+B_USER="probe_b_$RANDOM$RANDOM"
+curl -s -o /dev/null -c "$JAR_B" -A "$UA" \
+ -H 'content-type: application/json' -H "origin: $BASE" \
+ -d "{\"username\":\"$B_USER\",\"password\":\"probe-pass-123\"}" \
+ "$BASE/api/auth/register" >/dev/null
+
+events_body='{"pid":"probe-pid","name":"Probe","color":"#7630D7","events":[{"eventId":"probe-e1","op":{"kind":"design:rename","name":"hacked"}}]}'
+
+# 1. anonymous flush to an OWNED design → 403 READ_ONLY_DESIGN
+code=$(curl -s -o /dev/null -w '%{http_code}' -A "$UA" \
+ -H 'content-type: application/json' -H "origin: $BASE" \
+ -d "$events_body" "$BASE/api/collab/$OWNED/events")
+expect "anonymous → owned design: 403" 403 "$code"
+
+# 2. second account flush to an OWNED design → 403
+code=$(curl -s -o /dev/null -w '%{http_code}' -b "$JAR_B" -A "$UA" \
+ -H 'content-type: application/json' -H "origin: $BASE" \
+ -d "$events_body" "$BASE/api/collab/$OWNED/events")
+expect "account B → owned design: 403" 403 "$code"
+
+# 3. owner flush to their OWNED design → 200
+code=$(curl -s -o /dev/null -w '%{http_code}' -b "$JAR_A" -A "$UA" \
+ -H 'content-type: application/json' -H "origin: $BASE" \
+ -d "$events_body" "$BASE/api/collab/$OWNED/events")
+expect "owner → owned design: 200" 200 "$code"
+
+# 4. cross-site flush (evil origin, owner cookies) → 403 CSRF
+code=$(curl -s -o /dev/null -w '%{http_code}' -b "$JAR_A" -A "$UA" \
+ -H 'content-type: application/json' -H 'origin: https://evil.example' \
+ -d "$events_body" "$BASE/api/collab/$OWNED/events")
+expect "cross-site → 403 CSRF" 403 "$code"
+
+# ── ownerless design (no cookies anywhere) ─────────────────────
+resp=$(curl -s -A "$UA" \
+ -H 'content-type: application/json' -H "origin: $BASE" \
+ -d '{"name":"probe-ownerless","width":800,"height":600}' \
+ "$BASE/api/designs")
+FREE=$(printf '%s' "$resp" | node -e 'let d="";process.stdin.on("data",c=>d+=c).on("end",()=>console.log(JSON.parse(d).id))')
+note "ownerless design: $FREE"
+
+# 5. anonymous flush to an OWNERLESS design → 200 (link = edit, by design)
+code=$(curl -s -o /dev/null -w '%{http_code}' -A "$UA" \
+ -H 'content-type: application/json' -H "origin: $BASE" \
+ -d "$events_body" "$BASE/api/collab/$FREE/events")
+expect "anonymous → ownerless design: 200" 200 "$code"
+
+# 6. presence heartbeat on the owned design (anonymous viewer) → 200 (deliberate)
+code=$(curl -s -o /dev/null -w '%{http_code}' -A "$UA" \
+ -H 'content-type: application/json' -H "origin: $BASE" \
+ -d '{"pid":"probe-viewer","name":"Viewer","color":"#02C0CC"}' \
+ "$BASE/api/collab/$OWNED/presence")
+expect "anonymous viewer presence on owned design: 200" 200 "$code"
+
+# 7. presence on a nonexistent design → 404 (no junk rows)
+code=$(curl -s -o /dev/null -w '%{http_code}' -A "$UA" \
+ -H 'content-type: application/json' -H "origin: $BASE" \
+ -d '{"pid":"probe-viewer","name":"Viewer","color":"#02C0CC"}' \
+ "$BASE/api/collab/does-not-exist/presence")
+expect "presence on missing design: 404" 404 "$code"
+
+# ── cleanup: trash the probe designs ───────────────────────────
+curl -s -o /dev/null -b "$JAR_A" -A "$UA" -X DELETE -H "origin: $BASE" "$BASE/api/designs/$OWNED" >/dev/null
+curl -s -o /dev/null -A "$UA" -X DELETE -H "origin: $BASE" "$BASE/api/designs/$FREE" >/dev/null
+
+note ""
+note "probe result: $PASS passed, $FAIL failed"
+[ "$FAIL" -eq 0 ]
diff --git a/src/app/api/collab/[designId]/events/events.test.ts b/src/app/api/collab/[designId]/events/events.test.ts
new file mode 100644
index 0000000..bb79283
--- /dev/null
+++ b/src/app/api/collab/[designId]/events/events.test.ts
@@ -0,0 +1,141 @@
+// Unit tests for the collab events-rail access enforcement (v0.11.8).
+//
+// The rail used to check design existence only; it now enforces the same
+// three-case rule as the document rail (design-guard):
+// ownerless design + anyone → accepted (link = edit, by design)
+// owned design + owner → accepted
+// owned design + other / anon → 403 READ_ONLY_DESIGN, nothing persisted
+// cross-site POST → 403 CSRF
+// missing / trashed design → 404
+
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+const dbMock = vi.hoisted(() => ({
+ design: { findUnique: vi.fn() },
+ designEvent: { createMany: vi.fn() },
+ presence: { upsert: 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'
+
+const OWNER = { id: 'owner-1', username: 'ashiq', createdAt: new Date() }
+const OTHER = { id: 'other-2', username: 'mallory', createdAt: new Date() }
+
+function post(
+ designId: string,
+ opts: { origin?: string; events?: unknown[] } = {}
+) {
+ const headers: Record<string, string> = { host: 'canvix.test' }
+ if (opts.origin) headers.origin = opts.origin
+ const req = new NextRequest(`http://canvix.test/api/collab/${designId}/events`, {
+ method: 'POST',
+ headers,
+ body: JSON.stringify({
+ pid: 'pid-1',
+ name: 'Alice',
+ color: '#7630D7',
+ events:
+ opts.events ??
+ [{ eventId: 'e1', hlc: '1:2:a', op: { kind: 'design:rename', name: 'x' } }],
+ }),
+ })
+ return POST(req, { params: Promise.resolve({ designId }) })
+}
+
+function designRow(overrides: Record<string, unknown> = {}) {
+ return { id: 'd1', deletedAt: null, ownerId: null, ...overrides }
+}
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ getSessionUser.mockResolvedValue(null)
+ dbMock.design.findUnique.mockResolvedValue(designRow())
+ dbMock.designEvent.createMany.mockResolvedValue({ count: 1 })
+ dbMock.presence.upsert.mockResolvedValue({})
+})
+
+describe('POST /api/collab/[designId]/events — access enforcement (v0.11.8)', () => {
+ it('rejects cross-site requests (CSRF)', async () => {
+ const res = await post('d1', { origin: 'https://evil.example' })
+ expect(res.status).toBe(403)
+ expect(dbMock.design.findUnique).not.toHaveBeenCalled()
+ expect(dbMock.designEvent.createMany).not.toHaveBeenCalled()
+ })
+
+ it('404s for a missing design', async () => {
+ dbMock.design.findUnique.mockResolvedValue(null)
+ const res = await post('d1')
+ expect(res.status).toBe(404)
+ expect(dbMock.designEvent.createMany).not.toHaveBeenCalled()
+ })
+
+ it('404s for a trashed design', async () => {
+ dbMock.design.findUnique.mockResolvedValue(designRow({ deletedAt: new Date() }))
+ const res = await post('d1')
+ expect(res.status).toBe(404)
+ expect(dbMock.designEvent.createMany).not.toHaveBeenCalled()
+ })
+
+ it('blocks a signed-out visitor from flushing ops to an owned design', async () => {
+ dbMock.design.findUnique.mockResolvedValue(designRow({ ownerId: 'owner-1' }))
+ getSessionUser.mockResolvedValue(null)
+ const res = await post('d1')
+ expect(res.status).toBe(403)
+ const body = await res.json()
+ expect(body.code).toBe('READ_ONLY_DESIGN')
+ expect(dbMock.designEvent.createMany).not.toHaveBeenCalled()
+ expect(dbMock.presence.upsert).not.toHaveBeenCalled()
+ })
+
+ it('blocks a second account from flushing ops to an owned design', async () => {
+ dbMock.design.findUnique.mockResolvedValue(designRow({ ownerId: 'owner-1' }))
+ getSessionUser.mockResolvedValue(OTHER)
+ const res = await post('d1')
+ expect(res.status).toBe(403)
+ expect(dbMock.designEvent.createMany).not.toHaveBeenCalled()
+ })
+
+ it('accepts an anonymous flush to an ownerless design (link = edit, by design)', async () => {
+ dbMock.design.findUnique.mockResolvedValue(designRow({ ownerId: null }))
+ getSessionUser.mockResolvedValue(null)
+ const res = await post('d1')
+ expect(res.status).toBe(200)
+ const body = await res.json()
+ expect(body.ok).toBe(true)
+ expect(body.accepted).toBe(1)
+ expect(dbMock.designEvent.createMany).toHaveBeenCalledOnce()
+ })
+
+ it('accepts the owner flushing ops to their own design', async () => {
+ dbMock.design.findUnique.mockResolvedValue(designRow({ ownerId: 'owner-1' }))
+ getSessionUser.mockResolvedValue(OWNER)
+ const res = await post('d1')
+ expect(res.status).toBe(200)
+ const body = await res.json()
+ expect(body.accepted).toBe(1)
+ expect(dbMock.designEvent.createMany).toHaveBeenCalledOnce()
+ })
+
+ it('still drops malformed events without failing the flush', async () => {
+ const res = await post('d1', {
+ events: [{ eventId: 'bad', op: { kind: 'nonsense' } }],
+ })
+ expect(res.status).toBe(200)
+ const body = await res.json()
+ expect(body.accepted).toBe(0)
+ expect(body.rejected).toEqual(['bad'])
+ expect(dbMock.designEvent.createMany).not.toHaveBeenCalled()
+ })
+
+ it('passes Origin-less script clients through (curl / probe scripts)', async () => {
+ // verify-offline-merge.ts & friends POST without an Origin header —
+ // isSameOrigin's documented non-browser carve-out must keep working.
+ const res = await post('d1')
+ expect(res.status).toBe(200)
+ })
+})
diff --git a/src/app/api/collab/[designId]/events/route.ts b/src/app/api/collab/[designId]/events/route.ts
index a9e7d87..dc8a157 100644
--- a/src/app/api/collab/[designId]/events/route.ts
+++ b/src/app/api/collab/[designId]/events/route.ts
@@ -9,6 +9,9 @@ import {
type OpEnvelope,
} from '@/lib/collab/protocol'
import { formatHlc } from '@/lib/collab/hlc'
+import { canEditDesign, NOT_YOUR_DESIGN } from '@/lib/auth/design-guard'
+import { getSessionUser } from '@/lib/auth/session'
+import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'
export const runtime = 'nodejs'
export const maxDuration = 30
@@ -52,6 +55,11 @@ function serverHlc(): string {
export async function POST(req: NextRequest, { params }: { params: Promise<{ designId: string }> }) {
const { designId } = await params
try {
+ // v0.11.8: same-origin enforcement — every other mutating route already
+ // checks this; without it a cross-site page could drive an authenticated
+ // owner's session cookie at this endpoint.
+ if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })
+
const body = (await req.json().catch(() => ({}))) as EventsBody
const pid = (body.pid ?? '').replace(/[^a-zA-Z0-9_-]/g, '').slice(0, 40)
if (!pid) return NextResponse.json({ error: 'A participant id is required.' }, { status: 400 })
@@ -59,14 +67,28 @@ export async function POST(req: NextRequest, { params }: { params: Promise<{ des
const events = Array.isArray(body.events) ? body.events.slice(0, MAX_EVENTS_PER_FLUSH) : []
if (!events.length) return NextResponse.json({ ok: true, accepted: 0 })
- // verify design exists & is not trashed
- const design = await db.design.findUnique({
- where: { id: designId },
- select: { id: true, deletedAt: true },
- })
+ // v0.11.8: verify the design exists & is not trashed, and resolve the
+ // caller's edit rights. This route used to check existence only — the
+ // ownership rule the document rail (PUT /api/designs/[id]) enforces was
+ // missing here, so anyone holding an owned design's link could append
+ // ops (up to and including pages:replace) that reached the owner's live
+ // session and rode the owner's next autosave. Same three cases as
+ // design-guard now, resolved with a lean column set — this route is hot
+ // (a flush every 400 ms per client), so the full design row is
+ // deliberately not fetched.
+ const [design, user] = await Promise.all([
+ db.design.findUnique({
+ where: { id: designId },
+ select: { id: true, deletedAt: true, ownerId: true },
+ }),
+ getSessionUser(req),
+ ])
if (!design || design.deletedAt) {
return NextResponse.json({ error: 'Design not found.' }, { status: 404 })
}
+ if (!canEditDesign(design, user)) {
+ return NextResponse.json(NOT_YOUR_DESIGN, { status: 403 })
+ }
const seenEventIds = new Set<string>()
const rejected: string[] = []
diff --git a/src/app/api/collab/[designId]/presence/presence.test.ts b/src/app/api/collab/[designId]/presence/presence.test.ts
new file mode 100644
index 0000000..299606f
--- /dev/null
+++ b/src/app/api/collab/[designId]/presence/presence.test.ts
@@ -0,0 +1,87 @@
+// Unit tests for the collab presence rail (v0.11.8 hardening).
+//
+// Presence is deliberately open to signed-out visitors and read-only
+// viewers — they are legitimate room members and a presence row carries
+// no document authority (element ops go through /events, which enforces
+// ownership). What v0.11.8 adds: same-origin enforcement and a design
+// existence/trash check so arbitrary ids can no longer mint junk rows.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+const dbMock = vi.hoisted(() => ({
+ design: { findUnique: vi.fn() },
+ presence: { upsert: vi.fn(), update: vi.fn() },
+}))
+vi.mock('@/lib/db', () => ({ db: dbMock }))
+
+// the route dynamic-imports this for Prisma.JsonNull — stub it
+vi.mock('@/generated/prisma/client', () => ({
+ Prisma: { JsonNull: { __prismaJsonNull: true } },
+}))
+
+import { NextRequest } from 'next/server'
+import { POST } from './route'
+
+function post(designId: string, opts: { origin?: string } = {}) {
+ const headers: Record<string, string> = { host: 'canvix.test' }
+ if (opts.origin) headers.origin = opts.origin
+ const req = new NextRequest(`http://canvix.test/api/collab/${designId}/presence`, {
+ method: 'POST',
+ headers,
+ body: JSON.stringify({
+ pid: 'pid-1',
+ name: 'Alice',
+ color: '#7630D7',
+ cursor: { page: 0, x: 0.5, y: 0.5 },
+ }),
+ })
+ return POST(req, { params: Promise.resolve({ designId }) })
+}
+
+function designRow(overrides: Record<string, unknown> = {}) {
+ return { id: 'd1', deletedAt: null, ...overrides }
+}
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ dbMock.design.findUnique.mockResolvedValue(designRow())
+ dbMock.presence.upsert.mockResolvedValue({})
+})
+
+describe('POST /api/collab/[designId]/presence (v0.11.8)', () => {
+ it('rejects cross-site requests (CSRF)', async () => {
+ const res = await post('d1', { origin: 'https://evil.example' })
+ expect(res.status).toBe(403)
+ expect(dbMock.design.findUnique).not.toHaveBeenCalled()
+ expect(dbMock.presence.upsert).not.toHaveBeenCalled()
+ })
+
+ it('404s for a missing design instead of minting a junk presence row', async () => {
+ dbMock.design.findUnique.mockResolvedValue(null)
+ const res = await post('nope')
+ expect(res.status).toBe(404)
+ expect(dbMock.presence.upsert).not.toHaveBeenCalled()
+ })
+
+ it('404s for a trashed design', async () => {
+ dbMock.design.findUnique.mockResolvedValue(designRow({ deletedAt: new Date() }))
+ const res = await post('d1')
+ expect(res.status).toBe(404)
+ expect(dbMock.presence.upsert).not.toHaveBeenCalled()
+ })
+
+ it('accepts an anonymous heartbeat on an ownerless design (unchanged)', async () => {
+ const res = await post('d1')
+ expect(res.status).toBe(200)
+ expect(dbMock.presence.upsert).toHaveBeenCalledOnce()
+ })
+
+ it('accepts a read-only viewer heartbeat on an owned design (deliberate)', async () => {
+ // viewers watch live and appear in the room; the events rail is what
+ // blocks their mutations — presence itself carries no authority
+ dbMock.design.findUnique.mockResolvedValue(designRow({ ownerId: 'owner-1' }))
+ const res = await post('d1')
+ expect(res.status).toBe(200)
+ expect(dbMock.presence.upsert).toHaveBeenCalledOnce()
+ })
+})
diff --git a/src/app/api/collab/[designId]/presence/route.ts b/src/app/api/collab/[designId]/presence/route.ts
index 522386e..516e96f 100644
--- a/src/app/api/collab/[designId]/presence/route.ts
+++ b/src/app/api/collab/[designId]/presence/route.ts
@@ -1,5 +1,6 @@
import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'
+import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'
export const runtime = 'nodejs'
export const maxDuration = 20
@@ -20,10 +21,27 @@ const HEX_COLOR = /^#[0-9a-fA-F]{6}$/
export async function POST(req: NextRequest, { params }: { params: Promise<{ designId: string }> }) {
const { designId } = await params
try {
+ // v0.11.8: same-origin enforcement, matching every other mutating route.
+ if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })
+
const body = (await req.json().catch(() => ({}))) as PresenceBody
const pid = (body.pid ?? '').replace(/[^a-zA-Z0-9_-]/g, '').slice(0, 40)
if (!pid) return NextResponse.json({ error: 'A participant id is required.' }, { status: 400 })
+ // v0.11.8: verify the design exists (and is not trashed) before
+ // writing presence — this used to upsert blindly, leaving junk rows
+ // for arbitrary design ids. Presence stays open to signed-out visitors
+ // and read-only viewers ON PURPOSE: they are legitimate room members,
+ // and a presence row carries no document authority (element ops go
+ // through /events, which enforces ownership since v0.11.8).
+ const design = await db.design.findUnique({
+ where: { id: designId },
+ select: { id: true, deletedAt: true },
+ })
+ if (!design || design.deletedAt) {
+ return NextResponse.json({ error: 'Design not found.' }, { status: 404 })
+ }
+
const name = (body.name ?? '').replace(/[^\p{L}\p{N} ._-]/gu, '').slice(0, 40) || 'Guest'
const color = HEX_COLOR.test(body.color ?? '') ? body.color! : '#7630D7'
diff --git a/src/hooks/use-collab.ts b/src/hooks/use-collab.ts
index a5fd4cc..ae468f8 100644
--- a/src/hooks/use-collab.ts
+++ b/src/hooks/use-collab.ts
@@ -51,7 +51,12 @@ export function useCollab(): void {
}
session.onPresence = (collaborators) => useEditorStore.getState().setCollaborators(collaborators)
- setOpEmitter((op) => session.emit(op, `evt_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 9)}`))
+ setOpEmitter((op) => {
+ // v0.11.8: read-only designs never queue ops (the server would 403
+ // the flush) — presence/cursors still flow; only mutations stop.
+ if (useEditorStore.getState().readOnly) return
+ session.emit(op, `evt_${Date.now().toString(36)}_${Math.random().toString(36).slice(2, 9)}`)
+ })
session.start()
return () => {
diff --git a/src/lib/auth/design-guard.ts b/src/lib/auth/design-guard.ts
index 9bee1b1..623718c 100644
--- a/src/lib/auth/design-guard.ts
+++ b/src/lib/auth/design-guard.ts
@@ -24,6 +24,20 @@ export interface DesignAccess {
canEdit: boolean
}
+/**
+ * The three-case rule, pure — extracted (v0.11.8) so the document rail
+ * (PUT /api/designs/[id]) and the collab rail (POST /api/collab/[id]/events)
+ * can never drift:
+ * ownerless design → anyone with the link can edit (pre-accounts
+ * behaviour, deliberate); owned design → the owner only.
+ */
+export function canEditDesign(
+ design: { ownerId: string | null },
+ user: { id: string } | null
+): boolean {
+ return design.ownerId === null || design.ownerId === user?.id
+}
+
/**
* Load a design + resolve the caller's access. Returns null when the
* design does not exist. Never throws (DB errors bubble as usual so
@@ -38,8 +52,7 @@ export async function resolveDesignAccess(
getSessionUser(req),
])
if (!design) return null
- const canEdit = design.ownerId === null || design.ownerId === user?.id
- return { design: design as DesignAccess['design'], user, canEdit }
+ return { design: design as DesignAccess['design'], user, canEdit: canEditDesign(design, user) }
}
/** Standard 403 body for mutating routes. */
diff --git a/src/lib/collab/client.ts b/src/lib/collab/client.ts
index a84dd43..4f8cfb6 100644
--- a/src/lib/collab/client.ts
+++ b/src/lib/collab/client.ts
@@ -282,8 +282,11 @@ export class CollabSession {
if (res.ok) {
this.onQueueDepth?.(this.queue.length)
this.scheduleQueuePersist(100)
- } else if (res.status === 404 || res.status === 503) {
- // design gone / db down — drop the queue (local editor still works)
+ } else if (res.status === 403 || res.status === 404 || res.status === 503) {
+ // v0.11.8: 403 = this tab has no write authority on this design
+ // (owned by another account) — drop the queue like 404/503 instead
+ // of retrying forever; the local editor keeps working. Design gone
+ // (404) / db down (503) — same treatment.
this.queue = []
this.onQueueDepth?.(0)
this.scheduleQueuePersist(0)