d3ro-voice/server/supabase/functions/_shared/json-response.test.ts

106 lines
3.7 KiB
TypeScript

import {
buildJsonHeaders,
createJsonResponder,
createStatusJsonResponder,
JsonBodyError,
readJsonBody,
} from './json-response.ts'
function assert(condition: boolean, message: string): asserts condition {
if (!condition) throw new Error(message)
}
function assertEquals(actual: unknown, expected: unknown, message: string): void {
const a = JSON.stringify(actual)
const e = JSON.stringify(expected)
if (a !== e) throw new Error(`${message}: expected ${e}, got ${a}`)
}
Deno.test('buildJsonHeaders and responders preserve CORS, cache-control, pragma, and nosniff options', async () => {
const plain = createJsonResponder({ cors: false })
const plainResp = plain({ ok: true }, 201)
assertEquals(plainResp.status, 201, 'status')
assertEquals(plainResp.headers.get('Access-Control-Allow-Origin'), null, 'no cors')
assertEquals(plainResp.headers.get('Content-Type'), 'application/json', 'content-type')
assertEquals(await plainResp.json(), { ok: true }, 'body')
const strictNoStore = createStatusJsonResponder({
noStore: true,
pragmaNoCache: true,
noSniff: true,
})
const strictResp = strictNoStore(403, { error: 'forbidden' })
assertEquals(strictResp.status, 403, 'status')
assertEquals(strictResp.headers.get('Cache-Control'), 'no-store', 'no-store')
assertEquals(strictResp.headers.get('Pragma'), 'no-cache', 'pragma')
assertEquals(strictResp.headers.get('X-Content-Type-Options'), 'nosniff', 'nosniff')
assertEquals(
buildJsonHeaders().hasOwnProperty('Access-Control-Allow-Origin'),
true,
'cors default',
)
await strictResp.body?.cancel()
})
Deno.test('readJsonBody enforces Content-Type, byte cap, JSON syntax, and plain object shape', async () => {
let caught: unknown
try {
await readJsonBody(
new Request('http://localhost/test', { method: 'POST', headers: { 'Content-Type': 'text/plain' }, body: '{}' }),
{ requireContentType: true, contentTypeErrorCode: 'content_type_must_be_json' },
)
} catch (err) {
caught = err
}
assert(caught instanceof JsonBodyError && caught.status === 415 && caught.code === 'content_type_must_be_json', '415')
caught = undefined
try {
await readJsonBody(
new Request('http://localhost/test', { method: 'POST', body: 'not-json' }),
{ maxBytes: 1024 },
)
} catch (err) {
caught = err
}
assert(caught instanceof JsonBodyError && caught.status === 400 && caught.code === 'invalid_json', 'invalid json')
caught = undefined
try {
await readJsonBody(
new Request('http://localhost/test', { method: 'POST', body: JSON.stringify([1, 2, 3]) }),
{ maxBytes: 1024, requirePlainObject: true },
)
} catch (err) {
caught = err
}
assert(caught instanceof JsonBodyError && caught.status === 400 && caught.code === 'invalid_json', 'array rejected')
// Stream exceeding maxBytes without Content-Length cancels early with 413
let streamCancelled = false
const oversizedStream = new ReadableStream<Uint8Array>({
pull(controller) {
controller.enqueue(new Uint8Array(600))
},
cancel() {
streamCancelled = true
},
})
caught = undefined
try {
await readJsonBody(
new Request('http://localhost/test', { method: 'POST', body: oversizedStream }),
{ maxBytes: 512 },
)
} catch (err) {
caught = err
}
assert(caught instanceof JsonBodyError && caught.status === 413 && caught.code === 'request_too_large', '413 stream')
assert(streamCancelled, 'oversized stream must be cancelled')
const emptyAllowed = await readJsonBody(
new Request('http://localhost/test', { method: 'POST', body: '' }),
{ allowEmptyObject: true, requirePlainObject: true },
)
assertEquals(emptyAllowed, {}, 'empty body allowed when configured')
})