connection.js 13 KB

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