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.

feat(v0.12): rate limits & connection caps — per-IP budgets on designs/collab/comments/media, 6-connection SSE cap, load probe + honest multi-instance docs (H5) (#14)

Ashiq Hussain Mirc7efd48c0d93
diff --git a/.env.example b/.env.example
index 206f4ff..4c4b9d9 100644
--- a/.env.example
+++ b/.env.example
@@ -44,3 +44,10 @@ DATABASE_URL=postgresql://postgres.[YOUR-PROJECT-REF]:[YOUR-PASSWORD]@aws-0-eu-c
# you set a token; requests must send "Authorization: Bearer <token>".
# Generate one with: openssl rand -hex 24
# CANVIX_MCP_TOKEN=change-me-to-a-long-random-secret
+
+# ── Rate limiting (optional, v0.12.3) ─────────────────────────
+# Per-IP caps on designs CRUD, collab events/presence, comments and
+# media init + a 6-connections-per-IP cap on the SSE stream. Set to
+# "off" only when something in front of the app already throttles.
+# CANVIX_RATE_LIMITS=off
+# CANVIX_SSE_MAX_PER_IP=6
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 77b5c80..2fbafa5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,39 @@
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.12.3] — 2026-11-02
+
+### Added
+
+- **Rate limits & connection caps (H5).** The roadmap research
+ noted every mutating surface except `/api/mcp` accepted unlimited
+ traffic. Now a single limiter module (`src/lib/rate-limit.ts`)
+ guards the epic's list with per-IP fixed-window budgets — designs
+ create/update/delete (30/300/60 per min), collab events (600/min;
+ active clients flush 150/min each), presence heartbeats (120/min),
+ comment creation (60/min) and media upload init (30/min) — each
+ budget ≥ 4× the heaviest legitimate client, so a working editor
+ never notices. Rejected requests get `429` + `Retry-After` + a
+ `RATE_LIMITED` body and never touch the database. The SSE stream
+ route caps **concurrent connections per IP** (default 6, the
+ per-domain browser limit), releasing slots on every exit path —
+ abort, recycle, db-timeout and consumer cancel all funnel through
+ one `close()`. 12 unit tests cover the window math (injected
+ clock), bucket/IP isolation, the off switch and the slot
+ lifecycle; a mocked-route test proves POST /api/designs actually
+ 429s and stops short of the DB.
+- **Load probe** `scripts/rate-limit-probe.sh` — proves both caps
+ against a live instance: hammers design creation until the 429
+ (asserting `Retry-After`), opens the stream cap + 1 and asserts
+ the refusal, then verifies a fresh stream connects once slots are
+ released (no leak). Documented for scratch instances.
+- **README “Rate limiting” section** — the caps table, the knobs
+ (`CANVIX_RATE_LIMITS=off`, `CANVIX_SSE_MAX_PER_IP`), and the
+ honest multi-instance limitation the epic demanded: counters are
+ in-memory per instance, so an N-instance fleet enforces each cap
+ per instance, not per deployment; the shared-store upgrade is
+ deliberately deferred past 1.0 with the reasoning written down.
+
## [0.12.2] — 2026-11-02
### Added
diff --git a/README.md b/README.md
index a314014..b955eb2 100644
--- a/README.md
+++ b/README.md
@@ -541,6 +541,45 @@ pumps) fit the $5 paid plan better. Prisma's rust-free client keeps the
bundle ~85 % smaller than the classic engine, which is what makes it fit
at all. Full details: `research/CLOUDFLARE-WORKERS-PORTABILITY.md`.
+### 🚦 Rate limiting (v0.12.3)
+
+Every mutating surface carries a per-IP request limit, and the
+collaboration stream carries a per-IP concurrent-connection cap:
+
+| Surface | Cap (per IP) |
+|---|---|
+| `POST /api/designs` (create) | 30 / min |
+| `PUT /api/designs/<id>` (autosave) | 300 / min — autosave itself fires ≤ ~37/min |
+| `DELETE /api/designs/<id>` | 60 / min |
+| `POST …/collab/<id>/events` | 600 / min — active clients flush 150/min each |
+| `POST …/collab/<id>/presence` | 120 / min — heartbeats are 4/min per client |
+| `POST …/comments` | 60 / min |
+| `POST /api/media` (upload init) | 30 / min |
+| `GET …/collab/<id>/stream` (SSE) | 6 concurrent connections |
+
+Rejected requests get `429` with a `Retry-After` header and a
+`RATE_LIMITED` JSON body. The limits exist to stop abuse and runaway
+loops, never to throttle a working editor — every cap has at least 4×
+headroom over the heaviest legitimate client.
+
+**Multi-instance fleets — the honest limitation.** Counters live in
+memory, per server instance (the `/api/mcp` limiter always worked this
+way). A fleet of N instances behind one load balancer enforces each cap
+per instance, not per deployment: an abuser rotating across instances
+gets roughly N× the budget. The shared-store upgrade (Postgres or Redis
+counters) is deliberately deferred past 1.0 — it costs a round-trip on
+every mutation and matters only once you outgrow a single instance.
+Also: the client IP comes from `x-forwarded-for` / `x-real-ip` — the
+headers every reverse proxy and hosting platform sets. A bare
+`next start` with no proxy in front exposes no client address, so such
+deployments fall back to one shared bucket (localhost is trusted
+anyway; the caps still stop runaway loops).
+
+Knobs (in `.env`): `CANVIX_RATE_LIMITS=off` disables every cap (self-
+hosters behind their own throttle, load tests); `CANVIX_SSE_MAX_PER_IP`
+tunes the stream cap (default 6). Prove the caps on a scratch instance:
+`BASE_URL=http://localhost:3000 bash scripts/rate-limit-probe.sh`.
+
## 🛠 Tech stack
| Layer | Choice |
@@ -801,6 +840,12 @@ tool descriptions so agents pick the right format.
copy diagnostics with design id + last saved seq) instead of a white
screen; `reactStrictMode` re-enabled after a full-suite re-evaluation
*(v0.12.2)*
+- [x] Rate limits & connection caps — per-IP limits on designs CRUD,
+ collab events/presence, comments and media init (429 + `Retry-After`,
+ every cap ≥ 4× the heaviest legitimate client), SSE streams capped
+ at 6 concurrent connections per IP, a load-probe script that proves
+ both caps on a live instance, and an honest “multi-instance fleets”
+ section in the README *(v0.12.3)*
- [ ] 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 fc7f4de..9df73c7 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "canvix",
- "version": "0.12.2",
+ "version": "0.12.3",
"private": false,
"description": "Canvix — free & open-source graphic design tool. A community-built Canva alternative.",
"scripts": {
diff --git a/scripts/rate-limit-probe.sh b/scripts/rate-limit-probe.sh
new file mode 100755
index 0000000..100177a
--- /dev/null
+++ b/scripts/rate-limit-probe.sh
@@ -0,0 +1,91 @@
+#!/usr/bin/env bash
+# ─────────────────────────────────────────────────────────────
+# rate-limit-probe.sh (v0.12.3, roadmap H5) — proves the per-IP
+# caps on a live instance. Creates throwaway designs, so point it
+# at a scratch/dev server, not production.
+#
+# BASE_URL=http://localhost:3000 bash scripts/rate-limit-probe.sh
+#
+# Proves:
+# 1. POST /api/designs 429s after the designs:create budget
+# (default 30/min/IP) and the 429 carries Retry-After.
+# 2. The 7th concurrent SSE stream from one IP is refused 429
+# while the first 6 (CANVIX_SSE_MAX_PER_IP) stream fine.
+# Exit code 0 = every cap behaved.
+# ─────────────────────────────────────────────────────────────
+set -u
+BASE_URL="${BASE_URL:-http://localhost:3000}"
+CREATE_LIMIT="${CREATE_LIMIT:-30}" # keep in sync with src/lib/rate-limit.ts
+SSE_CAP="${SSE_CAP:-6}"
+
+pass=0; fail=0
+ok() { echo " ✓ $1"; pass=$((pass+1)); }
+bad() { echo " ✗ $1"; fail=$((fail+1)); }
+
+echo "── 1. designs:create cap ($CREATE_LIMIT/min per IP) ──"
+code=""; retry_after=""
+for i in $(seq 1 $((CREATE_LIMIT + 5))); do
+ # no Origin header → same-origin check passes for curl (no ambient
+ # cookie authority); the limiter keys on the shared unknown/local IP
+ headers=$(curl -s -o /dev/null -D - -X POST "$BASE_URL/api/designs" \
+ -H 'Content-Type: application/json' \
+ --data '{"name":"rate-limit probe","width":100,"height":100,"pages":[]}')
+ code=$(printf '%s' "$headers" | head -1 | awk '{print $2}')
+ retry_after=$(printf '%s' "$headers" | tr -d '\r' | awk 'tolower($1)=="retry-after:" {print $2}')
+ if [ "$code" = "429" ]; then
+ echo " hit the cap on request #$i (HTTP $code)"
+ break
+ fi
+done
+if [ "$code" = "429" ]; then
+ ok "POST /api/designs eventually returns 429"
+else
+ bad "never got a 429 (last code: $code) — is CANVIX_RATE_LIMITS=off set, or the limit raised?"
+fi
+if [ -n "$retry_after" ] && [ "$retry_after" -ge 1 ] 2>/dev/null; then
+ ok "429 carries Retry-After: $retry_after"
+else
+ bad "429 is missing a numeric Retry-After header"
+fi
+
+echo "── 2. SSE concurrent-stream cap ($SSE_CAP per IP) ──"
+design_id=$(curl -s -X POST "$BASE_URL/api/designs" \
+ -H 'Content-Type: application/json' \
+ --data '{"name":"sse cap probe","width":100,"height":100,"pages":[]}' \
+ | python3 -c 'import json,sys; print(json.load(sys.stdin).get("id",""))' 2>/dev/null || echo "")
+if [ -z "$design_id" ]; then
+ # the create budget may already be spent — reuse any existing design
+ design_id=$(curl -s "$BASE_URL/api/designs" | python3 -c 'import json,sys; d=json.load(sys.stdin).get("designs") or []; print(d[0]["id"] if d else "")' 2>/dev/null || echo "")
+fi
+if [ -z "$design_id" ]; then
+ bad "no design available to open streams against"
+else
+ pids=()
+ for i in $(seq 1 "$SSE_CAP"); do
+ # hold $SSE_CAP streams open for 6 s (long enough to fire the probe)
+ curl -s -N --max-time 6 "$BASE_URL/api/collab/$design_id/stream?pid=probe$i&since=0" \
+ > /dev/null 2>&1 &
+ pids+=($!)
+ done
+ sleep 1 # let the six connect
+ code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 3 \
+ "$BASE_URL/api/collab/$design_id/stream?pid=probe-over&since=0")
+ if [ "$code" = "429" ]; then
+ ok "stream #$((SSE_CAP + 1)) is refused with 429"
+ else
+ bad "stream #$((SSE_CAP + 1)) got HTTP $code (expected 429)"
+ fi
+ wait "${pids[@]}" 2>/dev/null
+ # after the six close, a new stream must be welcome again
+ code=$(curl -s -o /dev/null -w '%{http_code}' --max-time 3 \
+ "$BASE_URL/api/collab/$design_id/stream?pid=probe-after&since=0")
+ if [ "$code" = "200" ]; then
+ ok "a fresh stream connects after the slots are released"
+ else
+ bad "post-release stream got HTTP $code (expected 200) — slot leak?"
+ fi
+fi
+
+echo "── verdict ──"
+echo " passed: $pass failed: $fail"
+[ "$fail" -eq 0 ] && echo " RATE LIMITS VERIFIED" || { echo " RATE LIMIT PROBE FAILED"; exit 1; }
diff --git a/src/app/api/collab/[designId]/events/route.ts b/src/app/api/collab/[designId]/events/route.ts
index dc8a157..b4e5fb9 100644
--- a/src/app/api/collab/[designId]/events/route.ts
+++ b/src/app/api/collab/[designId]/events/route.ts
@@ -12,6 +12,7 @@ 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'
+import { checkRateLimit, rateLimitResponse } from '@/lib/rate-limit'
export const runtime = 'nodejs'
export const maxDuration = 30
@@ -59,6 +60,10 @@ export async function POST(req: NextRequest, { params }: { params: Promise<{ des
// 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 })
+ // v0.12.3 (H5): active clients flush every 400 ms (150/min each) —
+ // 600/min/IP covers a few tabs in one room, stops event floods.
+ const limit = checkRateLimit(req, 'collab:events')
+ if (!limit.ok) return rateLimitResponse(limit)
const body = (await req.json().catch(() => ({}))) as EventsBody
const pid = (body.pid ?? '').replace(/[^a-zA-Z0-9_-]/g, '').slice(0, 40)
diff --git a/src/app/api/collab/[designId]/presence/route.ts b/src/app/api/collab/[designId]/presence/route.ts
index 516e96f..2be63ce 100644
--- a/src/app/api/collab/[designId]/presence/route.ts
+++ b/src/app/api/collab/[designId]/presence/route.ts
@@ -1,6 +1,7 @@
import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'
import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'
+import { checkRateLimit, rateLimitResponse } from '@/lib/rate-limit'
export const runtime = 'nodejs'
export const maxDuration = 20
@@ -23,6 +24,10 @@ export async function POST(req: NextRequest, { params }: { params: Promise<{ des
try {
// v0.11.8: same-origin enforcement, matching every other mutating route.
if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })
+ // v0.12.3 (H5): heartbeats are 15 s/client — 120/min/IP is a floor
+ // so high it never bites a real room, and a ceiling for floods.
+ const limit = checkRateLimit(req, 'collab:presence')
+ if (!limit.ok) return rateLimitResponse(limit)
const body = (await req.json().catch(() => ({}))) as PresenceBody
const pid = (body.pid ?? '').replace(/[^a-zA-Z0-9_-]/g, '').slice(0, 40)
diff --git a/src/app/api/collab/[designId]/stream/route.ts b/src/app/api/collab/[designId]/stream/route.ts
index cf01d5c..98f4c20 100644
--- a/src/app/api/collab/[designId]/stream/route.ts
+++ b/src/app/api/collab/[designId]/stream/route.ts
@@ -1,6 +1,7 @@
import { NextRequest } from 'next/server'
import { db } from '@/lib/db'
import { presenceKey } from '@/lib/collab/presence-diff'
+import { acquireStreamSlot, clientIp, releaseStreamSlot } from '@/lib/rate-limit'
export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'
@@ -65,6 +66,17 @@ export async function GET(req: NextRequest, { params }: { params: Promise<{ desi
return new Response('Database unavailable', { status: 503 })
}
+ // v0.12.3 (H5): per-IP concurrent SSE cap (default 6 — a browser's
+ // per-domain HTTP/1.1 limit; CANVIX_SSE_MAX_PER_IP to tune). Every
+ // exit path funnels through close(), which releases the slot.
+ const ip = clientIp(req)
+ if (!acquireStreamSlot(ip)) {
+ return new Response('Too many live collaboration streams from this address.', {
+ status: 429,
+ headers: { 'Retry-After': '10', 'Content-Type': 'text/plain; charset=utf-8' },
+ })
+ }
+
const encoder = new TextEncoder()
let closed = false
let timer: ReturnType<typeof setTimeout> | null = null
@@ -101,6 +113,7 @@ export async function GET(req: NextRequest, { params }: { params: Promise<{ desi
const close = () => {
if (closed) return
closed = true
+ releaseStreamSlot(ip)
if (timer) clearTimeout(timer)
if (pumpTimeout) clearTimeout(pumpTimeout)
try {
@@ -258,6 +271,10 @@ export async function GET(req: NextRequest, { params }: { params: Promise<{ desi
}
await scheduleNext()
},
+ cancel() {
+ // consumer went away without an abort signal (platform teardown)
+ close()
+ },
})
return new Response(stream, {
diff --git a/src/app/api/designs/[id]/comments/route.ts b/src/app/api/designs/[id]/comments/route.ts
index ac4823b..39193e5 100644
--- a/src/app/api/designs/[id]/comments/route.ts
+++ b/src/app/api/designs/[id]/comments/route.ts
@@ -1,5 +1,6 @@
import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'
+import { checkRateLimit, rateLimitResponse } from '@/lib/rate-limit'
export const runtime = 'nodejs'
export const maxDuration = 30
@@ -56,6 +57,9 @@ interface CommentBody {
export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
const { id: designId } = await params
+ // v0.12.3 (H5): comment spam brake — humans don't post 60/min.
+ const limit = checkRateLimit(req, 'comments:create')
+ if (!limit.ok) return rateLimitResponse(limit)
try {
const body = (await req.json().catch(() => ({}))) as CommentBody
diff --git a/src/app/api/designs/[id]/route.ts b/src/app/api/designs/[id]/route.ts
index 3723278..2dca51f 100644
--- a/src/app/api/designs/[id]/route.ts
+++ b/src/app/api/designs/[id]/route.ts
@@ -3,6 +3,7 @@ import { Prisma } from '@/generated/prisma/client'
import { db } from '@/lib/db'
import { resolveDesignAccess, NOT_YOUR_DESIGN } from '@/lib/auth/design-guard'
import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'
+import { checkRateLimit, rateLimitResponse } from '@/lib/rate-limit'
import { mergePages } from '@/lib/collab/merge'
import type { PageData } from '@/lib/types'
@@ -58,6 +59,10 @@ export async function GET(req: NextRequest, { params }: { params: Promise<{ id:
// rule every client applies, so all replicas converge.
export async function PUT(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })
+ // v0.12.3 (H5): generous cap — autosave fires ≤ ~37/min after its
+ // 1.6 s debounce; 300/min leaves multi-tab headroom, stops runaway loops
+ const limit = checkRateLimit(req, 'designs:update')
+ if (!limit.ok) return rateLimitResponse(limit)
try {
const { id } = await params
const access = await resolveDesignAccess(req, id)
@@ -116,6 +121,8 @@ export async function PUT(req: NextRequest, { params }: { params: Promise<{ id:
// for their owner (403 otherwise). v0.9.1: same-origin enforced (CSRF).
export async function DELETE(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })
+ const limit = checkRateLimit(req, 'designs:delete')
+ if (!limit.ok) return rateLimitResponse(limit)
try {
const { id } = await params
const access = await resolveDesignAccess(req, id)
diff --git a/src/app/api/designs/rate-limits.test.ts b/src/app/api/designs/rate-limits.test.ts
new file mode 100644
index 0000000..30c4b87
--- /dev/null
+++ b/src/app/api/designs/rate-limits.test.ts
@@ -0,0 +1,77 @@
+// Route-level proof that the H5 rate limits are actually wired:
+// POST /api/designs must 429 (with Retry-After) once the
+// designs:create budget is spent, and must not consume any other
+// bucket's budget. The limiter itself has its own unit tests
+// (src/lib/rate-limit.test.ts); this file proves the plumbing.
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'
+
+const dbMock = vi.hoisted(() => ({
+ design: { create: vi.fn() },
+}))
+vi.mock('@/lib/db', () => ({ db: dbMock }))
+
+const getSessionUser = vi.hoisted(() => vi.fn())
+vi.mock('@/lib/auth/session', () => ({ getSessionUser }))
+
+import { NextRequest } from 'next/server'
+import { POST } from './route'
+import { RATE_LIMITS, resetRateLimitState } from '@/lib/rate-limit'
+
+function post() {
+ getSessionUser.mockResolvedValue(null)
+ dbMock.design.create.mockImplementation(({ data }: { data: { name: string } }) =>
+ Promise.resolve({ id: 'd_probe_' + data.name, ...data }))
+ return POST(
+ new NextRequest('http://canvix.test/api/designs', {
+ method: 'POST',
+ headers: { host: 'canvix.test', 'content-type': 'application/json' },
+ body: JSON.stringify({ name: 'probe', pages: [] }),
+ }),
+ )
+}
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ resetRateLimitState()
+ RATE_LIMITS['designs:create'] = { windowMs: 60_000, max: 3 }
+})
+
+afterEach(() => {
+ resetRateLimitState()
+})
+
+describe('POST /api/designs × rate limit (H5)', () => {
+ it('429s with Retry-After once the create budget is spent', async () => {
+ expect((await post()).status).toBe(201)
+ expect((await post()).status).toBe(201)
+ expect((await post()).status).toBe(201)
+
+ const blocked = await post()
+ expect(blocked.status).toBe(429)
+ const retryAfter = Number(blocked.headers.get('retry-after'))
+ expect(retryAfter).toBeGreaterThanOrEqual(1)
+ expect(retryAfter).toBeLessThanOrEqual(60)
+ const body = await blocked.json()
+ expect(body.code).toBe('RATE_LIMITED')
+
+ // the DB was touched exactly budget times — rejected requests
+ // never reach it
+ expect(dbMock.design.create).toHaveBeenCalledTimes(3)
+ })
+
+ it('a different IP is not blocked by the first one (proxy header)', async () => {
+ getSessionUser.mockResolvedValue(null)
+ const makeReq = (ip: string) =>
+ new NextRequest('http://canvix.test/api/designs', {
+ method: 'POST',
+ headers: { host: 'canvix.test', 'content-type': 'application/json', 'x-forwarded-for': ip },
+ body: JSON.stringify({ name: 'probe', pages: [] }),
+ })
+ for (let i = 0; i < 3; i++) await POST(makeReq('203.0.113.1'))
+ const blockedNeighbor = await POST(makeReq('203.0.113.2'))
+ expect(blockedNeighbor.status).toBe(201)
+ const blockedSelf = await POST(makeReq('203.0.113.1'))
+ expect(blockedSelf.status).toBe(429)
+ })
+})
diff --git a/src/app/api/designs/route.ts b/src/app/api/designs/route.ts
index 1ac264a..ad2700b 100644
--- a/src/app/api/designs/route.ts
+++ b/src/app/api/designs/route.ts
@@ -5,6 +5,7 @@ import { dbErrorResponse } from '@/lib/db-errors'
import { getSessionUser } from '@/lib/auth/session'
import { readAnonToken, newAnonToken, anonKeyHash, setAnonCookie, anonHashFrom } from '@/lib/auth/anon'
import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'
+import { checkRateLimit, rateLimitResponse } from '@/lib/rate-limit'
// Normalise incoming pages payload (accepts object or legacy JSON string)
// into a value suitable for the Postgres jsonb column.
@@ -111,6 +112,10 @@ export async function GET(req: NextRequest) {
// adopt-all can never claim someone else's work.
export async function POST(req: NextRequest) {
if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })
+ // v0.12.3 (H5): design creation is unauthenticated (anonymous
+ // ownerless mode) — a per-IP cap is the only brake on flooding.
+ const limit = checkRateLimit(req, 'designs:create')
+ if (!limit.ok) return rateLimitResponse(limit)
try {
const user = await getSessionUser(req)
const body = await req.json()
diff --git a/src/app/api/media/route.ts b/src/app/api/media/route.ts
index f38c702..491b7e9 100644
--- a/src/app/api/media/route.ts
+++ b/src/app/api/media/route.ts
@@ -1,6 +1,7 @@
import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'
import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'
+import { checkRateLimit, rateLimitResponse } from '@/lib/rate-limit'
import { getSessionUser } from '@/lib/auth/session'
import { anonKeyHash, newAnonToken, readAnonToken, setAnonCookie } from '@/lib/auth/anon'
@@ -21,6 +22,10 @@ const ALLOWED_PREFIXES = ['audio/', 'video/']
export async function POST(req: NextRequest) {
if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })
+ // v0.12.3 (H5): uploads are chunked but initiation is cheap — cap
+ // the init calls, not the chunk traffic (chunks carry real bytes).
+ const limit = checkRateLimit(req, 'media:init')
+ if (!limit.ok) return rateLimitResponse(limit)
try {
const body = (await req.json().catch(() => ({}))) as { mime?: unknown; size?: unknown }
const mime = typeof body.mime === 'string' ? body.mime.slice(0, 100) : ''
diff --git a/src/lib/rate-limit.test.ts b/src/lib/rate-limit.test.ts
new file mode 100644
index 0000000..08b0cbc
--- /dev/null
+++ b/src/lib/rate-limit.test.ts
@@ -0,0 +1,137 @@
+import { describe, it, expect, beforeEach, afterEach } from 'vitest'
+import { NextRequest } from 'next/server'
+import {
+ RATE_LIMITS,
+ acquireStreamSlot,
+ activeStreamsFor,
+ checkRateLimit,
+ clientIp,
+ maxStreamsPerIp,
+ rateLimitResponse,
+ rateLimitsDisabled,
+ releaseStreamSlot,
+ resetRateLimitState,
+ setRateLimitClock,
+} from './rate-limit'
+
+// H5: the per-instance limiter that backs the 429s. Deterministic
+// through an injected clock — no real waiting anywhere.
+
+function req(headers: Record<string, string> = {}) {
+ return new NextRequest('http://canvix.test/api/designs', { headers })
+}
+
+let realNow: () => number
+
+beforeEach(() => {
+ resetRateLimitState()
+ setRateLimitClock(null)
+ delete process.env.CANVIX_RATE_LIMITS
+ delete process.env.CANVIX_SSE_MAX_PER_IP
+})
+
+afterEach(() => {
+ setRateLimitClock(null)
+ delete process.env.CANVIX_RATE_LIMITS
+ delete process.env.CANVIX_SSE_MAX_PER_IP
+})
+
+describe('clientIp', () => {
+ it('takes the first x-forwarded-for hop', () => {
+ expect(clientIp(req({ 'x-forwarded-for': '203.0.113.9, 10.0.0.1' }))).toBe('203.0.113.9')
+ })
+ it('falls back to x-real-ip, then the shared unknown bucket', () => {
+ expect(clientIp(req({ 'x-real-ip': '198.51.100.7' }))).toBe('198.51.100.7')
+ expect(clientIp(req())).toBe('unknown')
+ })
+})
+
+describe('checkRateLimit (fixed window)', () => {
+ it('allows up to max, then 429s with a sane Retry-After', () => {
+ RATE_LIMITS['media:init'] = { windowMs: 60_000, max: 3 }
+ const r = req()
+ expect(checkRateLimit(r, 'media:init')).toEqual({ ok: true, retryAfterSec: 0 })
+ expect(checkRateLimit(r, 'media:init')).toEqual({ ok: true, retryAfterSec: 0 })
+ expect(checkRateLimit(r, 'media:init')).toEqual({ ok: true, retryAfterSec: 0 })
+ const blocked = checkRateLimit(r, 'media:init')
+ expect(blocked.ok).toBe(false)
+ expect(blocked.retryAfterSec).toBeGreaterThanOrEqual(1)
+ expect(blocked.retryAfterSec).toBeLessThanOrEqual(60)
+ })
+
+ it('buckets are independent — events never consume the designs budget', () => {
+ RATE_LIMITS['media:init'] = { windowMs: 60_000, max: 1 }
+ const r = req()
+ expect(checkRateLimit(r, 'media:init').ok).toBe(true)
+ expect(checkRateLimit(r, 'media:init').ok).toBe(false)
+ expect(checkRateLimit(r, 'designs:create').ok).toBe(true)
+ })
+
+ it('IPs are independent', () => {
+ RATE_LIMITS['media:init'] = { windowMs: 60_000, max: 1 }
+ expect(checkRateLimit(req({ 'x-forwarded-for': '203.0.113.1' }), 'media:init').ok).toBe(true)
+ expect(checkRateLimit(req({ 'x-forwarded-for': '203.0.113.2' }), 'media:init').ok).toBe(true)
+ expect(checkRateLimit(req({ 'x-forwarded-for': '203.0.113.1' }), 'media:init').ok).toBe(false)
+ })
+
+ it('the window rolls over and resets the count', () => {
+ RATE_LIMITS['media:init'] = { windowMs: 1_000, max: 1 }
+ let t = 1_000_000
+ setRateLimitClock(() => t)
+ expect(checkRateLimit(req(), 'media:init').ok).toBe(true)
+ expect(checkRateLimit(req(), 'media:init').ok).toBe(false)
+ t += 1_001 // past the window
+ expect(checkRateLimit(req(), 'media:init').ok).toBe(true)
+ })
+
+ it('CANVIX_RATE_LIMITS=off disables every bucket', () => {
+ process.env.CANVIX_RATE_LIMITS = 'off'
+ expect(rateLimitsDisabled()).toBe(true)
+ RATE_LIMITS['media:init'] = { windowMs: 60_000, max: 1 }
+ const r = req()
+ expect(checkRateLimit(r, 'media:init').ok).toBe(true)
+ expect(checkRateLimit(r, 'media:init').ok).toBe(true)
+ expect(checkRateLimit(r, 'media:init').ok).toBe(true)
+ })
+})
+
+describe('rateLimitResponse', () => {
+ it('carries Retry-After and the documented body', () => {
+ const res = rateLimitResponse({ ok: false, retryAfterSec: 42 })
+ expect(res.status).toBe(429)
+ expect(res.headers.get('retry-after')).toBe('42')
+ return res.json().then((body) => {
+ expect(body.code).toBe('RATE_LIMITED')
+ expect(body.retryAfterSec).toBe(42)
+ })
+ })
+})
+
+describe('SSE connection cap', () => {
+ it('caps concurrent streams per IP and releases slots', () => {
+ expect(maxStreamsPerIp()).toBe(6)
+ const ip = '203.0.113.30'
+ for (let i = 0; i < 6; i++) {
+ expect(acquireStreamSlot(ip)).toBe(true)
+ }
+ expect(activeStreamsFor(ip)).toBe(6)
+ expect(acquireStreamSlot(ip)).toBe(false) // the 7th connection: 429
+ releaseStreamSlot(ip)
+ expect(activeStreamsFor(ip)).toBe(5)
+ expect(acquireStreamSlot(ip)).toBe(true)
+ })
+
+ it('the cap is configurable and off-mode bypasses it', () => {
+ process.env.CANVIX_SSE_MAX_PER_IP = '2'
+ expect(maxStreamsPerIp()).toBe(2)
+ const ip = '203.0.113.31'
+ expect(acquireStreamSlot(ip)).toBe(true)
+ expect(acquireStreamSlot(ip)).toBe(true)
+ expect(acquireStreamSlot(ip)).toBe(false)
+ releaseStreamSlot(ip)
+ releaseStreamSlot(ip)
+
+ process.env.CANVIX_RATE_LIMITS = 'off'
+ expect(acquireStreamSlot(ip)).toBe(true)
+ })
+})
diff --git a/src/lib/rate-limit.ts b/src/lib/rate-limit.ts
new file mode 100644
index 0000000..d4c6401
--- /dev/null
+++ b/src/lib/rate-limit.ts
@@ -0,0 +1,205 @@
+// ─────────────────────────────────────────────────────────────
+// Per-IP rate limits + SSE connection caps (v0.12.3, roadmap H5 —
+// research/V0118-ROADMAP-RESEARCH.md §5.1).
+//
+// Scope (the epic's list): designs CRUD, collab events/presence,
+// comment creation and media upload init get per-IP request
+// limits; the SSE stream gets a per-IP concurrent-connection cap.
+// The MCP route already carries its own 120 req/min/IP limiter.
+//
+// Semantics, stated honestly (README → “Rate limiting”):
+// - fixed-window counters, IN MEMORY, PER SERVER INSTANCE. A
+// multi-instance fleet (or serverless platform spawning many
+// isolates) enforces each cap per instance, not per deployment
+// — the shared-store upgrade is deliberately post-1.0 (debt
+// #12) and documented as such.
+// - the client IP is taken from x-forwarded-for / x-real-ip —
+// the headers every reverse proxy and hosting platform sets.
+// A bare `next start` with no proxy in front exposes no
+// client address to route handlers, so such deployments fall
+// back to the shared “unknown” bucket (localhost is trusted
+// anyway; the caps still stop runaway loops).
+// - limits are generous enough for real editing (autosave fires
+// at most ~37/min after its 1.6 s debounce; collab flushes at
+// 2.5/min idle / 150/min active) — they exist to stop abuse
+// and runaway loops, never to throttle a working editor.
+//
+// Turn everything off with CANVIX_RATE_LIMITS=off (self-hosters
+// behind their own throttle, or load tests).
+// ─────────────────────────────────────────────────────────────
+
+import type { NextRequest } from 'next/server'
+
+export type RateLimitBucket =
+ | 'designs:create'
+ | 'designs:update'
+ | 'designs:delete'
+ | 'collab:events'
+ | 'collab:presence'
+ | 'comments:create'
+ | 'media:init'
+
+export interface RateLimitConfig {
+ /** window length in milliseconds */
+ windowMs: number
+ /** allowed requests per window per IP */
+ max: number
+}
+
+/** The defaults — override per bucket in tests via RATE_LIMITS. */
+export const RATE_LIMITS: Record<RateLimitBucket, RateLimitConfig> = {
+ 'designs:create': { windowMs: 60_000, max: 30 },
+ // autosave: 1.6 s debounce → ≤ 37/min per client; 300/min leaves
+ // room for multi-tab + collaboration saves before it ever bites
+ 'designs:update': { windowMs: 60_000, max: 300 },
+ 'designs:delete': { windowMs: 60_000, max: 60 },
+ // collab flush cadence is 400 ms per active client → 150/min
+ 'collab:events': { windowMs: 60_000, max: 600 },
+ // presence heartbeats every 15 s → 4/min per client
+ 'collab:presence': { windowMs: 60_000, max: 120 },
+ 'comments:create': { windowMs: 60_000, max: 60 },
+ 'media:init': { windowMs: 60_000, max: 30 },
+}
+
+export function rateLimitsDisabled(): boolean {
+ return process.env.CANVIX_RATE_LIMITS === 'off'
+}
+
+/**
+ * Best-effort client IP for rate keying. x-forwarded-for (first
+ * hop, left-most) wins, then x-real-ip; otherwise the shared
+ * “unknown” bucket. Never trusted for AUTHORIZATION — only for
+ * throttling, where a spoofed header at worst merges buckets.
+ */
+export function clientIp(req: NextRequest): string {
+ const fwd = req.headers.get('x-forwarded-for')
+ if (fwd) {
+ const first = fwd.split(',')[0]?.trim()
+ if (first) return first
+ }
+ const real = req.headers.get('x-real-ip')
+ if (real) return real.trim()
+ return 'unknown'
+}
+
+// ── fixed-window counters ─────────────────────────────────────
+
+interface WindowState {
+ count: number
+ resetAt: number
+}
+
+const windows = new Map<string, WindowState>()
+/** injectable clock — tests control the window rollover */
+let now: () => number = () => Date.now()
+
+const MAX_TRACKED_KEYS = 10_000
+
+function sweep(nowMs: number): void {
+ if (windows.size <= MAX_TRACKED_KEYS) return
+ for (const [key, state] of windows) {
+ if (state.resetAt <= nowMs) windows.delete(key)
+ }
+ // still oversized (an attacker spraying keys)? drop the oldest
+ // half wholesale — availability of the map beats precision
+ if (windows.size > MAX_TRACKED_KEYS) {
+ const entries = [...windows.entries()].sort((a, b) => a[1].resetAt - b[1].resetAt)
+ for (const [key] of entries.slice(0, Math.floor(entries.length / 2))) {
+ windows.delete(key)
+ }
+ }
+}
+
+export interface RateLimitResult {
+ ok: boolean
+ /** seconds until the window resets (0 when allowed) */
+ retryAfterSec: number
+}
+
+/**
+ * Consume one request from the bucket for this client. Pure bookkeeping —
+ * call once per request, on the hot path, before any DB work.
+ */
+export function checkRateLimit(
+ req: NextRequest,
+ bucket: RateLimitBucket,
+): RateLimitResult {
+ if (rateLimitsDisabled()) return { ok: true, retryAfterSec: 0 }
+ const config = RATE_LIMITS[bucket]
+ const nowMs = now()
+ const key = `${bucket}:${clientIp(req)}`
+ const state = windows.get(key)
+ if (!state || state.resetAt <= nowMs) {
+ windows.set(key, { count: 1, resetAt: nowMs + config.windowMs })
+ sweep(nowMs)
+ return { ok: true, retryAfterSec: 0 }
+ }
+ if (state.count < config.max) {
+ state.count += 1
+ return { ok: true, retryAfterSec: 0 }
+ }
+ return {
+ ok: false,
+ retryAfterSec: Math.max(1, Math.ceil((state.resetAt - nowMs) / 1000)),
+ }
+}
+
+/** Standard 429 body + Retry-After header for a rejected request. */
+export function rateLimitResponse(result: RateLimitResult): Response {
+ return Response.json(
+ {
+ error: 'Too many requests — slow down.',
+ code: 'RATE_LIMITED',
+ retryAfterSec: result.retryAfterSec,
+ },
+ {
+ status: 429,
+ headers: { 'Retry-After': String(result.retryAfterSec) },
+ },
+ )
+}
+
+// ── SSE concurrent-connection cap ────────────────────────────
+
+const streamCounts = new Map<string, number>()
+
+export function maxStreamsPerIp(): number {
+ return Math.max(1, Number(process.env.CANVIX_SSE_MAX_PER_IP ?? 6))
+}
+
+/**
+ * Reserve one SSE slot for this IP. Returns true when the
+ * connection may proceed; always pair with releaseStreamSlot()
+ * in the stream's cleanup path.
+ */
+export function acquireStreamSlot(ip: string): boolean {
+ if (rateLimitsDisabled()) return true
+ const current = streamCounts.get(ip) ?? 0
+ if (current >= maxStreamsPerIp()) return false
+ streamCounts.set(ip, current + 1)
+ return true
+}
+
+export function releaseStreamSlot(ip: string): void {
+ const current = streamCounts.get(ip)
+ if (current === undefined) return
+ if (current <= 1) streamCounts.delete(ip)
+ else streamCounts.set(ip, current - 1)
+}
+
+export function activeStreamsFor(ip: string): number {
+ return streamCounts.get(ip) ?? 0
+}
+
+// ── test hooks ───────────────────────────────────────────────
+
+/** Test-only: wipe all counters + restore defaults. */
+export function resetRateLimitState(): void {
+ windows.clear()
+ streamCounts.clear()
+}
+
+/** Test-only: control the clock. */
+export function setRateLimitClock(clock: (() => number) | null): void {
+ now = clock ?? (() => Date.now())
+}