Reputation: 67
We use vercel/micro and we need to allow multiple origins it makes local development easier and we need to support multiple clients for the future. I was having issues because ports are dynamic for local development. This is what I came up with, and its been working but would this be considered safe? Would it pass a security audit?
function isAllowedOrigin({ req, baseUrl }) {
const allowedOrigins = [new URL(baseUrl.replace(/\/$/g, ""))];
const origin = new URL(req.headers.origin);
const foundOrigin = allowedOrigins.find((allowedOrigin) => {
allowedOrigin.port = origin.port;
return allowedOrigin.origin === origin.origin;
});
return foundOrigin;
}
These are the headers
const headers = {
"Access-Control-Allow-Credentials": true,
"Access-Control-Allow-Headers":
"Origin, X-Requested-With, Content-Type, Accept, Authorization",
};
if (isAllowedOrigin({ req, baseUrl })) {
headers["Access-Control-Allow-Origin"] = req.headers.origin;
}
I could also have a local allowed ports for each micro service
Upvotes: 0
Views: 455
Reputation: 12900
The best answer is from the Open Web Application Security Project (OWASP) CORS Page A bad server configuration of the CORS headers may expose your users to Cross site scripting (XSS).
In your example, a malicious user could send a string in origin that lets you crash new URL('hello') // this throws an error
To support multiple env you could change the allowedOrigins
based on the process.env.NODE_ENV
, assuming you will have one route for dev, one for test and so on: this lets you check dynamically the ports for dev and strict for production.
For a large server farm, it is used the match of the root domain usually.
Upvotes: 1