/koa-cors-gate

Primary LanguageJavaScriptMIT LicenseMIT

build status code coverage code style styled with prettier made with lass license

CORS gate for Koa

Table of Contents

Install

npm:

npm install koa-cors-gate

yarn:

yarn add koa-cors-gate

Usage

const Koa = require('koa');
const CorsGate = require('koa-cors-gate');

const app = new Koa();

app.use(
  new CorsGate({
    allowSafe: false,
    origin: 'http://localhost'
  }).middleware
);

Alternative failure handling

By default, koa-cors-gate will return 403 Unauthorized to any requests that aren't permitted by the specified options.

The failure option offers a means to change this behavior. This way, unauthorized cross-origin requests can be permitted in a restricted manner - perhaps by requiring an explicit authentication mechanism rather than cookie-based authentication to prevent cross-site scripting. As such, cors-gate can serve as a CSRF mechanism without the need for a token, while still allowing limited forms of third-party cross-origin API requests.

app.use(new CorsGate({
  origin: 'http://localhost',
  failure: ({req, res}, next) => {
    // requests from other origins will have this flag set.
    req.requireExplicitAuthentication = true;
  }
}).middleware);

Firefox and the Origin header

Firefox does not set the Origin header on same-origin requests (see also csrf-request-tester) for same-origin requests, as of version 53. The corsGate.originFallbackToReferrer middleware will, if the Origin header is missing, fill it with the origin part of the Referer. This middleware thus enables verification of the Origin for same-origin requests.

Additionally, no browser sends the Origin header when sending a GET request to load an image. We could simply allow all GET requests - GET requests are safe, per HTTP - but we'd rather reject unauthorized cross-origin GET requests wholesale.

At present, Chrome and Safari do not support the strict-origin Referrer-Policy, so we can only patch the Origin from the Referer on Firefox. In patching it, however, we can reject unauthorized cross-origin GET requests from images, and once Chrome and Safari support strict-origin, we'll be able to do so on all three platforms.

In order to actually reject these requests, however, the patched Origin data must be visible to the cors middleware. This middleware is distinct because it must appear before cors and corsGate to perform all the described tasks.

app.use(corsGate.originFallbackToReferrer());
app.use(cors({ ... }));
app.use(new CorsGate({ ... }));

Contributors

Name Website
Alexis Tyler https://wvvw.me/

Trademark Notice

Lad, Lass, and their respective logos are trademarks of Niftylettuce LLC. These trademarks may not be reproduced, distributed, transmitted, or otherwise used, except with the prior written permission of Niftylettuce LLC. If you are seeking permission to use these trademarks, then please contact us.

License

MIT © Nick Baugh