• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1'use strict'
2
3const { kReadyState, kController, kResponse, kBinaryType, kWebSocketURL } = require('./symbols')
4const { states, opcodes } = require('./constants')
5const { MessageEvent, ErrorEvent } = require('./events')
6
7/* globals Blob */
8
9/**
10 * @param {import('./websocket').WebSocket} ws
11 */
12function isEstablished (ws) {
13  // If the server's response is validated as provided for above, it is
14  // said that _The WebSocket Connection is Established_ and that the
15  // WebSocket Connection is in the OPEN state.
16  return ws[kReadyState] === states.OPEN
17}
18
19/**
20 * @param {import('./websocket').WebSocket} ws
21 */
22function isClosing (ws) {
23  // Upon either sending or receiving a Close control frame, it is said
24  // that _The WebSocket Closing Handshake is Started_ and that the
25  // WebSocket connection is in the CLOSING state.
26  return ws[kReadyState] === states.CLOSING
27}
28
29/**
30 * @param {import('./websocket').WebSocket} ws
31 */
32function isClosed (ws) {
33  return ws[kReadyState] === states.CLOSED
34}
35
36/**
37 * @see https://dom.spec.whatwg.org/#concept-event-fire
38 * @param {string} e
39 * @param {EventTarget} target
40 * @param {EventInit | undefined} eventInitDict
41 */
42function fireEvent (e, target, eventConstructor = Event, eventInitDict) {
43  // 1. If eventConstructor is not given, then let eventConstructor be Event.
44
45  // 2. Let event be the result of creating an event given eventConstructor,
46  //    in the relevant realm of target.
47  // 3. Initialize event’s type attribute to e.
48  const event = new eventConstructor(e, eventInitDict) // eslint-disable-line new-cap
49
50  // 4. Initialize any other IDL attributes of event as described in the
51  //    invocation of this algorithm.
52
53  // 5. Return the result of dispatching event at target, with legacy target
54  //    override flag set if set.
55  target.dispatchEvent(event)
56}
57
58/**
59 * @see https://websockets.spec.whatwg.org/#feedback-from-the-protocol
60 * @param {import('./websocket').WebSocket} ws
61 * @param {number} type Opcode
62 * @param {Buffer} data application data
63 */
64function websocketMessageReceived (ws, type, data) {
65  // 1. If ready state is not OPEN (1), then return.
66  if (ws[kReadyState] !== states.OPEN) {
67    return
68  }
69
70  // 2. Let dataForEvent be determined by switching on type and binary type:
71  let dataForEvent
72
73  if (type === opcodes.TEXT) {
74    // -> type indicates that the data is Text
75    //      a new DOMString containing data
76    try {
77      dataForEvent = new TextDecoder('utf-8', { fatal: true }).decode(data)
78    } catch {
79      failWebsocketConnection(ws, 'Received invalid UTF-8 in text frame.')
80      return
81    }
82  } else if (type === opcodes.BINARY) {
83    if (ws[kBinaryType] === 'blob') {
84      // -> type indicates that the data is Binary and binary type is "blob"
85      //      a new Blob object, created in the relevant Realm of the WebSocket
86      //      object, that represents data as its raw data
87      dataForEvent = new Blob([data])
88    } else {
89      // -> type indicates that the data is Binary and binary type is "arraybuffer"
90      //      a new ArrayBuffer object, created in the relevant Realm of the
91      //      WebSocket object, whose contents are data
92      dataForEvent = new Uint8Array(data).buffer
93    }
94  }
95
96  // 3. Fire an event named message at the WebSocket object, using MessageEvent,
97  //    with the origin attribute initialized to the serialization of the WebSocket
98  //    object’s url's origin, and the data attribute initialized to dataForEvent.
99  fireEvent('message', ws, MessageEvent, {
100    origin: ws[kWebSocketURL].origin,
101    data: dataForEvent
102  })
103}
104
105/**
106 * @see https://datatracker.ietf.org/doc/html/rfc6455
107 * @see https://datatracker.ietf.org/doc/html/rfc2616
108 * @see https://bugs.chromium.org/p/chromium/issues/detail?id=398407
109 * @param {string} protocol
110 */
111function isValidSubprotocol (protocol) {
112  // If present, this value indicates one
113  // or more comma-separated subprotocol the client wishes to speak,
114  // ordered by preference.  The elements that comprise this value
115  // MUST be non-empty strings with characters in the range U+0021 to
116  // U+007E not including separator characters as defined in
117  // [RFC2616] and MUST all be unique strings.
118  if (protocol.length === 0) {
119    return false
120  }
121
122  for (const char of protocol) {
123    const code = char.charCodeAt(0)
124
125    if (
126      code < 0x21 ||
127      code > 0x7E ||
128      char === '(' ||
129      char === ')' ||
130      char === '<' ||
131      char === '>' ||
132      char === '@' ||
133      char === ',' ||
134      char === ';' ||
135      char === ':' ||
136      char === '\\' ||
137      char === '"' ||
138      char === '/' ||
139      char === '[' ||
140      char === ']' ||
141      char === '?' ||
142      char === '=' ||
143      char === '{' ||
144      char === '}' ||
145      code === 32 || // SP
146      code === 9 // HT
147    ) {
148      return false
149    }
150  }
151
152  return true
153}
154
155/**
156 * @see https://datatracker.ietf.org/doc/html/rfc6455#section-7-4
157 * @param {number} code
158 */
159function isValidStatusCode (code) {
160  if (code >= 1000 && code < 1015) {
161    return (
162      code !== 1004 && // reserved
163      code !== 1005 && // "MUST NOT be set as a status code"
164      code !== 1006 // "MUST NOT be set as a status code"
165    )
166  }
167
168  return code >= 3000 && code <= 4999
169}
170
171/**
172 * @param {import('./websocket').WebSocket} ws
173 * @param {string|undefined} reason
174 */
175function failWebsocketConnection (ws, reason) {
176  const { [kController]: controller, [kResponse]: response } = ws
177
178  controller.abort()
179
180  if (response?.socket && !response.socket.destroyed) {
181    response.socket.destroy()
182  }
183
184  if (reason) {
185    fireEvent('error', ws, ErrorEvent, {
186      error: new Error(reason)
187    })
188  }
189}
190
191module.exports = {
192  isEstablished,
193  isClosing,
194  isClosed,
195  fireEvent,
196  isValidSubprotocol,
197  isValidStatusCode,
198  failWebsocketConnection,
199  websocketMessageReceived
200}
201