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): observability floor — opt-in structured request logging on every API route, /api/health?v=2 counts + latency probe, optional error webhook via onRequestError (H7) (#16)

Ashiq Hussain Mird629dbb5383c
diff --git a/.env.example b/.env.example
index 4c4b9d9..14a67d1 100644
--- a/.env.example
+++ b/.env.example
@@ -51,3 +51,20 @@ DATABASE_URL=postgresql://postgres.[YOUR-PROJECT-REF]:[YOUR-PASSWORD]@aws-0-eu-c
# "off" only when something in front of the app already throttles.
# CANVIX_RATE_LIMITS=off
# CANVIX_SSE_MAX_PER_IP=6
+
+# ── Observability (optional, v0.12.5) ─────────────────────────
+# All off by default — a design tool's server logs are the
+# self-hoster's to read (privacy first).
+#
+# CANVIX_LOG=requests → one JSON line per API request on stdout:
+# method, path (no query strings), status,
+# duration. Values: requests | 1 | true
+# CANVIX_ERROR_WEBHOOK_URL=https://… → POST a JSON error report
+# (message, path, method, app version) for
+# every unhandled request error. Any endpoint
+# that accepts JSON works (Slack webhooks via
+# a relay, Discord, your own collector).
+# Health: GET /api/health?v=2 returns aggregate counts + a DB
+# latency probe (no env needed, counts only — never ids).
+# CANVIX_LOG=requests
+# CANVIX_ERROR_WEBHOOK_URL=
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8caec4e..e09ff2a 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -3,6 +3,45 @@
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.5] — 2026-11-02
+
+### Added
+
+- **Observability floor (H7) — all opt-in, off by default.** The
+ last v0.12 epic gives self-hosters the three primitives the
+ roadmap research named, with privacy as the design constraint:
+ - **Structured request logging** (`CANVIX_LOG=requests`): every
+ API request emits one JSON line on stdout — method, path,
+ status, duration (`event: http_request`). Query strings are
+ deliberately never logged (they carry design ids and cursor
+ data) and neither are IPs. Implemented as a `withLogging()`
+ wrapper applied to **every API route handler** (29 files, ~60
+ handlers — designs, collab, media, auth, comments, versions,
+ templates, health, MCP, photos and all eight AI routes); with
+ the env unset it is a zero-behavior-change passthrough, and
+ the SSE stream's response passes through untouched.
+ - **`/api/health?v=2`** — the observability payload: aggregate
+ counts (live designs, users, finalized media count **and
+ bytes**, version snapshots, comments), a DB latency probe
+ (measured on the existing `SELECT 1`), and app version +
+ uptime. Counts only, **never ids** — asserted by an e2e test
+ that scans the payload for cuid/uuid shapes. Plain
+ `/api/health` keeps its v1 shape (plus an explicit `v: 1`) so
+ liveness probes stay as cheap as before.
+ - **Optional error webhook** (`CANVIX_ERROR_WEBHOOK_URL`):
+ every *unhandled* request error — any route, page or server
+ action — POSTs a JSON report (message, stack head, path,
+ method, route type, app version, timestamp) via Next's
+ `onRequestError` hook in the new `src/instrumentation.ts`.
+ One file instruments the whole app; 5-second timeout,
+ fire-and-forget, and a failing webhook logs locally instead
+ of taking the error path down.
+- **8 unit tests** (`src/lib/observability.test.ts`): the opt-in
+ gate, passthrough-vs-logging behavior, JSON line shape, query-
+ string redaction, error-path 500 logging + rethrow, params
+ passthrough, and the webhook payload contract (bounded,
+ id-free). Plus a Playwright spec for health v1/v2.
+
## [0.12.4] — 2026-11-02
### Added
diff --git a/README.md b/README.md
index c7d9c72..995e018 100644
--- a/README.md
+++ b/README.md
@@ -589,6 +589,30 @@ 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`.
+### 📡 Observability (v0.12.5)
+
+Three primitives, **all off by default** — a design tool's server logs
+are the self-hoster's to read:
+
+- **Structured request logging** — set `CANVIX_LOG=requests` and every
+ API request emits one JSON line on stdout: method, path, status,
+ duration (`{"ts":…,"level":"info","event":"http_request","method":"PUT",
+"path":"/api/designs/abc","status":200,"duration_ms":18.4}`). Query
+ strings are never logged (they carry design ids and cursors); IPs
+ aren't either. Grep-able, JSON-parseable, zero dependencies.
+- **`/api/health?v=2`** — the observability payload: aggregate counts
+ (live designs, users, finalized media count **and bytes**, version
+ snapshots, comments), a DB latency probe, and the app version +
+ uptime. Counts only, never ids — safe to point monitoring at. Plain
+ `/api/health` keeps its v1 shape (plus an explicit `v: 1`) for
+ liveness probes that should stay cheap.
+- **Error webhook** — set `CANVIX_ERROR_WEBHOOK_URL` and every
+ *unhandled* request error (any route, page or server action — via
+ Next's `onRequestError` hook in `src/instrumentation.ts`) POSTs a
+ JSON report: message, path, method, route type, app version,
+ timestamp. 5-second timeout, fire-and-forget — a broken webhook
+ never takes the error path down with it.
+
## 🛠 Tech stack
| Layer | Choice |
@@ -861,6 +885,13 @@ tool descriptions so agents pick the right format.
scheduled-backup cron) and `docs/UPGRADING.md` (routine upgrades,
jumping minors, rollback with the forward-only-migrations caveat),
plus a media orphan GC script with its own verified drill *(v0.12.4)*
+- [x] Observability floor — opt-in structured request logging
+ (`CANVIX_LOG=requests`, one JSON line per API request, no query
+ strings, no IPs), `/api/health?v=2` with aggregate counts + DB
+ latency probe (never ids), and an optional error webhook
+ (`CANVIX_ERROR_WEBHOOK_URL`, POSTed from Next's `onRequestError`
+ hook for every unhandled error) — all off by default for
+ self-hoster privacy *(v0.12.5)*
- [ ] 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 565ade5..f784ec2 100644
--- a/package.json
+++ b/package.json
@@ -1,6 +1,6 @@
{
"name": "canvix",
- "version": "0.12.4",
+ "version": "0.12.5",
"private": false,
"description": "Canvix — free & open-source graphic design tool. A community-built Canva alternative.",
"scripts": {
diff --git a/src/app/api/ai/assistant/route.ts b/src/app/api/ai/assistant/route.ts
index b828cb3..9721b7b 100644
--- a/src/app/api/ai/assistant/route.ts
+++ b/src/app/api/ai/assistant/route.ts
@@ -1,5 +1,6 @@
import { NextRequest, NextResponse } from 'next/server'
import { withProvider } from '@/lib/ai/provider'
+import { withLogging } from '@/lib/observability'
export const runtime = 'nodejs'
export const maxDuration = 60
@@ -223,7 +224,7 @@ function sanitizeActions(input: unknown): DesignAction[] {
}
/** POST /api/ai/assistant — Canva AI 2.0-style design-aware assistant. */
-export async function POST(req: NextRequest) {
+async function __canvix_post(req: NextRequest) {
const body = (await req.json().catch(() => ({}))) as AssistantBody
const message = (body.message ?? '').trim().slice(0, 1500)
if (!message) return NextResponse.json({ error: 'A message is required.' }, { status: 400 })
@@ -312,3 +313,7 @@ export async function POST(req: NextRequest) {
return NextResponse.json(parsed)
})
}
+
+// v0.12.5 (H7): opt-in request logging wrapper — passthrough
+// unless CANVIX_LOG=requests (see src/lib/observability.ts)
+export const POST = withLogging('POST /api/ai/assistant', __canvix_post)
diff --git a/src/app/api/ai/capabilities/route.ts b/src/app/api/ai/capabilities/route.ts
index f59f188..e4c77c3 100644
--- a/src/app/api/ai/capabilities/route.ts
+++ b/src/app/api/ai/capabilities/route.ts
@@ -1,5 +1,6 @@
import { NextResponse } from 'next/server'
import { hasProvider } from '@/lib/ai/provider'
+import { withLogging } from '@/lib/observability'
export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'
@@ -10,7 +11,7 @@ export const dynamic = 'force-dynamic'
* show "requires server AI provider" states before the user tries a feature.
* Only ever exposes which capabilities exist — never config, never keys.
*/
-export async function GET() {
+async function __canvix_get() {
const configured = hasProvider()
return NextResponse.json({
configured,
@@ -28,3 +29,7 @@ export async function GET() {
},
})
}
+
+// v0.12.5 (H7): opt-in request logging wrapper — passthrough
+// unless CANVIX_LOG=requests (see src/lib/observability.ts)
+export const GET = withLogging('GET /api/ai/capabilities', __canvix_get)
diff --git a/src/app/api/ai/image-edit/route.ts b/src/app/api/ai/image-edit/route.ts
index 74ef864..ba54d69 100644
--- a/src/app/api/ai/image-edit/route.ts
+++ b/src/app/api/ai/image-edit/route.ts
@@ -1,5 +1,6 @@
import { NextRequest, NextResponse } from 'next/server'
import { withProvider } from '@/lib/ai/provider'
+import { withLogging } from '@/lib/observability'
export const runtime = 'nodejs'
export const maxDuration = 60
@@ -46,7 +47,7 @@ const MODE_PROMPTS: Record<string, string> = {
}
/** POST /api/ai/image-edit — Canva-style AI image tools (BG remover, Magic eraser, enhance). */
-export async function POST(req: NextRequest) {
+async function __canvix_post(req: NextRequest) {
const body = (await req.json().catch(() => ({}))) as EditBody
const image = (body.image ?? '').trim()
if (!image || !/^(data:image\/|https?:\/\/)/.test(image)) {
@@ -89,3 +90,7 @@ export async function POST(req: NextRequest) {
return NextResponse.json({ dataUrl: `data:image/png;base64,${base64}`, width: outW, height: outH })
})
}
+
+// v0.12.5 (H7): opt-in request logging wrapper — passthrough
+// unless CANVIX_LOG=requests (see src/lib/observability.ts)
+export const POST = withLogging('POST /api/ai/image-edit', __canvix_post)
diff --git a/src/app/api/ai/image/route.ts b/src/app/api/ai/image/route.ts
index f3bad16..a723fc9 100644
--- a/src/app/api/ai/image/route.ts
+++ b/src/app/api/ai/image/route.ts
@@ -1,5 +1,6 @@
import { NextRequest, NextResponse } from 'next/server'
import { withProvider } from '@/lib/ai/provider'
+import { withLogging } from '@/lib/observability'
export const runtime = 'nodejs'
export const maxDuration = 60
@@ -13,7 +14,7 @@ interface ImageBody {
}
/** POST /api/ai/image — AI image generation for the canvas. Returns a PNG dataURL. */
-export async function POST(req: NextRequest) {
+async function __canvix_post(req: NextRequest) {
const body = (await req.json().catch(() => ({}))) as ImageBody
const prompt = (body.prompt ?? '').trim().slice(0, 600)
const size = (SUPPORTED_SIZES as readonly string[]).includes(body.size ?? '')
@@ -39,3 +40,7 @@ export async function POST(req: NextRequest) {
return NextResponse.json({ dataUrl: `data:image/png;base64,${base64}`, width: w, height: h })
})
}
+
+// v0.12.5 (H7): opt-in request logging wrapper — passthrough
+// unless CANVIX_LOG=requests (see src/lib/observability.ts)
+export const POST = withLogging('POST /api/ai/image', __canvix_post)
diff --git a/src/app/api/ai/magic-layers/route.ts b/src/app/api/ai/magic-layers/route.ts
index a8b88cf..e242e35 100644
--- a/src/app/api/ai/magic-layers/route.ts
+++ b/src/app/api/ai/magic-layers/route.ts
@@ -1,6 +1,7 @@
import { NextRequest, NextResponse } from 'next/server'
import { withProvider, VISION_MODEL } from '@/lib/ai/provider'
import { validateAnalysis } from '@/lib/magic-layers/validate'
+import { withLogging } from '@/lib/observability'
export const runtime = 'nodejs'
export const maxDuration = 60
@@ -17,7 +18,7 @@ interface MagicLayersBody {
* elements. The model never dictates element creation directly; its JSON is
* schema-validated and clamped before it leaves this route.
*/
-export async function POST(req: NextRequest) {
+async function __canvix_post(req: NextRequest) {
const body = (await req.json().catch(() => ({}))) as MagicLayersBody
const image = (body.image ?? '').trim()
@@ -81,3 +82,7 @@ export async function POST(req: NextRequest) {
return NextResponse.json(analysis)
})
}
+
+// v0.12.5 (H7): opt-in request logging wrapper — passthrough
+// unless CANVIX_LOG=requests (see src/lib/observability.ts)
+export const POST = withLogging('POST /api/ai/magic-layers', __canvix_post)
diff --git a/src/app/api/ai/translate/route.ts b/src/app/api/ai/translate/route.ts
index 86d1767..570c7ab 100644
--- a/src/app/api/ai/translate/route.ts
+++ b/src/app/api/ai/translate/route.ts
@@ -1,5 +1,6 @@
import { NextRequest, NextResponse } from 'next/server'
import { withProvider } from '@/lib/ai/provider'
+import { withLogging } from '@/lib/observability'
export const runtime = 'nodejs'
export const maxDuration = 60
@@ -32,7 +33,7 @@ function parseTranslations(raw: string, expected: number): string[] | null {
}
/** POST /api/ai/translate — Canva "Translate": translate an array of design texts. */
-export async function POST(req: NextRequest) {
+async function __canvix_post(req: NextRequest) {
const body = (await req.json().catch(() => ({}))) as TranslateBody
const language = (body.language ?? '').trim()
const texts = Array.isArray(body.texts) ? body.texts.filter((t) => typeof t === 'string') : []
@@ -71,3 +72,7 @@ export async function POST(req: NextRequest) {
return NextResponse.json({ language, translations })
})
}
+
+// v0.12.5 (H7): opt-in request logging wrapper — passthrough
+// unless CANVIX_LOG=requests (see src/lib/observability.ts)
+export const POST = withLogging('POST /api/ai/translate', __canvix_post)
diff --git a/src/app/api/ai/write/route.ts b/src/app/api/ai/write/route.ts
index b892990..05cf5de 100644
--- a/src/app/api/ai/write/route.ts
+++ b/src/app/api/ai/write/route.ts
@@ -1,5 +1,6 @@
import { NextRequest, NextResponse } from 'next/server'
import { withProvider } from '@/lib/ai/provider'
+import { withLogging } from '@/lib/observability'
export const runtime = 'nodejs'
export const maxDuration = 60
@@ -20,7 +21,7 @@ const KIND_HINTS: Record<string, string> = {
const TONES = ['bold', 'playful', 'elegant', 'minimal', 'corporate', 'warm'] as const
/** POST /api/ai/write — Magic Write: generate on-brand copy variants for designs. */
-export async function POST(req: NextRequest) {
+async function __canvix_post(req: NextRequest) {
const body = (await req.json().catch(() => ({}))) as WriteBody
const prompt = (body.prompt ?? '').trim().slice(0, 500)
const kind = body.kind && KIND_HINTS[body.kind] ? body.kind : 'tagline'
@@ -60,3 +61,7 @@ export async function POST(req: NextRequest) {
return NextResponse.json({ options })
})
}
+
+// v0.12.5 (H7): opt-in request logging wrapper — passthrough
+// unless CANVIX_LOG=requests (see src/lib/observability.ts)
+export const POST = withLogging('POST /api/ai/write', __canvix_post)
diff --git a/src/app/api/auth/login/route.ts b/src/app/api/auth/login/route.ts
index 1571231..128ad26 100644
--- a/src/app/api/auth/login/route.ts
+++ b/src/app/api/auth/login/route.ts
@@ -5,12 +5,13 @@ import { canonicalUsername, checkUsername } from '@/lib/auth/validate'
import { createSession } from '@/lib/auth/session'
import { rateLimit } from '@/lib/ai/provider'
import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'
+import { withLogging } from '@/lib/observability'
// POST /api/auth/login — exchange username + password for a session cookie.
// One deliberately generic error message: never reveal whether the
// username exists (account enumeration).
// v0.9.1: same-origin enforced (blocks login CSRF / session fixation).
-export async function POST(req: NextRequest) {
+async function __canvix_post(req: NextRequest) {
if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })
const rl = rateLimit('auth:login', req, 10, 600)
if (!rl.ok) {
@@ -42,3 +43,7 @@ export async function POST(req: NextRequest) {
return NextResponse.json({ error: 'Sign-in failed. Please try again.' }, { status: 500 })
}
}
+
+// v0.12.5 (H7): opt-in request logging wrapper — passthrough
+// unless CANVIX_LOG=requests (see src/lib/observability.ts)
+export const POST = withLogging('POST /api/auth/login', __canvix_post)
diff --git a/src/app/api/auth/logout/route.ts b/src/app/api/auth/logout/route.ts
index e33a07e..134de62 100644
--- a/src/app/api/auth/logout/route.ts
+++ b/src/app/api/auth/logout/route.ts
@@ -1,13 +1,18 @@
import { NextRequest, NextResponse } from 'next/server'
import { destroySession } from '@/lib/auth/session'
import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'
+import { withLogging } from '@/lib/observability'
// POST /api/auth/logout — revoke the current session + clear the cookie.
// v0.9.1: same-origin enforced (a cross-site page must not be able to
// log the visitor out — logout CSRF).
-export async function POST(req: NextRequest) {
+async function __canvix_post(req: NextRequest) {
if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })
const res = NextResponse.json({ ok: true })
await destroySession(req, res)
return res
}
+
+// v0.12.5 (H7): opt-in request logging wrapper — passthrough
+// unless CANVIX_LOG=requests (see src/lib/observability.ts)
+export const POST = withLogging('POST /api/auth/logout', __canvix_post)
diff --git a/src/app/api/auth/me/route.ts b/src/app/api/auth/me/route.ts
index 76f0b04..bdb38ae 100644
--- a/src/app/api/auth/me/route.ts
+++ b/src/app/api/auth/me/route.ts
@@ -1,9 +1,14 @@
import { NextRequest, NextResponse } from 'next/server'
import { getSessionUser } from '@/lib/auth/session'
+import { withLogging } from '@/lib/observability'
// GET /api/auth/me — the signed-in user (or null). Public endpoint the
// dashboard/editor use to decide between account mode and anonymous mode.
-export async function GET(req: NextRequest) {
+async function __canvix_get(req: NextRequest) {
const user = await getSessionUser(req)
return NextResponse.json({ user: user ? { id: user.id, username: user.username, createdAt: user.createdAt } : null })
}
+
+// v0.12.5 (H7): opt-in request logging wrapper — passthrough
+// unless CANVIX_LOG=requests (see src/lib/observability.ts)
+export const GET = withLogging('GET /api/auth/me', __canvix_get)
diff --git a/src/app/api/auth/register/route.ts b/src/app/api/auth/register/route.ts
index 8de6c5f..cbcfd5a 100644
--- a/src/app/api/auth/register/route.ts
+++ b/src/app/api/auth/register/route.ts
@@ -5,12 +5,13 @@ import { canonicalUsername, checkUsername, checkPassword } from '@/lib/auth/vali
import { createSession } from '@/lib/auth/session'
import { rateLimit } from '@/lib/ai/provider'
import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'
+import { withLogging } from '@/lib/observability'
// POST /api/auth/register — create an account (username + password).
// Free forever: no email, no verification, no external provider — a
// self-hosted account system with zero moving parts beyond the DB.
// v0.9.1: same-origin enforced (blocks cross-site forced sign-ups).
-export async function POST(req: NextRequest) {
+async function __canvix_post(req: NextRequest) {
if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })
const rl = rateLimit('auth:register', req, 5, 3600)
if (!rl.ok) {
@@ -41,3 +42,7 @@ export async function POST(req: NextRequest) {
return NextResponse.json({ error: 'Could not create the account. Please try again.' }, { status: 500 })
}
}
+
+// v0.12.5 (H7): opt-in request logging wrapper — passthrough
+// unless CANVIX_LOG=requests (see src/lib/observability.ts)
+export const POST = withLogging('POST /api/auth/register', __canvix_post)
diff --git a/src/app/api/collab/[designId]/events/route.ts b/src/app/api/collab/[designId]/events/route.ts
index b4e5fb9..5abdec3 100644
--- a/src/app/api/collab/[designId]/events/route.ts
+++ b/src/app/api/collab/[designId]/events/route.ts
@@ -13,6 +13,7 @@ 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'
+import { withLogging } from '@/lib/observability'
export const runtime = 'nodejs'
export const maxDuration = 30
@@ -53,7 +54,7 @@ function serverHlc(): string {
* bounded payload size, bounded counts. Malformed events are dropped and
* reported — never crash, never 500 on bad input.
*/
-export async function POST(req: NextRequest, { params }: { params: Promise<{ designId: string }> }) {
+async function __canvix_post(req: NextRequest, { params }: { params: Promise<{ designId: string }> }) {
const { designId } = await params
try {
// v0.11.8: same-origin enforcement — every other mutating route already
@@ -188,3 +189,7 @@ export async function POST(req: NextRequest, { params }: { params: Promise<{ des
return NextResponse.json({ error: 'Could not persist collaboration events.' }, { status: 502 })
}
}
+
+// v0.12.5 (H7): opt-in request logging wrapper — passthrough
+// unless CANVIX_LOG=requests (see src/lib/observability.ts)
+export const POST = withLogging('POST /api/collab/[designId]/events', __canvix_post)
diff --git a/src/app/api/collab/[designId]/presence/route.ts b/src/app/api/collab/[designId]/presence/route.ts
index 2be63ce..bfedd24 100644
--- a/src/app/api/collab/[designId]/presence/route.ts
+++ b/src/app/api/collab/[designId]/presence/route.ts
@@ -2,6 +2,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 { withLogging } from '@/lib/observability'
export const runtime = 'nodejs'
export const maxDuration = 20
@@ -19,7 +20,7 @@ const HEX_COLOR = /^#[0-9a-fA-F]{6}$/
* POST /api/collab/[designId]/presence — heartbeat + cursor broadcast.
* Called every ~5 s (heartbeat) and throttled on cursor moves.
*/
-export async function POST(req: NextRequest, { params }: { params: Promise<{ designId: string }> }) {
+async function __canvix_post(req: NextRequest, { params }: { params: Promise<{ designId: string }> }) {
const { designId } = await params
try {
// v0.11.8: same-origin enforcement, matching every other mutating route.
@@ -96,3 +97,7 @@ export async function POST(req: NextRequest, { params }: { params: Promise<{ des
return NextResponse.json({ error: 'Could not update presence.' }, { status: 502 })
}
}
+
+// v0.12.5 (H7): opt-in request logging wrapper — passthrough
+// unless CANVIX_LOG=requests (see src/lib/observability.ts)
+export const POST = withLogging('POST /api/collab/[designId]/presence', __canvix_post)
diff --git a/src/app/api/collab/[designId]/stream/route.ts b/src/app/api/collab/[designId]/stream/route.ts
index 98f4c20..3a7e640 100644
--- a/src/app/api/collab/[designId]/stream/route.ts
+++ b/src/app/api/collab/[designId]/stream/route.ts
@@ -2,6 +2,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'
+import { withLogging } from '@/lib/observability'
export const runtime = 'nodejs'
export const dynamic = 'force-dynamic'
@@ -52,7 +53,7 @@ const MAX_STREAM_AGE_MS = Number(process.env.CANVIX_STREAM_TTL_MS ?? 240_000)
* real changes, and heartbeats (15 s) reorder rows and bump lastSeen
* without touching the key.
*/
-export async function GET(req: NextRequest, { params }: { params: Promise<{ designId: string }> }) {
+async function __canvix_get(req: NextRequest, { params }: { params: Promise<{ designId: string }> }) {
const { designId } = await params
const pid = req.nextUrl.searchParams.get('pid')?.slice(0, 40) ?? ''
let since = Number(req.nextUrl.searchParams.get('since'))
@@ -286,3 +287,7 @@ export async function GET(req: NextRequest, { params }: { params: Promise<{ desi
},
})
}
+
+// v0.12.5 (H7): opt-in request logging wrapper — passthrough
+// unless CANVIX_LOG=requests (see src/lib/observability.ts)
+export const GET = withLogging('GET /api/collab/[designId]/stream', __canvix_get)
diff --git a/src/app/api/comments/[id]/route.ts b/src/app/api/comments/[id]/route.ts
index 5cec5dd..672675c 100644
--- a/src/app/api/comments/[id]/route.ts
+++ b/src/app/api/comments/[id]/route.ts
@@ -1,5 +1,6 @@
import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'
+import { withLogging } from '@/lib/observability'
export const runtime = 'nodejs'
export const maxDuration = 30
@@ -8,7 +9,7 @@ export const maxDuration = 30
* PATCH /api/comments/[id] — resolve / reopen / edit own comment.
* DELETE /api/comments/[id] — delete own comment (or thread with replies).
*/
-export async function PATCH(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
+async function __canvix_patch(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
const { id } = await params
try {
const body = (await req.json().catch(() => ({}))) as {
@@ -51,7 +52,7 @@ export async function PATCH(req: NextRequest, { params }: { params: Promise<{ id
}
}
-export async function DELETE(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
+async function __canvix_delete(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
const { id } = await params
try {
const actorId = req.nextUrl.searchParams.get('actorId')?.replace(/[^a-zA-Z0-9_-]/g, '').slice(0, 40) ?? ''
@@ -80,3 +81,8 @@ export async function DELETE(req: NextRequest, { params }: { params: Promise<{ i
return NextResponse.json({ error: 'Could not delete the comment.' }, { status: 502 })
}
}
+
+// v0.12.5 (H7): opt-in request logging wrapper — passthrough
+// unless CANVIX_LOG=requests (see src/lib/observability.ts)
+export const PATCH = withLogging('PATCH /api/comments/[id]', __canvix_patch)
+export const DELETE = withLogging('DELETE /api/comments/[id]', __canvix_delete)
diff --git a/src/app/api/designs/[id]/adopt/route.ts b/src/app/api/designs/[id]/adopt/route.ts
index 7fd438a..6c82fb0 100644
--- a/src/app/api/designs/[id]/adopt/route.ts
+++ b/src/app/api/designs/[id]/adopt/route.ts
@@ -4,6 +4,7 @@ import { getSessionUser } from '@/lib/auth/session'
import { anonHashFrom } from '@/lib/auth/anon'
import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'
import { NOT_YOUR_DESIGN } from '@/lib/auth/design-guard'
+import { withLogging } from '@/lib/observability'
// POST /api/designs/[id]/adopt — deliberately claim ONE ownerless
// design into the signed-in account.
@@ -17,7 +18,7 @@ import { NOT_YOUR_DESIGN } from '@/lib/auth/design-guard'
//
// The claim itself is a single conditional updateMany (WHERE ownerId IS
// NULL), so two racing accounts can never both win.
-export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
+async function __canvix_post(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })
const user = await getSessionUser(req)
if (!user) {
@@ -61,3 +62,7 @@ export async function POST(req: NextRequest, { params }: { params: Promise<{ id:
return NextResponse.json({ error: 'Failed to adopt design.' }, { status: 500 })
}
}
+
+// v0.12.5 (H7): opt-in request logging wrapper — passthrough
+// unless CANVIX_LOG=requests (see src/lib/observability.ts)
+export const POST = withLogging('POST /api/designs/[id]/adopt', __canvix_post)
diff --git a/src/app/api/designs/[id]/comments/route.ts b/src/app/api/designs/[id]/comments/route.ts
index 39193e5..1a55400 100644
--- a/src/app/api/designs/[id]/comments/route.ts
+++ b/src/app/api/designs/[id]/comments/route.ts
@@ -1,6 +1,7 @@
import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'
import { checkRateLimit, rateLimitResponse } from '@/lib/rate-limit'
+import { withLogging } from '@/lib/observability'
export const runtime = 'nodejs'
export const maxDuration = 30
@@ -11,7 +12,7 @@ const HEX_COLOR = /^#[0-9a-fA-F]{6}$/
* GET /api/designs/[id]/comments — all comment threads for a design.
* POST — add a comment (top-level pin or reply via parentId).
*/
-export async function GET(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
+async function __canvix_get(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
const { id } = await params
try {
const comments = await db.comment.findMany({
@@ -55,7 +56,7 @@ interface CommentBody {
parentId?: string
}
-export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
+async function __canvix_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')
@@ -144,3 +145,8 @@ export async function POST(req: NextRequest, { params }: { params: Promise<{ id:
return NextResponse.json({ error: 'Could not create the comment.' }, { status: 502 })
}
}
+
+// v0.12.5 (H7): opt-in request logging wrapper — passthrough
+// unless CANVIX_LOG=requests (see src/lib/observability.ts)
+export const GET = withLogging('GET /api/designs/[id]/comments', __canvix_get)
+export const POST = withLogging('POST /api/designs/[id]/comments', __canvix_post)
diff --git a/src/app/api/designs/[id]/restore/route.ts b/src/app/api/designs/[id]/restore/route.ts
index b0b68ac..346d840 100644
--- a/src/app/api/designs/[id]/restore/route.ts
+++ b/src/app/api/designs/[id]/restore/route.ts
@@ -2,11 +2,12 @@ import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'
import { resolveDesignAccess, NOT_YOUR_DESIGN } from '@/lib/auth/design-guard'
import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'
+import { withLogging } from '@/lib/observability'
// POST /api/designs/[id]/restore — restore a design from the Trash.
// v0.9: owner-only for owned designs (403 otherwise); ownerless unchanged.
// v0.9.1: same-origin enforced (CSRF).
-export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
+async function __canvix_post(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })
try {
const { id } = await params
@@ -23,3 +24,7 @@ export async function POST(req: NextRequest, { params }: { params: Promise<{ id:
return NextResponse.json({ error: 'Failed to restore design' }, { status: 500 })
}
}
+
+// v0.12.5 (H7): opt-in request logging wrapper — passthrough
+// unless CANVIX_LOG=requests (see src/lib/observability.ts)
+export const POST = withLogging('POST /api/designs/[id]/restore', __canvix_post)
diff --git a/src/app/api/designs/[id]/route.ts b/src/app/api/designs/[id]/route.ts
index 2dca51f..d79f71e 100644
--- a/src/app/api/designs/[id]/route.ts
+++ b/src/app/api/designs/[id]/route.ts
@@ -6,6 +6,7 @@ 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'
+import { withLogging } from '@/lib/observability'
// Normalise incoming pages payload (accepts object or legacy JSON string)
// into a value suitable for the Postgres jsonb column.
@@ -27,7 +28,7 @@ function asPages(value: unknown): PageData[] {
// v0.10: also returns `seq` (the design's current event-log cursor) so a
// freshly loaded editor does not replay pre-load events over a document
// that already contains them.
-export async function GET(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
+async function __canvix_get(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
try {
const { id } = await params
const access = await resolveDesignAccess(req, id)
@@ -57,7 +58,7 @@ export async function GET(req: NextRequest, { params }: { params: Promise<{ id:
// tab was offline while others saved), the server MERGES element-wise by
// HLC stamps (`_m`) + tombstones instead of clobbering — the same pure
// rule every client applies, so all replicas converge.
-export async function PUT(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
+async function __canvix_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
@@ -119,7 +120,7 @@ export async function PUT(req: NextRequest, { params }: { params: Promise<{ id:
// ?permanent=1 → delete permanently (also removes version snapshots).
// v0.9: ownerless designs stay link-editable; owned designs only delete
// for their owner (403 otherwise). v0.9.1: same-origin enforced (CSRF).
-export async function DELETE(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
+async function __canvix_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)
@@ -140,3 +141,9 @@ export async function DELETE(req: NextRequest, { params }: { params: Promise<{ i
return NextResponse.json({ error: 'Failed to delete design' }, { status: 500 })
}
}
+
+// v0.12.5 (H7): opt-in request logging wrapper — passthrough
+// unless CANVIX_LOG=requests (see src/lib/observability.ts)
+export const GET = withLogging('GET /api/designs/[id]', __canvix_get)
+export const PUT = withLogging('PUT /api/designs/[id]', __canvix_put)
+export const DELETE = withLogging('DELETE /api/designs/[id]', __canvix_delete)
diff --git a/src/app/api/designs/[id]/versions/route.ts b/src/app/api/designs/[id]/versions/route.ts
index e21a81d..d0adbb0 100644
--- a/src/app/api/designs/[id]/versions/route.ts
+++ b/src/app/api/designs/[id]/versions/route.ts
@@ -2,9 +2,10 @@ import { NextRequest, NextResponse } from 'next/server'
import { Prisma } from '@/generated/prisma/client'
import { db } from '@/lib/db'
import { resolveDesignAccess, NOT_YOUR_DESIGN } from '@/lib/auth/design-guard'
+import { withLogging } from '@/lib/observability'
// GET /api/designs/[id]/versions — list server-side version snapshots (newest first)
-export async function GET(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
+async function __canvix_get(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
try {
const { id } = await params
const versions = await db.designVersion.findMany({
@@ -32,7 +33,7 @@ export async function GET(_req: NextRequest, { params }: { params: Promise<{ id:
// POST /api/designs/[id]/versions — save a new version snapshot
// v0.9: owner-only for owned designs (403 otherwise); ownerless unchanged.
-export async function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
+async function __canvix_post(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
try {
const { id } = await params
const access = await resolveDesignAccess(req, id)
@@ -83,3 +84,8 @@ export async function POST(req: NextRequest, { params }: { params: Promise<{ id:
return NextResponse.json({ error: 'Failed to save version' }, { status: 500 })
}
}
+
+// v0.12.5 (H7): opt-in request logging wrapper — passthrough
+// unless CANVIX_LOG=requests (see src/lib/observability.ts)
+export const GET = withLogging('GET /api/designs/[id]/versions', __canvix_get)
+export const POST = withLogging('POST /api/designs/[id]/versions', __canvix_post)
diff --git a/src/app/api/designs/adopt-all/route.ts b/src/app/api/designs/adopt-all/route.ts
index a5fe4d5..bd43ad5 100644
--- a/src/app/api/designs/adopt-all/route.ts
+++ b/src/app/api/designs/adopt-all/route.ts
@@ -3,6 +3,7 @@ import { db } from '@/lib/db'
import { getSessionUser } from '@/lib/auth/session'
import { anonHashFrom } from '@/lib/auth/anon'
import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'
+import { withLogging } from '@/lib/observability'
// POST /api/designs/adopt-all — one-click migration into an account.
//
@@ -16,7 +17,7 @@ import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'
// attributed to OTHER browsers remain untouchable.
//
// Idempotent; already-owned designs are excluded by the query itself.
-export async function POST(req: NextRequest) {
+async function __canvix_post(req: NextRequest) {
if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })
const user = await getSessionUser(req)
if (!user) {
@@ -54,3 +55,7 @@ export async function POST(req: NextRequest) {
return NextResponse.json({ error: 'Failed to adopt designs.' }, { status: 500 })
}
}
+
+// v0.12.5 (H7): opt-in request logging wrapper — passthrough
+// unless CANVIX_LOG=requests (see src/lib/observability.ts)
+export const POST = withLogging('POST /api/designs/adopt-all', __canvix_post)
diff --git a/src/app/api/designs/route.ts b/src/app/api/designs/route.ts
index ad2700b..7f392a6 100644
--- a/src/app/api/designs/route.ts
+++ b/src/app/api/designs/route.ts
@@ -6,6 +6,7 @@ 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'
+import { withLogging } from '@/lib/observability'
// Normalise incoming pages payload (accepts object or legacy JSON string)
// into a value suitable for the Postgres jsonb column.
@@ -38,7 +39,7 @@ function toPages(value: unknown): Prisma.InputJsonValue {
// 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) {
+async function __canvix_get(req: NextRequest) {
try {
const trash = req.nextUrl.searchParams.get('trash') === '1'
const cursor = req.nextUrl.searchParams.get('cursor')
@@ -110,7 +111,7 @@ export async function GET(req: NextRequest) {
// v0.9.1: anonymous creations are attributed to the creating browser
// (anonKey = sha256 of the canvix_anon cookie, minted on first use) so
// adopt-all can never claim someone else's work.
-export async function POST(req: NextRequest) {
+async function __canvix_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.
@@ -157,3 +158,8 @@ export async function POST(req: NextRequest) {
return dbErrorResponse(error, 'POST /api/designs')
}
}
+
+// v0.12.5 (H7): opt-in request logging wrapper — passthrough
+// unless CANVIX_LOG=requests (see src/lib/observability.ts)
+export const GET = withLogging('GET /api/designs', __canvix_get)
+export const POST = withLogging('POST /api/designs', __canvix_post)
diff --git a/src/app/api/health/route.ts b/src/app/api/health/route.ts
index cbb7e3a..4a789e8 100644
--- a/src/app/api/health/route.ts
+++ b/src/app/api/health/route.ts
@@ -1,12 +1,19 @@
-import { NextResponse } from 'next/server'
+import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'
import { describeDatabaseUrl } from '@/lib/db-url'
+import { APP_VERSION } from '@/lib/observability'
+import { withLogging } from '@/lib/observability'
// GET /api/health — one-shot setup diagnostics.
// Tells you whether the database is reachable, migrated and seeded,
// and prints the exact fix when it is not. Point a browser here first
// whenever designs/templates fail to open after a host switch
// (e.g. Neon → Supabase).
+//
+// v0.12.5 (H7): ?v=2 adds the observability payload — aggregate
+// counts (never ids), a DB latency probe and the app version —
+// behind an explicit opt-in so plain liveness probes stay as cheap
+// as they were. v1's shape is otherwise unchanged (additive `v`).
const REQUIRED_TABLES = [
'Design',
@@ -21,9 +28,10 @@ const REQUIRED_TABLES = [
'Session',
] as const
-export async function GET() {
+async function __canvix_get(req: NextRequest) {
const url = process.env.DATABASE_URL
const info = describeDatabaseUrl(url)
+ const wantsV2 = req.nextUrl.searchParams.get('v') === '2'
// 1. no DATABASE_URL at all
if (!url) {
@@ -38,7 +46,8 @@ export async function GET() {
)
}
- // 2. reachable at all?
+ // 2. reachable at all? (also the v2 latency probe)
+ const probeStart = Date.now()
try {
await db.$queryRaw`SELECT 1`
} catch (error) {
@@ -59,6 +68,7 @@ export async function GET() {
{ status: 503 }
)
}
+ const dbLatencyMs = Date.now() - probeStart
// 3. migrated? (all tables present)
// (::text — the rust-free query compiler, unlike the classic engine,
@@ -100,20 +110,62 @@ export async function GET() {
)
}
- // 5. all green
+ // 5. all green (v1: unchanged shape + explicit version tag)
+ if (!wantsV2) {
+ return NextResponse.json(
+ {
+ v: 1,
+ 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',
+ },
+ }
+ )
+ }
+
+ // 5b. v2: the observability payload — counts only, never ids
+ // (H7 acceptance: “returns counts without leaking ids”)
+ const [designs, users, media, versions, comments] = await Promise.all([
+ db.$queryRaw<{ count: bigint }[]>`SELECT COUNT(*)::bigint AS count FROM "Design" WHERE "deletedAt" IS NULL`,
+ db.$queryRaw<{ count: bigint }[]>`SELECT COUNT(*)::bigint AS count FROM "User"`,
+ db.$queryRaw<{ count: bigint; bytes: bigint | null }[]>`SELECT COUNT(*)::bigint AS count, COALESCE(SUM("size"), 0)::bigint AS bytes FROM "Media" WHERE "finalizedAt" IS NOT NULL`,
+ db.$queryRaw<{ count: bigint }[]>`SELECT COUNT(*)::bigint AS count FROM "DesignVersion"`,
+ db.$queryRaw<{ count: bigint }[]>`SELECT COUNT(*)::bigint AS count FROM "Comment"`,
+ ])
+ const n = (r: { count: bigint }[] | undefined) => Number(r?.[0]?.count ?? 0)
return NextResponse.json(
{
+ v: 2,
ok: true,
database: { kind: info.kind, host: info.host, database: info.database },
templates,
+ counts: {
+ designs: n(designs),
+ users: n(users),
+ media: n(media),
+ mediaBytes: Number(media?.[0]?.bytes ?? 0),
+ versions: n(versions),
+ comments: n(comments),
+ },
+ db: { latencyMs: dbLatencyMs },
+ app: { version: APP_VERSION, uptimeSec: Math.round(process.uptime()) },
},
{
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',
},
}
)
}
+
+// v0.12.5 (H7): opt-in request logging wrapper — passthrough
+// unless CANVIX_LOG=requests (see src/lib/observability.ts)
+export const GET = withLogging('GET /api/health', __canvix_get)
diff --git a/src/app/api/mcp/route.ts b/src/app/api/mcp/route.ts
index d817d2d..9557842 100644
--- a/src/app/api/mcp/route.ts
+++ b/src/app/api/mcp/route.ts
@@ -1,5 +1,6 @@
import { NextRequest, NextResponse } from 'next/server'
import { checkAuth, handleMcpRequest, mcpRateLimit, mcpTokenConfigured } from '@/lib/mcp/server'
+import { withLogging } from '@/lib/observability'
export const runtime = 'nodejs'
export const maxDuration = 60
@@ -14,7 +15,7 @@ export const maxDuration = 60
// GET: 405 (no server-initiated SSE stream — spec-compliant)
// ─────────────────────────────────────────────────────────────
-export async function POST(req: NextRequest) {
+async function __canvix_post(req: NextRequest) {
const authError = checkAuth(req)
if (authError) {
const status = authError.error?.code === -32001 ? 401 : 503
@@ -34,26 +35,34 @@ export async function POST(req: NextRequest) {
}
// stateless server: no SSE stream for server-initiated messages
-export async function GET() {
+async function __canvix_get() {
return NextResponse.json(
{ jsonrpc: '2.0', id: null, error: { code: -32000, message: 'This MCP server is stateless — use POST. GET streams are not offered.' } },
{ status: 405, headers: { Allow: 'POST' } }
)
}
-export async function DELETE() {
+async function __canvix_delete() {
// no sessions to terminate (stateless)
return new NextResponse(null, { status: 405, headers: { Allow: 'POST' } })
}
-export async function PUT() {
+async function __canvix_put() {
return new NextResponse(null, { status: 405, headers: { Allow: 'POST' } })
}
// let capability probes know whether the server is configured
-export async function OPTIONS() {
+async function __canvix_options() {
return NextResponse.json(
{ mcp: mcpTokenConfigured() ? 'enabled' : 'disabled', transport: 'streamable-http', endpoint: '/api/mcp' },
{ status: 200, headers: { Allow: 'POST, OPTIONS' } }
)
}
+
+// v0.12.5 (H7): opt-in request logging wrapper — passthrough
+// unless CANVIX_LOG=requests (see src/lib/observability.ts)
+export const POST = withLogging('POST /api/mcp', __canvix_post)
+export const GET = withLogging('GET /api/mcp', __canvix_get)
+export const DELETE = withLogging('DELETE /api/mcp', __canvix_delete)
+export const PUT = withLogging('PUT /api/mcp', __canvix_put)
+export const OPTIONS = withLogging('OPTIONS /api/mcp', __canvix_options)
diff --git a/src/app/api/media/[id]/route.ts b/src/app/api/media/[id]/route.ts
index 2fb0753..16cf7e0 100644
--- a/src/app/api/media/[id]/route.ts
+++ b/src/app/api/media/[id]/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 { withLogging } from '@/lib/observability'
export const runtime = 'nodejs'
export const maxDuration = 30
@@ -13,7 +14,7 @@ export const maxDuration = 30
const MAX_CHUNK = 3 * 1024 * 1024 + 64 * 1024 // transport headroom over the client chunk size
/** PATCH /api/media/[id]?offset=<n> — append one chunk (raw body). */
-export async function PATCH(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
+async function __canvix_patch(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })
const { id } = await params
try {
@@ -48,7 +49,7 @@ export async function PATCH(req: NextRequest, { params }: { params: Promise<{ id
}
/** PUT /api/media/[id] — finalize: verify length, mark complete. */
-export async function PUT(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
+async function __canvix_put(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })
const { id } = await params
try {
@@ -78,7 +79,7 @@ export async function PUT(req: NextRequest, { params }: { params: Promise<{ id:
/** GET /api/media/[id] — stream the bytes (Range-aware for <audio>/<video>
* seeking). Finalized media only; immutable content-addressed by id. */
-export async function GET(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
+async function __canvix_get(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
const { id } = await params
try {
const rows = await db.$queryRawUnsafe<{ bytes: Buffer; mime: string }[]>(
@@ -131,3 +132,9 @@ export async function GET(req: NextRequest, { params }: { params: Promise<{ id:
return new Response('Media unavailable', { status: 500 })
}
}
+
+// v0.12.5 (H7): opt-in request logging wrapper — passthrough
+// unless CANVIX_LOG=requests (see src/lib/observability.ts)
+export const PATCH = withLogging('PATCH /api/media/[id]', __canvix_patch)
+export const PUT = withLogging('PUT /api/media/[id]', __canvix_put)
+export const GET = withLogging('GET /api/media/[id]', __canvix_get)
diff --git a/src/app/api/media/route.ts b/src/app/api/media/route.ts
index 491b7e9..e488e9d 100644
--- a/src/app/api/media/route.ts
+++ b/src/app/api/media/route.ts
@@ -4,6 +4,7 @@ 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'
+import { withLogging } from '@/lib/observability'
export const runtime = 'nodejs'
export const maxDuration = 30
@@ -20,7 +21,7 @@ const MAX_MEDIA_MB = Math.max(1, Number(process.env.CANVIX_MAX_MEDIA_MB ?? 32))
const ALLOWED_PREFIXES = ['audio/', 'video/']
-export async function POST(req: NextRequest) {
+async function __canvix_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).
@@ -71,3 +72,7 @@ export async function POST(req: NextRequest) {
return NextResponse.json({ error: 'Could not start the upload.' }, { status: 500 })
}
}
+
+// v0.12.5 (H7): opt-in request logging wrapper — passthrough
+// unless CANVIX_LOG=requests (see src/lib/observability.ts)
+export const POST = withLogging('POST /api/media', __canvix_post)
diff --git a/src/app/api/photos/search/route.ts b/src/app/api/photos/search/route.ts
index b131bff..3e9b577 100644
--- a/src/app/api/photos/search/route.ts
+++ b/src/app/api/photos/search/route.ts
@@ -1,5 +1,6 @@
import { NextRequest, NextResponse } from 'next/server'
import { withProvider } from '@/lib/ai/provider'
+import { withLogging } from '@/lib/observability'
export const runtime = 'nodejs'
export const maxDuration = 30
@@ -10,7 +11,7 @@ interface SearchBody {
}
/** POST /api/photos/search — runtime stock-photo search (Canva-like photo search). */
-export async function POST(req: NextRequest) {
+async function __canvix_post(req: NextRequest) {
const body = (await req.json().catch(() => ({}))) as SearchBody
const query = (body.query ?? '').trim().slice(0, 120)
if (!query) return NextResponse.json({ error: 'A query is required.' }, { status: 400 })
@@ -30,3 +31,7 @@ export async function POST(req: NextRequest) {
return NextResponse.json({ query, count: results.length, results })
})
}
+
+// v0.12.5 (H7): opt-in request logging wrapper — passthrough
+// unless CANVIX_LOG=requests (see src/lib/observability.ts)
+export const POST = withLogging('POST /api/photos/search', __canvix_post)
diff --git a/src/app/api/templates/route.ts b/src/app/api/templates/route.ts
index e2b2f9f..09233b0 100644
--- a/src/app/api/templates/route.ts
+++ b/src/app/api/templates/route.ts
@@ -1,6 +1,7 @@
-import { NextResponse } from 'next/server'
+import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'
import { dbErrorResponse } from '@/lib/db-errors'
+import { withLogging } from '@/lib/observability'
// GET /api/templates — built-in template library (from DB, falls back empty)
//
@@ -10,7 +11,9 @@ import { dbErrorResponse } from '@/lib/db-errors'
// 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() {
+// (_req: Next always passes the request; the handler just ignores it —
+// the logging wrapper wants it)
+async function __canvix_get(_req: NextRequest) {
try {
const templates = await db.template.findMany({
orderBy: { createdAt: 'asc' },
@@ -38,3 +41,7 @@ export async function GET() {
return dbErrorResponse(error, 'GET /api/templates')
}
}
+
+// v0.12.5 (H7): opt-in request logging wrapper — passthrough
+// unless CANVIX_LOG=requests (see src/lib/observability.ts)
+export const GET = withLogging('GET /api/templates', __canvix_get)
diff --git a/src/app/api/templates/templates.test.ts b/src/app/api/templates/templates.test.ts
index 819d9ff..6909d56 100644
--- a/src/app/api/templates/templates.test.ts
+++ b/src/app/api/templates/templates.test.ts
@@ -2,6 +2,7 @@
// public payload must be edge-cacheable so it stops counting against
// Fluid CPU + Fast Origin Transfer on every request.
+import { NextRequest } from 'next/server'
import { describe, it, expect, vi, beforeEach } from 'vitest'
const dbMock = vi.hoisted(() => ({
@@ -30,7 +31,7 @@ beforeEach(() => {
describe('GET /api/templates (v0.9.2 CDN caching)', () => {
it('serves the full template list with edge-cache headers', async () => {
- const res = await GET()
+ const res = await GET(new NextRequest('http://canvix.test/api/templates'))
expect(res.status).toBe(200)
const cc = res.headers.get('cache-control') ?? ''
expect(cc).toContain('public')
@@ -43,7 +44,7 @@ describe('GET /api/templates (v0.9.2 CDN caching)', () => {
it('still surfaces classified DB errors (never a bare 500)', async () => {
dbMock.template.findMany.mockRejectedValue(new Error('connect ECONNREFUSED'))
- const res = await GET()
+ const res = await GET(new NextRequest('http://canvix.test/api/templates'))
expect(res.status).toBeGreaterThanOrEqual(500)
const body = await res.json()
expect(typeof body.error).toBe('string')
diff --git a/src/app/api/versions/[id]/route.ts b/src/app/api/versions/[id]/route.ts
index f12f663..45bffe9 100644
--- a/src/app/api/versions/[id]/route.ts
+++ b/src/app/api/versions/[id]/route.ts
@@ -1,8 +1,9 @@
import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'
+import { withLogging } from '@/lib/observability'
// DELETE /api/versions/[id] — remove one saved version snapshot
-export async function DELETE(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
+async function __canvix_delete(_req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
try {
const { id } = await params
await db.designVersion.delete({ where: { id } })
@@ -12,3 +13,7 @@ export async function DELETE(_req: NextRequest, { params }: { params: Promise<{
return NextResponse.json({ error: 'Failed to delete version' }, { status: 500 })
}
}
+
+// v0.12.5 (H7): opt-in request logging wrapper — passthrough
+// unless CANVIX_LOG=requests (see src/lib/observability.ts)
+export const DELETE = withLogging('DELETE /api/versions/[id]', __canvix_delete)
diff --git a/src/instrumentation.ts b/src/instrumentation.ts
new file mode 100644
index 0000000..c4ed596
--- /dev/null
+++ b/src/instrumentation.ts
@@ -0,0 +1,27 @@
+// src/instrumentation.ts (v0.12.5, roadmap H7) — Next's server
+// lifecycle hooks, used for exactly one thing: the opt-in error
+// webhook. `onRequestError` fires for every UNHANDLED error across
+// pages, route handlers, server actions and middleware — Next's
+// own route-catch — so one file instruments the whole app.
+//
+// When CANVIX_ERROR_WEBHOOK_URL is unset (the default) this file
+// does nothing beyond a structured local log line. See
+// src/lib/observability.ts for the payload contract.
+import { buildErrorReport, logLine, postErrorWebhook } from './lib/observability'
+
+export async function onRequestError(
+ error: unknown,
+ request: { path: string; method: string; headers: Record<string, string | string[] | undefined> },
+ context: { routePath: string; routeType: string },
+): Promise<void> {
+ const report = buildErrorReport(error, request, context)
+ logLine('error', 'unhandled_request_error', {
+ message: report.message,
+ path: report.path,
+ method: report.method,
+ route_type: report.routeType,
+ route_path: context.routePath,
+ app_version: report.appVersion,
+ })
+ await postErrorWebhook(report)
+}
diff --git a/src/lib/observability.test.ts b/src/lib/observability.test.ts
new file mode 100644
index 0000000..4cb17bc
--- /dev/null
+++ b/src/lib/observability.test.ts
@@ -0,0 +1,181 @@
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'
+import { NextRequest } from 'next/server'
+import {
+ buildErrorReport,
+ logApiRequest,
+ requestLoggingEnabled,
+ withLogging,
+} from './observability'
+
+// H7: the observability floor — logging is opt-in, the wrapper is a
+// zero-behavior-change passthrough by default, and the webhook
+// payload never carries more than the documented fields.
+
+beforeEach(() => {
+ delete process.env.CANVIX_LOG
+ vi.restoreAllMocks()
+})
+
+afterEach(() => {
+ delete process.env.CANVIX_LOG
+})
+
+describe('request logging gate', () => {
+ it('is off by default and for unknown values', () => {
+ expect(requestLoggingEnabled()).toBe(false)
+ process.env.CANVIX_LOG = 'off'
+ expect(requestLoggingEnabled()).toBe(false)
+ process.env.CANVIX_LOG = 'requests'
+ expect(requestLoggingEnabled()).toBe(true)
+ process.env.CANVIX_LOG = '1'
+ expect(requestLoggingEnabled()).toBe(true)
+ })
+})
+
+describe('withLogging', () => {
+ it('is a passthrough (same response, no logs) when disabled', async () => {
+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {})
+ const handler = vi.fn(async () => new Response('ok', { status: 201 }))
+ const wrapped = withLogging('GET /api/x', handler)
+ const res = await wrapped(new NextRequest('http://canvix.test/api/x?secret=1'))
+ expect(res.status).toBe(201)
+ expect(await res.text()).toBe('ok')
+ expect(handler).toHaveBeenCalledOnce()
+ expect(logSpy).not.toHaveBeenCalled()
+ })
+
+ it('logs one JSON line with method, path (no query), status, duration', async () => {
+ process.env.CANVIX_LOG = 'requests'
+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {})
+ const wrapped = withLogging('GET /api/designs', async () => new Response('ok'))
+ const res = await wrapped(new NextRequest('http://canvix.test/api/designs?cursor=abc&id=x'))
+ expect(res.status).toBe(200)
+ expect(logSpy).toHaveBeenCalledOnce()
+ const line = JSON.parse(logSpy.mock.calls[0][0] as string)
+ expect(line.event).toBe('http_request')
+ expect(line.method).toBe('GET')
+ // privacy: the query string (cursor/id data) must not be logged
+ expect(line.path).toBe('/api/designs')
+ expect(String(line.path)).not.toContain('cursor')
+ expect(line.status).toBe(200)
+ expect(typeof line.duration_ms).toBe('number')
+ expect(typeof line.ts).toBe('string')
+ })
+
+ it('logs status 500 and rethrows when the handler throws', async () => {
+ process.env.CANVIX_LOG = 'requests'
+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {})
+ const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {})
+ const wrapped = withLogging('POST /api/x', async () => {
+ throw new Error('boom')
+ })
+ await expect(wrapped(new NextRequest('http://canvix.test/api/x', { method: 'POST' }))).rejects.toThrow('boom')
+ const line = JSON.parse(logSpy.mock.calls[0][0] as string)
+ expect(line.status).toBe(500)
+ expect(errSpy).not.toHaveBeenCalled() // the wrapper logs via the info line
+ })
+
+ it('passes route params through untouched (typed second arg)', async () => {
+ const handler = vi.fn(
+ async (_req: NextRequest, ctx: { params: Promise<{ id: string }> }) =>
+ new Response(JSON.stringify(ctx ? 'has-ctx' : 'no-ctx')),
+ )
+ const wrapped = withLogging('PUT /api/designs/[id]', handler)
+ const ctx = { params: Promise.resolve({ id: 'd1' }) }
+ const res = await wrapped(
+ new NextRequest('http://canvix.test/api/designs/d1', { method: 'PUT' }),
+ ctx,
+ )
+ expect(handler).toHaveBeenCalledWith(expect.anything(), ctx)
+ expect(res.status).toBe(200)
+ })
+})
+
+describe('logApiRequest (shape)', () => {
+ it('rounds duration and carries a request id when present', () => {
+ const logSpy = vi.spyOn(console, 'log').mockImplementation(() => {})
+ logApiRequest({ method: 'GET', path: '/api/health', status: 200, durationMs: 12.3456, requestId: 'r-1' })
+ const line = JSON.parse(logSpy.mock.calls[0][0] as string)
+ expect(line.duration_ms).toBe(12.35)
+ expect(line.request_id).toBe('r-1')
+ })
+})
+
+describe('buildErrorReport (webhook payload)', () => {
+ it('carries the documented fields, bounded and id-free', () => {
+ const report = buildErrorReport(
+ new Error('exploded'),
+ { path: '/api/designs/d123', method: 'PUT' },
+ { routeType: 'route' },
+ )
+ expect(report.message).toBe('Error: exploded')
+ expect(report.path).toBe('/api/designs/d123')
+ expect(report.method).toBe('PUT')
+ expect(report.routeType).toBe('route')
+ expect(typeof report.appVersion).toBe('string')
+ expect(typeof report.at).toBe('string')
+ expect(Object.keys(report).sort()).toEqual(
+ ['appVersion', 'at', 'message', 'method', 'path', 'routeType', 'stackHead'].sort(),
+ )
+ })
+
+ it('stringifies non-Error throws and bounds the message', () => {
+ const report = buildErrorReport('just a string', { path: '/x', method: 'GET' })
+ expect(report.message).toBe('Error: just a string')
+ const long = buildErrorReport(new Error('x'.repeat(2000)), { path: '/x', method: 'GET' })
+ expect(report.message.length).toBeLessThanOrEqual(500)
+ })
+})
+
+describe('error webhook wiring (instrumentation.onRequestError)', () => {
+ it('POSTs the report to CANVIX_ERROR_WEBHOOK_URL over real HTTP', async () => {
+ // local receiver on an ephemeral port
+ const { createServer } = await import('node:http')
+ const received: Array<{ body: string; contentType: string }> = []
+ const server = createServer((req, res) => {
+ let body = ''
+ req.on('data', (c) => (body += c))
+ req.on('end', () => {
+ received.push({ body, contentType: req.headers['content-type'] ?? '' })
+ res.writeHead(204)
+ res.end()
+ })
+ })
+ await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
+ const port = (server.address() as { port: number }).port
+ process.env.CANVIX_ERROR_WEBHOOK_URL = `http://127.0.0.1:${port}/hook`
+
+ vi.spyOn(console, 'error').mockImplementation(() => {})
+ // the real hook, exactly as Next invokes it
+ const { onRequestError } = await import('../instrumentation')
+ await onRequestError(
+ new Error('route blew up'),
+ { path: '/api/designs/xyz?cursor=1', method: 'PUT', headers: {} },
+ { routePath: '/api/designs/[id]/route', routeType: 'route' },
+ )
+
+ // fire-and-forget POST lands shortly
+ await new Promise((resolve) => setTimeout(resolve, 300))
+ expect(received).toHaveLength(1)
+ expect(received[0].contentType).toBe('application/json')
+ const payload = JSON.parse(received[0].body)
+ expect(payload.message).toBe('Error: route blew up')
+ expect(payload.method).toBe('PUT')
+ expect(payload.routeType).toBe('route')
+
+ delete process.env.CANVIX_ERROR_WEBHOOK_URL
+ await new Promise<void>((resolve) => server.close(() => resolve()))
+ })
+
+ it('does nothing (no fetch) when the webhook is unset', async () => {
+ delete process.env.CANVIX_ERROR_WEBHOOK_URL
+ vi.spyOn(console, 'error').mockImplementation(() => {})
+ const { onRequestError } = await import('../instrumentation')
+ // resolves without touching the network
+ await onRequestError(
+ new Error('quiet'),
+ { path: '/x', method: 'GET', headers: {} },
+ { routePath: '/x', routeType: 'route' },
+ )
+ })
+})
diff --git a/src/lib/observability.ts b/src/lib/observability.ts
new file mode 100644
index 0000000..c8f38ce
--- /dev/null
+++ b/src/lib/observability.ts
@@ -0,0 +1,160 @@
+// ─────────────────────────────────────────────────────────────
+// Observability floor (v0.12.5, roadmap H7 — research/V0118-
+// ROADMAP-RESEARCH.md §5.1). Three opt-in, zero-dependency
+// primitives for the self-hoster:
+//
+// 1. Structured request logging — CANVIX_LOG=requests turns every
+// API request into one JSON line on stdout (method, path,
+// status, duration). OFF by default: a design tool's server
+// logs are the self-hoster's to read, and silent-by-default
+// is the privacy-correct choice. Query strings are
+// deliberately NOT logged (they carry design ids and cursor
+// data); IPs are not logged either.
+// 2. /api/health?v=2 — aggregate counts + a DB latency probe
+// (see src/app/api/health/route.ts). Counts only, never ids.
+// 3. Error webhook — CANVIX_ERROR_WEBHOOK_URL receives a POST
+// for every unhandled request error (src/instrumentation.ts,
+// Next's onRequestError hook). Also off unless configured.
+//
+// Everything here is stdlib-only (console, fetch, Date) so it runs
+// on every runtime Canvix supports — Node, Bun, workerd.
+// ─────────────────────────────────────────────────────────────
+
+import type { NextRequest } from 'next/server'
+
+/** The app version answering requests — from package.json at build time. */
+export const APP_VERSION = process.env.npm_package_version ?? 'unknown'
+
+export type LogLevel = 'debug' | 'info' | 'warn' | 'error'
+
+/** One structured JSON line — machine-greppable, human-readable. */
+export function logLine(level: LogLevel, event: string, fields: Record<string, unknown> = {}): void {
+ const line = JSON.stringify({ ts: new Date().toISOString(), level, event, ...fields })
+ if (level === 'error') console.error(line)
+ else if (level === 'warn') console.warn(line)
+ else console.log(line)
+}
+
+// ── 1. request logging ────────────────────────────────────────
+
+export function requestLoggingEnabled(): boolean {
+ const value = process.env.CANVIX_LOG
+ return value === 'requests' || value === '1' || value === 'true'
+}
+
+/** Path without the query string — privacy: ids and cursors stay out. */
+function loggedPath(url: string): string {
+ const q = url.indexOf('?')
+ return q === -1 ? url : url.slice(0, q)
+}
+
+export interface ApiRequestLog {
+ method: string
+ path: string
+ status: number
+ durationMs: number
+ requestId?: string
+}
+
+export function logApiRequest(entry: ApiRequestLog): void {
+ logLine('info', 'http_request', {
+ method: entry.method,
+ path: loggedPath(entry.path),
+ status: entry.status,
+ duration_ms: Math.round(entry.durationMs * 100) / 100,
+ ...(entry.requestId ? { request_id: entry.requestId } : {}),
+ })
+}
+
+/**
+ * Wrap an API route handler with opt-in request logging. Zero-cost
+ * passthrough when CANVIX_LOG is unset (the default): the wrapper
+ * checks once per call and never touches the response otherwise.
+ * Never mutates the response — the handler's headers, streams and
+ * status codes pass through untouched (the SSE route included).
+ */
+export function withLogging<A extends unknown[]>(
+ name: string,
+ handler: (req: NextRequest, ...args: A) => Promise<Response>,
+): (req: NextRequest, ...args: A) => Promise<Response> {
+ return async (req, ...args) => {
+ if (!requestLoggingEnabled()) return handler(req, ...args)
+ const start = now()
+ try {
+ const res = await handler(req, ...args)
+ logApiRequest({
+ method: req.method,
+ path: new URL(req.url).pathname,
+ status: res.status,
+ durationMs: now() - start,
+ })
+ return res
+ } catch (error) {
+ logApiRequest({
+ method: req.method,
+ path: new URL(req.url).pathname,
+ status: 500,
+ durationMs: now() - start,
+ })
+ throw error
+ }
+ }
+}
+
+const now = (): number =>
+ typeof performance !== 'undefined' && performance.now ? performance.now() : Date.now()
+
+// ── 3. error webhook ──────────────────────────────────────────
+
+export interface ErrorReport {
+ message: string
+ stackHead?: string
+ path: string
+ method: string
+ routeType?: string
+ appVersion: string
+ at: string
+}
+
+/** Build the webhook payload — pure, unit-testable. */
+export function buildErrorReport(
+ error: unknown,
+ request: { path: string; method: string },
+ context?: { routeType?: string },
+): ErrorReport {
+ const err = error instanceof Error ? error : new Error(String(error))
+ return {
+ message: `${err.name}: ${err.message}`.slice(0, 500),
+ stackHead: (err.stack ?? '').split('\n').slice(0, 6).join('\n').slice(0, 1000) || undefined,
+ path: request.path.slice(0, 300),
+ method: request.method,
+ routeType: context?.routeType,
+ appVersion: APP_VERSION,
+ at: new Date().toISOString(),
+ }
+}
+
+/**
+ * Fire-and-forget POST of an error report to CANVIX_ERROR_WEBHOOK_URL.
+ * Returns the fetch promise (callers may void it) — never throws:
+ * a broken webhook must not take the error path down with it.
+ */
+export function postErrorWebhook(report: ErrorReport): Promise<void> {
+ const url = process.env.CANVIX_ERROR_WEBHOOK_URL
+ if (!url) return Promise.resolve()
+ return fetch(url, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify(report),
+ signal: AbortSignal.timeout(5_000),
+ })
+ .then(() => undefined)
+ .catch((err) => {
+ // the watcher cannot become the watched — log locally, move on
+ logLine('warn', 'error_webhook_failed', { reason: String(err).slice(0, 200) })
+ })
+}
+
+export function errorWebhookConfigured(): boolean {
+ return Boolean(process.env.CANVIX_ERROR_WEBHOOK_URL)
+}
diff --git a/tests/e2e/health-v2.spec.ts b/tests/e2e/health-v2.spec.ts
new file mode 100644
index 0000000..235fc9e
--- /dev/null
+++ b/tests/e2e/health-v2.spec.ts
@@ -0,0 +1,54 @@
+import { test, expect } from '@playwright/test'
+
+/**
+ * H7 (v0.12.5): /api/health?v=2 — the observability payload.
+ * Counts and latency, never ids; v1 stays shape-compatible.
+ */
+test('health v2 returns counts + latency probe without ids', async ({ request }) => {
+ const res = await request.get('/api/health?v=2')
+ expect(res.status()).toBe(200)
+ const body = await res.json()
+
+ expect(body.v).toBe(2)
+ expect(body.ok).toBe(true)
+ expect(body.templates).toBeGreaterThan(0)
+
+ // the counts the epic named — designs, users, media (count + bytes)
+ expect(typeof body.counts.designs).toBe('number')
+ expect(body.counts.designs).toBeGreaterThanOrEqual(0)
+ expect(typeof body.counts.users).toBe('number')
+ expect(typeof body.counts.media).toBe('number')
+ expect(typeof body.counts.mediaBytes).toBe('number')
+ expect(body.counts.mediaBytes).toBeGreaterThanOrEqual(0)
+
+ // the DB latency probe
+ expect(typeof body.db.latencyMs).toBe('number')
+ expect(body.db.latencyMs).toBeLessThan(2000)
+
+ // app identity
+ expect(typeof body.app.version).toBe('string')
+ expect(body.app.version).not.toBe('')
+ expect(typeof body.app.uptimeSec).toBe('number')
+
+ // acceptance: counts without leaking ids — no cuid-shaped strings
+ // anywhere in the payload
+ const json = JSON.stringify(body)
+ expect(json).not.toMatch(/cmv[a-z0-9]{20,}/) // cuid v2 (designs, media)
+ expect(json).not.toMatch(/clt[a-z0-9]{20,}/) // cuid (comments, versions)
+ expect(json).not.toMatch(/[0-9a-f-]{36}/) // uuid (sessions, users)
+
+ // diagnostics are never cached
+ expect(res.headers()['cache-control']).toBe('no-store')
+})
+
+test('health v1 stays shape-compatible (plus the explicit version tag)', async ({ request }) => {
+ const res = await request.get('/api/health')
+ expect(res.status()).toBe(200)
+ const body = await res.json()
+ expect(body.v).toBe(1)
+ expect(body.ok).toBe(true)
+ expect(typeof body.database.kind).toBe('string')
+ expect(typeof body.templates).toBe('number')
+ // v1 does NOT pay for the counts
+ expect(body.counts).toBeUndefined()
+})