Self-hosted personal gallery application with online photo management and albums, supporting Live/Motion Photos, EXIF parsing, geolocation recognition, and an explore map.
TypeScript albumsexif-extractiongeocodinglive-photomotion-photophoto-galleryphoto-sharingwebgl-viewer
fix(cloud): bound site request bodies before parsing
Timothy Yin190396f8ed8f
diff --git a/apps/cloud/server/utils/site-body.ts b/apps/cloud/server/utils/site-body.tsnew file mode 100644index 00000000..6b64db26--- /dev/null+++ b/apps/cloud/server/utils/site-body.ts@@ -0,0 +1,36 @@+import { createError } from 'h3'++/** Bound bytes before decoding or parsing, including requests with no length header. */+export async function readSiteBody(+ stream: ReadableStream<Uint8Array> | null | undefined,+): Promise<Record<string, unknown>> {+ if (!stream) throw createError({ statusCode: 400 })+ const reader = stream.getReader()+ const bytes = new Uint8Array(4096)+ let size = 0+ try {+ while (true) {+ const { done, value } = await reader.read()+ if (done) break+ if (size + value.byteLength > bytes.byteLength) {+ await reader.cancel().catch(() => undefined)+ throw createError({ statusCode: 400 })+ }+ bytes.set(value, size)+ size += value.byteLength+ }+ } finally {+ reader.releaseLock()+ }+ let body: unknown+ try {+ body = JSON.parse(+ new TextDecoder('utf-8', { fatal: true }).decode(bytes.subarray(0, size)),+ )+ } catch {+ throw createError({ statusCode: 400 })+ }+ if (!body || typeof body !== 'object' || Array.isArray(body))+ throw createError({ statusCode: 400 })+ return body as Record<string, unknown>+}diff --git a/apps/cloud/server/utils/site-management.ts b/apps/cloud/server/utils/site-management.tsindex f1321f05..1c283595 100644--- a/apps/cloud/server/utils/site-management.ts+++ b/apps/cloud/server/utils/site-management.ts@@ -1,5 +1,6 @@-import { createError, getHeader, readBody } from 'h3'+import { createError, getHeader, getRequestWebStream } from 'h3'import type { H3Event } from 'h3'+import { readSiteBody } from './site-body'import { requirePlatformSession } from '../../../shared/platform/context'import {platformDatabase,@@ -22,13 +23,6 @@ export async function siteManagementBody(event: H3Event) {Number(getHeader(event, 'content-length')) > 4096)throw createError({ statusCode: 400 })- const body: unknown = await readBody(event)- if (- !body ||- typeof body !== 'object' ||- Array.isArray(body) ||- JSON.stringify(body).length > 4096- )- throw createError({ statusCode: 400 })- return body as Record<string, unknown>+ // Nitro may already hold the original Cloudflare Request; read H3's active stream.+ return readSiteBody(getRequestWebStream(event))}diff --git a/tests/cloud-site-body.test.ts b/tests/cloud-site-body.test.tsnew file mode 100644index 00000000..35474884--- /dev/null+++ b/tests/cloud-site-body.test.ts@@ -0,0 +1,63 @@+import test from 'node:test'+import assert from 'node:assert/strict'+import { readSiteBody } from '../apps/cloud/server/utils/site-body.ts'+const encode = (value: string) => new TextEncoder().encode(value)+function chunks(values: Uint8Array[]) {+ return new ReadableStream<Uint8Array>({+ start(controller) {+ for (const value of values) controller.enqueue(value)+ controller.close()+ },+ })+}++test('Site JSON body handles split UTF-8 and accepts the exact byte boundary', async () => {+ const value = encode(JSON.stringify({ name: '摄影集' }))+ assert.deepEqual(+ await readSiteBody(+ chunks([...value].map((byte) => new Uint8Array([byte]))),+ ),+ { name: '摄影集' },+ )+ const exact = encode(JSON.stringify({ name: 'a'.repeat(4085) }))+ assert.equal(exact.byteLength, 4096)+ assert.equal((await readSiteBody(chunks([exact]))).name, 'a'.repeat(4085))+ const over = encode(JSON.stringify({ name: 'a'.repeat(4086) }))+ assert.equal(over.byteLength, 4097)+ await assert.rejects(readSiteBody(chunks([over])), { statusCode: 400 })+})++test('Oversized unbounded streams are cancelled before the remaining body is read', async () => {+ let pulls = 0+ let cancelled = false+ const stream = new ReadableStream<Uint8Array>(+ {+ pull(controller) {+ pulls+++ controller.enqueue(new Uint8Array(2048))+ if (pulls > 100) throw new Error('The oversized stream was drained')+ },+ cancel() {+ cancelled = true+ },+ },+ { highWaterMark: 0 },+ )+ await assert.rejects(readSiteBody(stream), { statusCode: 400 })+ assert.equal(pulls, 3)+ assert.equal(cancelled, true)+ assert.equal(stream.locked, false)+})++test('The body cap counts bytes, not characters, and rejects malformed/non-object JSON', async () => {+ const oversized = encode(JSON.stringify({ name: '摄'.repeat(1400) }))+ await assert.rejects(readSiteBody(chunks([oversized])), { statusCode: 400 })+ for (const value of ['', '{', 'null', 'false', '42', '"text"', '[]'])+ await assert.rejects(readSiteBody(chunks([encode(value)])), {+ statusCode: 400,+ })+ await assert.rejects(readSiteBody(chunks([new Uint8Array([0xff])])), {+ statusCode: 400,+ })+ await assert.rejects(readSiteBody(null), { statusCode: 400 })+})