connection.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329
  1. 'use strict'
  2. const { uid, states, sentCloseFrameState, emptyBuffer, opcodes } = require('./constants')
  3. const { parseExtensions, isClosed, isClosing, isEstablished, isConnecting, validateCloseCodeAndReason } = require('./util')
  4. const { makeRequest } = require('../fetch/request')
  5. const { fetching } = require('../fetch/index')
  6. const { Headers, getHeadersList } = require('../fetch/headers')
  7. const { getDecodeSplit } = require('../fetch/util')
  8. const { WebsocketFrameSend } = require('./frame')
  9. const assert = require('node:assert')
  10. const { runtimeFeatures } = require('../../util/runtime-features')
  11. const crypto = runtimeFeatures.has('crypto')
  12. ? require('node:crypto')
  13. : null
  14. let warningEmitted = false
  15. /**
  16. * @see https://websockets.spec.whatwg.org/#concept-websocket-establish
  17. * @param {URL} url
  18. * @param {string|string[]} protocols
  19. * @param {import('./websocket').Handler} handler
  20. * @param {Partial<import('../../../types/websocket').WebSocketInit>} options
  21. */
  22. function establishWebSocketConnection (url, protocols, client, handler, options) {
  23. // 1. Let requestURL be a copy of url, with its scheme set to "http", if url’s
  24. // scheme is "ws", and to "https" otherwise.
  25. const requestURL = url
  26. requestURL.protocol = url.protocol === 'ws:' ? 'http:' : 'https:'
  27. // 2. Let request be a new request, whose URL is requestURL, client is client,
  28. // service-workers mode is "none", referrer is "no-referrer", mode is
  29. // "websocket", credentials mode is "include", cache mode is "no-store" ,
  30. // redirect mode is "error", and use-URL-credentials flag is set.
  31. const request = makeRequest({
  32. urlList: [requestURL],
  33. client,
  34. serviceWorkers: 'none',
  35. referrer: 'no-referrer',
  36. mode: 'websocket',
  37. credentials: 'include',
  38. cache: 'no-store',
  39. redirect: 'error',
  40. useURLCredentials: true
  41. })
  42. // Note: undici extension, allow setting custom headers.
  43. if (options.headers) {
  44. const headersList = getHeadersList(new Headers(options.headers))
  45. request.headersList = headersList
  46. }
  47. // 3. Append (`Upgrade`, `websocket`) to request’s header list.
  48. // 4. Append (`Connection`, `Upgrade`) to request’s header list.
  49. // Note: both of these are handled by undici currently.
  50. // https://github.com/nodejs/undici/blob/68c269c4144c446f3f1220951338daef4a6b5ec4/lib/client.js#L1397
  51. // 5. Let keyValue be a nonce consisting of a randomly selected
  52. // 16-byte value that has been forgiving-base64-encoded and
  53. // isomorphic encoded.
  54. const keyValue = crypto.randomBytes(16).toString('base64')
  55. // 6. Append (`Sec-WebSocket-Key`, keyValue) to request’s
  56. // header list.
  57. request.headersList.append('sec-websocket-key', keyValue, true)
  58. // 7. Append (`Sec-WebSocket-Version`, `13`) to request’s
  59. // header list.
  60. request.headersList.append('sec-websocket-version', '13', true)
  61. // 8. For each protocol in protocols, combine
  62. // (`Sec-WebSocket-Protocol`, protocol) in request’s header
  63. // list.
  64. for (const protocol of protocols) {
  65. request.headersList.append('sec-websocket-protocol', protocol, true)
  66. }
  67. // 9. Let permessageDeflate be a user-agent defined
  68. // "permessage-deflate" extension header value.
  69. // https://github.com/mozilla/gecko-dev/blob/ce78234f5e653a5d3916813ff990f053510227bc/netwerk/protocol/websocket/WebSocketChannel.cpp#L2673
  70. const permessageDeflate = 'permessage-deflate; client_max_window_bits'
  71. // 10. Append (`Sec-WebSocket-Extensions`, permessageDeflate) to
  72. // request’s header list.
  73. request.headersList.append('sec-websocket-extensions', permessageDeflate, true)
  74. // 11. Fetch request with useParallelQueue set to true, and
  75. // processResponse given response being these steps:
  76. const controller = fetching({
  77. request,
  78. useParallelQueue: true,
  79. dispatcher: options.dispatcher,
  80. processResponse (response) {
  81. // 1. If response is a network error or its status is not 101,
  82. // fail the WebSocket connection.
  83. // if (response.type === 'error' || ((response.socket?.session != null && response.status !== 200) && response.status !== 101)) {
  84. if (response.type === 'error' || response.status !== 101) {
  85. // The presence of a session property on the socket indicates HTTP2
  86. // HTTP1
  87. if (response.socket?.session == null) {
  88. failWebsocketConnection(handler, 1002, 'Received network error or non-101 status code.', response.error)
  89. return
  90. }
  91. // HTTP2
  92. if (response.status !== 200) {
  93. failWebsocketConnection(handler, 1002, 'Received network error or non-200 status code.', response.error)
  94. return
  95. }
  96. }
  97. if (warningEmitted === false && response.socket?.session != null) {
  98. process.emitWarning('WebSocket over HTTP2 is experimental, and subject to change.', 'ExperimentalWarning')
  99. warningEmitted = true
  100. }
  101. // 2. If protocols is not the empty list and extracting header
  102. // list values given `Sec-WebSocket-Protocol` and response’s
  103. // header list results in null, failure, or the empty byte
  104. // sequence, then fail the WebSocket connection.
  105. if (protocols.length !== 0 && !response.headersList.get('Sec-WebSocket-Protocol')) {
  106. failWebsocketConnection(handler, 1002, 'Server did not respond with sent protocols.')
  107. return
  108. }
  109. // 3. Follow the requirements stated step 2 to step 6, inclusive,
  110. // of the last set of steps in section 4.1 of The WebSocket
  111. // Protocol to validate response. This either results in fail
  112. // the WebSocket connection or the WebSocket connection is
  113. // established.
  114. // 2. If the response lacks an |Upgrade| header field or the |Upgrade|
  115. // header field contains a value that is not an ASCII case-
  116. // insensitive match for the value "websocket", the client MUST
  117. // _Fail the WebSocket Connection_.
  118. // For H2, no upgrade header is expected.
  119. if (response.socket.session == null && response.headersList.get('Upgrade')?.toLowerCase() !== 'websocket') {
  120. failWebsocketConnection(handler, 1002, 'Server did not set Upgrade header to "websocket".')
  121. return
  122. }
  123. // 3. If the response lacks a |Connection| header field or the
  124. // |Connection| header field doesn't contain a token that is an
  125. // ASCII case-insensitive match for the value "Upgrade", the client
  126. // MUST _Fail the WebSocket Connection_.
  127. // For H2, no connection header is expected.
  128. if (response.socket.session == null && response.headersList.get('Connection')?.toLowerCase() !== 'upgrade') {
  129. failWebsocketConnection(handler, 1002, 'Server did not set Connection header to "upgrade".')
  130. return
  131. }
  132. // 4. If the response lacks a |Sec-WebSocket-Accept| header field or
  133. // the |Sec-WebSocket-Accept| contains a value other than the
  134. // base64-encoded SHA-1 of the concatenation of the |Sec-WebSocket-
  135. // Key| (as a string, not base64-decoded) with the string "258EAFA5-
  136. // E914-47DA-95CA-C5AB0DC85B11" but ignoring any leading and
  137. // trailing whitespace, the client MUST _Fail the WebSocket
  138. // Connection_.
  139. const secWSAccept = response.headersList.get('Sec-WebSocket-Accept')
  140. const digest = crypto.hash('sha1', keyValue + uid, 'base64')
  141. if (secWSAccept !== digest) {
  142. failWebsocketConnection(handler, 1002, 'Incorrect hash received in Sec-WebSocket-Accept header.')
  143. return
  144. }
  145. // 5. If the response includes a |Sec-WebSocket-Extensions| header
  146. // field and this header field indicates the use of an extension
  147. // that was not present in the client's handshake (the server has
  148. // indicated an extension not requested by the client), the client
  149. // MUST _Fail the WebSocket Connection_. (The parsing of this
  150. // header field to determine which extensions are requested is
  151. // discussed in Section 9.1.)
  152. const secExtension = response.headersList.get('Sec-WebSocket-Extensions')
  153. let extensions
  154. if (secExtension !== null) {
  155. extensions = parseExtensions(secExtension)
  156. if (!extensions.has('permessage-deflate')) {
  157. failWebsocketConnection(handler, 1002, 'Sec-WebSocket-Extensions header does not match.')
  158. return
  159. }
  160. }
  161. // 6. If the response includes a |Sec-WebSocket-Protocol| header field
  162. // and this header field indicates the use of a subprotocol that was
  163. // not present in the client's handshake (the server has indicated a
  164. // subprotocol not requested by the client), the client MUST _Fail
  165. // the WebSocket Connection_.
  166. const secProtocol = response.headersList.get('Sec-WebSocket-Protocol')
  167. if (secProtocol !== null) {
  168. const requestProtocols = getDecodeSplit('sec-websocket-protocol', request.headersList)
  169. // The client can request that the server use a specific subprotocol by
  170. // including the |Sec-WebSocket-Protocol| field in its handshake. If it
  171. // is specified, the server needs to include the same field and one of
  172. // the selected subprotocol values in its response for the connection to
  173. // be established.
  174. if (!requestProtocols.includes(secProtocol)) {
  175. failWebsocketConnection(handler, 1002, 'Protocol was not set in the opening handshake.')
  176. return
  177. }
  178. }
  179. response.socket.on('data', handler.onSocketData)
  180. response.socket.on('close', handler.onSocketClose)
  181. response.socket.on('error', handler.onSocketError)
  182. handler.wasEverConnected = true
  183. handler.onConnectionEstablished(response, extensions)
  184. }
  185. })
  186. return controller
  187. }
  188. /**
  189. * @see https://whatpr.org/websockets/48.html#close-the-websocket
  190. * @param {import('./websocket').Handler} object
  191. * @param {number} [code=null]
  192. * @param {string} [reason='']
  193. */
  194. function closeWebSocketConnection (object, code, reason, validate = false) {
  195. // 1. If code was not supplied, let code be null.
  196. code ??= null
  197. // 2. If reason was not supplied, let reason be the empty string.
  198. reason ??= ''
  199. // 3. Validate close code and reason with code and reason.
  200. if (validate) validateCloseCodeAndReason(code, reason)
  201. // 4. Run the first matching steps from the following list:
  202. // - If object’s ready state is CLOSING (2) or CLOSED (3)
  203. // - If the WebSocket connection is not yet established [WSP]
  204. // - If the WebSocket closing handshake has not yet been started [WSP]
  205. // - Otherwise
  206. if (isClosed(object.readyState) || isClosing(object.readyState)) {
  207. // Do nothing.
  208. } else if (!isEstablished(object.readyState)) {
  209. // Fail the WebSocket connection and set object’s ready state to CLOSING (2). [WSP]
  210. failWebsocketConnection(object)
  211. object.readyState = states.CLOSING
  212. } else if (!object.closeState.has(sentCloseFrameState.SENT) && !object.closeState.has(sentCloseFrameState.RECEIVED)) {
  213. // Upon either sending or receiving a Close control frame, it is said
  214. // that _The WebSocket Closing Handshake is Started_ and that the
  215. // WebSocket connection is in the CLOSING state.
  216. const frame = new WebsocketFrameSend()
  217. // If neither code nor reason is present, the WebSocket Close
  218. // message must not have a body.
  219. // If code is present, then the status code to use in the
  220. // WebSocket Close message must be the integer given by code.
  221. // If code is null and reason is the empty string, the WebSocket Close frame must not have a body.
  222. // If reason is non-empty but code is null, then set code to 1000 ("Normal Closure").
  223. if (reason.length !== 0 && code === null) {
  224. code = 1000
  225. }
  226. // If code is set, then the status code to use in the WebSocket Close frame must be the integer given by code.
  227. assert(code === null || Number.isInteger(code))
  228. if (code === null && reason.length === 0) {
  229. frame.frameData = emptyBuffer
  230. } else if (code !== null && reason === null) {
  231. frame.frameData = Buffer.allocUnsafe(2)
  232. frame.frameData.writeUInt16BE(code, 0)
  233. } else if (code !== null && reason !== null) {
  234. // If reason is also present, then reasonBytes must be
  235. // provided in the Close message after the status code.
  236. frame.frameData = Buffer.allocUnsafe(2 + Buffer.byteLength(reason))
  237. frame.frameData.writeUInt16BE(code, 0)
  238. // the body MAY contain UTF-8-encoded data with value /reason/
  239. frame.frameData.write(reason, 2, 'utf-8')
  240. } else {
  241. frame.frameData = emptyBuffer
  242. }
  243. object.socket.write(frame.createFrame(opcodes.CLOSE))
  244. object.closeState.add(sentCloseFrameState.SENT)
  245. // Upon either sending or receiving a Close control frame, it is said
  246. // that _The WebSocket Closing Handshake is Started_ and that the
  247. // WebSocket connection is in the CLOSING state.
  248. object.readyState = states.CLOSING
  249. } else {
  250. // Set object’s ready state to CLOSING (2).
  251. object.readyState = states.CLOSING
  252. }
  253. }
  254. /**
  255. * @param {import('./websocket').Handler} handler
  256. * @param {number} code
  257. * @param {string|undefined} reason
  258. * @param {unknown} cause
  259. * @returns {void}
  260. */
  261. function failWebsocketConnection (handler, code, reason, cause) {
  262. // If _The WebSocket Connection is Established_ prior to the point where
  263. // the endpoint is required to _Fail the WebSocket Connection_, the
  264. // endpoint SHOULD send a Close frame with an appropriate status code
  265. // (Section 7.4) before proceeding to _Close the WebSocket Connection_.
  266. if (isEstablished(handler.readyState)) {
  267. closeWebSocketConnection(handler, code, reason, false)
  268. }
  269. handler.controller.abort()
  270. if (isConnecting(handler.readyState)) {
  271. // If the connection was not established, we must still emit an 'error' and 'close' events
  272. handler.onSocketClose()
  273. } else if (handler.socket?.destroyed === false) {
  274. handler.socket.destroy()
  275. }
  276. }
  277. module.exports = {
  278. establishWebSocketConnection,
  279. failWebsocketConnection,
  280. closeWebSocketConnection
  281. }