import { NextResponse } from "next/server"; import { DEV_ORIGINS, SITE_URL } from "@/lib/site"; const ALLOWED_ORIGIN = SITE_URL; function isDev(): boolean { return process.env.NODE_ENV !== "production"; } export function isAllowedOrigin(request: Request): boolean { const origin = request.headers.get("origin"); if (origin === null) { return true; } if (origin === ALLOWED_ORIGIN) { return true; } if (isDev() && DEV_ORIGINS.has(origin)) { return true; } return false; } function resolveAllowedOrigin(origin: string | null): string { if (origin !== null && (origin === ALLOWED_ORIGIN || (isDev() && DEV_ORIGINS.has(origin)))) { return origin; } return ALLOWED_ORIGIN; } export function corsHeaders(origin?: string | null): Record { return { "Access-Control-Allow-Origin": resolveAllowedOrigin(origin ?? null), Vary: "Origin", }; } export function forbidden(origin?: string | null): NextResponse { return NextResponse.json( { error: "Forbidden" }, { status: 403, headers: { "Cache-Control": "public, s-maxage=0, stale-while-revalidate=86400", ...corsHeaders(origin), }, }, ); } export async function parseAppId(context: { params: Promise<{ id: string }>; }): Promise { const { id } = await context.params; if (!/^\d{1,20}$/.test(id)) { return null; } return id; } export function invalidIdResponse(origin?: string | null): NextResponse { return jsonErrorWithCors({ error: "Invalid application id" }, 400, 0, origin); } export function jsonErrorWithCors( data: unknown, status: number, sMaxage = 60, origin?: string | null, ): NextResponse { return NextResponse.json(data, { status, headers: { "Cache-Control": `public, s-maxage=${sMaxage}, stale-while-revalidate=86400`, ...corsHeaders(origin), }, }); } export function jsonWithCors(data: unknown, sMaxage = 3600, origin?: string | null): NextResponse { return NextResponse.json(data, { headers: { "Cache-Control": `public, s-maxage=${sMaxage}, stale-while-revalidate=86400`, ...corsHeaders(origin), }, }); } export function requestOrigin(request: Request): string | null { return request.headers.get("origin"); }