ws: req.setHeader() in finishRequest does not replace a header of options.headers with an uppercase name
What version of Bun is running?
1.4.2+744846f84. Also main at a4f1429148.
What platform is your computer?
Linux x64
What steps can reproduce the bug?
Give the ws client a header in options.headers. Then replace it with req.setHeader() in finishRequest. The name has an uppercase letter.
const net = require("net");
const { WebSocket } = require("ws");
const server = net.createServer(socket => {
socket.on("error", () => {});
socket.once("data", chunk => {
console.log(chunk.toString("latin1").split("\r\n").filter(line => /^x-token\s*:/i.test(line)));
socket.destroy();
});
});
server.listen(0, "127.0.0.1", () => {
const ws = new WebSocket(`ws://127.0.0.1:${server.address().port}/`, {
headers: { "X-Token": "a" },
finishRequest(req) {
console.log(req.getHeader("X-Token"), req.hasHeader("X-Token"));
req.setHeader("X-Token", "b");
console.log(req.getHeaders()["x-token"], Object.keys(req.getHeaders()).filter(k => /x-token/i.test(k)));
req.end();
},
});
ws.on("error", () => {});
ws.on("close", () => {
server.close();
process.exit(0);
});
});What is the expected behavior?
The new value replaces the old one. Node v26.3.0 with ws 8.18.3 prints:
a true
b [ 'x-token' ]
[ 'X-Token: b' ]What do you see instead?
The server gets both values in one header. The request does not find the header of options.headers.
undefined false
b [ "X-Token", "x-token" ]
[ "X-Token: a, b" ]Additional information
The cause is in src/js/thirdparty/ws.js. The request that finishRequest gets keeps a copy of options.headers with the names as the caller wrote them (line 227). setHeader(), getHeader(), hasHeader() and removeHeader() use the name in lowercase (lines 236 to 251). A name with an uppercase letter thus has two keys, and the native WebSocket joins the two values.
The effects:
| Call | Node + ws 8.18.3 |
Bun |
|---|---|---|
req.getHeader("X-Token") before setHeader() |
"a" |
undefined |
req.hasHeader("X-Token") before setHeader() |
true |
false |
req.setHeader("X-Token", "b") |
the server gets X-Token: b |
the server gets X-Token: a, b |
req.removeHeader("X-Token") |
the header is not sent | the server gets X-Token: a |
req.getHeaders() after setHeader() |
one key, x-token |
two keys, X-Token and x-token |
A header that options.headers names in lowercase is not affected.
One client in this repository has the pattern. packages/bun-inspector-protocol/src/inspector/websocket.ts (lines 53 to 61) sets Ref-Event-Loop: 0 in options.headers and again with setHeader(). On Bun the server gets Ref-Event-Loop: 0, 0. src/js/internal/debugger.ts:531 compares the value with "0".
Found during the work on #44098. #44123 does not change this behaviour.
Source: oven-sh/bun