Skip to content

Commit

Permalink
feat: use the cors module to handle cross-origin requests
Browse files Browse the repository at this point in the history
We'll now rely on the standard cors module (https://github.com/expressjs/cors),
instead of the custom implementation that is error-prone and not
really user-friendly.

Breaking change: the handlePreflightRequest option is removed by the
change.

Before:

```
new Server({
  handlePreflightRequest: (req, res) => {
    res.writeHead(200, {
      "Access-Control-Allow-Origin": 'https://example.com',
      "Access-Control-Allow-Methods": 'GET',
      "Access-Control-Allow-Headers": 'Authorization',
      "Access-Control-Allow-Credentials": true
    });
    res.end();
  }
})
```

After:

```
new Server({
  cors: {
    origin: "https://example.com",
    methods: ["GET"],
    allowedHeaders: ["Authorization"],
    credentials: true
  }
})
```
  • Loading branch information
darrachequesne committed Feb 11, 2020
1 parent bafe684 commit 61b9492
Show file tree
Hide file tree
Showing 7 changed files with 164 additions and 143 deletions.
2 changes: 1 addition & 1 deletion README.md
Expand Up @@ -249,6 +249,7 @@ to a single process.
headers. This cookie might be used for sticky-session. Defaults to not sending any cookie (`false`).
See [here](https://github.com/jshttp/cookie#options-1) for all supported options.
- `wsEngine` (`String`): what WebSocket server implementation to use. Specified module must conform to the `ws` interface (see [ws module api docs](https://github.com/websockets/ws/blob/master/doc/ws.md)). Default value is `ws`. An alternative c++ addon is also available by installing `uws` module.
- `cors` (`Object`): the options that will be forwarded to the cors module. See [there](https://github.com/expressjs/cors#configuration-options) for all available options. Defaults to no CORS allowed.
- `initialPacket` (`Object`): an optional packet which will be concatenated to the handshake packet emitted by Engine.IO.
- `close`
- Closes all clients
Expand Down Expand Up @@ -277,7 +278,6 @@ to a single process.
- `path` (`String`): name of the path to capture (`/engine.io`).
- `destroyUpgrade` (`Boolean`): destroy unhandled upgrade requests (`true`)
- `destroyUpgradeTimeout` (`Number`): milliseconds after which unhandled requests are ended (`1000`)
- `handlePreflightRequest` (`Boolean|Function`): whether to let engine.io handle the OPTIONS requests. You can also pass a custom function to handle the requests (`true`)
- `generateId`
- Generate a socket id.
- Overwrite this method to generate your custom socket id.
Expand Down
39 changes: 19 additions & 20 deletions lib/server.js
Expand Up @@ -34,7 +34,8 @@ class Server extends EventEmitter {
},
httpCompression: {
threshold: 1024
}
},
cors: false
},
opts
);
Expand All @@ -51,6 +52,10 @@ class Server extends EventEmitter {
);
}

if (this.opts.cors) {
this.corsMiddleware = require("cors")(this.opts.cors);
}

this.init();
}

Expand Down Expand Up @@ -183,20 +188,27 @@ class Server extends EventEmitter {
this.prepare(req);
req.res = res;

const self = this;
this.verify(req, false, function(err, success) {
const callback = (err, success) => {
if (!success) {
sendErrorMessage(req, res, err);
return;
}

if (req._query.sid) {
debug("setting new request for existing client");
self.clients[req._query.sid].transport.onRequest(req);
this.clients[req._query.sid].transport.onRequest(req);
} else {
self.handshake(req._query.transport, req);
this.handshake(req._query.transport, req);
}
});
};

if (this.corsMiddleware) {
this.corsMiddleware.call(null, req, res, () => {
this.verify(req, false, callback);
});
} else {
this.verify(req, false, callback);
}
}

/**
Expand Down Expand Up @@ -380,12 +392,6 @@ class Server extends EventEmitter {
path += "/";

function check(req) {
if (
"OPTIONS" === req.method &&
false === options.handlePreflightRequest
) {
return false;
}
return path === req.url.substr(0, path.length);
}

Expand All @@ -399,14 +405,7 @@ class Server extends EventEmitter {
server.on("request", function(req, res) {
if (check(req)) {
debug('intercepting request for path "%s"', path);
if (
"OPTIONS" === req.method &&
"function" === typeof options.handlePreflightRequest
) {
options.handlePreflightRequest.call(server, req, res);
} else {
self.handleRequest(req, res);
}
self.handleRequest(req, res);
} else {
let i = 0;
const l = listeners.length;
Expand Down
2 changes: 1 addition & 1 deletion lib/transports/index.js
@@ -1,4 +1,4 @@
const XHR = require("./polling-xhr");
const XHR = require("./polling");
const JSONP = require("./polling-jsonp");

/**
Expand Down
43 changes: 0 additions & 43 deletions lib/transports/polling-xhr.js

This file was deleted.

17 changes: 15 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 3 additions & 2 deletions package.json
Expand Up @@ -28,6 +28,7 @@
"accepts": "~1.3.4",
"base64id": "2.0.0",
"cookie": "0.3.1",
"cors": "~2.8.5",
"debug": "~4.1.0",
"engine.io-parser": "git+https://github.com/socketio/engine.io-parser.git#v4",
"ws": "^7.1.2"
Expand Down Expand Up @@ -57,7 +58,7 @@
"files": [
"lib/"
],
"engines" : {
"node" : ">=8.0.0"
"engines": {
"node": ">=8.0.0"
}
}

0 comments on commit 61b9492

Please sign in to comment.