11'use strict'
22
3- const { randomBytes, createHash } = require ( 'crypto' )
43const diagnosticsChannel = require ( 'diagnostics_channel' )
54const { uid, states } = require ( './constants' )
65const {
@@ -22,6 +21,14 @@ channels.open = diagnosticsChannel.channel('undici:websocket:open')
2221channels . close = diagnosticsChannel . channel ( 'undici:websocket:close' )
2322channels . 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
0 commit comments