Skip to content

Commit

Permalink
feat: serve client bundles with CORS headers
Browse files Browse the repository at this point in the history
The version of the `cors` package matches the one used by `engine.io`.

Related: #3552
  • Loading branch information
darrachequesne committed Jun 20, 2023
1 parent a250e28 commit 63f181c
Show file tree
Hide file tree
Showing 4 changed files with 41 additions and 2 deletions.
18 changes: 17 additions & 1 deletion lib/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import {
SecondArg,
} from "./typed-events";
import { patchAdapter, restoreAdapter, serveFile } from "./uws";
import corsMiddleware from "cors";

const debug = debugModule("socket.io:server");

Expand Down Expand Up @@ -202,6 +203,11 @@ export class Server<
*/
_connectTimeout: number;
private httpServer: http.Server | HTTPSServer | Http2SecureServer;
private _corsMiddleware: (
req: http.IncomingMessage,
res: http.ServerResponse,
next: () => void
) => void;

/**
* Server constructor.
Expand Down Expand Up @@ -267,6 +273,10 @@ export class Server<
this.attach(
srv as http.Server | HTTPSServer | Http2SecureServer | number
);

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

get _opts() {
Expand Down Expand Up @@ -548,7 +558,13 @@ export class Server<
srv.removeAllListeners("request");
srv.on("request", (req, res) => {
if (this.clientPathRegex.test(req.url!)) {
this.serve(req, res);
if (this._corsMiddleware) {
this._corsMiddleware(req, res, () => {
this.serve(req, res);
});
} else {
this.serve(req, res);
}
} else {
for (let i = 0; i < evs.length; i++) {
evs[i].call(srv, req, res);
Expand Down
3 changes: 2 additions & 1 deletion package-lock.json

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

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@
"dependencies": {
"accepts": "~1.3.4",
"base64id": "~2.0.0",
"cors": "~2.8.5",
"debug": "~4.3.2",
"engine.io": "~6.5.0",
"socket.io-adapter": "~2.5.2",
Expand Down
21 changes: 21 additions & 0 deletions test/server-attachment.ts
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,27 @@ describe("server attachment", () => {
});
});

it("should serve client with necessary CORS headers", (done) => {
const srv = createServer();
new Server(srv, {
cors: {
origin: "https://good-origin.com",
},
});
request(srv)
.get("/socket.io/socket.io.js")
.set("origin", "https://good-origin.com")
.buffer(true)
.end((err, res) => {
if (err) return done(err);
expect(res.headers["access-control-allow-origin"]).to.be(
"https://good-origin.com"
);
expect(res.status).to.be(200);
done();
});
});

it(
"should serve bundle with msgpack parser",
testSource("socket.io.msgpack.min.js")
Expand Down

0 comments on commit 63f181c

Please sign in to comment.