Skip to content

Commit b85ac78

Browse files
authored
fix loading websockets when node is built w/ --without-ssl (#2282)
1 parent ba95ff6 commit b85ac78

2 files changed

Lines changed: 19 additions & 5 deletions

File tree

lib/websocket/connection.js

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,5 @@
11
'use strict'
22

3-
const { randomBytes, createHash } = require('crypto')
43
const diagnosticsChannel = require('diagnostics_channel')
54
const { uid, states } = require('./constants')
65
const {
@@ -22,6 +21,14 @@ channels.open = diagnosticsChannel.channel('undici:websocket:open')
2221
channels.close = diagnosticsChannel.channel('undici:websocket:close')
2322
channels.socketError = diagnosticsChannel.channel('undici:websocket:socket_error')
2423

24+
/** @type {import('crypto')} */
25+
let crypto
26+
try {
27+
crypto = require('crypto')
28+
} catch {
29+
30+
}
31+
2532
/**
2633
* @see https://websockets.spec.whatwg.org/#concept-websocket-establish
2734
* @param {URL} url
@@ -66,7 +73,7 @@ function establishWebSocketConnection (url, protocols, ws, onEstablish, options)
6673
// 5. Let keyValue be a nonce consisting of a randomly selected
6774
// 16-byte value that has been forgiving-base64-encoded and
6875
// isomorphic encoded.
69-
const keyValue = randomBytes(16).toString('base64')
76+
const keyValue = crypto.randomBytes(16).toString('base64')
7077

7178
// 6. Append (`Sec-WebSocket-Key`, keyValue) to request’s
7279
// header list.
@@ -148,7 +155,7 @@ function establishWebSocketConnection (url, protocols, ws, onEstablish, options)
148155
// trailing whitespace, the client MUST _Fail the WebSocket
149156
// Connection_.
150157
const secWSAccept = response.headersList.get('Sec-WebSocket-Accept')
151-
const digest = createHash('sha1').update(keyValue + uid).digest('base64')
158+
const digest = crypto.createHash('sha1').update(keyValue + uid).digest('base64')
152159
if (secWSAccept !== digest) {
153160
failWebsocketConnection(ws, 'Incorrect hash received in Sec-WebSocket-Accept header.')
154161
return

lib/websocket/frame.js

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,22 @@
11
'use strict'
22

3-
const { randomBytes } = require('crypto')
43
const { maxUnsigned16Bit } = require('./constants')
54

5+
/** @type {import('crypto')} */
6+
let crypto
7+
try {
8+
crypto = require('crypto')
9+
} catch {
10+
11+
}
12+
613
class WebsocketFrameSend {
714
/**
815
* @param {Buffer|undefined} data
916
*/
1017
constructor (data) {
1118
this.frameData = data
12-
this.maskKey = randomBytes(4)
19+
this.maskKey = crypto.randomBytes(4)
1320
}
1421

1522
createFrame (opcode) {

0 commit comments

Comments
 (0)