/** * Verified request scope for customer-facing 0pt routes. * * Middleware (`middleware.ts`) performs real Zitadel Bearer verification and * forwards the verified subject/tenant only when a principal was verified. * Customer routes must NOT fall back to client-supplied tenant/actor values: * that fallback exists only for the explicit local-development mode, and even * there this helper requires an explicit dev tenant header. */ import { NextResponse, type NextRequest } from 'next/server'; import { VERIFIED_TENANT_HEADER } from './tenant-guard'; export const VERIFIED_SUBJECT_HEADER = 'x-0pt-verified-sub'; /** Dev-only header (AUTH_ENFORCE=false) so local flows still have a scope. */ export const DEV_TENANT_HEADER = 'x-0pt-dev-tenant'; export const DEV_SUBJECT_HEADER = 'x-0pt-dev-subject'; const idPattern = /^[\x21-\x7e]{1,256}$/; export interface VerifiedScope { tenantId: string; actorId: string; } function devMode(): boolean { return process.env.AUTH_ENFORCE === 'false' && process.env.NODE_ENV !== 'production'; } export function resolveVerifiedScope( request: NextRequest, ): { scope: VerifiedScope } | { response: NextResponse } { const tenantId = request.headers.get(VERIFIED_TENANT_HEADER); const actorId = request.headers.get(VERIFIED_SUBJECT_HEADER); if (tenantId && actorId && idPattern.test(tenantId) && idPattern.test(actorId)) { return { scope: { tenantId, actorId } }; } if (devMode()) { const devTenant = request.headers.get(DEV_TENANT_HEADER); const devActor = request.headers.get(DEV_SUBJECT_HEADER); if (devTenant && devActor && idPattern.test(devTenant) && idPattern.test(devActor)) { return { scope: { tenantId: devTenant, actorId: devActor } }; } } return { response: NextResponse.json( { error: 'OPT_UNAUTHENTICATED', message: 'A verified tenant and subject are required', }, { status: 401 }, ), }; } export function isValidScopeId(value: unknown): value is string { return typeof value === 'string' && idPattern.test(value); }