Skip to content

Commit

Permalink
fix loading websockets when node is built w/ --without-ssl (nodejs#2282)
Browse files Browse the repository at this point in the history
  • Loading branch information
KhafraDev authored and crysmags committed Feb 27, 2024
1 parent 2325d13 commit 0d18011
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 5 deletions.
13 changes: 10 additions & 3 deletions lib/websocket/connection.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
'use strict'

const { randomBytes, createHash } = require('crypto')
const diagnosticsChannel = require('diagnostics_channel')
const { uid, states } = require('./constants')
const {
Expand All @@ -22,6 +21,14 @@ channels.open = diagnosticsChannel.channel('undici:websocket:open')
channels.close = diagnosticsChannel.channel('undici:websocket:close')
channels.socketError = diagnosticsChannel.channel('undici:websocket:socket_error')

/** @type {import('crypto')} */
let crypto
try {
crypto = require('crypto')
} catch {

}

/**
* @see https://websockets.spec.whatwg.org/#concept-websocket-establish
* @param {URL} url
Expand Down Expand Up @@ -66,7 +73,7 @@ function establishWebSocketConnection (url, protocols, ws, onEstablish, options)
// 5. Let keyValue be a nonce consisting of a randomly selected
// 16-byte value that has been forgiving-base64-encoded and
// isomorphic encoded.
const keyValue = randomBytes(16).toString('base64')
const keyValue = crypto.randomBytes(16).toString('base64')

// 6. Append (`Sec-WebSocket-Key`, keyValue) to request’s
// header list.
Expand Down Expand Up @@ -148,7 +155,7 @@ function establishWebSocketConnection (url, protocols, ws, onEstablish, options)
// trailing whitespace, the client MUST _Fail the WebSocket
// Connection_.
const secWSAccept = response.headersList.get('Sec-WebSocket-Accept')
const digest = createHash('sha1').update(keyValue + uid).digest('base64')
const digest = crypto.createHash('sha1').update(keyValue + uid).digest('base64')
if (secWSAccept !== digest) {
failWebsocketConnection(ws, 'Incorrect hash received in Sec-WebSocket-Accept header.')
return
Expand Down
11 changes: 9 additions & 2 deletions lib/websocket/frame.js
Original file line number Diff line number Diff line change
@@ -1,15 +1,22 @@
'use strict'

const { randomBytes } = require('crypto')
const { maxUnsigned16Bit } = require('./constants')

/** @type {import('crypto')} */
let crypto
try {
crypto = require('crypto')
} catch {

}

class WebsocketFrameSend {
/**
* @param {Buffer|undefined} data
*/
constructor (data) {
this.frameData = data
this.maskKey = randomBytes(4)
this.maskKey = crypto.randomBytes(4)
}

createFrame (opcode) {
Expand Down

0 comments on commit 0d18011

Please sign in to comment.