Skip to content

Commit 0aaedc4

Browse files
authoredMar 19, 2024··
CORS origins of an array of one are made a scalar. (#1536)
The access-control-allowed-origins CORS header only allows a single origin or "*" as its response. To support multiple origins, the cors middleware makes this header dynamic based on the origin header of the request when the middleware is configured with anything but a single string. To help avoid a few edge cases customers may encounter, we can unwrap an array of one element into a scalar to encourage the cors middleware to make the access-control-allowed-origin header static. As a very minor performance boost, this change also instantiates the cors middleware once and uses it on all requests rather than constructing it dynamically within a request.
1 parent 3d8d595 commit 0aaedc4

File tree

1 file changed

+15
-2
lines changed

1 file changed

+15
-2
lines changed
 

‎src/v2/providers/https.ts

+15-2
Original file line numberDiff line numberDiff line change
@@ -265,12 +265,19 @@ export function onRequest(
265265
// Respect `cors: false` to turn off cors even if debug feature is enabled.
266266
origin = opts.cors === false ? false : true;
267267
}
268+
// Arrays cause the access-control-allow-origin header to be dynamic based
269+
// on the origin header of the request. If there is only one element in the
270+
// array, this is unnecessary.
271+
if (Array.isArray(origin) && origin.length === 1) {
272+
origin = origin[1];
273+
}
274+
const middleware = cors({ origin });
268275

269276
const userProvidedHandler = handler;
270277
handler = (req: Request, res: express.Response): void | Promise<void> => {
271278
return new Promise((resolve) => {
272279
res.on("finish", resolve);
273-
cors({ origin })(req, res, () => {
280+
middleware(req, res, () => {
274281
resolve(userProvidedHandler(req, res));
275282
});
276283
});
@@ -363,7 +370,13 @@ export function onCall<T = any, Return = any | Promise<any>>(
363370
opts = optsOrHandler as CallableOptions;
364371
}
365372

366-
const origin = isDebugFeatureEnabled("enableCors") ? true : "cors" in opts ? opts.cors : true;
373+
let origin = isDebugFeatureEnabled("enableCors") ? true : "cors" in opts ? opts.cors : true;
374+
// Arrays cause the access-control-allow-origin header to be dynamic based
375+
// on the origin header of the request. If there is only one element in the
376+
// array, this is unnecessary.
377+
if (Array.isArray(origin) && origin.length === 1) {
378+
origin = origin[1];
379+
}
367380

368381
// onCallHandler sniffs the function length to determine which API to present.
369382
// fix the length to prevent api versions from being mismatched.

0 commit comments

Comments
 (0)
Please sign in to comment.