import 'server-only' import type { NextRequest } from 'next/server' import { AdminBackendError } from '@/lib/backend-session' export const ADMIN_UUID_PATTERN = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i export function isSameOriginRequest(request: Pick): boolean { const origin = request.headers.get('origin') if (!origin) return request.headers.get('sec-fetch-site') !== 'cross-site' try { const requestOrigin = new URL(origin).origin if (requestOrigin === request.nextUrl.origin) return true const forwardedProto = request.headers.get('x-forwarded-proto')?.split(',')[0]?.trim().toLowerCase() const forwardedHost = request.headers.get('x-forwarded-host')?.split(',')[0]?.trim() ?? request.headers.get('host')?.trim() if ( (forwardedProto !== 'http' && forwardedProto !== 'https') || !forwardedHost || !/^[A-Za-z0-9.:[\]-]+$/.test(forwardedHost) ) { return false } return requestOrigin === `${forwardedProto}://${forwardedHost}` } catch { return false } } export async function readBoundedTextBody(request: Request, maxBytes: number): Promise { const contentLengthHeader = request.headers.get('content-length')?.trim() if (contentLengthHeader) { const declaredLength = Number(contentLengthHeader) if (Number.isFinite(declaredLength) && declaredLength > maxBytes) { throw new AdminBackendError('request_too_large', 413) } } if (!request.body) { return '' } const reader = request.body.getReader() const chunks: Uint8Array[] = [] let totalBytes = 0 try { for (let next = await reader.read(); !next.done; next = await reader.read()) { const { value } = next totalBytes += value.byteLength if (totalBytes > maxBytes) { await reader.cancel().catch(() => undefined) throw new AdminBackendError('request_too_large', 413) } chunks.push(value) } } finally { reader.releaseLock() } const combined = new Uint8Array(totalBytes) let offset = 0 for (const chunk of chunks) { combined.set(chunk, offset) offset += chunk.byteLength } return new TextDecoder().decode(combined) } export async function readBoundedJsonObject( request: Request, maxBytes: number, options: { requireJsonContentType?: boolean } = {}, ): Promise> { if (options.requireJsonContentType) { const contentType = request.headers.get('content-type')?.split(';', 1)[0]?.trim().toLowerCase() if (contentType !== 'application/json') { throw new AdminBackendError('application_json_required', 415) } } const text = await readBoundedTextBody(request, maxBytes) try { const parsed = JSON.parse(text) as unknown if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) { throw new Error('non_object_json') } return parsed as Record } catch { throw new AdminBackendError('invalid_request', 400) } }