fix(server): return clean CORS rejection instead of 500 error

When an unknown origin made a request, the CORS middleware called
callback(new Error('Not allowed by CORS')) which bubbled into Express's
default error handler, returning a 500 Internal Server Error with a stack
trace. The browser showed a confusing CORS + 500 error instead of a clean
CORS block.

Fix: pass `false` to the cors callback for rejected origins. This omits
the Access-Control-Allow-Origin header (so the browser blocks the request)
without triggering a server error.

Closes #640

Co-Authored-By: Claude Opus 4.6 (1M context) <noreply@anthropic.com>
This commit is contained in:
Abhigyan Patwari 2026-04-04 07:22:48 +05:30
parent 5c4fca21c3
commit cd62bc64a0

View file

@ -276,14 +276,13 @@ export const createServer = async (port: number, host: string = '127.0.0.1') =>
// CORS: allow localhost, private/LAN networks, and the deployed site.
// Non-browser requests (curl, server-to-server) have no origin and are allowed.
// Disallowed origins get the response without Access-Control-Allow-Origin,
// so the browser blocks it. We pass `false` instead of throwing an Error to
// avoid crashing into Express's default error handler (which returned 500).
app.use(
cors({
origin: (origin, callback) => {
if (isAllowedOrigin(origin)) {
callback(null, true);
} else {
callback(new Error('Not allowed by CORS'));
}
callback(null, isAllowedOrigin(origin) ? true : false);
},
}),
);