Skip to content

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

fix(v0.9.2): cut Fluid CPU & Fast Origin Transfer — evidence-based cost fixes

Ashiq Hussain Mir06822025cb42
diff --git a/public/robots.txt b/public/robots.txt
index 6018e70..d73f049 100644
--- a/public/robots.txt
+++ b/public/robots.txt
@@ -1,14 +1,23 @@
+# Canvix — the app is a single client-rendered page; /api/ is private
+# machinery (designs, auth, AI, collab streams) that crawlers should
+# never enumerate. v0.9.2: politely keeps crawlers off metered routes.
+
User-agent: Googlebot
Allow: /
+Disallow: /api/
User-agent: Bingbot
Allow: /
+Disallow: /api/
User-agent: Twitterbot
Allow: /
+Disallow: /api/
User-agent: facebookexternalhit
Allow: /
+Disallow: /api/
User-agent: *
Allow: /
+Disallow: /api/
diff --git a/src/app/api/ai/image-edit/route.ts b/src/app/api/ai/image-edit/route.ts
index bf02a5b..74ef864 100644
--- a/src/app/api/ai/image-edit/route.ts
+++ b/src/app/api/ai/image-edit/route.ts
@@ -70,7 +70,7 @@ export async function POST(req: NextRequest) {
const h = Number(body.naturalHeight) || 0
const size: ImgSize = w && h ? bestSize(w, h) : '1024x1024'
- return withProvider('image-edit', req, { limit: 12, windowSec: 60 }, async (zai) => {
+ return withProvider('image-edit', req, { limit: 5, windowSec: 60 }, async (zai) => {
// NOTE: the SDK's TS type declares `image`, but the backend API requires
// `images: [{ url }]` (verified — API error 1210 "must provide images").
// The SDK forwards the body verbatim, so we send the correct runtime shape.
diff --git a/src/app/api/ai/image/image-guard.test.ts b/src/app/api/ai/image/image-guard.test.ts
new file mode 100644
index 0000000..bbaeea6
--- /dev/null
+++ b/src/app/api/ai/image/image-guard.test.ts
@@ -0,0 +1,97 @@
+// Unit tests for the v0.9.2 AI-route abuse guard (strict same-origin)
+// and rate-limit tightening — see src/lib/ai/provider.ts.
+//
+// Invariants:
+// 1. POSTs without Origin/Referer (direct API bots) → 403, zero provider work
+// 2. POSTs with a foreign Origin → 403
+// 3. Same-origin POSTs (browser fetch from the app) → pass the guard
+// (then reach the provider path; unconfigured providers answer 503)
+
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+// This sandbox (and dev machines) can carry a real /etc/.z-ai-config, which
+// would make getZAI() hit the live gateway from unit tests. Mock the SDK
+// module itself so the route's full happy path runs hermetically.
+const generationsCreate = vi.fn(async () => ({ data: [{ base64: 'aGVsbG8=' }] }))
+vi.mock('z-ai-web-dev-sdk', () => ({
+ default: {
+ create: vi.fn(async () => ({
+ images: { generations: { create: generationsCreate } },
+ })),
+ },
+}))
+
+// recordUsage is fire-and-forget against the DB — mock it so tests never
+// open a real connection (which would hang the vitest worker).
+const dbMock = vi.hoisted(() => ({
+ aIUsage: { create: vi.fn().mockResolvedValue({}) },
+}))
+vi.mock('@/lib/db', () => ({ db: dbMock }))
+
+import { NextRequest } from 'next/server'
+import { POST } from './route'
+
+function post(opts: { origin?: string; referer?: string } = {}) {
+ const headers: Record<string, string> = {
+ host: 'canvix.test',
+ 'content-type': 'application/json',
+ }
+ if (opts.origin) headers.origin = opts.origin
+ if (opts.referer) headers.referer = opts.referer
+ return POST(
+ new NextRequest('http://canvix.test/api/ai/image', {
+ method: 'POST',
+ headers,
+ body: JSON.stringify({ prompt: 'a poster' }),
+ }),
+ )
+}
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ dbMock.aIUsage.create.mockResolvedValue({})
+ generationsCreate.mockResolvedValue({ data: [{ base64: 'aGVsbG8=' }] })
+})
+
+describe('POST /api/ai/image — v0.9.2 abuse guard', () => {
+ it('rejects Origin-less POSTs (direct API bots) before any provider work', async () => {
+ const res = await post()
+ expect(res.status).toBe(403)
+ // guard fired before the rate limit even ran → no usage accounting
+ expect(dbMock.aIUsage.create).not.toHaveBeenCalled()
+ })
+
+ it('rejects foreign origins', async () => {
+ const res = await post({ origin: 'https://evil.example' })
+ expect(res.status).toBe(403)
+ })
+
+ it('lets same-origin POSTs through the guard (full happy path)', async () => {
+ const res = await post({ origin: 'http://canvix.test' })
+ expect(res.status).toBe(200)
+ const body = await res.json()
+ expect(body.dataUrl).toBe('data:image/png;base64,aGVsbG8=')
+ expect(generationsCreate).toHaveBeenCalledTimes(1)
+ })
+
+ it('accepts a same-origin Referer fallback', async () => {
+ const res = await post({ referer: 'http://canvix.test/editor' })
+ expect(res.status).not.toBe(403)
+ })
+
+ it('rejects when the Referer matches neither host nor x-forwarded-host', async () => {
+ const res = await POST(
+ new NextRequest('http://canvix.test/api/ai/image', {
+ method: 'POST',
+ headers: {
+ host: 'canvix.test',
+ 'x-forwarded-host': 'canvix.real',
+ referer: 'http://evil.example/editor',
+ 'content-type': 'application/json',
+ },
+ body: JSON.stringify({ prompt: 'x' }),
+ }),
+ )
+ expect(res.status).toBe(403)
+ })
+})
diff --git a/src/app/api/ai/image/route.ts b/src/app/api/ai/image/route.ts
index 975f2b8..f3bad16 100644
--- a/src/app/api/ai/image/route.ts
+++ b/src/app/api/ai/image/route.ts
@@ -24,7 +24,7 @@ export async function POST(req: NextRequest) {
return NextResponse.json({ error: 'A prompt is required.' }, { status: 400 })
}
- return withProvider('image', req, { limit: 12, windowSec: 60 }, async (zai) => {
+ return withProvider('image', req, { limit: 5, windowSec: 60 }, async (zai) => {
const response = await zai.images.generations.create({
prompt,
size,
diff --git a/src/app/api/collab/[designId]/stream/route.ts b/src/app/api/collab/[designId]/stream/route.ts
index ddb68db..3c7e3f7 100644
--- a/src/app/api/collab/[designId]/stream/route.ts
+++ b/src/app/api/collab/[designId]/stream/route.ts
@@ -8,10 +8,20 @@ export const maxDuration = 300 // Vercel-friendly bounded stream duration
/**
* GET /api/collab/[designId]/stream?since=<seq>&pid=<participantId>
*
- * SSE downstream: every ~800 ms tick, emit new DesignEvents (id > since) +
- * live presence (lastSeen < 30 s). Postgres is the source of truth — a
- * reconnect with ?since=<lastSeq> replays gap-free. Also lazily GCs stale
- * presence rows and prunes the event log.
+ * SSE downstream: emit new DesignEvents (id > since) + live presence
+ * (lastSeen < 30 s). Postgres is the source of truth — a reconnect with
+ * ?since=<lastSeq> replays gap-free. Also lazily GCs stale presence rows
+ * and prunes the event log.
+ *
+ * v0.9.2 cost fix: this used to fire THREE Postgres queries every 800 ms
+ * per connected client for the full stream lifetime — the single biggest
+ * Fluid-CPU driver in the app. The pump is now adaptive:
+ * - events query every tick, but the tick backs off 800 ms → 3.2 s
+ * when nothing is happening and snaps back on the first event
+ * - presence query every 2nd tick (clients heartbeat every 15 s)
+ * - the MAX(id) aggregate only every 5th tick (gap detection)
+ * Idle collaboration sessions now cost ~10× less; active editing latency
+ * is unchanged (first event after activity still arrives in ≤ 800 ms).
*/
export async function GET(req: NextRequest, { params }: { params: Promise<{ designId: string }> }) {
const { designId } = await params
@@ -29,11 +39,13 @@ export async function GET(req: NextRequest, { params }: { params: Promise<{ desi
const encoder = new TextEncoder()
let closed = false
+ let timer: ReturnType<typeof setTimeout> | null = null
const stream = new ReadableStream<Uint8Array>({
async start(controller) {
let lastSeq = since
let tick = 0
+ let delay = 800
const send = (frame: unknown) => {
if (closed) return
@@ -55,7 +67,7 @@ export async function GET(req: NextRequest, { params }: { params: Promise<{ desi
const close = () => {
if (closed) return
closed = true
- clearInterval(timer)
+ if (timer) clearTimeout(timer)
try {
controller.close()
} catch {
@@ -63,8 +75,8 @@ export async function GET(req: NextRequest, { params }: { params: Promise<{ desi
}
}
- const pump = async () => {
- if (closed) return
+ const pump = async (): Promise<boolean> => {
+ if (closed) return false
try {
const [events, presence, maxRow, gcRows] = await Promise.all([
db.designEvent.findMany({
@@ -72,12 +84,20 @@ export async function GET(req: NextRequest, { params }: { params: Promise<{ desi
orderBy: { id: 'asc' },
take: 200,
}),
- db.presence.findMany({
- where: { designId, lastSeen: { gt: new Date(Date.now() - 30_000) } },
- orderBy: { lastSeen: 'desc' },
- take: 30,
- }),
- db.designEvent.aggregate({ where: { designId }, _max: { id: true } }),
+ // v0.9.2: presence every 2nd tick — clients heartbeat every 15 s,
+ // so a 1.6 s refresh window (when active) is still real-time.
+ tick % 2 === 0
+ ? db.presence.findMany({
+ where: { designId, lastSeen: { gt: new Date(Date.now() - 30_000) } },
+ orderBy: { lastSeen: 'desc' },
+ take: 30,
+ })
+ : Promise.resolve([]),
+ // v0.9.2: the MAX(id) aggregate only matters for gap detection
+ // after pruning — every 5th tick is plenty.
+ tick % 5 === 0
+ ? db.designEvent.aggregate({ where: { designId }, _max: { id: true } })
+ : Promise.resolve(null),
// heartbeat GC: drop presence rows older than 24 h (cheap, throttled by tick)
tick % 90 === 0
? db.presence.deleteMany({ where: { designId, lastSeen: { lt: new Date(Date.now() - 86_400_000) } } })
@@ -88,31 +108,34 @@ export async function GET(req: NextRequest, { params }: { params: Promise<{ desi
if (events.length) {
lastSeq = Number(events[events.length - 1].id)
}
- const serverSeq = Number(maxRow._max.id ?? lastSeq)
+ const serverSeq = maxRow ? Number(maxRow._max.id ?? lastSeq) : lastSeq
// only send a frame when something actually changed (plus periodic keepalive)
const filteredPresence = presence.filter((p) => p.id !== pid)
- const frame = {
- events: events.map((e) => ({
- seq: Number(e.id),
- id: e.id.toString(),
- designId: e.designId,
- actorId: e.actorId,
- kind: e.kind,
- payload: e.payload,
- createdAt: e.createdAt.toISOString(),
- })),
- presence: filteredPresence.map((p) => ({
- id: p.id,
- name: p.name,
- color: p.color,
- cursor: p.cursor,
- lastSeen: p.lastSeen.toISOString(),
- })),
- seq: serverSeq,
+ if (events.length || tick % 20 === 0) {
+ const frame = {
+ events: events.map((e) => ({
+ seq: Number(e.id),
+ id: e.id.toString(),
+ designId: e.designId,
+ actorId: e.actorId,
+ kind: e.kind,
+ payload: e.payload,
+ createdAt: e.createdAt.toISOString(),
+ })),
+ presence: filteredPresence.map((p) => ({
+ id: p.id,
+ name: p.name,
+ color: p.color,
+ cursor: p.cursor,
+ lastSeen: p.lastSeen.toISOString(),
+ })),
+ seq: serverSeq,
+ }
+ send(frame)
+ } else {
+ comment('keepalive')
}
- if (events.length || tick % 20 === 0) send(frame)
- else comment('keepalive')
// event-log pruning: keep the last 500 events per design
if (events.length && serverSeq - lastSeq === 0 && serverSeq > 500 && tick % 30 === 0) {
@@ -122,21 +145,31 @@ export async function GET(req: NextRequest, { params }: { params: Promise<{ desi
/* pruning is best-effort */
}
}
+ return events.length > 0
} catch (err) {
console.error('[collab/stream] tick failed', err)
comment('retry')
+ return false
+ } finally {
+ tick += 1
}
}
- const timer = setInterval(() => {
- tick += 1
- void pump()
- }, 800)
+ // v0.9.2: adaptive self-scheduling pump — backs off to 3.2 s when the
+ // design is quiet, returns to 800 ms the moment anything happens.
+ const scheduleNext = async () => {
+ if (closed) return
+ const hadEvents = await pump()
+ delay = hadEvents ? 800 : Math.min(Math.round(delay * 1.5), 3200)
+ if (closed) return
+ timer = setTimeout(() => void scheduleNext(), delay)
+ }
+
req.signal.addEventListener('abort', close)
// initial frame immediately (replay from `since`)
comment(`open design=${designId} since=${since}`)
- await pump()
+ await scheduleNext()
},
})
diff --git a/src/app/api/designs/designs.test.ts b/src/app/api/designs/designs.test.ts
new file mode 100644
index 0000000..9e16d79
--- /dev/null
+++ b/src/app/api/designs/designs.test.ts
@@ -0,0 +1,129 @@
+// Unit tests for GET /api/designs list pagination (v0.9.2) — the cost fix
+// that caps the unbounded thumbnail-heavy list response.
+//
+// Invariants under test:
+// 1. pagination envelope { designs, nextCursor } with 60-row pages
+// 2. ownership scoping survives cursor pagination — a signed-in user
+// must NEVER receive another account's private designs, even when
+// a keyset cursor is present (the AND-composition regression)
+// 3. the keyset cursor pages forward without re-serving rows
+// 4. anonymous visitors still see ownerless designs only
+
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+const dbMock = vi.hoisted(() => ({
+ design: { findMany: 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 { GET } from './route'
+
+const USER_A = { id: 'user-a', username: 'alpha', createdAt: new Date() }
+
+function designRow(opts: {
+ id: string
+ ownerId: string | null
+ updatedAt?: Date
+ anonKey?: string | null
+ name?: string
+}) {
+ return {
+ id: opts.id,
+ name: opts.name ?? opts.id,
+ width: 1080,
+ height: 1080,
+ thumbnail: null,
+ source: 'blank',
+ ownerId: opts.ownerId,
+ anonKey: opts.anonKey ?? null,
+ deletedAt: null,
+ createdAt: opts.updatedAt ?? new Date('2026-10-01T00:00:00Z'),
+ updatedAt: opts.updatedAt ?? new Date('2026-10-01T00:00:00Z'),
+ }
+}
+
+function get(opts: { user?: unknown; url?: string } = {}) {
+ getSessionUser.mockResolvedValue(opts.user ?? null)
+ return GET(new NextRequest(opts.url ?? 'http://canvix.test/api/designs', {
+ headers: { host: 'canvix.test' },
+ }))
+}
+
+beforeEach(() => {
+ vi.clearAllMocks()
+})
+
+describe('GET /api/designs (v0.9.2 pagination)', () => {
+ it('returns the { designs, nextCursor } envelope with ≤60 rows', async () => {
+ const rows = Array.from({ length: 61 }, (_, i) =>
+ designRow({ id: `d${i}`, ownerId: null, updatedAt: new Date(2026, 9, 1, 0, i) }),
+ )
+ dbMock.design.findMany.mockResolvedValue(rows)
+ const res = await get()
+ expect(res.status).toBe(200)
+ const body = await res.json()
+ expect(Array.isArray(body.designs)).toBe(true)
+ expect(body.designs).toHaveLength(60)
+ expect(body.nextCursor).toEqual({ cursor: rows[59].updatedAt.toISOString(), id: 'd59' })
+ // requests 61 rows to detect hasMore
+ expect(dbMock.design.findMany.mock.calls[0][0].take).toBe(61)
+ })
+
+ it('returns nextCursor null when the page is not full', async () => {
+ dbMock.design.findMany.mockResolvedValue([
+ designRow({ id: 'only', ownerId: null }),
+ ])
+ const res = await get()
+ const body = await res.json()
+ expect(body.designs).toHaveLength(1)
+ expect(body.nextCursor).toBeNull()
+ })
+
+ it('keeps ownership isolation when a cursor is present (regression)', async () => {
+ // user A paginating must still be scoped to (ownerless OR own) —
+ // the cursor filter must not replace the ownership filter.
+ dbMock.design.findMany.mockResolvedValue([])
+ await get({
+ user: USER_A,
+ url: 'http://canvix.test/api/designs?cursor=2026-10-01T00:00:00.000Z&id=d59',
+ })
+ const where = dbMock.design.findMany.mock.calls[0][0].where
+ expect(where.AND).toHaveLength(2)
+ const scope = where.AND[0]
+ expect(scope.OR).toEqual([{ ownerId: null }, { ownerId: 'user-a' }])
+ const keyset = where.AND[1]
+ expect(keyset.OR[0]).toEqual({ updatedAt: { lt: new Date('2026-10-01T00:00:00.000Z') } })
+ })
+
+ it('scopes anonymous visitors to ownerless designs (with and without cursor)', async () => {
+ dbMock.design.findMany.mockResolvedValue([])
+ await get()
+ expect(dbMock.design.findMany.mock.calls[0][0].where.AND).toEqual([{ ownerId: null }])
+
+ await get({ url: 'http://canvix.test/api/designs?cursor=2026-10-01T00:00:00.000Z' })
+ const withCursor = dbMock.design.findMany.mock.calls[1][0].where
+ expect(withCursor.AND[0]).toEqual({ ownerId: null })
+ expect(withCursor.AND[1].OR[0]).toEqual({ updatedAt: { lt: new Date('2026-10-01T00:00:00.000Z') } })
+ })
+
+ it('ignores a malformed cursor instead of erroring', async () => {
+ dbMock.design.findMany.mockResolvedValue([])
+ const res = await get({ url: 'http://canvix.test/api/designs?cursor=not-a-date' })
+ expect(res.status).toBe(200)
+ // no keyset filter was added
+ expect(dbMock.design.findMany.mock.calls[0][0].where.AND).toEqual([{ ownerId: null }])
+ })
+
+ it('orders by (updatedAt desc, id desc) for stable keyset paging', async () => {
+ dbMock.design.findMany.mockResolvedValue([])
+ await get()
+ expect(dbMock.design.findMany.mock.calls[0][0].orderBy).toEqual([
+ { updatedAt: 'desc' },
+ { id: 'desc' },
+ ])
+ })
+})
diff --git a/src/app/api/designs/route.ts b/src/app/api/designs/route.ts
index b539097..8f7713f 100644
--- a/src/app/api/designs/route.ts
+++ b/src/app/api/designs/route.ts
@@ -17,6 +17,7 @@ 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
+// ?cursor=<updatedAt ISO>&id=<designId> → next page (keyset pagination)
//
// v0.9 scoping: signed-in users see their designs + ownerless (shared)
// designs; anonymous visitors see ownerless designs only. Owned designs
@@ -28,19 +29,45 @@ function toPages(value: unknown): Prisma.InputJsonValue {
// (this browser's attribution OR a legacy pre-accounts row)
// mine — attributed to THIS browser; the only rows the bulk
// "Save my designs" action will claim
+//
+// v0.9.2 cost fix: the list used to return EVERY matching row including
+// base64 thumbnails — with a crowded shared workspace that was a multi-MB
+// JSON response on every dashboard load (CPU to serialize, bandwidth to
+// ship). It is now keyset-paginated: 60 rows per page, `nextCursor` tells
+// the client there is more. Worst case per page is now ~0.5 MB.
+const DESIGNS_PAGE_SIZE = 60
+
export async function GET(req: NextRequest) {
try {
const trash = req.nextUrl.searchParams.get('trash') === '1'
+ const cursor = req.nextUrl.searchParams.get('cursor')
+ const cursorId = req.nextUrl.searchParams.get('id')
const user = await getSessionUser(req)
+
+ // Compose scoping + keyset via AND — never spread two `OR` keys into
+ // the same object (the second would silently replace the first and
+ // leak private designs to other accounts).
+ const filters: Prisma.DesignWhereInput[] = [
+ user
+ ? { OR: [{ ownerId: null }, { ownerId: user.id }] }
+ : { ownerId: null },
+ ]
+ if (cursor && !Number.isNaN(Date.parse(cursor))) {
+ filters.push({
+ OR: [
+ { updatedAt: { lt: new Date(cursor) } },
+ ...(cursorId ? [{ updatedAt: new Date(cursor), id: { lt: cursorId } }] : []),
+ ],
+ })
+ }
const where: Prisma.DesignWhereInput = {
deletedAt: trash ? { not: null } : null,
- ...(user
- ? { OR: [{ ownerId: null }, { ownerId: user.id }] }
- : { ownerId: null }),
+ AND: filters,
}
const designs = await db.design.findMany({
where,
- orderBy: { updatedAt: 'desc' },
+ orderBy: [{ updatedAt: 'desc' }, { id: 'desc' }],
+ take: DESIGNS_PAGE_SIZE + 1,
select: {
id: true,
name: true,
@@ -55,13 +82,22 @@ export async function GET(req: NextRequest) {
updatedAt: true,
},
})
+ const hasMore = designs.length > DESIGNS_PAGE_SIZE
+ const page = hasMore ? designs.slice(0, DESIGNS_PAGE_SIZE) : designs
+ const last = page[page.length - 1]
const myHash = anonHashFrom(req)
- const out = designs.map(({ anonKey, ...d }) => ({
+ const out = page.map(({ anonKey, ...d }) => ({
...d,
claimable: d.ownerId === null && (anonKey === null || anonKey === myHash),
mine: d.ownerId === null && anonKey !== null && anonKey === myHash,
}))
- return NextResponse.json(out)
+ return NextResponse.json({
+ designs: out,
+ nextCursor:
+ hasMore && last
+ ? { cursor: last.updatedAt.toISOString(), id: last.id }
+ : null,
+ })
} catch (error) {
return dbErrorResponse(error, 'GET /api/designs')
}
diff --git a/src/app/api/health/route.ts b/src/app/api/health/route.ts
index ec87faf..5bea2ec 100644
--- a/src/app/api/health/route.ts
+++ b/src/app/api/health/route.ts
@@ -99,9 +99,19 @@ export async function GET() {
}
// 5. all green
- return NextResponse.json({
- ok: true,
- database: { kind: info.kind, host: info.host, database: info.database },
- templates,
- })
+ return NextResponse.json(
+ {
+ ok: true,
+ database: { kind: info.kind, host: info.host, database: info.database },
+ templates,
+ },
+ {
+ headers: {
+ // v0.9.2: diagnostics must never be cached (stale health is worse
+ // than none) and should not be indexed.
+ 'Cache-Control': 'no-store',
+ 'X-Robots-Tag': 'noindex',
+ },
+ }
+ )
}
diff --git a/src/app/api/photos/search/route.ts b/src/app/api/photos/search/route.ts
index fa7dbeb..b131bff 100644
--- a/src/app/api/photos/search/route.ts
+++ b/src/app/api/photos/search/route.ts
@@ -16,7 +16,7 @@ export async function POST(req: NextRequest) {
if (!query) return NextResponse.json({ error: 'A query is required.' }, { status: 400 })
const count = Math.min(Math.max(Number(body.count) || 24, 1), 40)
- return withProvider('search', req, { limit: 30, windowSec: 60 }, async (zai) => {
+ return withProvider('search', req, { limit: 12, windowSec: 60 }, async (zai) => {
const response = await zai.images.search.create({ query, count })
const results = (response.results ?? []).map((r) => ({
diff --git a/src/app/api/templates/route.ts b/src/app/api/templates/route.ts
index bcb6ca6..e2b2f9f 100644
--- a/src/app/api/templates/route.ts
+++ b/src/app/api/templates/route.ts
@@ -3,6 +3,13 @@ import { db } from '@/lib/db'
import { dbErrorResponse } from '@/lib/db-errors'
// GET /api/templates — built-in template library (from DB, falls back empty)
+//
+// v0.9.2 cost fix: this payload is ~0.7 MB of public, deploy-stable data
+// that was re-fetched (and re-serialized from Postgres) on every hit —
+// an open faucet for both Fluid CPU and Fast Origin Transfer. It now
+// carries explicit CDN cache headers: first hit per region serves from
+// the function, everything after that is an edge HIT for 24 h (and a
+// stale-while-revalidate revalidation window of 7 d).
export async function GET() {
try {
const templates = await db.template.findMany({
@@ -18,7 +25,14 @@ export async function GET() {
height: t.height,
accent: t.accent,
pages: t.pages ?? [],
- }))
+ })),
+ {
+ headers: {
+ // public + immutable-enough: content only changes with a new
+ // deploy or a re-seed, both of which ship a fresh deployment.
+ 'Cache-Control': 'public, max-age=0, s-maxage=86400, stale-while-revalidate=604800',
+ },
+ }
)
} catch (error) {
return dbErrorResponse(error, 'GET /api/templates')
diff --git a/src/app/api/templates/templates.test.ts b/src/app/api/templates/templates.test.ts
new file mode 100644
index 0000000..819d9ff
--- /dev/null
+++ b/src/app/api/templates/templates.test.ts
@@ -0,0 +1,51 @@
+// Unit tests for GET /api/templates CDN caching (v0.9.2) — the ~0.7 MB
+// public payload must be edge-cacheable so it stops counting against
+// Fluid CPU + Fast Origin Transfer on every request.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+const dbMock = vi.hoisted(() => ({
+ template: { findMany: vi.fn() },
+}))
+vi.mock('@/lib/db', () => ({ db: dbMock }))
+
+import { GET } from './route'
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ dbMock.template.findMany.mockResolvedValue([
+ {
+ id: 't1',
+ slug: 'instagram-post',
+ name: 'Instagram post',
+ category: 'social',
+ width: 1080,
+ height: 1080,
+ accent: '#00C4CC',
+ pages: [{ id: 'p1', elements: [] }],
+ createdAt: new Date('2026-10-01T00:00:00Z'),
+ },
+ ])
+})
+
+describe('GET /api/templates (v0.9.2 CDN caching)', () => {
+ it('serves the full template list with edge-cache headers', async () => {
+ const res = await GET()
+ expect(res.status).toBe(200)
+ const cc = res.headers.get('cache-control') ?? ''
+ expect(cc).toContain('public')
+ expect(cc).toContain('s-maxage=86400')
+ expect(cc).toContain('stale-while-revalidate')
+ const body = await res.json()
+ expect(body).toHaveLength(1)
+ expect(body[0].pages).toEqual([{ id: 'p1', elements: [] }])
+ })
+
+ it('still surfaces classified DB errors (never a bare 500)', async () => {
+ dbMock.template.findMany.mockRejectedValue(new Error('connect ECONNREFUSED'))
+ const res = await GET()
+ expect(res.status).toBeGreaterThanOrEqual(500)
+ const body = await res.json()
+ expect(typeof body.error).toBe('string')
+ })
+})
diff --git a/src/components/dashboard/Dashboard.tsx b/src/components/dashboard/Dashboard.tsx
index ad982a0..d4d15e9 100644
--- a/src/components/dashboard/Dashboard.tsx
+++ b/src/components/dashboard/Dashboard.tsx
@@ -111,7 +111,7 @@ export function Dashboard() {
const goLanding = useAppStore((s) => s.goLanding)
const openEditor = useAppStore((s) => s.openEditor)
const loadEditorDesign = useEditorStore((s) => s.loadDesign)
- const { designs, loading, refresh, dbIssue } = useDesigns()
+ const { designs, loading, refresh, dbIssue, hasMore, loadMore } = useDesigns()
const isMobile = useIsMobile()
const [helpOpen, setHelpOpen] = useState(false)
@@ -722,6 +722,17 @@ export function Dashboard() {
))}
</div>
)}
+ {hasMore && !loading && (
+ <div className="mt-6 flex justify-center">
+ <Button
+ variant="outline"
+ className="rounded-full px-6 gap-2 border-white/15 text-white/80 hover:bg-white/10 hover:text-white"
+ onClick={() => void loadMore()}
+ >
+ Load more designs
+ </Button>
+ </div>
+ )}
</section>
{/* ── Trash (v0.4 — soft-deleted designs) ── */}
<section id="cv-trash" className="pt-12 scroll-mt-20">
diff --git a/src/components/dashboard/hooks.ts b/src/components/dashboard/hooks.ts
index 98b9bc6..d083812 100644
--- a/src/components/dashboard/hooks.ts
+++ b/src/components/dashboard/hooks.ts
@@ -1,6 +1,6 @@
'use client'
-import { useCallback, useEffect, useState } from 'react'
+import { useCallback, useEffect, useRef, useState } from 'react'
import type { DesignRecord, PageData } from '@/lib/types'
export interface DesignMeta {
@@ -49,31 +49,67 @@ export class ApiError extends Error {
}
}
+/** v0.9.2: /api/designs is keyset-paginated (60 rows/page) — this is the
+ * cursor the server hands back for the next page. */
+interface DesignsPage {
+ designs: DesignMeta[]
+ nextCursor: { cursor: string; id: string } | null
+}
+
+async function fetchDesignsPage(cursor?: { cursor: string; id: string } | null): Promise<DesignsPage> {
+ const qs = cursor ? `?cursor=${encodeURIComponent(cursor.cursor)}&id=${encodeURIComponent(cursor.id)}` : ''
+ const res = await fetch(`/api/designs${qs}`, { cache: 'no-store' })
+ if (!res.ok) {
+ const err = await readApiError(res)
+ throw new ApiError(err.message, err.code, err.fix)
+ }
+ const body = (await res.json()) as Partial<DesignsPage>
+ return { designs: body.designs ?? [], nextCursor: body.nextCursor ?? null }
+}
+
export function useDesigns() {
const [designs, setDesigns] = useState<DesignMeta[] | null>(null)
const [loading, setLoading] = useState(true)
// v0.8: null = healthy; otherwise an error code/message from the API
const [dbIssue, setDbIssue] = useState<string | null>(null)
+ // v0.9.2: pagination state — true when the server says there is another page
+ const [hasMore, setHasMore] = useState(false)
+ const loadingMoreRef = useRef(false)
+ const nextCursorRef = useRef<{ cursor: string; id: string } | null>(null)
const refresh = useCallback(async () => {
try {
- const res = await fetch('/api/designs', { cache: 'no-store' })
- if (res.ok) {
- setDesigns(await res.json())
- } else {
- // v0.8: surface DB setup trouble (host switch, missing migration…)
- const err = await readApiError(res)
- setDbIssue(err.code ?? err.message)
- setDesigns([])
- }
- } catch {
- setDbIssue('NETWORK')
+ const page = await fetchDesignsPage()
+ setDesigns(page.designs)
+ setHasMore(page.nextCursor !== null)
+ nextCursorRef.current = page.nextCursor
+ } catch (err) {
+ const e = err as ApiError
+ setDbIssue(e.code ?? e.message)
setDesigns([])
+ setHasMore(false)
+ nextCursorRef.current = null
} finally {
setLoading(false)
}
}, [])
+ /** v0.9.2: append the next page (guard against double-clicks/stale calls). */
+ const loadMore = useCallback(async () => {
+ if (loadingMoreRef.current || !nextCursorRef.current) return
+ loadingMoreRef.current = true
+ try {
+ const page = await fetchDesignsPage(nextCursorRef.current)
+ nextCursorRef.current = page.nextCursor
+ setHasMore(page.nextCursor !== null)
+ setDesigns((prev) => (prev ? [...prev, ...page.designs] : page.designs))
+ } catch {
+ /* transient — the user can click Load more again */
+ } finally {
+ loadingMoreRef.current = false
+ }
+ }, [])
+
useEffect(() => {
// kick the fetch off in a microtask so the effect body itself never
// calls setState synchronously (react-hooks/set-state-in-effect);
@@ -81,7 +117,7 @@ export function useDesigns() {
void Promise.resolve().then(() => refresh())
}, [refresh])
- return { designs, loading, refresh, dbIssue, clearDbIssue: () => setDbIssue(null) }
+ return { designs, loading, refresh, dbIssue, clearDbIssue: () => setDbIssue(null), hasMore, loadMore }
}
export async function createDesign(opts: {
@@ -138,7 +174,10 @@ export async function deleteDesign(id: string): Promise<void> {
export async function listTrash(): Promise<DesignMeta[]> {
const res = await fetch('/api/designs?trash=1', { cache: 'no-store' })
if (!res.ok) throw new Error('Failed to list trash')
- return res.json()
+ // v0.9.2: same paginated envelope as the main list — the trash dialog
+ // only needs the most recent page.
+ const body = (await res.json()) as Partial<DesignsPage>
+ return body.designs ?? []
}
export async function restoreDesign(id: string): Promise<void> {
diff --git a/src/lib/ai/provider.ts b/src/lib/ai/provider.ts
index 813d482..f9b6dac 100644
--- a/src/lib/ai/provider.ts
+++ b/src/lib/ai/provider.ts
@@ -1,5 +1,6 @@
import { NextResponse, type NextRequest } from 'next/server'
import { existsSync, readFileSync } from 'fs'
+import { CSRF_REJECTED } from '@/lib/auth/csrf'
/**
* Canvix AI provider abstraction (v0.5).
@@ -150,12 +151,45 @@ export function providerUnavailable(res: NextResponse): NextResponse {
}
/** Helper: wrap a route's provider call with rate limit + usage accounting. */
+
+/**
+ * v0.9.2 abuse guard — strict same-origin check for AI routes.
+ *
+ * Unlike the cookie-CSRF variant in lib/auth/csrf.ts (which lets
+ * Origin-less server-to-server calls through), AI generation is expensive
+ * metered compute that must ONLY be drivable from the app's own pages.
+ * Browsers always send Origin (or Referer) on POST — including same-origin
+ * fetch() — so anything without a matching Origin is a direct API bot and
+ * gets a flat 403 before any provider work happens.
+ */
+function isFromApp(req: NextRequest): boolean {
+ const origin = req.headers.get('origin') ?? req.headers.get('referer')
+ if (!origin) return false
+ try {
+ const parsed = new URL(origin)
+ const hosts = [
+ req.headers.get('host'),
+ req.headers.get('x-forwarded-host')?.split(',')[0]?.trim(),
+ ].filter((h): h is string => Boolean(h))
+ return hosts.includes(parsed.host)
+ } catch {
+ return false
+ }
+}
+
export async function withProvider(
feature: string,
req: NextRequest,
limits: { limit: number; windowSec: number },
fn: (zai: NonNullable<Awaited<ReturnType<typeof getZAI>>>) => Promise<NextResponse>
): Promise<NextResponse> {
+ // v0.9.2 abuse guard: every AI route is only ever called by the app's own
+ // pages (same origin). Cross-origin or Origin-less POSTs — the signature
+ // of a bot hitting the public endpoint directly — are rejected before any
+ // provider work. Anonymous in-app usage stays fully allowed (free forever).
+ if (req.method === 'POST' && !isFromApp(req)) {
+ return NextResponse.json(CSRF_REJECTED, { status: 403 })
+ }
const rl = rateLimit(feature, req, limits.limit, limits.windowSec)
if (!rl.ok) {
return NextResponse.json(
diff --git a/src/lib/collab/client.ts b/src/lib/collab/client.ts
index daae2ab..47b9c23 100644
--- a/src/lib/collab/client.ts
+++ b/src/lib/collab/client.ts
@@ -7,7 +7,9 @@ import type { Collaborator, CollabOp, CollabStatus, DesignEventRow, OpEnvelope,
*
* Transport: SSE downstream (Postgres event log), POST upstream (batched).
* - local ops queue and flush every 400 ms (≤ 20 per flush)
- * - cursor updates throttled (~120 ms), presence heartbeat every 5 s
+ * - cursor updates throttled (~300 ms), presence heartbeat every 15 s
+ * (v0.9.2: was 120 ms / 5 s — each write is a remote-DB upsert, and
+ * the old rates let a single moving mouse generate ~8 writes/s)
* - reconnect with exponential backoff (0.5 s → 8 s), gap-free replay via ?since
*
* Zustand stays the local rendering truth; collab never blocks input.
@@ -50,7 +52,9 @@ export class CollabSession {
if (this.disposed) return
this.connect()
this.flushTimer = setInterval(() => void this.flush(), 400)
- this.heartbeatTimer = setInterval(() => void this.heartbeat(), 5_000)
+ // v0.9.2: 15 s heartbeat — the server treats presence as live for 30 s,
+ // so this still tolerates one lost beat before a collaborator fades out.
+ this.heartbeatTimer = setInterval(() => void this.heartbeat(), 15_000)
}
dispose() {
@@ -204,11 +208,13 @@ export class CollabSession {
}
}
- /** Throttled cursor broadcast (page coords + current selection). */
+ /** Throttled cursor broadcast (page coords + current selection).
+ * v0.9.2: 300 ms floor — ~3 updates/s is plenty for remote cursors and
+ * cuts the presence-write storm (each write is a remote-DB upsert). */
sendCursor(cursor: { page: number; x: number; y: number; selection?: string[] }) {
this.pendingCursor = cursor
const now = Date.now()
- if (now - this.lastCursorSent < 120) return
+ if (now - this.lastCursorSent < 300) return
this.lastCursorSent = now
void fetch(`/api/collab/${encodeURIComponent(this.designId)}/presence`, {
method: 'POST',