diff --git a/server/middleware/00.cors.ts b/server/middleware/00.cors.ts index d03e86d..8ba4ad3 100644 --- a/server/middleware/00.cors.ts +++ b/server/middleware/00.cors.ts @@ -3,6 +3,8 @@ * * Maneja las solicitudes OPTIONS (preflight) para rutas de API externa * y agrega headers CORS a las respuestas. + * + * Solo permite origenes de *.nucleoriofrio.com y localhost (dev) */ // Rutas que necesitan CORS (API externa) @@ -11,6 +13,23 @@ const CORS_ROUTES = [ '/api/mcp' ] +// Validar si el origen está permitido +function isAllowedOrigin(origin: string | undefined): boolean { + if (!origin) return false + + // Permitir cualquier subdominio de nucleoriofrio.com + if (origin.match(/^https?:\/\/([a-z0-9-]+\.)?nucleoriofrio\.com$/)) { + return true + } + + // Permitir localhost para desarrollo + if (origin.match(/^http:\/\/localhost(:\d+)?$/)) { + return true + } + + return false +} + export default defineEventHandler((event) => { const path = getRequestURL(event).pathname @@ -21,13 +40,18 @@ export default defineEventHandler((event) => { return } - // Agregar headers CORS a todas las respuestas de estas rutas - setResponseHeaders(event, { - 'Access-Control-Allow-Origin': '*', - 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS', - 'Access-Control-Allow-Headers': 'Content-Type, Authorization', - 'Access-Control-Max-Age': '86400' // Cache preflight por 24 horas - }) + const origin = getHeader(event, 'origin') + + // Si el origen está permitido, agregar headers CORS + if (isAllowedOrigin(origin)) { + setResponseHeaders(event, { + 'Access-Control-Allow-Origin': origin!, + 'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS', + 'Access-Control-Allow-Headers': 'Content-Type, Authorization', + 'Access-Control-Allow-Credentials': 'true', + 'Access-Control-Max-Age': '86400' // Cache preflight por 24 horas + }) + } // Si es una solicitud OPTIONS (preflight), responder inmediatamente if (getMethod(event) === 'OPTIONS') {