144 lines
4.7 KiB
TypeScript
144 lines
4.7 KiB
TypeScript
// server/supabase/functions/_shared/json-response.ts
|
|
// JSON response + auth-error mapping shared by the knowledge functions.
|
|
|
|
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 buildJsonResponse(body, status)
|
|
}
|
|
|
|
export function isAuthError(error: unknown): error is AuthError {
|
|
return Boolean(
|
|
error
|
|
&& typeof error === 'object'
|
|
&& 'status' in error
|
|
&& (error.status === 401 || error.status === 403)
|
|
&& 'message' in error
|
|
&& typeof error.message === 'string',
|
|
)
|
|
}
|
|
|
|
/** Map a thrown value to a response: auth errors keep their status, anything else is a 500. */
|
|
export function errorResponse(error: unknown): Response {
|
|
// Same shape as auth.ts authErrorResponse, without loading the Supabase client.
|
|
if (isAuthError(error)) return jsonResponse(error.status, { error: error.message })
|
|
return jsonResponse(500, { error: 'internal_error' })
|
|
}
|