connection.js 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371
  1. 'use strict'
  2. const { uid, states, sentCloseFrameState, emptyBuffer, opcodes } = require('./constants')
  3. const {
  4. kReadyState,
  5. kSentClose,
  6. kByteParser,
  7. kReceivedClose,
  8. kResponse
  9. } = require('./symbols')
  10. const { fireEvent, failWebsocketConnection, isClosing, isClosed, isEstablished, parseExtensions } = require('./util')
  11. const { channels } = require('../../core/diagnostics')
  12. const { CloseEvent } = require('./events')
  13. const { makeRequest } = require('../fetch/request')
  14. const { fetching } = require('../fetch/index')
  15. const { Headers, getHeadersList } = require('../fetch/headers')
  16. const { getDecodeSplit } = require('../fetch/util')
  17. const { WebsocketFrameSend } = require('./frame')
  18. /** @type {import('crypto')} */
  19. let crypto
  20. try {
  21. crypto = require('node:crypto')
  22. /* c8 ignore next 3 */
  23. } catch {
  24. }
  25. /**
  26. * @see https://websockets.spec.whatwg.org/#concept-websocket-establish
  27. * @param {URL} url
  28. * @param {string|string[]} protocols
  29. * @param {import('./websocket').WebSocket} ws
  30. * @param {(response: any, extensions: string[] | undefined) => void} onEstablish
  31. * @param {Partial<import('../../types/websocket').WebSocketInit>} options
  32. */
  33. function establishWebSocketConnection (url, protocols, client, ws, onEstablish, options) {
  34. // 1. Let requestURL be a copy of url, with its scheme set to "http", if url’s
  35. // scheme is "ws", and to "https" otherwise.
  36. const requestURL = url
  37. requestURL.protocol = url.protocol === 'ws:' ? 'http:' : 'https:'
  38. // 2. Let request be a new request, whose URL is requestURL, client is client,
  39. // service-workers mode is "none", referrer is "no-referrer", mode is
  40. // "websocket", credentials mode is "include", cache mode is "no-store" ,
  41. // and redirect mode is "error".
  42. const request = makeRequest({
  43. urlList: [requestURL],
  44. client,
  45. serviceWorkers: 'none',
  46. referrer: 'no-referrer',
  47. mode: 'websocket',
  48. credentials: 'include',
  49. cache: 'no-store',
  50. redirect: 'error'
  51. })
  52. // Note: undici extension, allow setting custom headers.
  53. if (options.headers) {
  54. const headersList = getHeadersList(new Headers(options.headers))
  55. request.headersList = headersList
  56. }
  57. // 3. Append (`Upgrade`, `websocket`) to request’s header list.
  58. // 4. Append (`Connection`, `Upgrade`) to request’s header list.
  59. // Note: both of these are handled by undici currently.
  60. // https://github.com/nodejs/undici/blob/68c269c4144c446f3f1220951338daef4a6b5ec4/lib/client.js#L1397
  61. // 5. Let keyValue be a nonce consisting of a randomly selected
  62. // 16-byte value that has been forgiving-base64-encoded and
  63. // isomorphic encoded.
  64. const keyValue = crypto.randomBytes(16).toString('base64')
  65. // 6. Append (`Sec-WebSocket-Key`, keyValue) to request’s
  66. // header list.
  67. request.headersList.append('sec-websocket-key', keyValue)
  68. // 7. Append (`Sec-WebSocket-Version`, `13`) to request’s
  69. // header list.
  70. request.headersList.append('sec-websocket-version', '13')
  71. // 8. For each protocol in protocols, combine
  72. // (`Sec-WebSocket-Protocol`, protocol) in request’s header
  73. // list.
  74. for (const protocol of protocols) {
  75. request.headersList.append('sec-websocket-protocol', protocol)
  76. }
  77. // 9. Let permessageDeflate be a user-agent defined
  78. // "permessage-deflate" extension header value.
  79. // https://github.com/mozilla/gecko-dev/blob/ce78234f5e653a5d3916813ff990f053510227bc/netwerk/protocol/websocket/WebSocketChannel.cpp#L2673
  80. const permessageDeflate = 'permessage-deflate; client_max_window_bits'
  81. // 10. Append (`Sec-WebSocket-Extensions`, permessageDeflate) to
  82. // request’s header list.
  83. request.headersList.append('sec-websocket-extensions', permessageDeflate)
  84. // 11. Fetch request with useParallelQueue set to true, and
  85. // processResponse given response being these steps:
  86. const controller = fetching({
  87. request,
  88. useParallelQueue: true,
  89. dispatcher: options.dispatcher,
  90. processResponse (response) {
  91. // 1. If response is a network error or its status is not 101,
  92. // fail the WebSocket connection.
  93. if (response.type === 'error' || response.status !== 101) {
  94. failWebsocketConnection(ws, 'Received network error or non-101 status code.')
  95. return
  96. }
  97. // 2. If protocols is not the empty list and extracting header
  98. // list values given `Sec-WebSocket-Protocol` and response’s
  99. // header list results in null, failure, or the empty byte
  100. // sequence, then fail the WebSocket connection.
  101. if (protocols.length !== 0 && !response.headersList.get('Sec-WebSocket-Protocol')) {
  102. failWebsocketConnection(ws, 'Server did not respond with sent protocols.')
  103. return
  104. }
  105. // 3. Follow the requirements stated step 2 to step 6, inclusive,
  106. // of the last set of steps in section 4.1 of The WebSocket
  107. // Protocol to validate response. This either results in fail
  108. // the WebSocket connection or the WebSocket connection is
  109. // established.
  110. // 2. If the response lacks an |Upgrade| header field or the |Upgrade|
  111. // header field contains a value that is not an ASCII case-
  112. // insensitive match for the value "websocket", the client MUST
  113. // _Fail the WebSocket Connection_.
  114. if (response.headersList.get('Upgrade')?.toLowerCase() !== 'websocket') {
  115. failWebsocketConnection(ws, 'Server did not set Upgrade header to "websocket".')
  116. return
  117. }
  118. // 3. If the response lacks a |Connection| header field or the
  119. // |Connection| header field doesn't contain a token that is an
  120. // ASCII case-insensitive match for the value "Upgrade", the client
  121. // MUST _Fail the WebSocket Connection_.
  122. if (response.headersList.get('Connection')?.toLowerCase() !== 'upgrade') {
  123. failWebsocketConnection(ws, 'Server did not set Connection header to "upgrade".')
  124. return
  125. }
  126. // 4. If the response lacks a |Sec-WebSocket-Accept| header field or
  127. // the |Sec-WebSocket-Accept| contains a value other than the
  128. // base64-encoded SHA-1 of the concatenation of the |Sec-WebSocket-
  129. // Key| (as a string, not base64-decoded) with the string "258EAFA5-
  130. // E914-47DA-95CA-C5AB0DC85B11" but ignoring any leading and
  131. // trailing whitespace, the client MUST _Fail the WebSocket
  132. // Connection_.
  133. const secWSAccept = response.headersList.get('Sec-WebSocket-Accept')
  134. const digest = crypto.createHash('sha1').update(keyValue + uid).digest('base64')
  135. if (secWSAccept !== digest) {
  136. failWebsocketConnection(ws, 'Incorrect hash received in Sec-WebSocket-Accept header.')
  137. return
  138. }
  139. // 5. If the response includes a |Sec-WebSocket-Extensions| header
  140. // field and this header field indicates the use of an extension
  141. // that was not present in the client's handshake (the server has
  142. // indicated an extension not requested by the client), the client
  143. // MUST _Fail the WebSocket Connection_. (The parsing of this
  144. // header field to determine which extensions are requested is
  145. // discussed in Section 9.1.)
  146. const secExtension = response.headersList.get('Sec-WebSocket-Extensions')
  147. let extensions
  148. if (secExtension !== null) {
  149. extensions = parseExtensions(secExtension)
  150. if (!extensions.has('permessage-deflate')) {
  151. failWebsocketConnection(ws, 'Sec-WebSocket-Extensions header does not match.')
  152. return
  153. }
  154. }
  155. // 6. If the response includes a |Sec-WebSocket-Protocol| header field
  156. // and this header field indicates the use of a subprotocol that was
  157. // not present in the client's handshake (the server has indicated a
  158. // subprotocol not requested by the client), the client MUST _Fail
  159. // the WebSocket Connection_.
  160. const secProtocol = response.headersList.get('Sec-WebSocket-Protocol')
  161. if (secProtocol !== null) {
  162. const requestProtocols = getDecodeSplit('sec-websocket-protocol', request.headersList)
  163. // The client can request that the server use a specific subprotocol by
  164. // including the |Sec-WebSocket-Protocol| field in its handshake. If it
  165. // is specified, the server needs to include the same field and one of
  166. // the selected subprotocol values in its response for the connection to
  167. // be established.
  168. if (!requestProtocols.includes(secProtocol)) {
  169. failWebsocketConnection(ws, 'Protocol was not set in the opening handshake.')
  170. return
  171. }
  172. }
  173. response.socket.on('data', onSocketData)
  174. response.socket.on('close', onSocketClose)
  175. response.socket.on('error', onSocketError)
  176. if (channels.open.hasSubscribers) {
  177. channels.open.publish({
  178. address: response.socket.address(),
  179. protocol: secProtocol,
  180. extensions: secExtension
  181. })
  182. }
  183. onEstablish(response, extensions)
  184. }
  185. })
  186. return controller
  187. }
  188. function closeWebSocketConnection (ws, code, reason, reasonByteLength) {
  189. if (isClosing(ws) || isClosed(ws)) {
  190. // If this's ready state is CLOSING (2) or CLOSED (3)
  191. // Do nothing.
  192. } else if (!isEstablished(ws)) {
  193. // If the WebSocket connection is not yet established
  194. // Fail the WebSocket connection and set this's ready state
  195. // to CLOSING (2).
  196. failWebsocketConnection(ws, 'Connection was closed before it was established.')
  197. ws[kReadyState] = states.CLOSING
  198. } else if (ws[kSentClose] === sentCloseFrameState.NOT_SENT) {
  199. // If the WebSocket closing handshake has not yet been started
  200. // Start the WebSocket closing handshake and set this's ready
  201. // state to CLOSING (2).
  202. // - If neither code nor reason is present, the WebSocket Close
  203. // message must not have a body.
  204. // - If code is present, then the status code to use in the
  205. // WebSocket Close message must be the integer given by code.
  206. // - If reason is also present, then reasonBytes must be
  207. // provided in the Close message after the status code.
  208. ws[kSentClose] = sentCloseFrameState.PROCESSING
  209. const frame = new WebsocketFrameSend()
  210. // If neither code nor reason is present, the WebSocket Close
  211. // message must not have a body.
  212. // If code is present, then the status code to use in the
  213. // WebSocket Close message must be the integer given by code.
  214. if (code !== undefined && reason === undefined) {
  215. frame.frameData = Buffer.allocUnsafe(2)
  216. frame.frameData.writeUInt16BE(code, 0)
  217. } else if (code !== undefined && reason !== undefined) {
  218. // If reason is also present, then reasonBytes must be
  219. // provided in the Close message after the status code.
  220. frame.frameData = Buffer.allocUnsafe(2 + reasonByteLength)
  221. frame.frameData.writeUInt16BE(code, 0)
  222. // the body MAY contain UTF-8-encoded data with value /reason/
  223. frame.frameData.write(reason, 2, 'utf-8')
  224. } else {
  225. frame.frameData = emptyBuffer
  226. }
  227. /** @type {import('stream').Duplex} */
  228. const socket = ws[kResponse].socket
  229. socket.write(frame.createFrame(opcodes.CLOSE))
  230. ws[kSentClose] = sentCloseFrameState.SENT
  231. // Upon either sending or receiving a Close control frame, it is said
  232. // that _The WebSocket Closing Handshake is Started_ and that the
  233. // WebSocket connection is in the CLOSING state.
  234. ws[kReadyState] = states.CLOSING
  235. } else {
  236. // Otherwise
  237. // Set this's ready state to CLOSING (2).
  238. ws[kReadyState] = states.CLOSING
  239. }
  240. }
  241. /**
  242. * @param {Buffer} chunk
  243. */
  244. function onSocketData (chunk) {
  245. if (!this.ws[kByteParser].write(chunk)) {
  246. this.pause()
  247. }
  248. }
  249. /**
  250. * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
  251. * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4
  252. */
  253. function onSocketClose () {
  254. const { ws } = this
  255. const { [kResponse]: response } = ws
  256. response.socket.off('data', onSocketData)
  257. response.socket.off('close', onSocketClose)
  258. response.socket.off('error', onSocketError)
  259. // If the TCP connection was closed after the
  260. // WebSocket closing handshake was completed, the WebSocket connection
  261. // is said to have been closed _cleanly_.
  262. const wasClean = ws[kSentClose] === sentCloseFrameState.SENT && ws[kReceivedClose]
  263. let code = 1005
  264. let reason = ''
  265. const result = ws[kByteParser].closingInfo
  266. if (result && !result.error) {
  267. code = result.code ?? 1005
  268. reason = result.reason
  269. } else if (!ws[kReceivedClose]) {
  270. // If _The WebSocket
  271. // Connection is Closed_ and no Close control frame was received by the
  272. // endpoint (such as could occur if the underlying transport connection
  273. // is lost), _The WebSocket Connection Close Code_ is considered to be
  274. // 1006.
  275. code = 1006
  276. }
  277. // 1. Change the ready state to CLOSED (3).
  278. ws[kReadyState] = states.CLOSED
  279. // 2. If the user agent was required to fail the WebSocket
  280. // connection, or if the WebSocket connection was closed
  281. // after being flagged as full, fire an event named error
  282. // at the WebSocket object.
  283. // TODO
  284. // 3. Fire an event named close at the WebSocket object,
  285. // using CloseEvent, with the wasClean attribute
  286. // initialized to true if the connection closed cleanly
  287. // and false otherwise, the code attribute initialized to
  288. // the WebSocket connection close code, and the reason
  289. // attribute initialized to the result of applying UTF-8
  290. // decode without BOM to the WebSocket connection close
  291. // reason.
  292. // TODO: process.nextTick
  293. fireEvent('close', ws, (type, init) => new CloseEvent(type, init), {
  294. wasClean, code, reason
  295. })
  296. if (channels.close.hasSubscribers) {
  297. channels.close.publish({
  298. websocket: ws,
  299. code,
  300. reason
  301. })
  302. }
  303. }
  304. function onSocketError (error) {
  305. const { ws } = this
  306. ws[kReadyState] = states.CLOSING
  307. if (channels.socketError.hasSubscribers) {
  308. channels.socketError.publish(error)
  309. }
  310. this.destroy()
  311. }
  312. module.exports = {
  313. establishWebSocketConnection,
  314. closeWebSocketConnection
  315. }