diff --git a/packages/engine.io-client/lib/transports/polling-fetch.ts b/packages/engine.io-client/lib/transports/polling-fetch.ts index 7d85b66c6..c4dccf6ba 100644 --- a/packages/engine.io-client/lib/transports/polling-fetch.ts +++ b/packages/engine.io-client/lib/transports/polling-fetch.ts @@ -52,7 +52,9 @@ export class Fetch extends Polling { method: isPost ? "POST" : "GET", body: isPost ? data : null, headers, - credentials: this.opts.withCredentials ? "include" : "omit", + // same behavior as XMLHttpRequest: cookies are always sent for same-origin requests, and only with + // `withCredentials: true` for cross-origin requests + credentials: this.opts.withCredentials ? "include" : "same-origin", }).then((res) => { // @ts-ignore getSetCookie() was added in Node.js v19.7.0 this.socket._cookieJar?.parseCookies(res.headers.getSetCookie()); diff --git a/packages/engine.io-client/test/node.js b/packages/engine.io-client/test/node.js index 1f756a13b..5e3fb2cb7 100644 --- a/packages/engine.io-client/test/node.js +++ b/packages/engine.io-client/test/node.js @@ -1,6 +1,6 @@ const path = require("node:path"); const { execFile } = require("node:child_process"); -const { Socket } = require("../"); +const { Socket, Fetch } = require("../"); const { repeat } = require("./util"); const expect = require("expect.js"); const { parse } = require("../build/cjs/globals.node.js"); @@ -109,6 +109,50 @@ describe("node.js", () => { }); }); + describe("credentials mode of the fetch() transport", () => { + const originalFetch = globalThis.fetch; + let credentials; + + beforeEach(() => { + credentials = []; + globalThis.fetch = (url, init) => { + credentials.push(init.credentials); + return originalFetch(url, init); + }; + }); + + afterEach(() => { + globalThis.fetch = originalFetch; + }); + + it("should send same-origin cookies with withCredentials: false", (done) => { + const socket = new Socket({ + transports: [Fetch], + withCredentials: false, + }); + + socket.on("open", () => { + // like XMLHttpRequest, and unlike "omit", which drops the cookies of the page origin + expect(credentials).to.eql(["same-origin"]); + socket.close(); + done(); + }); + }); + + it("should send cross-origin cookies with withCredentials: true", (done) => { + const socket = new Socket({ + transports: [Fetch], + withCredentials: true, + }); + + socket.on("open", () => { + expect(credentials).to.eql(["include"]); + socket.close(); + done(); + }); + }); + }); + it("should not modify the extraHeaders option with withCredentials: true", (done) => { const extraHeaders = { foo: "bar" }; const socket = new Socket("http://localhost:3000", {