Skip to content

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

fix(security): close the unauthenticated stored XSS in /api/media (CWE-79)

Ashiq Hussain Mirfde7f25fd63b
diff --git a/src/app/api/media/[id]/route.ts b/src/app/api/media/[id]/route.ts
index 342d23d..783fc19 100644
--- a/src/app/api/media/[id]/route.ts
+++ b/src/app/api/media/[id]/route.ts
@@ -2,6 +2,9 @@ import { createHash } from 'node:crypto'
import { NextRequest, NextResponse } from 'next/server'
import { db } from '@/lib/db'
import { isSameOrigin, CSRF_REJECTED } from '@/lib/auth/csrf'
+import { anonKeyHash, readAnonToken } from '@/lib/auth/anon'
+import { getSessionUser } from '@/lib/auth/session'
+import { uploadBytesMatchMime, mayServeInline } from '@/lib/media/sniff'
import { withLogging } from '@/lib/observability'
export const runtime = 'nodejs'
@@ -11,9 +14,46 @@ export const maxDuration = 30
// See POST /api/media for the protocol. The append is a single raw SQL
// UPDATE with an offset guard (`octet_length(bytes) = $offset`) so a
// retried or racing chunk can never corrupt the byte stream.
+//
+// v0.31 (CWE-79 hardening, per the 2026-11-25 report — credit
+// @hackchang): PATCH/PUT now require the upload's owner (session id
+// or anon cookie hash — the same attribution the library routes
+// enforce), finalize verifies the stored bytes against the declared
+// type by magic numbers, and GET serves anything not provably inert
+// as an opaque download with a sandboxing CSP.
const MAX_CHUNK = 3 * 1024 * 1024 + 64 * 1024 // transport headroom over the client chunk size
+/** Hard headers for EVERY media response: nosniff plus a CSP that,
+ * should the bytes ever be instantiated as a document, strips them
+ * of script execution AND same-origin authority (sandbox = unique
+ * origin — fetches stop carrying the victim's session cookie). */
+const MEDIA_SECURITY_HEADERS: Record<string, string> = {
+ 'X-Content-Type-Options': 'nosniff',
+ 'Content-Security-Policy': "default-src 'none'; sandbox",
+}
+
+/** The caller's attribution, in the row-comparable shape (same
+ * resolution order as the library routes). */
+async function callerAttribution(req: NextRequest): Promise<{ ownerId: string | null; anonKey: string | null }> {
+ const user = await getSessionUser(req)
+ const token = readAnonToken(req)
+ return {
+ ownerId: user?.id ?? null,
+ anonKey: user ? null : token ? anonKeyHash(token) : null,
+ }
+}
+
+/** Attribution match — the caller must BE the row's owner. */
+function attributionMatches(
+ caller: { ownerId: string | null; anonKey: string | null },
+ row: { ownerId: string | null; anonKey: string | null },
+): boolean {
+ if (caller.ownerId) return caller.ownerId === row.ownerId
+ if (caller.anonKey) return row.anonKey !== null && caller.anonKey === row.anonKey
+ return false
+}
+
/** PATCH /api/media/[id]?offset=<n> — append one chunk (raw body). */
async function __canvix_patch(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
if (!isSameOrigin(req)) return NextResponse.json(CSRF_REJECTED, { status: 403 })
@@ -27,6 +67,16 @@ async function __canvix_patch(req: NextRequest, { params }: { params: Promise<{
if (!chunk.length) return NextResponse.json({ error: 'Empty chunk.' }, { status: 400 })
if (chunk.length > MAX_CHUNK) return NextResponse.json({ error: 'Chunk too large.' }, { status: 413 })
+ // v0.31: the uploader's attribution must match the row — a flat
+ // 404 (no existence oracle) mirrors the library routes.
+ const ownerRows = await db.$queryRawUnsafe<{ ownerId: string | null; anonKey: string | null }[]>(
+ `SELECT "ownerId", "anonKey" FROM "Media" WHERE id = $1 AND "finalizedAt" IS NULL`,
+ id,
+ )
+ if (!ownerRows.length || !attributionMatches(await callerAttribution(req), ownerRows[0]!)) {
+ return NextResponse.json({ error: 'Not found or already finalized.' }, { status: 404 })
+ }
+
// offset-guarded append: the UPDATE only lands when the stored length
// matches — a replayed/racing chunk is rejected instead of interleaved
const updated = await db.$executeRawUnsafe(
@@ -74,12 +124,32 @@ async function __canvix_put(req: NextRequest, { params }: { params: Promise<{ id
// attribution (account or anon cookie — never across accounts, so
// one user's uploads can't be probed through another's), then keep
// the row in the persistent uploads library.
- const byteRows = await db.$queryRawUnsafe<{ bytes: Buffer; ownerId: string | null; anonKey: Buffer | null }[]>(
- `SELECT bytes, "ownerId", "anonKey" FROM "Media" WHERE id = $1 AND "finalizedAt" IS NULL`,
+ const byteRows = await db.$queryRawUnsafe<
+ { bytes: Buffer; mime: string; ownerId: string | null; anonKey: string | null }[]
+ >(
+ `SELECT bytes, mime, "ownerId", "anonKey" FROM "Media" WHERE id = $1 AND "finalizedAt" IS NULL`,
id,
)
if (!byteRows.length) return NextResponse.json({ error: 'Not found or already finalized.' }, { status: 404 })
- const { ownerId, anonKey } = byteRows[0]
+ const { ownerId, anonKey } = byteRows[0]!
+
+ // v0.31: only the row's owner may finalize — flat 404, no oracle.
+ if (!attributionMatches(await callerAttribution(req), { ownerId, anonKey })) {
+ return NextResponse.json({ error: 'Not found or already finalized.' }, { status: 404 })
+ }
+
+ // v0.31 (CWE-79 fix): magic-byte verification — the bytes must
+ // prove they are what the row claims. A file declared image/png
+ // that actually carries SVG (or any other) content never becomes
+ // servable from this origin as an active document. The row stays
+ // unfinalized and is GC'd like any abandoned upload.
+ if (!uploadBytesMatchMime(new Uint8Array(byteRows[0]!.bytes), byteRows[0]!.mime)) {
+ return NextResponse.json(
+ { error: 'File contents do not match the declared type — the upload was rejected.' },
+ { status: 415 },
+ )
+ }
+
const contentHash = createHash('sha256').update(byteRows[0].bytes).digest('hex')
const dupe = await db.$queryRawUnsafe<{ id: string }[]>(
@@ -111,7 +181,15 @@ async function __canvix_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. */
+ * seeking). Finalized media only; immutable content-addressed by id.
+ *
+ * v0.31 (CWE-79 fix): the stored mime is re-verified against the actual
+ * bytes on EVERY response — legacy rows stored before this hardening
+ * (or bytes that no longer match their claim) are served as
+ * application/octet-stream with Content-Disposition: attachment and a
+ * sandboxing CSP, so no media URL from this origin can ever instantiate
+ * attacker-controlled script. Verified raster images and audio/video
+ * containers are inert by construction in every embedding context. */
async function __canvix_get(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
const { id } = await params
try {
@@ -121,9 +199,18 @@ async function __canvix_get(req: NextRequest, { params }: { params: Promise<{ id
)
if (!rows.length) return new Response('Not found', { status: 404 })
const buf = rows[0].bytes
- const mime = rows[0].mime || 'application/octet-stream'
+ const storedMime = rows[0].mime || 'application/octet-stream'
const total = buf.length
+ // inline only what the bytes prove to be; everything else is an
+ // opaque download — belt-and-braces for rows predating the
+ // finalize-time verification (their bytes were never checked)
+ const inline = mayServeInline(new Uint8Array(buf), storedMime)
+ const contentType = inline ? storedMime : 'application/octet-stream'
+ const hardening: Record<string, string> = inline
+ ? MEDIA_SECURITY_HEADERS
+ : { ...MEDIA_SECURITY_HEADERS, 'Content-Disposition': 'attachment' }
+
const range = req.headers.get('range')
if (range) {
const m = /bytes=(\d*)-(\d*)/.exec(range)
@@ -135,11 +222,12 @@ async function __canvix_get(req: NextRequest, { params }: { params: Promise<{ id
return new Response(new Uint8Array(slice), {
status: 206,
headers: {
- 'Content-Type': mime,
+ 'Content-Type': contentType,
'Content-Length': String(slice.length),
'Content-Range': `bytes ${start}-${end}/${total}`,
'Accept-Ranges': 'bytes',
'Cache-Control': 'public, max-age=31536000, immutable',
+ ...hardening,
},
})
}
@@ -154,10 +242,11 @@ async function __canvix_get(req: NextRequest, { params }: { params: Promise<{ id
return new Response(new Uint8Array(buf), {
status: 200,
headers: {
- 'Content-Type': mime,
+ 'Content-Type': contentType,
'Content-Length': String(total),
'Accept-Ranges': 'bytes',
'Cache-Control': 'public, max-age=31536000, immutable',
+ ...hardening,
},
})
} catch (error) {
diff --git a/src/app/api/media/finalize-dedupe.test.ts b/src/app/api/media/finalize-dedupe.test.ts
index b6710bb..78934cc 100644
--- a/src/app/api/media/finalize-dedupe.test.ts
+++ b/src/app/api/media/finalize-dedupe.test.ts
@@ -22,12 +22,18 @@ vi.mock('@/lib/observability', () => ({
withLogging: (_name: string, fn: unknown) => fn,
}))
+// v0.31: finalize resolves the caller's attribution — the dedupe
+// suite's rows belong to session user 'user-a'
+const getSessionUserMock = vi.hoisted(() => vi.fn(async (_req: unknown) => ({ id: 'user-a' })))
+vi.mock('@/lib/auth/session', () => ({ getSessionUser: getSessionUserMock }))
+
import { createHash } from 'node:crypto'
import { NextRequest } from 'next/server'
import { PUT } from './[id]/route'
beforeEach(() => {
vi.clearAllMocks()
+ getSessionUserMock.mockResolvedValue({ id: 'user-a' })
mediaDelete.mockResolvedValue({ id: 'gone' })
mediaUpdate.mockResolvedValue({ id: 'kept' })
})
@@ -41,12 +47,18 @@ function putReq(id: string, expectedSize: number) {
}
const OWNER = { ownerId: 'user-a', anonKey: null }
-const BYTES = Buffer.from('pngbytes')
+// v0.31: finalize verifies magic bytes — 'pngbytes' would fail, so
+// the fixture is a real PNG header (12-byte signature)
+const BYTES = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 0])
-function mockFinalizeQueries(bytes: Buffer, owner: { ownerId: string | null; anonKey: Buffer | null }, dupe: { id: string }[]) {
+function mockFinalizeQueries(
+ bytes: Buffer,
+ owner: { ownerId: string | null; anonKey: string | null },
+ dupe: { id: string }[],
+) {
queryRaw
.mockResolvedValueOnce([{ len: bytes.length }]) // length check
- .mockResolvedValueOnce([{ bytes, ...owner }]) // bytes + attribution
+ .mockResolvedValueOnce([{ bytes, mime: 'image/png', ...owner }]) // bytes + attribution
.mockResolvedValueOnce(dupe) // dedupe lookup
}
diff --git a/src/app/api/media/media-security.test.ts b/src/app/api/media/media-security.test.ts
new file mode 100644
index 0000000..1895ffb
--- /dev/null
+++ b/src/app/api/media/media-security.test.ts
@@ -0,0 +1,254 @@
+// Security regression tests for the media store (v0.31, CWE-79 fix —
+// the 2026-11-25 report, credit @hackchang).
+//
+// Replays the report's proof of concept against the hardened routes:
+// · init rejects image/svg+xml (and html/xml) outright
+// · finalize rejects SVG bytes smuggled under an allowed mime,
+// and requires the upload's owner
+// · PATCH requires the upload's owner
+// · GET never serves attacker-controlled bytes as an
+// instantiable document: unverified rows become
+// application/octet-stream + attachment + sandbox CSP
+import { describe, it, expect, vi, beforeEach } from 'vitest'
+
+const queryRaw = vi.hoisted(() => vi.fn())
+const executeRaw = vi.hoisted(() => vi.fn())
+const mediaCreate = vi.hoisted(() => vi.fn())
+const mediaUpdate = vi.hoisted(() => vi.fn())
+const mediaDelete = vi.hoisted(() => vi.fn())
+const mediaDeleteMany = vi.hoisted(() => vi.fn())
+const dbMock = vi.hoisted(() => ({
+ $queryRawUnsafe: queryRaw,
+ $executeRawUnsafe: executeRaw,
+ media: { create: mediaCreate, update: mediaUpdate, delete: mediaDelete, deleteMany: mediaDeleteMany },
+}))
+vi.mock('@/lib/db', () => ({ db: dbMock }))
+vi.mock('@/lib/observability', () => ({
+ withLogging: (_name: string, fn: unknown) => fn,
+}))
+vi.mock('@/lib/rate-limit', () => ({
+ checkRateLimit: vi.fn(() => ({ ok: true })),
+ rateLimitResponse: vi.fn(() => new Response('rate limited', { status: 429 })),
+}))
+const getSessionUserMock = vi.hoisted(() => vi.fn(async (_req: unknown) => null as { id: string } | null))
+vi.mock('@/lib/auth/session', () => ({ getSessionUser: getSessionUserMock }))
+
+import { NextRequest } from 'next/server'
+import { POST } from './route'
+import { GET, PATCH, PUT } from './[id]/route'
+import { anonKeyHash } from '@/lib/auth/anon'
+
+// real signatures the finalize gate demands
+const PNG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 0])
+const SVG_POC = Buffer.from(
+ '<svg xmlns="http://www.w3.org/2000/svg"><script>alert(document.domain)</script></svg>',
+)
+
+beforeEach(() => {
+ vi.clearAllMocks()
+ getSessionUserMock.mockResolvedValue(null)
+ mediaCreate.mockResolvedValue({ id: 'm-new' })
+ mediaUpdate.mockResolvedValue({ id: 'm-new' })
+ mediaDelete.mockResolvedValue({ id: 'gone' })
+ mediaDeleteMany.mockResolvedValue(0)
+})
+
+// ── helpers ───────────────────────────────────────────────────
+
+function postInit(mime: string, size = 57) {
+ return new NextRequest('http://localhost/api/media', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ mime, size, name: 'a.bin' }),
+ })
+}
+
+function patchChunk(id: string, offset: number, body: Buffer, cookie?: string) {
+ return new NextRequest(`http://localhost/api/media/${id}?offset=${offset}`, {
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/octet-stream', ...(cookie ? { Cookie: cookie } : {}) },
+ body: new Uint8Array(body),
+ })
+}
+
+function putFinalize(id: string, expectedSize: number, cookie?: string) {
+ return new NextRequest(`http://localhost/api/media/${id}`, {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json', ...(cookie ? { Cookie: cookie } : {}) },
+ body: JSON.stringify({ expectedSize }),
+ })
+}
+
+function getMedia(id: string, range?: string) {
+ return new NextRequest(`http://localhost/api/media/${id}`, {
+ method: 'GET',
+ ...(range ? { headers: { Range: range } } : {}),
+ })
+}
+
+const ANON = 'anon-token-a'
+
+function row(over: Partial<{ bytes: Buffer; mime: string; ownerId: string | null; anonKey: string | null }> = {}) {
+ return {
+ bytes: PNG,
+ mime: 'image/png',
+ ownerId: null,
+ anonKey: anonKeyHash(ANON),
+ ...over,
+ }
+}
+
+// ── init: the exact allowlist ─────────────────────────────────
+
+describe('POST /api/media — init (CWE-79 fix)', () => {
+ it('rejects the report payload: image/svg+xml never enters the store', async () => {
+ const res = await POST(postInit('image/svg+xml'))
+ expect(res.status).toBe(415)
+ expect(mediaCreate).not.toHaveBeenCalled()
+ })
+
+ it('rejects html/xhtml/xml and unknown image/* shapes the old prefix check let through', async () => {
+ for (const mime of ['text/html', 'application/xhtml+xml', 'text/xml', 'image/svg+xml; charset=utf-8', 'image/hack']) {
+ const res = await POST(postInit(mime))
+ expect(res.status, mime).toBe(415)
+ }
+ expect(mediaCreate).not.toHaveBeenCalled()
+ })
+
+ it('accepts raster/audio/video and stores the CANONICAL type, not the client string', async () => {
+ queryRaw.mockResolvedValue([{ used: 0 }])
+ const res = await POST(postInit('image/jpg'))
+ expect(res.status).toBe(201)
+ expect(mediaCreate).toHaveBeenCalledTimes(1)
+ expect(mediaCreate.mock.calls[0]![0].data.mime).toBe('image/jpeg')
+ })
+})
+
+// ── PATCH: ownership ──────────────────────────────────────────
+
+describe('PATCH /api/media/[id] — ownership (CWE-79 fix)', () => {
+ it('404s before any byte write when the caller has no attribution', async () => {
+ queryRaw.mockResolvedValue([row()])
+ const res = await PATCH(patchChunk('m-new', 0, Buffer.from('chunk')), { params: Promise.resolve({ id: 'm-new' }) })
+ expect(res.status).toBe(404)
+ expect(executeRaw).not.toHaveBeenCalled()
+ })
+
+ it('404s when the caller is not the row owner (flat — no existence oracle)', async () => {
+ queryRaw.mockResolvedValue([row()])
+ const res = await PATCH(patchChunk('m-new', 0, Buffer.from('chunk'), `canvix_anon=someone-else`),
+ { params: Promise.resolve({ id: 'm-new' }) })
+ expect(res.status).toBe(404)
+ expect(executeRaw).not.toHaveBeenCalled()
+ })
+
+ it('appends for the row owner', async () => {
+ queryRaw
+ .mockResolvedValueOnce([row()]) // ownership
+ .mockResolvedValueOnce([{ len: 5 }]) // post-append length
+ executeRaw.mockResolvedValue(1)
+ const res = await PATCH(patchChunk('m-new', 0, Buffer.from('chunk'), `canvix_anon=${ANON}`),
+ { params: Promise.resolve({ id: 'm-new' }) })
+ expect(res.status).toBe(200)
+ expect(executeRaw).toHaveBeenCalledTimes(1)
+ })
+})
+
+// ── finalize: ownership + byte verification ───────────────────
+
+describe('PUT /api/media/[id] — finalize (CWE-79 fix)', () => {
+ it('rejects SVG bytes smuggled under an allowed mime — the PoC upload', async () => {
+ queryRaw
+ .mockResolvedValueOnce([{ len: SVG_POC.length }])
+ .mockResolvedValueOnce([row({ bytes: SVG_POC })])
+ const res = await PUT(putFinalize('m-new', SVG_POC.length, `canvix_anon=${ANON}`),
+ { params: Promise.resolve({ id: 'm-new' }) })
+ expect(res.status).toBe(415)
+ expect(mediaUpdate).not.toHaveBeenCalled()
+ expect(mediaDelete).not.toHaveBeenCalled()
+ })
+
+ it('rejects a legacy-shaped row (mime image/svg+xml) even from its owner', async () => {
+ queryRaw
+ .mockResolvedValueOnce([{ len: SVG_POC.length }])
+ .mockResolvedValueOnce([row({ bytes: SVG_POC, mime: 'image/svg+xml' })])
+ const res = await PUT(putFinalize('m-new', SVG_POC.length, `canvix_anon=${ANON}`),
+ { params: Promise.resolve({ id: 'm-new' }) })
+ expect(res.status).toBe(415)
+ expect(mediaUpdate).not.toHaveBeenCalled()
+ })
+
+ it('404s a non-owner before reading bytes or hashing', async () => {
+ queryRaw
+ .mockResolvedValueOnce([{ len: PNG.length }])
+ .mockResolvedValueOnce([row({ ownerId: 'user-a', anonKey: null })])
+ const res = await PUT(putFinalize('m-new', PNG.length, `canvix_anon=${ANON}`),
+ { params: Promise.resolve({ id: 'm-new' }) })
+ expect(res.status).toBe(404)
+ expect(mediaUpdate).not.toHaveBeenCalled()
+ })
+
+ it('finalizes a verified PNG for its owner', async () => {
+ queryRaw
+ .mockResolvedValueOnce([{ len: PNG.length }])
+ .mockResolvedValueOnce([row()])
+ .mockResolvedValueOnce([]) // no dupe
+ const res = await PUT(putFinalize('m-new', PNG.length, `canvix_anon=${ANON}`),
+ { params: Promise.resolve({ id: 'm-new' }) })
+ expect(res.status).toBe(200)
+ expect(mediaUpdate).toHaveBeenCalledWith(
+ expect.objectContaining({ where: { id: 'm-new' }, data: expect.objectContaining({ keepInLibrary: true }) }),
+ )
+ })
+})
+
+// ── GET: the response hardening ───────────────────────────────
+
+describe('GET /api/media/[id] — stream hardening (CWE-79 fix)', () => {
+ it('serves the stored SVG row (the report end state) as an inert download', async () => {
+ queryRaw.mockResolvedValue([{ bytes: SVG_POC, mime: 'image/svg+xml' }])
+ const res = await GET(getMedia('m-evil'), { params: Promise.resolve({ id: 'm-evil' }) })
+ expect(res.status).toBe(200)
+ expect(res.headers.get('content-type')).toBe('application/octet-stream')
+ expect(res.headers.get('content-disposition')).toBe('attachment')
+ expect(res.headers.get('content-security-policy')).toBe("default-src 'none'; sandbox")
+ expect(res.headers.get('x-content-type-options')).toBe('nosniff')
+ expect(res.headers.get('cache-control')).toContain('immutable')
+ })
+
+ it('downgrades a legacy row whose bytes no longer prove the claim', async () => {
+ queryRaw.mockResolvedValue([{ bytes: SVG_POC, mime: 'image/png' }])
+ const res = await GET(getMedia('m-legacy'), { params: Promise.resolve({ id: 'm-legacy' }) })
+ expect(res.status).toBe(200)
+ expect(res.headers.get('content-type')).toBe('application/octet-stream')
+ expect(res.headers.get('content-disposition')).toBe('attachment')
+ })
+
+ it('serves a verified raster inline — the editor flow is unchanged', async () => {
+ queryRaw.mockResolvedValue([{ bytes: PNG, mime: 'image/png' }])
+ const res = await GET(getMedia('m-good'), { params: Promise.resolve({ id: 'm-good' }) })
+ expect(res.status).toBe(200)
+ expect(res.headers.get('content-type')).toBe('image/png')
+ expect(res.headers.get('content-disposition')).toBeNull()
+ expect(res.headers.get('content-security-policy')).toBe("default-src 'none'; sandbox")
+ expect(res.headers.get('x-content-type-options')).toBe('nosniff')
+ })
+
+ it('serves real audio/video containers inline (audio/wav)', async () => {
+ const WAV = Buffer.concat([Buffer.from('RIFF'), Buffer.from([0x24, 0x08, 0, 0]), Buffer.from('WAVEfmt ')])
+ queryRaw.mockResolvedValue([{ bytes: WAV, mime: 'audio/wav' }])
+ const res = await GET(getMedia('m-wav'), { params: Promise.resolve({ id: 'm-wav' }) })
+ expect(res.status).toBe(200)
+ expect(res.headers.get('content-type')).toBe('audio/wav')
+ expect(res.headers.get('content-disposition')).toBeNull()
+ })
+
+ it('Range requests carry the same hardening (206 path)', async () => {
+ queryRaw.mockResolvedValue([{ bytes: SVG_POC, mime: 'image/svg+xml' }])
+ const res = await GET(getMedia('m-evil', 'bytes=0-9'), { params: Promise.resolve({ id: 'm-evil' }) })
+ expect(res.status).toBe(206)
+ expect(res.headers.get('content-type')).toBe('application/octet-stream')
+ expect(res.headers.get('content-disposition')).toBe('attachment')
+ expect(res.headers.get('content-security-policy')).toBe("default-src 'none'; sandbox")
+ })
+})
diff --git a/src/app/api/media/route.ts b/src/app/api/media/route.ts
index f50a009..76ab16a 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 { canonicalMediaMime } from '@/lib/media/sniff'
import { withLogging } from '@/lib/observability'
export const runtime = 'nodejs'
@@ -23,7 +24,14 @@ const MAX_MEDIA_MB = Math.max(1, Number(process.env.CANVIX_MAX_MEDIA_MB ?? 32))
// library needs server-side bytes (survive reload, follow the account,
// sha256-deduped). Document embedding (data URLs) remains available to
// plugins/legacy designs; new uploads land here.
-const ALLOWED_PREFIXES = ['audio/', 'video/', 'image/']
+//
+// v0.31 (CWE-79 fix): the allowlist is EXACT, not prefix-based. The
+// client-declared mime is canonicalized and must be one of the types
+// in src/lib/media/sniff.ts — image/svg+xml (and any HTML/XML shape)
+// is structurally rejected here, and finalize re-verifies the actual
+// bytes by magic numbers, so a file can never be served from this
+// origin as a type the origin did not prove it to be. See the
+// 2026-11-25 report (credit @hackchang) for the original vector.
/** library quota — the bytes an attribution (account or anon cookie)
* may keep in the library. Self-hosters can raise it freely. */
@@ -38,14 +46,23 @@ async function __canvix_post(req: NextRequest) {
if (!limit.ok) return rateLimitResponse(limit)
try {
const body = (await req.json().catch(() => ({}))) as { mime?: unknown; size?: unknown; name?: unknown }
- const mime = typeof body.mime === 'string' ? body.mime.slice(0, 100) : ''
+ const declared = typeof body.mime === 'string' ? body.mime.slice(0, 100) : ''
const size = Number(body.size)
// v0.14 (D1): original filename for the library listing — strip
// path fragments browsers sometimes send, cap hard
const name = typeof body.name === 'string' ? body.name.split(/[\\/]/).pop()!.slice(0, 200) || null : null
- if (!ALLOWED_PREFIXES.some((p) => mime.startsWith(p))) {
- return NextResponse.json({ error: 'Only audio and video files are supported.' }, { status: 415 })
+ // v0.31 (CWE-79 fix): exact allowlist — the stored mime is the
+ // canonical server-side form, never the raw client string.
+ const mime = canonicalMediaMime(declared)
+ if (!mime) {
+ return NextResponse.json(
+ {
+ error:
+ 'Unsupported file type. PNG, JPEG, GIF, WebP, AVIF and BMP images plus common audio and video files are supported; SVG and HTML are not.',
+ },
+ { status: 415 },
+ )
}
if (!Number.isFinite(size) || size <= 0 || size > MAX_MEDIA_MB * 1024 * 1024) {
return NextResponse.json(
diff --git a/src/lib/media/sniff.test.ts b/src/lib/media/sniff.test.ts
new file mode 100644
index 0000000..a9b2163
--- /dev/null
+++ b/src/lib/media/sniff.test.ts
@@ -0,0 +1,135 @@
+// Unit tests for the media type-truth layer (v0.31, CWE-79 fix).
+// Real magic bytes for every claim: the sniffers must recognize each
+// allowed raster image and each audio/video container exactly, and
+// must NEVER mistake SVG/HTML/XML for any of them.
+
+import { describe, it, expect } from 'vitest'
+import {
+ canonicalMediaMime,
+ sniffImageMime,
+ sniffIsMediaContainer,
+ uploadBytesMatchMime,
+ mayServeInline,
+} from './sniff'
+
+// real file signatures (trimmed to the bytes the sniffers read)
+const PNG = Buffer.from([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 0, 0, 0, 0])
+const JPEG = Buffer.from([0xff, 0xd8, 0xff, 0xe0, 0, 0x10, 0x4a, 0x46, 0x49, 0x46, 0, 1, 1])
+const GIF = Buffer.from('GIF89a' + '\x00'.repeat(6))
+const WEBP = Buffer.concat([Buffer.from('RIFF'), Buffer.from([0x24, 0x38, 0, 0]), Buffer.from('WEBPVP8 ')])
+const AVIF = Buffer.concat([Buffer.from([0, 0, 0, 0x18]), Buffer.from('ftypavif')])
+const BMP = Buffer.concat([Buffer.from('BM'), Buffer.alloc(10)])
+
+const ID3 = Buffer.concat([Buffer.from('ID3'), Buffer.alloc(9)])
+const OGG = Buffer.concat([Buffer.from('OggS'), Buffer.alloc(8)])
+const FLAC = Buffer.concat([Buffer.from('fLaC'), Buffer.alloc(8)])
+const MP4 = Buffer.concat([Buffer.from([0, 0, 0, 0x18]), Buffer.from('ftypisom')])
+const EBML = Buffer.concat([Buffer.from([0x1a, 0x45, 0xdf, 0xa3]), Buffer.alloc(8)])
+const WAV = Buffer.concat([Buffer.from('RIFF'), Buffer.from([0x24, 0x08, 0, 0]), Buffer.from('WAVEfmt ')])
+const MP3_SYNC = Buffer.from([0xff, 0xfb, 0x90, 0x00, 0, 0, 0, 0, 0, 0, 0, 0])
+const ADTS = Buffer.from([0xff, 0xf1, 0x50, 0x80, 0, 0, 0, 0, 0, 0, 0, 0])
+
+// the report's payload, exactly
+const SVG_POC = Buffer.from(
+ '<svg xmlns="http://www.w3.org/2000/svg"><script>alert(document.domain)</script></svg>',
+)
+const HTML = Buffer.from('<!DOCTYPE html><html><script>alert(1)</script></html>')
+const XML = Buffer.from('<?xml version="1.0"?><foo/>')
+
+describe('canonicalMediaMime — the exact init allowlist', () => {
+ it('accepts the raster/audio/video types with canonicalization', () => {
+ expect(canonicalMediaMime('image/png')).toBe('image/png')
+ expect(canonicalMediaMime('image/jpg')).toBe('image/jpeg') // browser alias
+ expect(canonicalMediaMime('audio/mp3')).toBe('audio/mpeg')
+ expect(canonicalMediaMime('audio/x-m4a')).toBe('audio/mp4')
+ expect(canonicalMediaMime('video/quicktime')).toBe('video/quicktime')
+ })
+
+ it('rejects image/svg+xml and every active-content shape — the v0.30 vector', () => {
+ expect(canonicalMediaMime('image/svg+xml')).toBeNull()
+ expect(canonicalMediaMime('text/html')).toBeNull()
+ expect(canonicalMediaMime('application/xhtml+xml')).toBeNull()
+ expect(canonicalMediaMime('text/xml')).toBeNull()
+ expect(canonicalMediaMime('application/xml')).toBeNull()
+ // the old prefix check accepted these shapes; exactness must not regress
+ expect(canonicalMediaMime('image/svg+xml; charset=utf-8')).toBeNull()
+ expect(canonicalMediaMime('image/whatever')).toBeNull()
+ })
+})
+
+describe('sniffImageMime — exact raster identification', () => {
+ it('identifies each supported raster format by magic bytes', () => {
+ expect(sniffImageMime(PNG)).toBe('image/png')
+ expect(sniffImageMime(JPEG)).toBe('image/jpeg')
+ expect(sniffImageMime(GIF)).toBe('image/gif')
+ expect(sniffImageMime(WEBP)).toBe('image/webp')
+ expect(sniffImageMime(AVIF)).toBe('image/avif')
+ expect(sniffImageMime(BMP)).toBe('image/bmp')
+ })
+
+ it('never identifies SVG/HTML/XML as a raster image', () => {
+ expect(sniffImageMime(SVG_POC)).toBeNull()
+ expect(sniffImageMime(HTML)).toBeNull()
+ expect(sniffImageMime(XML)).toBeNull()
+ expect(sniffImageMime(Buffer.alloc(0))).toBeNull()
+ expect(sniffImageMime(Buffer.alloc(11))).toBeNull() // too short to verify
+ })
+})
+
+describe('sniffIsMediaContainer — audio/video container proof', () => {
+ it('recognizes every common container signature', () => {
+ expect(sniffIsMediaContainer(ID3)).toBe(true)
+ expect(sniffIsMediaContainer(OGG)).toBe(true)
+ expect(sniffIsMediaContainer(FLAC)).toBe(true)
+ expect(sniffIsMediaContainer(MP4)).toBe(true)
+ expect(sniffIsMediaContainer(EBML)).toBe(true)
+ expect(sniffIsMediaContainer(WAV)).toBe(true)
+ expect(sniffIsMediaContainer(MP3_SYNC)).toBe(true) // tagless mp3
+ expect(sniffIsMediaContainer(ADTS)).toBe(true) // raw aac
+ })
+
+ it('never recognizes SVG/HTML/XML or rasters as a media container', () => {
+ expect(sniffIsMediaContainer(SVG_POC)).toBe(false)
+ expect(sniffIsMediaContainer(HTML)).toBe(false)
+ expect(sniffIsMediaContainer(XML)).toBe(false)
+ expect(sniffIsMediaContainer(PNG)).toBe(false)
+ expect(sniffIsMediaContainer(JPEG)).toBe(false)
+ })
+})
+
+describe('uploadBytesMatchMime — the finalize gate', () => {
+ it('accepts bytes that prove their declared type', () => {
+ expect(uploadBytesMatchMime(PNG, 'image/png')).toBe(true)
+ expect(uploadBytesMatchMime(WEBP, 'image/webp')).toBe(true)
+ expect(uploadBytesMatchMime(ID3, 'audio/mpeg')).toBe(true)
+ expect(uploadBytesMatchMime(MP4, 'video/mp4')).toBe(true)
+ })
+
+ it('rejects the smuggle: SVG bytes under any allowed declaration', () => {
+ expect(uploadBytesMatchMime(SVG_POC, 'image/png')).toBe(false)
+ expect(uploadBytesMatchMime(SVG_POC, 'audio/mpeg')).toBe(false)
+ expect(uploadBytesMatchMime(SVG_POC, 'video/mp4')).toBe(false)
+ expect(uploadBytesMatchMime(HTML, 'image/png')).toBe(false)
+ })
+
+ it('rejects cross-format lies (jpeg bytes declared as png)', () => {
+ expect(uploadBytesMatchMime(JPEG, 'image/png')).toBe(false)
+ expect(uploadBytesMatchMime(PNG, 'image/jpeg')).toBe(false)
+ })
+})
+
+describe('mayServeInline — the GET gate', () => {
+ it('serves verified rasters and real containers inline', () => {
+ expect(mayServeInline(PNG, 'image/png')).toBe(true)
+ expect(mayServeInline(WAV, 'audio/wav')).toBe(true)
+ expect(mayServeInline(MP4, 'video/mp4')).toBe(true)
+ })
+
+ it('downgrades the legacy vector payload to a download', () => {
+ // the exact stored shape the 2026-11-25 report demonstrated
+ expect(mayServeInline(SVG_POC, 'image/svg+xml')).toBe(false)
+ // legacy row claiming a raster while carrying SVG bytes
+ expect(mayServeInline(SVG_POC, 'image/png')).toBe(false)
+ expect(mayServeInline(HTML, 'text/html')).toBe(false)
+ })
+})
diff --git a/src/lib/media/sniff.ts b/src/lib/media/sniff.ts
new file mode 100644
index 0000000..9260128
--- /dev/null
+++ b/src/lib/media/sniff.ts
@@ -0,0 +1,151 @@
+// ─────────────────────────────────────────────────────────────
+// Media store type verification (v0.31 security hardening).
+//
+// The 2026-11-25 report (CWE-79, unauthenticated stored XSS via
+// /api/media, credit @hackchang) showed that trusting the
+// client-declared MIME prefix let `image/svg+xml` into the store,
+// and GET served those bytes inline as a same-origin SVG document
+// whose <script> ran with the viewer's session authority. This
+// module is the server-side truth layer that ends client control
+// over what this origin will instantiate as a document:
+//
+// · init (POST /api/media) — exact MIME allowlist, no
+// prefixes, svg/html/xml never
+// accepted, aliases canonicalized
+// · finalize (PUT /api/media/[id])— magic-byte verification: the
+// stored bytes must prove they
+// are what the row claims
+// · stream (GET /api/media/[id]) — bytes re-verified on every
+// response; anything not
+// provably inert is served as
+// application/octet-stream with
+// Content-Disposition: attachment
+//
+// Pure byte inspection — no DOM, no dependencies, runtime-safe.
+// ─────────────────────────────────────────────────────────────
+
+/** The only MIME types this origin will ever serve inline as an
+ * image: raster formats only. A raster image document cannot
+ * carry script; an SVG one can, so SVG is structurally absent. */
+export const INLINE_SAFE_IMAGE_MIMES = [
+ 'image/png',
+ 'image/jpeg',
+ 'image/gif',
+ 'image/webp',
+ 'image/avif',
+ 'image/bmp',
+] as const
+
+/** Everything the media store accepts at init, in canonical form.
+ * Deliberately exact — no prefix matching, ever again. */
+export const MEDIA_MIME_ALLOWLIST: ReadonlySet<string> = new Set([
+ ...INLINE_SAFE_IMAGE_MIMES,
+ // audio containers
+ 'audio/mpeg',
+ 'audio/mp4',
+ 'audio/aac',
+ 'audio/ogg',
+ 'audio/wav',
+ 'audio/webm',
+ 'audio/flac',
+ // video containers
+ 'video/mp4',
+ 'video/webm',
+ 'video/ogg',
+ 'video/quicktime',
+ 'video/x-matroska',
+ 'video/avi',
+])
+
+/** Common browser-reported aliases mapped to the canonical form
+ * that gets stored — one truth per type, no prefix surprises. */
+const MIME_ALIASES: Readonly<Record<string, string>> = {
+ 'image/jpg': 'image/jpeg',
+ 'audio/mp3': 'audio/mpeg',
+ 'audio/m4a': 'audio/mp4',
+ 'audio/x-m4a': 'audio/mp4',
+ 'audio/x-wav': 'audio/wav',
+ 'audio/x-flac': 'audio/flac',
+ 'video/x-msvideo': 'video/avi',
+ 'video/mkv': 'video/x-matroska',
+}
+
+/** Canonical allowed type for a declared MIME string, or null when
+ * the type is not exactly allowed (svg, html, xml, …). */
+export function canonicalMediaMime(declared: string): string | null {
+ const mime = MIME_ALIASES[declared] ?? declared
+ return MEDIA_MIME_ALLOWLIST.has(mime) ? mime : null
+}
+
+/** True when the stored type is one of the audio/video families —
+ * media-element types that never execute script in any context. */
+export function isAudioVideoMime(mime: string): boolean {
+ return mime.startsWith('audio/') || mime.startsWith('video/')
+}
+
+function ascii(b: Uint8Array, start: number, end: number): string {
+ let out = ''
+ for (let i = start; i < end; i++) out += String.fromCharCode(b[i]!)
+ return out
+}
+
+/** Exact raster-image type from magic bytes, or null. AVIF shares
+ * the ISO-BMFF `ftyp` header with mp4/mov, so the brand at offset
+ * 8 disambiguates; WEBP shares RIFF with WAVE/AVI, same trick. */
+export function sniffImageMime(b: Uint8Array): string | null {
+ if (b.length < 12) return null
+ // PNG — 89 50 4E 47 0D 0A 1A 0A
+ if (b[0] === 0x89 && b[1] === 0x50 && b[2] === 0x4e && b[3] === 0x47) return 'image/png'
+ // JPEG — FF D8 FF
+ if (b[0] === 0xff && b[1] === 0xd8 && b[2] === 0xff) return 'image/jpeg'
+ // GIF — "GIF8"
+ if (b[0] === 0x47 && b[1] === 0x49 && b[2] === 0x46 && b[3] === 0x38) return 'image/gif'
+ // RIFF container — only WEBP is an image (WAVE/AVI are media)
+ if (ascii(b, 0, 4) === 'RIFF' && ascii(b, 8, 12) === 'WEBP') return 'image/webp'
+ // ISO-BMFF — only avif/avis brands are images
+ if (ascii(b, 4, 8) === 'ftyp') {
+ const brand = ascii(b, 8, 12)
+ if (brand === 'avif' || brand === 'avis') return 'image/avif'
+ }
+ // BMP — "BM" (checked last: a two-byte prefix alone is weak)
+ if (b[0] === 0x42 && b[1] === 0x4d) return 'image/bmp'
+ return null
+}
+
+/** Do the bytes carry a known audio/video container signature?
+ * Used at finalize to prove a declared audio/video upload really
+ * is a media container — SVG/HTML/XML never match. */
+export function sniffIsMediaContainer(b: Uint8Array): boolean {
+ if (b.length < 12) return false
+ if (ascii(b, 0, 3) === 'ID3') return true // mp3 with ID3v2 tags (3-byte tag + version byte)
+ const s4 = ascii(b, 0, 4)
+ if (s4 === 'OggS') return true // vorbis / opus / theora
+ if (s4 === 'fLaC') return true // flac
+ if (s4 === 'RIFF') return true // WAVE / AVI / WEBP
+ if (ascii(b, 4, 8) === 'ftyp') return true // mp4 / m4a / mov
+ // EBML — webm / matroska
+ if (b[0] === 0x1a && b[1] === 0x45 && b[2] === 0xdf && b[3] === 0xa3) return true
+ // MPEG audio frame sync (mp3 without ID3) and ADTS AAC —
+ // 11-bit sync: FF followed by a byte whose top 3 bits are set.
+ // (JPEG is FF D8, whose second byte fails the mask — no clash.)
+ if (b[0] === 0xff && (b[1]! & 0xe0) === 0xe0) return true
+ return false
+}
+
+/** Finalize-time verdict: do the actual bytes justify the row's
+ * declared type? Raster images must match their magic exactly;
+ * audio/video must carry a known container signature. */
+export function uploadBytesMatchMime(bytes: Uint8Array, declaredMime: string): boolean {
+ if (isAudioVideoMime(declaredMime)) return sniffIsMediaContainer(bytes)
+ const sniffed = sniffImageMime(bytes)
+ return sniffed !== null && sniffed === declaredMime
+}
+
+/** GET-time verdict: may these bytes be served inline as the
+ * stored type? The exact-match rule means a legacy row claiming
+ * image/png while carrying SVG bytes is downgraded to a download —
+ * trust nothing that was stored before this hardening shipped. */
+export function mayServeInline(bytes: Uint8Array, storedMime: string): boolean {
+ if (isAudioVideoMime(storedMime)) return sniffIsMediaContainer(bytes)
+ return sniffImageMime(bytes) === storedMime
+}