Files
worldmonitor/server/cors.ts
Nicolas Gomes Ferreira Dos Santos f5b2d4c82c refactor(server): consolidate declare const process into shared env.d.ts (#752)
The same ambient process declaration was duplicated across 35 server
files. Move it to a single server/env.d.ts file that tsconfig.api.json
automatically includes.

Addresses #197 (L-15).

Co-authored-by: Claude Opus 4.6 <noreply@anthropic.com>
2026-03-02 14:01:41 +04:00

48 lines
1.5 KiB
TypeScript

/**
* CORS header generation -- TypeScript port of api/_cors.js.
*
* Identical ALLOWED_ORIGIN_PATTERNS and logic, with methods set
* to 'GET, POST, OPTIONS' (sebuf routes support GET and POST).
*/
const PRODUCTION_PATTERNS: RegExp[] = [
/^https:\/\/(.*\.)?worldmonitor\.app$/,
/^https:\/\/worldmonitor-[a-z0-9-]+-elie-[a-z0-9]+\.vercel\.app$/,
/^https?:\/\/tauri\.localhost(:\d+)?$/,
/^https?:\/\/[a-z0-9-]+\.tauri\.localhost(:\d+)?$/i,
/^tauri:\/\/localhost$/,
/^asset:\/\/localhost$/,
];
const DEV_PATTERNS: RegExp[] = [
/^https?:\/\/localhost(:\d+)?$/,
/^https?:\/\/127\.0\.0\.1(:\d+)?$/,
];
const ALLOWED_ORIGIN_PATTERNS: RegExp[] =
process.env.NODE_ENV === 'production'
? PRODUCTION_PATTERNS
: [...PRODUCTION_PATTERNS, ...DEV_PATTERNS];
function isAllowedOrigin(origin: string): boolean {
return Boolean(origin) && ALLOWED_ORIGIN_PATTERNS.some((pattern) => pattern.test(origin));
}
export function getCorsHeaders(req: Request): Record<string, string> {
const origin = req.headers.get('origin') || '';
const allowOrigin = isAllowedOrigin(origin) ? origin : 'https://worldmonitor.app';
return {
'Access-Control-Allow-Origin': allowOrigin,
'Access-Control-Allow-Methods': 'GET, POST, OPTIONS',
'Access-Control-Allow-Headers': 'Content-Type, Authorization, X-WorldMonitor-Key',
'Access-Control-Max-Age': '86400',
'Vary': 'Origin',
};
}
export function isDisallowedOrigin(req: Request): boolean {
const origin = req.headers.get('origin');
if (!origin) return false;
return !isAllowedOrigin(origin);
}