util.js 9.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339
  1. 'use strict'
  2. const { states, opcodes } = require('./constants')
  3. const { isUtf8 } = require('node:buffer')
  4. const { removeHTTPWhitespace } = require('../fetch/data-url')
  5. const { collectASequenceOfCodePointsFast } = require('../infra')
  6. /**
  7. * @param {number} readyState
  8. * @returns {boolean}
  9. */
  10. function isConnecting (readyState) {
  11. // If the WebSocket connection is not yet established, and the connection
  12. // is not yet closed, then the WebSocket connection is in the CONNECTING state.
  13. return readyState === states.CONNECTING
  14. }
  15. /**
  16. * @param {number} readyState
  17. * @returns {boolean}
  18. */
  19. function isEstablished (readyState) {
  20. // If the server's response is validated as provided for above, it is
  21. // said that _The WebSocket Connection is Established_ and that the
  22. // WebSocket Connection is in the OPEN state.
  23. return readyState === states.OPEN
  24. }
  25. /**
  26. * @param {number} readyState
  27. * @returns {boolean}
  28. */
  29. function isClosing (readyState) {
  30. // Upon either sending or receiving a Close control frame, it is said
  31. // that _The WebSocket Closing Handshake is Started_ and that the
  32. // WebSocket connection is in the CLOSING state.
  33. return readyState === states.CLOSING
  34. }
  35. /**
  36. * @param {number} readyState
  37. * @returns {boolean}
  38. */
  39. function isClosed (readyState) {
  40. return readyState === states.CLOSED
  41. }
  42. /**
  43. * @see https://dom.spec.whatwg.org/#concept-event-fire
  44. * @param {string} e
  45. * @param {EventTarget} target
  46. * @param {(...args: ConstructorParameters<typeof Event>) => Event} eventFactory
  47. * @param {EventInit | undefined} eventInitDict
  48. * @returns {void}
  49. */
  50. function fireEvent (e, target, eventFactory = (type, init) => new Event(type, init), eventInitDict = {}) {
  51. // 1. If eventConstructor is not given, then let eventConstructor be Event.
  52. // 2. Let event be the result of creating an event given eventConstructor,
  53. // in the relevant realm of target.
  54. // 3. Initialize event’s type attribute to e.
  55. const event = eventFactory(e, eventInitDict)
  56. // 4. Initialize any other IDL attributes of event as described in the
  57. // invocation of this algorithm.
  58. // 5. Return the result of dispatching event at target, with legacy target
  59. // override flag set if set.
  60. target.dispatchEvent(event)
  61. }
  62. /**
  63. * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
  64. * @param {import('./websocket').Handler} handler
  65. * @param {number} type Opcode
  66. * @param {Buffer} data application data
  67. * @returns {void}
  68. */
  69. function websocketMessageReceived (handler, type, data) {
  70. handler.onMessage(type, data)
  71. }
  72. /**
  73. * @param {Buffer} buffer
  74. * @returns {ArrayBuffer}
  75. */
  76. function toArrayBuffer (buffer) {
  77. if (buffer.byteLength === buffer.buffer.byteLength) {
  78. return buffer.buffer
  79. }
  80. return new Uint8Array(buffer).buffer
  81. }
  82. /**
  83. * @see https://datatracker.ietf.org/doc/html/rfc6455
  84. * @see https://datatracker.ietf.org/doc/html/rfc2616
  85. * @see https://bugs.chromium.org/p/chromium/issues/detail?id=398407
  86. * @param {string} protocol
  87. * @returns {boolean}
  88. */
  89. function isValidSubprotocol (protocol) {
  90. // If present, this value indicates one
  91. // or more comma-separated subprotocol the client wishes to speak,
  92. // ordered by preference. The elements that comprise this value
  93. // MUST be non-empty strings with characters in the range U+0021 to
  94. // U+007E not including separator characters as defined in
  95. // [RFC2616] and MUST all be unique strings.
  96. if (protocol.length === 0) {
  97. return false
  98. }
  99. for (let i = 0; i < protocol.length; ++i) {
  100. const code = protocol.charCodeAt(i)
  101. if (
  102. code < 0x21 || // CTL, contains SP (0x20) and HT (0x09)
  103. code > 0x7E ||
  104. code === 0x22 || // "
  105. code === 0x28 || // (
  106. code === 0x29 || // )
  107. code === 0x2C || // ,
  108. code === 0x2F || // /
  109. code === 0x3A || // :
  110. code === 0x3B || // ;
  111. code === 0x3C || // <
  112. code === 0x3D || // =
  113. code === 0x3E || // >
  114. code === 0x3F || // ?
  115. code === 0x40 || // @
  116. code === 0x5B || // [
  117. code === 0x5C || // \
  118. code === 0x5D || // ]
  119. code === 0x7B || // {
  120. code === 0x7D // }
  121. ) {
  122. return false
  123. }
  124. }
  125. return true
  126. }
  127. /**
  128. * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7-4
  129. * @param {number} code
  130. * @returns {boolean}
  131. */
  132. function isValidStatusCode (code) {
  133. if (code >= 1000 && code < 1015) {
  134. return (
  135. code !== 1004 && // reserved
  136. code !== 1005 && // "MUST NOT be set as a status code"
  137. code !== 1006 // "MUST NOT be set as a status code"
  138. )
  139. }
  140. return code >= 3000 && code <= 4999
  141. }
  142. /**
  143. * @see https://datatracker.ietf.org/doc/html/rfc6455#section-5.5
  144. * @param {number} opcode
  145. * @returns {boolean}
  146. */
  147. function isControlFrame (opcode) {
  148. return (
  149. opcode === opcodes.CLOSE ||
  150. opcode === opcodes.PING ||
  151. opcode === opcodes.PONG
  152. )
  153. }
  154. /**
  155. * @param {number} opcode
  156. * @returns {boolean}
  157. */
  158. function isContinuationFrame (opcode) {
  159. return opcode === opcodes.CONTINUATION
  160. }
  161. /**
  162. * @param {number} opcode
  163. * @returns {boolean}
  164. */
  165. function isTextBinaryFrame (opcode) {
  166. return opcode === opcodes.TEXT || opcode === opcodes.BINARY
  167. }
  168. /**
  169. *
  170. * @param {number} opcode
  171. * @returns {boolean}
  172. */
  173. function isValidOpcode (opcode) {
  174. return isTextBinaryFrame(opcode) || isContinuationFrame(opcode) || isControlFrame(opcode)
  175. }
  176. /**
  177. * Parses a Sec-WebSocket-Extensions header value.
  178. * @param {string} extensions
  179. * @returns {Map<string, string>}
  180. */
  181. // TODO(@Uzlopak, @KhafraDev): make compliant https://datatracker.ietf.org/doc/html/rfc6455#section-9.1
  182. function parseExtensions (extensions) {
  183. const position = { position: 0 }
  184. const extensionList = new Map()
  185. while (position.position < extensions.length) {
  186. const pair = collectASequenceOfCodePointsFast(';', extensions, position)
  187. const [name, value = ''] = pair.split('=', 2)
  188. extensionList.set(
  189. removeHTTPWhitespace(name, true, false),
  190. removeHTTPWhitespace(value, false, true)
  191. )
  192. position.position++
  193. }
  194. return extensionList
  195. }
  196. /**
  197. * @see https://www.rfc-editor.org/rfc/rfc7692#section-7.1.2.2
  198. * @description "client-max-window-bits = 1*DIGIT"
  199. * @param {string} value
  200. * @returns {boolean}
  201. */
  202. function isValidClientWindowBits (value) {
  203. for (let i = 0; i < value.length; i++) {
  204. const byte = value.charCodeAt(i)
  205. if (byte < 0x30 || byte > 0x39) {
  206. return false
  207. }
  208. }
  209. return true
  210. }
  211. /**
  212. * @see https://whatpr.org/websockets/48/7b748d3...d5570f3.html#get-a-url-record
  213. * @param {string} url
  214. * @param {string} [baseURL]
  215. */
  216. function getURLRecord (url, baseURL) {
  217. // 1. Let urlRecord be the result of applying the URL parser to url with baseURL .
  218. // 2. If urlRecord is failure, then throw a " SyntaxError " DOMException .
  219. let urlRecord
  220. try {
  221. urlRecord = new URL(url, baseURL)
  222. } catch (e) {
  223. throw new DOMException(e, 'SyntaxError')
  224. }
  225. // 3. If urlRecord ’s scheme is " http ", then set urlRecord ’s scheme to " ws ".
  226. // 4. Otherwise, if urlRecord ’s scheme is " https ", set urlRecord ’s scheme to " wss ".
  227. if (urlRecord.protocol === 'http:') {
  228. urlRecord.protocol = 'ws:'
  229. } else if (urlRecord.protocol === 'https:') {
  230. urlRecord.protocol = 'wss:'
  231. }
  232. // 5. If urlRecord ’s scheme is not " ws " or " wss ", then throw a " SyntaxError " DOMException .
  233. if (urlRecord.protocol !== 'ws:' && urlRecord.protocol !== 'wss:') {
  234. throw new DOMException('expected a ws: or wss: url', 'SyntaxError')
  235. }
  236. // If urlRecord ’s fragment is non-null, then throw a " SyntaxError " DOMException .
  237. if (urlRecord.hash.length || urlRecord.href.endsWith('#')) {
  238. throw new DOMException('hash', 'SyntaxError')
  239. }
  240. // Return urlRecord .
  241. return urlRecord
  242. }
  243. // https://whatpr.org/websockets/48.html#validate-close-code-and-reason
  244. function validateCloseCodeAndReason (code, reason) {
  245. // 1. If code is not null, but is neither an integer equal to
  246. // 1000 nor an integer in the range 3000 to 4999, inclusive,
  247. // throw an "InvalidAccessError" DOMException.
  248. if (code !== null) {
  249. if (code !== 1000 && (code < 3000 || code > 4999)) {
  250. throw new DOMException('invalid code', 'InvalidAccessError')
  251. }
  252. }
  253. // 2. If reason is not null, then:
  254. if (reason !== null) {
  255. // 2.1. Let reasonBytes be the result of UTF-8 encoding reason.
  256. // 2.2. If reasonBytes is longer than 123 bytes, then throw a
  257. // "SyntaxError" DOMException.
  258. const reasonBytesLength = Buffer.byteLength(reason)
  259. if (reasonBytesLength > 123) {
  260. throw new DOMException(`Reason must be less than 123 bytes; received ${reasonBytesLength}`, 'SyntaxError')
  261. }
  262. }
  263. }
  264. /**
  265. * Converts a Buffer to utf-8, even on platforms without icu.
  266. * @type {(buffer: Buffer) => string}
  267. */
  268. const utf8Decode = (() => {
  269. if (typeof process.versions.icu === 'string') {
  270. const fatalDecoder = new TextDecoder('utf-8', { fatal: true })
  271. return fatalDecoder.decode.bind(fatalDecoder)
  272. }
  273. return function (buffer) {
  274. if (isUtf8(buffer)) {
  275. return buffer.toString('utf-8')
  276. }
  277. throw new TypeError('Invalid utf-8 received.')
  278. }
  279. })()
  280. module.exports = {
  281. isConnecting,
  282. isEstablished,
  283. isClosing,
  284. isClosed,
  285. fireEvent,
  286. isValidSubprotocol,
  287. isValidStatusCode,
  288. websocketMessageReceived,
  289. utf8Decode,
  290. isControlFrame,
  291. isContinuationFrame,
  292. isTextBinaryFrame,
  293. isValidOpcode,
  294. parseExtensions,
  295. isValidClientWindowBits,
  296. toArrayBuffer,
  297. getURLRecord,
  298. validateCloseCodeAndReason
  299. }