feat: ship Wave 5-6 multi-surface hygiene, optimization, and bug fixes
This commit is contained in:
parent
01ef3293cf
commit
66b6b45ba9
399 changed files with 17828 additions and 11330 deletions
|
|
@ -4,11 +4,125 @@
|
|||
import { corsHeaders } from './cors.ts'
|
||||
import type { AuthError } from './auth.ts'
|
||||
|
||||
export interface JsonHeaderOptions {
|
||||
cors?: boolean
|
||||
noStore?: boolean
|
||||
pragmaNoCache?: boolean
|
||||
noSniff?: boolean
|
||||
}
|
||||
|
||||
export class JsonBodyError extends Error {
|
||||
readonly status: number
|
||||
readonly code: string
|
||||
|
||||
constructor(code: string, status = 400) {
|
||||
super(code)
|
||||
this.name = 'JsonBodyError'
|
||||
this.status = status
|
||||
this.code = code
|
||||
}
|
||||
}
|
||||
|
||||
export interface ReadJsonOptions {
|
||||
maxBytes?: number
|
||||
requireContentType?: boolean
|
||||
contentTypeErrorCode?: string
|
||||
allowEmptyObject?: boolean
|
||||
requirePlainObject?: boolean
|
||||
}
|
||||
|
||||
export function buildJsonHeaders(options: JsonHeaderOptions = {}): Record<string, string> {
|
||||
const headers: Record<string, string> = options.cors !== false ? { ...corsHeaders } : {}
|
||||
headers['Content-Type'] = 'application/json'
|
||||
if (options.noStore) headers['Cache-Control'] = 'no-store'
|
||||
if (options.pragmaNoCache) headers['Pragma'] = 'no-cache'
|
||||
if (options.noSniff) headers['X-Content-Type-Options'] = 'nosniff'
|
||||
return headers
|
||||
}
|
||||
|
||||
export function buildJsonResponse(
|
||||
body: unknown,
|
||||
status = 200,
|
||||
headers: HeadersInit = buildJsonHeaders(),
|
||||
): Response {
|
||||
return new Response(JSON.stringify(body), { status, headers })
|
||||
}
|
||||
|
||||
export function createJsonResponder(options: JsonHeaderOptions = {}): (body: unknown, status?: number) => Response {
|
||||
const headers = buildJsonHeaders(options)
|
||||
return (body: unknown, status = 200): Response => buildJsonResponse(body, status, headers)
|
||||
}
|
||||
|
||||
export function createStatusJsonResponder(options: JsonHeaderOptions = {}): (status: number, body: unknown) => Response {
|
||||
const headers = buildJsonHeaders(options)
|
||||
return (status: number, body: unknown): Response => buildJsonResponse(body, status, headers)
|
||||
}
|
||||
|
||||
async function readLimitedUtf8Body(req: Request, maxBytes?: number): Promise<string> {
|
||||
if (maxBytes === undefined) return await req.text()
|
||||
if (!req.body) return ''
|
||||
const reader = req.body.getReader()
|
||||
const chunks: Uint8Array[] = []
|
||||
let total = 0
|
||||
try {
|
||||
while (true) {
|
||||
const { done, value } = await reader.read()
|
||||
if (done) break
|
||||
if (!value) continue
|
||||
total += value.byteLength
|
||||
if (total > maxBytes) {
|
||||
await reader.cancel().catch(() => undefined)
|
||||
throw new JsonBodyError('request_too_large', 413)
|
||||
}
|
||||
chunks.push(value)
|
||||
}
|
||||
} finally {
|
||||
reader.releaseLock()
|
||||
}
|
||||
const combined = new Uint8Array(total)
|
||||
let offset = 0
|
||||
for (const chunk of chunks) {
|
||||
combined.set(chunk, offset)
|
||||
offset += chunk.byteLength
|
||||
}
|
||||
return new TextDecoder().decode(combined)
|
||||
}
|
||||
|
||||
export async function readJsonBody(req: Request, options: ReadJsonOptions = {}): Promise<unknown> {
|
||||
if (options.requireContentType) {
|
||||
const contentType = req.headers.get('content-type')?.split(';', 1)[0].trim().toLowerCase() ?? ''
|
||||
if (contentType !== 'application/json') {
|
||||
throw new JsonBodyError(options.contentTypeErrorCode ?? 'unsupported_media_type', 415)
|
||||
}
|
||||
}
|
||||
if (options.maxBytes !== undefined) {
|
||||
const rawLength = req.headers.get('content-length')
|
||||
if (rawLength !== null) {
|
||||
const declaredLength = Number(rawLength)
|
||||
if (Number.isFinite(declaredLength) && declaredLength > options.maxBytes) {
|
||||
await req.body?.cancel().catch(() => undefined)
|
||||
throw new JsonBodyError('request_too_large', 413)
|
||||
}
|
||||
}
|
||||
}
|
||||
const text = await readLimitedUtf8Body(req, options.maxBytes)
|
||||
if (options.allowEmptyObject && text.trim().length === 0) {
|
||||
return {}
|
||||
}
|
||||
let parsed: unknown
|
||||
try {
|
||||
parsed = JSON.parse(text)
|
||||
} catch {
|
||||
throw new JsonBodyError('invalid_json', 400)
|
||||
}
|
||||
if (options.requirePlainObject && (!parsed || typeof parsed !== 'object' || Array.isArray(parsed))) {
|
||||
throw new JsonBodyError('invalid_json', 400)
|
||||
}
|
||||
return parsed
|
||||
}
|
||||
|
||||
export function jsonResponse(status: number, body: Record<string, unknown>): Response {
|
||||
return new Response(JSON.stringify(body), {
|
||||
status,
|
||||
headers: { ...corsHeaders, 'Content-Type': 'application/json' },
|
||||
})
|
||||
return buildJsonResponse(body, status)
|
||||
}
|
||||
|
||||
export function isAuthError(error: unknown): error is AuthError {
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue