Sec: Restringir CORS a dominios autorizados
All checks were successful
build-and-deploy / build-and-deploy (push) Successful in 1m8s

Solo permite origenes de:
- *.nucleoriofrio.com (produccion)
- localhost:* (desarrollo)

Esto mejora la seguridad al no aceptar solicitudes
de cualquier origen arbitrario.
This commit is contained in:
2025-12-04 17:39:27 -06:00
parent 6ba9dee293
commit 9a7f270e3f

View File

@@ -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') {