Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion lib/web/websocket/connection.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,14 @@ function establishWebSocketConnection (url, protocols, client, handler, options)
request.headersList = headersList
}

// If the URL has credentials, add Authorization header (unless already set by options.headers)
// @see https://fetch.spec.whatwg.org/#concept-basic-fetch (step 12.2.3)
if ((url.username || url.password) && !request.headersList.contains('authorization', true)) {
const credentials = `${url.username}:${url.password}`
const encoded = Buffer.from(credentials).toString('base64')
request.headersList.append('authorization', `Basic ${encoded}`, true)
}
Comment on lines +55 to +61
Copy link
Member

@KhafraDev KhafraDev Jan 17, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

See my reasoning for why this should not be set: #4744 (comment)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

step 12.2.3

What is this referring to? scheme fetch doesn't have a 12.2.3


// 3. Append (`Upgrade`, `websocket`) to request’s header list.
// 4. Append (`Connection`, `Upgrade`) to request’s header list.
// Note: both of these are handled by undici currently.
Expand Down Expand Up @@ -315,7 +323,8 @@ function failWebsocketConnection (handler, code, reason, cause) {

if (isConnecting(handler.readyState)) {
// If the connection was not established, we must still emit an 'error' and 'close' events
handler.onSocketClose()
// Queue via microtask so close() returns before events fire and readyState transitions correctly
queueMicrotask(() => handler.onSocketClose())
} else if (handler.socket?.destroyed === false) {
handler.socket.destroy()
}
Expand Down
5 changes: 5 additions & 0 deletions lib/web/websocket/websocket.js
Original file line number Diff line number Diff line change
Expand Up @@ -554,6 +554,11 @@ class WebSocket extends EventTarget {
* @see https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4
*/
#onSocketClose () {
// Guard against duplicate calls
if (this.#handler.readyState === states.CLOSED) {
return
}
Comment on lines +558 to +560
Copy link
Member

@KhafraDev KhafraDev Jan 17, 2026

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

From local testing, this only seems to be called once. If we kept this in we'd be hiding other bugs.

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sorry, I don't understand what you want to be done here

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The reference is actually wrong, I'll amend.


// If the TCP connection was closed after the
// WebSocket closing handshake was completed, the WebSocket connection
// is said to have been closed _cleanly_.
Expand Down
27 changes: 9 additions & 18 deletions test/web-platform-tests/expectation.json
Original file line number Diff line number Diff line change
Expand Up @@ -37734,8 +37734,7 @@
"cases": [
{
"name": "close event should be fired asynchronously when WebSocket is connecting",
"success": false,
"message": "assert_true: ws.close() should have returned expected true got false"
"success": true
}
]
},
Expand All @@ -37744,8 +37743,7 @@
"cases": [
{
"name": "close event should be fired asynchronously when WebSocket is connecting",
"success": false,
"message": "assert_true: ws.close() should have returned expected true got false"
"success": true
}
]
},
Expand All @@ -37754,8 +37752,7 @@
"cases": [
{
"name": "close event should be fired asynchronously when WebSocket is connecting",
"success": false,
"message": "assert_true: ws.close() should have returned expected true got false"
"success": true
}
]
},
Expand All @@ -37764,8 +37761,7 @@
"cases": [
{
"name": "close-connecting",
"success": false,
"message": "assert_unreached: Reached unreachable code"
"success": true
}
]
},
Expand All @@ -37774,8 +37770,7 @@
"cases": [
{
"name": "close-connecting",
"success": false,
"message": "assert_unreached: Reached unreachable code"
"success": true
}
]
},
Expand All @@ -37784,8 +37779,7 @@
"cases": [
{
"name": "close-multiple",
"success": false,
"message": "assert_equals: expected 1 but got 2"
"success": true
}
]
},
Expand All @@ -37794,8 +37788,7 @@
"cases": [
{
"name": "close-multiple",
"success": false,
"message": "assert_equals: expected 1 but got 2"
"success": true
}
]
},
Expand All @@ -37804,8 +37797,7 @@
"cases": [
{
"name": "close-nested",
"success": false,
"message": "assert_equals: expected 1 but got 2"
"success": true
}
]
},
Expand All @@ -37814,8 +37806,7 @@
"cases": [
{
"name": "close-nested",
"success": false,
"message": "assert_equals: expected 1 but got 2"
"success": true
}
]
},
Expand Down
11 changes: 11 additions & 0 deletions test/web-platform-tests/runner/test-runner.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,8 @@ import {
Request,
Response,
setGlobalOrigin,
setGlobalDispatcher,
Agent,
CloseEvent,
WebSocket,
caches,
Expand All @@ -16,6 +18,15 @@ import { Cache } from '../../../lib/web/cache/cache.js'
import { CacheStorage } from '../../../lib/web/cache/cachestorage.js'
import { runInThisContext } from 'node:vm'
import { debuglog } from 'node:util'
import { readFileSync } from 'node:fs'
import { join } from 'node:path'

// Configure global dispatcher to trust WPT server's CA certificate
const caCertPath = join(import.meta.dirname, 'certs/cacert.pem')
const ca = readFileSync(caCertPath)
setGlobalDispatcher(new Agent({
connect: { ca }
}))

const globalPropertyDescriptors = {
writable: true,
Expand Down
4 changes: 3 additions & 1 deletion test/web-platform-tests/wpt-runner.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,7 @@ import * as jsondiffpatch from 'jsondiffpatch'

const WPT_DIR = join(import.meta.dirname, 'wpt')
const EXPECTATION_PATH = join(import.meta.dirname, 'expectation.json')
const CA_CERT_PATH = join(import.meta.dirname, 'runner/certs/cacert.pem')

const log = debuglog('UNDICI_WPT')

Expand Down Expand Up @@ -76,7 +77,8 @@ function runSingleTest (url, options, expectation, timeout = 10000) {
stdio: ['ignore', 'pipe', 'pipe'],
env: {
...process.env,
NO_COLOR: '1'
NO_COLOR: '1',
NODE_EXTRA_CA_CERTS: CA_CERT_PATH
}
})

Expand Down
89 changes: 89 additions & 0 deletions test/websocket/url-credentials.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,89 @@
'use strict'

const { test } = require('node:test')
const { once } = require('node:events')
const { createServer } = require('node:http')
const { WebSocket } = require('../..')

test('WebSocket sets Authorization header from URL credentials', async (t) => {
const server = createServer((req, res) => {
const expected = 'Basic ' + Buffer.from('foo:bar').toString('base64')
t.assert.strictEqual(req.headers.authorization, expected)
res.end()
}).listen(0)

await once(server, 'listening')
t.after(() => server.close())

const ws = new WebSocket(`ws://foo:bar@localhost:${server.address().port}/`)
ws.onerror = () => {} // Expected - server doesn't complete WebSocket handshake

await once(server, 'request')
})

test('WebSocket sets Authorization header with only username', async (t) => {
const server = createServer((req, res) => {
const expected = 'Basic ' + Buffer.from('foo:').toString('base64')
t.assert.strictEqual(req.headers.authorization, expected)
res.end()
}).listen(0)

await once(server, 'listening')
t.after(() => server.close())

const ws = new WebSocket(`ws://foo@localhost:${server.address().port}/`)
ws.onerror = () => {}

await once(server, 'request')
})

test('WebSocket sets Authorization header with only password', async (t) => {
const server = createServer((req, res) => {
const expected = 'Basic ' + Buffer.from(':bar').toString('base64')
t.assert.strictEqual(req.headers.authorization, expected)
res.end()
}).listen(0)

await once(server, 'listening')
t.after(() => server.close())

const ws = new WebSocket(`ws://:bar@localhost:${server.address().port}/`)
ws.onerror = () => {}

await once(server, 'request')
})

test('WebSocket does not set Authorization header when no credentials', async (t) => {
const server = createServer((req, res) => {
t.assert.strictEqual(req.headers.authorization, undefined)
res.end()
}).listen(0)

await once(server, 'listening')
t.after(() => server.close())

const ws = new WebSocket(`ws://localhost:${server.address().port}/`)
ws.onerror = () => {}

await once(server, 'request')
})

test('WebSocket custom Authorization header takes precedence over URL credentials', async (t) => {
const customAuth = 'Bearer mytoken'
const server = createServer((req, res) => {
t.assert.strictEqual(req.headers.authorization, customAuth)
res.end()
}).listen(0)

await once(server, 'listening')
t.after(() => server.close())

const ws = new WebSocket(`ws://foo:bar@localhost:${server.address().port}/`, {
headers: {
Authorization: customAuth
}
})
ws.onerror = () => {}

await once(server, 'request')
})
Loading