{"version":3,"file":"connection.mjs","sources":["../../../../lib/web/websocket/connection.js"],"sourcesContent":["'use strict'\n\nconst { uid, states, sentCloseFrameState, emptyBuffer, opcodes } = require('./constants')\nconst { parseExtensions, isClosed, isClosing, isEstablished, isConnecting, validateCloseCodeAndReason } = require('./util')\nconst { makeRequest } = require('../fetch/request')\nconst { fetching } = require('../fetch/index')\nconst { Headers, getHeadersList } = require('../fetch/headers')\nconst { getDecodeSplit } = require('../fetch/util')\nconst { WebsocketFrameSend } = require('./frame')\nconst assert = require('node:assert')\nconst { runtimeFeatures } = require('../../util/runtime-features')\n\nconst crypto = runtimeFeatures.has('crypto')\n  ? require('node:crypto')\n  : null\n\nlet warningEmitted = false\n\n/**\n * @see https://websockets.spec.whatwg.org/#concept-websocket-establish\n * @param {URL} url\n * @param {string|string[]} protocols\n * @param {import('./websocket').Handler} handler\n * @param {Partial<import('../../../types/websocket').WebSocketInit>} options\n */\nfunction establishWebSocketConnection (url, protocols, client, handler, options) {\n  // 1. Let requestURL be a copy of url, with its scheme set to \"http\", if url’s\n  //    scheme is \"ws\", and to \"https\" otherwise.\n  const requestURL = url\n\n  requestURL.protocol = url.protocol === 'ws:' ? 'http:' : 'https:'\n\n  // 2. Let request be a new request, whose URL is requestURL, client is client,\n  //    service-workers mode is \"none\", referrer is \"no-referrer\", mode is\n  //    \"websocket\", credentials mode is \"include\", cache mode is \"no-store\" ,\n  //    redirect mode is \"error\", and use-URL-credentials flag is set.\n  const request = makeRequest({\n    urlList: [requestURL],\n    client,\n    serviceWorkers: 'none',\n    referrer: 'no-referrer',\n    mode: 'websocket',\n    credentials: 'include',\n    cache: 'no-store',\n    redirect: 'error',\n    useURLCredentials: true\n  })\n\n  // Note: undici extension, allow setting custom headers.\n  if (options.headers) {\n    const headersList = getHeadersList(new Headers(options.headers))\n\n    request.headersList = headersList\n  }\n\n  // 3. Append (`Upgrade`, `websocket`) to request’s header list.\n  // 4. Append (`Connection`, `Upgrade`) to request’s header list.\n  // Note: both of these are handled by undici currently.\n  // https://github.com/nodejs/undici/blob/68c269c4144c446f3f1220951338daef4a6b5ec4/lib/client.js#L1397\n\n  // 5. Let keyValue be a nonce consisting of a randomly selected\n  //    16-byte value that has been forgiving-base64-encoded and\n  //    isomorphic encoded.\n  const keyValue = crypto.randomBytes(16).toString('base64')\n\n  // 6. Append (`Sec-WebSocket-Key`, keyValue) to request’s\n  //    header list.\n  request.headersList.append('sec-websocket-key', keyValue, true)\n\n  // 7. Append (`Sec-WebSocket-Version`, `13`) to request’s\n  //    header list.\n  request.headersList.append('sec-websocket-version', '13', true)\n\n  // 8. For each protocol in protocols, combine\n  //    (`Sec-WebSocket-Protocol`, protocol) in request’s header\n  //    list.\n  for (const protocol of protocols) {\n    request.headersList.append('sec-websocket-protocol', protocol, true)\n  }\n\n  // 9. Let permessageDeflate be a user-agent defined\n  //    \"permessage-deflate\" extension header value.\n  // https://github.com/mozilla/gecko-dev/blob/ce78234f5e653a5d3916813ff990f053510227bc/netwerk/protocol/websocket/WebSocketChannel.cpp#L2673\n  const permessageDeflate = 'permessage-deflate; client_max_window_bits'\n\n  // 10. Append (`Sec-WebSocket-Extensions`, permessageDeflate) to\n  //     request’s header list.\n  request.headersList.append('sec-websocket-extensions', permessageDeflate, true)\n\n  // 11. Fetch request with useParallelQueue set to true, and\n  //     processResponse given response being these steps:\n  const controller = fetching({\n    request,\n    useParallelQueue: true,\n    dispatcher: options.dispatcher,\n    processResponse (response) {\n      // 1. If response is a network error or its status is not 101,\n      //    fail the WebSocket connection.\n      // if (response.type === 'error' || ((response.socket?.session != null && response.status !== 200) && response.status !== 101)) {\n      if (response.type === 'error' || response.status !== 101) {\n        // The presence of a session property on the socket indicates HTTP2\n        // HTTP1\n        if (response.socket?.session == null) {\n          failWebsocketConnection(handler, 1002, 'Received network error or non-101 status code.', response.error)\n          return\n        }\n\n        // HTTP2\n        if (response.status !== 200) {\n          failWebsocketConnection(handler, 1002, 'Received network error or non-200 status code.', response.error)\n          return\n        }\n      }\n\n      if (warningEmitted === false && response.socket?.session != null) {\n        process.emitWarning('WebSocket over HTTP2 is experimental, and subject to change.', 'ExperimentalWarning')\n        warningEmitted = true\n      }\n\n      // 2. If protocols is not the empty list and extracting header\n      //    list values given `Sec-WebSocket-Protocol` and response’s\n      //    header list results in null, failure, or the empty byte\n      //    sequence, then fail the WebSocket connection.\n      if (protocols.length !== 0 && !response.headersList.get('Sec-WebSocket-Protocol')) {\n        failWebsocketConnection(handler, 1002, 'Server did not respond with sent protocols.')\n        return\n      }\n\n      // 3. Follow the requirements stated step 2 to step 6, inclusive,\n      //    of the last set of steps in section 4.1 of The WebSocket\n      //    Protocol to validate response. This either results in fail\n      //    the WebSocket connection or the WebSocket connection is\n      //    established.\n\n      // 2. If the response lacks an |Upgrade| header field or the |Upgrade|\n      //    header field contains a value that is not an ASCII case-\n      //    insensitive match for the value \"websocket\", the client MUST\n      //    _Fail the WebSocket Connection_.\n      //    For H2, no upgrade header is expected.\n      if (response.socket.session == null && response.headersList.get('Upgrade')?.toLowerCase() !== 'websocket') {\n        failWebsocketConnection(handler, 1002, 'Server did not set Upgrade header to \"websocket\".')\n        return\n      }\n\n      // 3. If the response lacks a |Connection| header field or the\n      //    |Connection| header field doesn't contain a token that is an\n      //    ASCII case-insensitive match for the value \"Upgrade\", the client\n      //    MUST _Fail the WebSocket Connection_.\n      //    For H2, no connection header is expected.\n      if (response.socket.session == null && response.headersList.get('Connection')?.toLowerCase() !== 'upgrade') {\n        failWebsocketConnection(handler, 1002, 'Server did not set Connection header to \"upgrade\".')\n        return\n      }\n\n      // 4. If the response lacks a |Sec-WebSocket-Accept| header field or\n      //    the |Sec-WebSocket-Accept| contains a value other than the\n      //    base64-encoded SHA-1 of the concatenation of the |Sec-WebSocket-\n      //    Key| (as a string, not base64-decoded) with the string \"258EAFA5-\n      //    E914-47DA-95CA-C5AB0DC85B11\" but ignoring any leading and\n      //    trailing whitespace, the client MUST _Fail the WebSocket\n      //    Connection_.\n      const secWSAccept = response.headersList.get('Sec-WebSocket-Accept')\n      const digest = crypto.hash('sha1', keyValue + uid, 'base64')\n      if (secWSAccept !== digest) {\n        failWebsocketConnection(handler, 1002, 'Incorrect hash received in Sec-WebSocket-Accept header.')\n        return\n      }\n\n      // 5. If the response includes a |Sec-WebSocket-Extensions| header\n      //    field and this header field indicates the use of an extension\n      //    that was not present in the client's handshake (the server has\n      //    indicated an extension not requested by the client), the client\n      //    MUST _Fail the WebSocket Connection_.  (The parsing of this\n      //    header field to determine which extensions are requested is\n      //    discussed in Section 9.1.)\n      const secExtension = response.headersList.get('Sec-WebSocket-Extensions')\n      let extensions\n\n      if (secExtension !== null) {\n        extensions = parseExtensions(secExtension)\n\n        if (!extensions.has('permessage-deflate')) {\n          failWebsocketConnection(handler, 1002, 'Sec-WebSocket-Extensions header does not match.')\n          return\n        }\n      }\n\n      // 6. If the response includes a |Sec-WebSocket-Protocol| header field\n      //    and this header field indicates the use of a subprotocol that was\n      //    not present in the client's handshake (the server has indicated a\n      //    subprotocol not requested by the client), the client MUST _Fail\n      //    the WebSocket Connection_.\n      const secProtocol = response.headersList.get('Sec-WebSocket-Protocol')\n\n      if (secProtocol !== null) {\n        const requestProtocols = getDecodeSplit('sec-websocket-protocol', request.headersList)\n\n        // The client can request that the server use a specific subprotocol by\n        // including the |Sec-WebSocket-Protocol| field in its handshake.  If it\n        // is specified, the server needs to include the same field and one of\n        // the selected subprotocol values in its response for the connection to\n        // be established.\n        if (!requestProtocols.includes(secProtocol)) {\n          failWebsocketConnection(handler, 1002, 'Protocol was not set in the opening handshake.')\n          return\n        }\n      }\n\n      response.socket.on('data', handler.onSocketData)\n      response.socket.on('close', handler.onSocketClose)\n      response.socket.on('error', handler.onSocketError)\n\n      handler.wasEverConnected = true\n      handler.onConnectionEstablished(response, extensions)\n    }\n  })\n\n  return controller\n}\n\n/**\n * @see https://whatpr.org/websockets/48.html#close-the-websocket\n * @param {import('./websocket').Handler} object\n * @param {number} [code=null]\n * @param {string} [reason='']\n */\nfunction closeWebSocketConnection (object, code, reason, validate = false) {\n  // 1. If code was not supplied, let code be null.\n  code ??= null\n\n  // 2. If reason was not supplied, let reason be the empty string.\n  reason ??= ''\n\n  // 3. Validate close code and reason with code and reason.\n  if (validate) validateCloseCodeAndReason(code, reason)\n\n  // 4. Run the first matching steps from the following list:\n  //     - If object’s ready state is CLOSING (2) or CLOSED (3)\n  //     - If the WebSocket connection is not yet established [WSP]\n  //     - If the WebSocket closing handshake has not yet been started [WSP]\n  //     - Otherwise\n  if (isClosed(object.readyState) || isClosing(object.readyState)) {\n    // Do nothing.\n  } else if (!isEstablished(object.readyState)) {\n    // Fail the WebSocket connection and set object’s ready state to CLOSING (2). [WSP]\n    failWebsocketConnection(object)\n    object.readyState = states.CLOSING\n  } else if (!object.closeState.has(sentCloseFrameState.SENT) && !object.closeState.has(sentCloseFrameState.RECEIVED)) {\n    // Upon either sending or receiving a Close control frame, it is said\n    // that _The WebSocket Closing Handshake is Started_ and that the\n    // WebSocket connection is in the CLOSING state.\n\n    const frame = new WebsocketFrameSend()\n\n    // If neither code nor reason is present, the WebSocket Close\n    // message must not have a body.\n\n    // If code is present, then the status code to use in the\n    // WebSocket Close message must be the integer given by code.\n    // If code is null and reason is the empty string, the WebSocket Close frame must not have a body.\n    // If reason is non-empty but code is null, then set code to 1000 (\"Normal Closure\").\n    if (reason.length !== 0 && code === null) {\n      code = 1000\n    }\n\n    // If code is set, then the status code to use in the WebSocket Close frame must be the integer given by code.\n    assert(code === null || Number.isInteger(code))\n\n    if (code === null && reason.length === 0) {\n      frame.frameData = emptyBuffer\n    } else if (code !== null && reason === null) {\n      frame.frameData = Buffer.allocUnsafe(2)\n      frame.frameData.writeUInt16BE(code, 0)\n    } else if (code !== null && reason !== null) {\n      // If reason is also present, then reasonBytes must be\n      // provided in the Close message after the status code.\n      frame.frameData = Buffer.allocUnsafe(2 + Buffer.byteLength(reason))\n      frame.frameData.writeUInt16BE(code, 0)\n      // the body MAY contain UTF-8-encoded data with value /reason/\n      frame.frameData.write(reason, 2, 'utf-8')\n    } else {\n      frame.frameData = emptyBuffer\n    }\n\n    object.socket.write(frame.createFrame(opcodes.CLOSE))\n\n    object.closeState.add(sentCloseFrameState.SENT)\n\n    // Upon either sending or receiving a Close control frame, it is said\n    // that _The WebSocket Closing Handshake is Started_ and that the\n    // WebSocket connection is in the CLOSING state.\n    object.readyState = states.CLOSING\n  } else {\n    // Set object’s ready state to CLOSING (2).\n    object.readyState = states.CLOSING\n  }\n}\n\n/**\n * @param {import('./websocket').Handler} handler\n * @param {number} code\n * @param {string|undefined} reason\n * @param {unknown} cause\n * @returns {void}\n */\nfunction failWebsocketConnection (handler, code, reason, cause) {\n  // If _The WebSocket Connection is Established_ prior to the point where\n  // the endpoint is required to _Fail the WebSocket Connection_, the\n  // endpoint SHOULD send a Close frame with an appropriate status code\n  // (Section 7.4) before proceeding to _Close the WebSocket Connection_.\n  if (isEstablished(handler.readyState)) {\n    closeWebSocketConnection(handler, code, reason, false)\n  }\n\n  handler.controller.abort()\n\n  if (isConnecting(handler.readyState)) {\n    // If the connection was not established, we must still emit an 'error' and 'close' events\n    handler.onSocketClose()\n  } else if (handler.socket?.destroyed === false) {\n    handler.socket.destroy()\n  }\n}\n\nmodule.exports = {\n  establishWebSocketConnection,\n  failWebsocketConnection,\n  closeWebSocketConnection\n}\n"],"names":["uid","states","sentCloseFrameState","emptyBuffer","opcodes","require$$0","parseExtensions","isClosed","isClosing","isEstablished","isConnecting","validateCloseCodeAndReason","require$$1","makeRequest","require$$2","fetching","require$$3","Headers","getHeadersList","require$$4","getDecodeSplit","require$$5","WebsocketFrameSend","require$$6","assert","require$$7","runtimeFeatures","require$$8","crypto","has","require$$9","warningEmitted","closeWebSocketConnection","object","code","reason","validate","readyState","closeState","SENT","RECEIVED","CLOSING","frame","length","Number","isInteger","frameData","Buffer","allocUnsafe","writeUInt16BE","byteLength","write","socket","createFrame","CLOSE","add","failWebsocketConnection","handler","cause","controller","abort","onSocketClose","destroyed","destroy","connection","establishWebSocketConnection","url","protocols","client","options","requestURL","protocol","request","urlList","serviceWorkers","referrer","mode","credentials","cache","redirect","useURLCredentials","headers","headersList","keyValue","randomBytes","toString","append","useParallelQueue","dispatcher","processResponse","response","type","status","session","error","process","emitWarning","get","toLowerCase","hash","secExtension","extensions","secProtocol","includes","on","onSocketData","onSocketError","wasEverConnected","onConnectionEstablished"],"mappings":"yxBAEA,MAAMA,IAAKC,OAAQC,oBAAqBC,YAAaC,SAAcC,oBAC7DC,gBAAiBC,SAAUC,UAAWC,cAAeC,aAAcC,4BAAiCC,eACpGC,aAAkBC,kBAClBC,UAAeC,gBACfC,QAASC,gBAAqBC,kBAC9BC,gBAAqBC,iBACrBC,oBAAyBC,eACzBC,OAASC,YACTC,iBAAsBC,yBAEtBC,SAASF,gBAAgBG,IAAI,UAC/BC,OACA,KAEJ,IAAIC,gBAAiB;;;;;;;;;;;;;;AAkNrB,SAASC,yBAA0BC,OAAQC,KAAMC,OAAQC,UAAW;;;;;;AAelE;;AAbAF,OAAS;;AAGTC,SAAW;;AAGPC,UAAUzB,2BAA2BuB,KAAMC,QAO3C5B,SAAS0B,OAAOI,aAAe7B,UAAUyB,OAAOI,kBAE7C,GAAK5B,cAAcwB,OAAOI,YAI1B,GAAKJ,OAAOK,WAAWT,IAAI3B,oBAAoBqC,OAAUN,OAAOK,WAAWT,IAAI3B,oBAAoBsC;;AA+CxGP,OAAOI,WAAapC,OAAOwC,YA/CwF;;;;AAKnH,MAAMC,MAAQ,IAAIpB;;;;;;qFASI;IAAlBa,OAAOQ,QAAyB,OAATT,OACzBA,KAAO;;AAITV,OAAgB,OAATU,MAAiBU,OAAOC,UAAUX,OAE5B,OAATA,MAAmC,IAAlBC,OAAOQ,OAC1BD,MAAMI,UAAY3C,YACA,OAAT+B,MAA4B,OAAXC,QAC1BO,MAAMI,UAAYC,OAAOC,YAAY,GACrCN,MAAMI,UAAUG,cAAcf,KAAM,IAClB,OAATA,MAA4B,OAAXC;;;AAG1BO,MAAMI,UA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