Files
FFF_vtt_frozen/tools/wsheaders.test.mjs
T

73 lines
2.7 KiB
JavaScript

// #16: re-check the Node 26 header behaviour for the global WebSocket {headers} (research #8
// verified v24 only; the prototype lib.mjs note said "Node 22" and is stale). Recorded here as a
// test so a Node upgrade that drops the option fails loudly instead of silently un-authenticating
// every harness. Result: printed as a RECORD line and in results/node-test.log.
import test from 'node:test'
import assert from 'node:assert/strict'
import crypto from 'node:crypto'
import net from 'node:net'
const WS_GUID = '258EAFA5-E914-47DA-95CA-C5AB0DC85B11'
// A TCP trap that answers a WebSocket upgrade and hands back the raw request head.
async function upgradeTrap() {
let resolveSeen
const seen = new Promise(res => { resolveSeen = res })
const sockets = new Set()
const srv = net.createServer(sock => {
sockets.add(sock)
sock.on('close', () => sockets.delete(sock))
sock.on('error', () => {})
let buf = ''
sock.on('data', d => {
buf += d.toString('latin1')
if (!buf.includes('\r\n\r\n')) return
const key = /sec-websocket-key:\s*(\S+)/i.exec(buf)?.[1] ?? ''
const accept = crypto.createHash('sha1').update(key + WS_GUID).digest('base64')
sock.write(['HTTP/1.1 101 Switching Protocols', 'Upgrade: websocket',
'Connection: Upgrade', `Sec-WebSocket-Accept: ${accept}`, '', ''].join('\r\n'))
resolveSeen(buf)
})
})
await new Promise(res => srv.listen(0, '127.0.0.1', res))
return {
port: srv.address().port,
seen,
async close() {
for (const s of sockets) s.destroy()
await new Promise(res => srv.close(res))
},
}
}
test('global WebSocket {headers} puts Cookie and Origin on the wire (Node 26 check)', async () => {
const trap = await upgradeTrap()
try {
const ws = new WebSocket(`ws://127.0.0.1:${trap.port}/ws`, {
headers: { Cookie: 'fff_session=abc123', Origin: 'https://evil.example' },
})
ws.onerror = () => {} // the trap speaks no frames; a teardown error is irrelevant
const request = await trap.seen
assert.match(request, /^GET \/ws HTTP\/1\.1/m)
assert.match(request, /^cookie: fff_session=abc123$/im)
assert.match(request, /^origin: https:\/\/evil\.example$/im)
console.log(`RECORD ws-headers node=${process.version} cookie=ok origin=ok`)
ws.close()
} finally {
await trap.close()
}
})
test('without {headers} no Origin is sent: later Origin checks need it explicitly', async () => {
const trap = await upgradeTrap()
try {
const ws = new WebSocket(`ws://127.0.0.1:${trap.port}/ws`)
ws.onerror = () => {}
const request = await trap.seen
assert.doesNotMatch(request, /^origin:/im)
ws.close()
} finally {
await trap.close()
}
})