connection.js 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284
  1. 'use strict'
  2. const { randomBytes, createHash } = require('crypto')
  3. const diagnosticsChannel = require('diagnostics_channel')
  4. const { uid, states } = require('./constants')
  5. const {
  6. kReadyState,
  7. kSentClose,
  8. kByteParser,
  9. kReceivedClose
  10. } = require('./symbols')
  11. const { fireEvent, failWebsocketConnection } = require('./util')
  12. const { CloseEvent } = require('./events')
  13. const { makeRequest } = require('../fetch/request')
  14. const { fetching } = require('../fetch/index')
  15. const { Headers } = require('../fetch/headers')
  16. const { getGlobalDispatcher } = require('../global')
  17. const { kHeadersList } = require('../core/symbols')
  18. const channels = {}
  19. channels.open = diagnosticsChannel.channel('undici:websocket:open')
  20. channels.close = diagnosticsChannel.channel('undici:websocket:close')
  21. channels.socketError = diagnosticsChannel.channel('undici:websocket:socket_error')
  22. /**
  23. * @see https://websockets.spec.whatwg.org/#concept-websocket-establish
  24. * @param {URL} url
  25. * @param {string|string[]} protocols
  26. * @param {import('./websocket').WebSocket} ws
  27. * @param {(response: any) => void} onEstablish
  28. * @param {Partial<import('../../types/websocket').WebSocketInit>} options
  29. */
  30. function establishWebSocketConnection (url, protocols, ws, onEstablish, options) {
  31. // 1. Let requestURL be a copy of url, with its scheme set to "http", if url’s
  32. // scheme is "ws", and to "https" otherwise.
  33. const requestURL = url
  34. requestURL.protocol = url.protocol === 'ws:' ? 'http:' : 'https:'
  35. // 2. Let request be a new request, whose URL is requestURL, client is client,
  36. // service-workers mode is "none", referrer is "no-referrer", mode is
  37. // "websocket", credentials mode is "include", cache mode is "no-store" ,
  38. // and redirect mode is "error".
  39. const request = makeRequest({
  40. urlList: [requestURL],
  41. serviceWorkers: 'none',
  42. referrer: 'no-referrer',
  43. mode: 'websocket',
  44. credentials: 'include',
  45. cache: 'no-store',
  46. redirect: 'error'
  47. })
  48. // Note: undici extension, allow setting custom headers.
  49. if (options.headers) {
  50. const headersList = new Headers(options.headers)[kHeadersList]
  51. request.headersList = headersList
  52. }
  53. // 3. Append (`Upgrade`, `websocket`) to request’s header list.
  54. // 4. Append (`Connection`, `Upgrade`) to request’s header list.
  55. // Note: both of these are handled by undici currently.
  56. // https://github.com/nodejs/undici/blob/68c269c4144c446f3f1220951338daef4a6b5ec4/lib/client.js#L1397
  57. // 5. Let keyValue be a nonce consisting of a randomly selected
  58. // 16-byte value that has been forgiving-base64-encoded and
  59. // isomorphic encoded.
  60. const keyValue = randomBytes(16).toString('base64')
  61. // 6. Append (`Sec-WebSocket-Key`, keyValue) to request’s
  62. // header list.
  63. request.headersList.append('sec-websocket-key', keyValue)
  64. // 7. Append (`Sec-WebSocket-Version`, `13`) to request’s
  65. // header list.
  66. request.headersList.append('sec-websocket-version', '13')
  67. // 8. For each protocol in protocols, combine
  68. // (`Sec-WebSocket-Protocol`, protocol) in request’s header
  69. // list.
  70. for (const protocol of protocols) {
  71. request.headersList.append('sec-websocket-protocol', protocol)
  72. }
  73. // 9. Let permessageDeflate be a user-agent defined
  74. // "permessage-deflate" extension header value.
  75. // https://github.com/mozilla/gecko-dev/blob/ce78234f5e653a5d3916813ff990f053510227bc/netwerk/protocol/websocket/WebSocketChannel.cpp#L2673
  76. // TODO: enable once permessage-deflate is supported
  77. const permessageDeflate = '' // 'permessage-deflate; 15'
  78. // 10. Append (`Sec-WebSocket-Extensions`, permessageDeflate) to
  79. // request’s header list.
  80. // request.headersList.append('sec-websocket-extensions', permessageDeflate)
  81. // 11. Fetch request with useParallelQueue set to true, and
  82. // processResponse given response being these steps:
  83. const controller = fetching({
  84. request,
  85. useParallelQueue: true,
  86. dispatcher: options.dispatcher ?? getGlobalDispatcher(),
  87. processResponse (response) {
  88. // 1. If response is a network error or its status is not 101,
  89. // fail the WebSocket connection.
  90. if (response.type === 'error' || response.status !== 101) {
  91. failWebsocketConnection(ws, 'Received network error or non-101 status code.')
  92. return
  93. }
  94. // 2. If protocols is not the empty list and extracting header
  95. // list values given `Sec-WebSocket-Protocol` and response’s
  96. // header list results in null, failure, or the empty byte
  97. // sequence, then fail the WebSocket connection.
  98. if (protocols.length !== 0 && !response.headersList.get('Sec-WebSocket-Protocol')) {
  99. failWebsocketConnection(ws, 'Server did not respond with sent protocols.')
  100. return
  101. }
  102. // 3. Follow the requirements stated step 2 to step 6, inclusive,
  103. // of the last set of steps in section 4.1 of The WebSocket
  104. // Protocol to validate response. This either results in fail
  105. // the WebSocket connection or the WebSocket connection is
  106. // established.
  107. // 2. If the response lacks an |Upgrade| header field or the |Upgrade|
  108. // header field contains a value that is not an ASCII case-
  109. // insensitive match for the value "websocket", the client MUST
  110. // _Fail the WebSocket Connection_.
  111. if (response.headersList.get('Upgrade')?.toLowerCase() !== 'websocket') {
  112. failWebsocketConnection(ws, 'Server did not set Upgrade header to "websocket".')
  113. return
  114. }
  115. // 3. If the response lacks a |Connection| header field or the
  116. // |Connection| header field doesn't contain a token that is an
  117. // ASCII case-insensitive match for the value "Upgrade", the client
  118. // MUST _Fail the WebSocket Connection_.
  119. if (response.headersList.get('Connection')?.toLowerCase() !== 'upgrade') {
  120. failWebsocketConnection(ws, 'Server did not set Connection header to "upgrade".')
  121. return
  122. }
  123. // 4. If the response lacks a |Sec-WebSocket-Accept| header field or
  124. // the |Sec-WebSocket-Accept| contains a value other than the
  125. // base64-encoded SHA-1 of the concatenation of the |Sec-WebSocket-
  126. // Key| (as a string, not base64-decoded) with the string "258EAFA5-
  127. // E914-47DA-95CA-C5AB0DC85B11" but ignoring any leading and
  128. // trailing whitespace, the client MUST _Fail the WebSocket
  129. // Connection_.
  130. const secWSAccept = response.headersList.get('Sec-WebSocket-Accept')
  131. const digest = createHash('sha1').update(keyValue + uid).digest('base64')
  132. if (secWSAccept !== digest) {
  133. failWebsocketConnection(ws, 'Incorrect hash received in Sec-WebSocket-Accept header.')
  134. return
  135. }
  136. // 5. If the response includes a |Sec-WebSocket-Extensions| header
  137. // field and this header field indicates the use of an extension
  138. // that was not present in the client's handshake (the server has
  139. // indicated an extension not requested by the client), the client
  140. // MUST _Fail the WebSocket Connection_. (The parsing of this
  141. // header field to determine which extensions are requested is
  142. // discussed in Section 9.1.)
  143. const secExtension = response.headersList.get('Sec-WebSocket-Extensions')
  144. if (secExtension !== null && secExtension !== permessageDeflate) {
  145. failWebsocketConnection(ws, 'Received different permessage-deflate than the one set.')
  146. return
  147. }
  148. // 6. If the response includes a |Sec-WebSocket-Protocol| header field
  149. // and this header field indicates the use of a subprotocol that was
  150. // not present in the client's handshake (the server has indicated a
  151. // subprotocol not requested by the client), the client MUST _Fail
  152. // the WebSocket Connection_.
  153. const secProtocol = response.headersList.get('Sec-WebSocket-Protocol')
  154. if (secProtocol !== null && secProtocol !== request.headersList.get('Sec-WebSocket-Protocol')) {
  155. failWebsocketConnection(ws, 'Protocol was not set in the opening handshake.')
  156. return
  157. }
  158. response.socket.on('data', onSocketData)
  159. response.socket.on('close', onSocketClose)
  160. response.socket.on('error', onSocketError)
  161. if (channels.open.hasSubscribers) {
  162. channels.open.publish({
  163. address: response.socket.address(),
  164. protocol: secProtocol,
  165. extensions: secExtension
  166. })
  167. }
  168. onEstablish(response)
  169. }
  170. })
  171. return controller
  172. }
  173. /**
  174. * @param {Buffer} chunk
  175. */
  176. function onSocketData (chunk) {
  177. if (!this.ws[kByteParser].write(chunk)) {
  178. this.pause()
  179. }
  180. }
  181. /**
  182. * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
  183. * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7.1.4
  184. */
  185. function onSocketClose () {
  186. const { ws } = this
  187. // If the TCP connection was closed after the
  188. // WebSocket closing handshake was completed, the WebSocket connection
  189. // is said to have been closed _cleanly_.
  190. const wasClean = ws[kSentClose] && ws[kReceivedClose]
  191. let code = 1005
  192. let reason = ''
  193. const result = ws[kByteParser].closingInfo
  194. if (result) {
  195. code = result.code ?? 1005
  196. reason = result.reason
  197. } else if (!ws[kSentClose]) {
  198. // If _The WebSocket
  199. // Connection is Closed_ and no Close control frame was received by the
  200. // endpoint (such as could occur if the underlying transport connection
  201. // is lost), _The WebSocket Connection Close Code_ is considered to be
  202. // 1006.
  203. code = 1006
  204. }
  205. // 1. Change the ready state to CLOSED (3).
  206. ws[kReadyState] = states.CLOSED
  207. // 2. If the user agent was required to fail the WebSocket
  208. // connection, or if the WebSocket connection was closed
  209. // after being flagged as full, fire an event named error
  210. // at the WebSocket object.
  211. // TODO
  212. // 3. Fire an event named close at the WebSocket object,
  213. // using CloseEvent, with the wasClean attribute
  214. // initialized to true if the connection closed cleanly
  215. // and false otherwise, the code attribute initialized to
  216. // the WebSocket connection close code, and the reason
  217. // attribute initialized to the result of applying UTF-8
  218. // decode without BOM to the WebSocket connection close
  219. // reason.
  220. fireEvent('close', ws, CloseEvent, {
  221. wasClean, code, reason
  222. })
  223. if (channels.close.hasSubscribers) {
  224. channels.close.publish({
  225. websocket: ws,
  226. code,
  227. reason
  228. })
  229. }
  230. }
  231. function onSocketError (error) {
  232. const { ws } = this
  233. ws[kReadyState] = states.CLOSING
  234. if (channels.socketError.hasSubscribers) {
  235. channels.socketError.publish(error)
  236. }
  237. this.destroy()
  238. }
  239. module.exports = {
  240. establishWebSocketConnection
  241. }