Skip to content

Commit 448aec0

Browse files
committed
fix(cors): improve CORS origin validation and error handling
1 parent f21f403 commit 448aec0

File tree

1 file changed

+15
-10
lines changed

1 file changed

+15
-10
lines changed

server.ts

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -66,31 +66,36 @@ const fastify = Fastify({
6666
logger: true,
6767
});
6868

69+
Sentry.setupFastifyErrorHandler(fastify);
70+
await fastify.register(envPlugin);
71+
6972
fastify.register(cors, {
7073
origin: isLocalDev
7174
? true // Allow all origins in local development
7275
: (origin, callback) => {
7376
// In production, validate against allowed origins
74-
// @ts-ignore
75-
const allowedOrigins = fastify.config.ALLOWED_CORS_ORIGINS
76-
? // @ts-ignore
77-
fastify.config.ALLOWED_CORS_ORIGINS.split(',').map((o) => o.trim())
78-
: // @ts-ignore
79-
[fastify.config.POST_LOGIN_REDIRECT]; // Fallback to POST_LOGIN_REDIRECT
77+
const allowedOrigins =
78+
// @ts-ignore
79+
fastify.config.ALLOWED_CORS_ORIGINS && fastify.config.ALLOWED_CORS_ORIGINS.trim()
80+
? // @ts-ignore
81+
fastify.config.ALLOWED_CORS_ORIGINS.split(',')
82+
// @ts-ignore
83+
.map((o) => o.trim())
84+
// @ts-ignore
85+
.filter((o) => o)
86+
: // @ts-ignore
87+
[fastify.config.POST_LOGIN_REDIRECT]; // Fallback to POST_LOGIN_REDIRECT
8088

8189
if (!origin || allowedOrigins.includes(origin)) {
8290
callback(null, true);
8391
} else {
84-
callback(new Error(`Origin ${origin} not allowed by CORS policy`), false);
92+
callback(null, false);
8593
}
8694
},
8795
methods: ['GET', 'HEAD', 'POST', 'PUT', 'PATCH', 'DELETE'],
8896
credentials: true, // Required for cookie-based sessions
8997
});
9098

91-
Sentry.setupFastifyErrorHandler(fastify);
92-
await fastify.register(envPlugin);
93-
9499
let sentryHost = '';
95100
// @ts-ignore
96101
if (fastify.config.FRONTEND_SENTRY_DSN && fastify.config.FRONTEND_SENTRY_DSN.length > 0) {

0 commit comments

Comments
 (0)