diff --git a/src/main.ts b/src/main.ts index b037a0b..31c35fc 100644 --- a/src/main.ts +++ b/src/main.ts @@ -28,6 +28,29 @@ async function bootstrap() { validateEnv(); const app = await NestFactory.create(AppModule); + const corsOrigins = (process.env.FABRIC_BACKEND_CENTER_CORS_ORIGINS ?? '') + .split(',') + .map((x) => x.trim()) + .filter(Boolean); + + app.enableCors({ + origin: (origin, callback) => { + // no Origin header: curl/server-to-server/most desktop local calls + if (!origin) return callback(null, true); + + // desktop/electron local file origin + if (origin === 'null') return callback(null, true); + + // empty allowlist => allow all origins + if (!corsOrigins.length) return callback(null, true); + + if (corsOrigins.includes(origin)) return callback(null, true); + return callback(new Error('CORS origin not allowed'), false); + }, + methods: ['GET', 'POST', 'PATCH', 'PUT', 'DELETE', 'OPTIONS'], + allowedHeaders: ['Content-Type', 'Authorization', 'x-client-name', 'x-request-id', 'x-api-key'], + credentials: false, + }); app.setGlobalPrefix('api'); const metrics = app.get(MetricsService); app.use(createRequestContextMiddleware('center', metrics));