serve icon indicating copy to clipboard operation
serve copied to clipboard

Support avoiding the wildcard in CORS headers

Open matthias-ccri opened this issue 4 years ago • 4 comments

Followon to https://github.com/vercel/serve/issues/319

Serve sends CORS headers, however the Access-Control-Allow-Origin header is * which is problematic because in certain requests, the browser blocks the * wildcard because of security or something. So you have to mirror the Origin header back, instead of sending *.

A sample browser error:

Failed to load http://localhost:3010/appentries.json: The value of the 'Access-Control-Allow-Origin' header 
in the response must not be the wildcard '*' when the request's credentials mode is 'include'. 
Origin 'http://localhost:4000' is therefore not allowed access. The credentials mode of requests initiated 
by the XMLHttpRequest is controlled by the withCredentials attribute.

You can create a serve.json file to send the right headers:

{
  "headers": [
    {
      "source": "**/*",
      "headers": [
        {
          "key": "Access-Control-Allow-Origin",
          "value": "http://localhost:8088"
        },
        {
          "key": "Access-Control-Allow-Credentials",
          "value": "true"
        }
      ]
    }
  ]
}

However this is not ideal because 1) it's not dynamic; you have to hard-code the origin, and there can only be one origin, and 2) it's not as convenient as npx serve; you have to create a file.

It would be nice to have a flag for this, like --cors-mirror-origin. Would a PR for that be welcome?

matthias-ccri avatar Sep 16 '21 01:09 matthias-ccri

shameless self-promotion alert:
this feature is available in my @warren-bank/serve fork of serve

notes:

  • when the --cors cli option is enabled:
    • when a request includes an origin header:
      • the cors response header echoes this origin
      • credentials are allowed
    • when no origin header is present:
      • wildcards are used
      • credentials are not allowed

warren-bank avatar Feb 16 '22 04:02 warren-bank

http-server also has the issue https://github.com/http-party/http-server/issues/729

matthias-ccri avatar Feb 16 '22 05:02 matthias-ccri

live-server got it right.

npx serve --cors does not work correctly against latest Chrome 100.0.4896.75, but npx live-server --cors works nicely.

dhlavaty avatar Apr 12 '22 12:04 dhlavaty

Seems like this is still an issue if I'm not mistaken? Trying to find a solution to this. We actually have a security audit complaining about the * allow origin header in our frontend app served from Vercel.

I'm aware a specific origin can be set in vercel.json now but as far as I'm aware that remains only a hardcoded option and won't even accept regex etc. to match a set of origins?

EthanML avatar Apr 18 '23 10:04 EthanML