werift 0.27.0 → 0.28.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +119 -8
- package/lib/common/src/event.d.ts +26 -0
- package/lib/common/src/event.js +87 -2
- package/lib/common/src/event.js.map +1 -1
- package/lib/common/src/network.d.ts +6 -1
- package/lib/common/src/network.js +8 -2
- package/lib/common/src/network.js.map +1 -1
- package/lib/common/src/transport.d.ts +12 -5
- package/lib/common/src/transport.js +3 -2
- package/lib/common/src/transport.js.map +1 -1
- package/lib/dtls/src/alert.d.ts +49 -0
- package/lib/dtls/src/alert.js +103 -0
- package/lib/dtls/src/alert.js.map +1 -0
- package/lib/dtls/src/client.js +15 -1
- package/lib/dtls/src/client.js.map +1 -1
- package/lib/dtls/src/context/dtls.d.ts +2 -0
- package/lib/dtls/src/context/dtls.js +7 -0
- package/lib/dtls/src/context/dtls.js.map +1 -1
- package/lib/dtls/src/context/transport.d.ts +17 -1
- package/lib/dtls/src/context/transport.js +38 -2
- package/lib/dtls/src/context/transport.js.map +1 -1
- package/lib/dtls/src/flight/client/flight5.js +4 -1
- package/lib/dtls/src/flight/client/flight5.js.map +1 -1
- package/lib/dtls/src/flight/flight.d.ts +5 -0
- package/lib/dtls/src/flight/flight.js +10 -1
- package/lib/dtls/src/flight/flight.js.map +1 -1
- package/lib/dtls/src/flight/server/flight6.js +4 -1
- package/lib/dtls/src/flight/server/flight6.js.map +1 -1
- package/lib/dtls/src/index.d.ts +3 -1
- package/lib/dtls/src/index.js +10 -1
- package/lib/dtls/src/index.js.map +1 -1
- package/lib/dtls/src/record/const.d.ts +9 -0
- package/lib/dtls/src/record/const.js +9 -1
- package/lib/dtls/src/record/const.js.map +1 -1
- package/lib/dtls/src/record/receive.d.ts +6 -0
- package/lib/dtls/src/record/receive.js +50 -19
- package/lib/dtls/src/record/receive.js.map +1 -1
- package/lib/dtls/src/server.js +19 -1
- package/lib/dtls/src/server.js.map +1 -1
- package/lib/dtls/src/socket.d.ts +134 -2
- package/lib/dtls/src/socket.js +322 -6
- package/lib/dtls/src/socket.js.map +1 -1
- package/lib/ice/src/candidateError.d.ts +155 -0
- package/lib/ice/src/candidateError.js +246 -0
- package/lib/ice/src/candidateError.js.map +1 -0
- package/lib/ice/src/candidateGatherer.d.ts +127 -0
- package/lib/ice/src/candidateGatherer.js +745 -0
- package/lib/ice/src/candidateGatherer.js.map +1 -0
- package/lib/ice/src/consent.d.ts +49 -0
- package/lib/ice/src/consent.js +258 -0
- package/lib/ice/src/consent.js.map +1 -0
- package/lib/ice/src/ice.d.ts +223 -71
- package/lib/ice/src/ice.js +873 -975
- package/lib/ice/src/ice.js.map +1 -1
- package/lib/ice/src/iceBase.d.ts +207 -8
- package/lib/ice/src/iceBase.js +94 -31
- package/lib/ice/src/iceBase.js.map +1 -1
- package/lib/ice/src/index.d.ts +1 -0
- package/lib/ice/src/index.js +1 -0
- package/lib/ice/src/index.js.map +1 -1
- package/lib/ice/src/internal/checkMessages.d.ts +41 -0
- package/lib/ice/src/internal/checkMessages.js +63 -0
- package/lib/ice/src/internal/checkMessages.js.map +1 -0
- package/lib/ice/src/internal/defaultRoute.d.ts +20 -0
- package/lib/ice/src/internal/defaultRoute.js +134 -0
- package/lib/ice/src/internal/defaultRoute.js.map +1 -0
- package/lib/ice/src/internal/hostInterfaces.d.ts +17 -0
- package/lib/ice/src/internal/hostInterfaces.js +77 -0
- package/lib/ice/src/internal/hostInterfaces.js.map +1 -0
- package/lib/ice/src/internal/hostPreference.d.ts +24 -0
- package/lib/ice/src/internal/hostPreference.js +38 -0
- package/lib/ice/src/internal/hostPreference.js.map +1 -0
- package/lib/ice/src/internal/resolveHostAddresses.d.ts +56 -8
- package/lib/ice/src/internal/resolveHostAddresses.js +127 -24
- package/lib/ice/src/internal/resolveHostAddresses.js.map +1 -1
- package/lib/ice/src/internal/selectAddresses.d.ts +27 -0
- package/lib/ice/src/internal/selectAddresses.js +37 -18
- package/lib/ice/src/internal/selectAddresses.js.map +1 -1
- package/lib/ice/src/nomination/regularNomination.d.ts +200 -0
- package/lib/ice/src/nomination/regularNomination.js +311 -0
- package/lib/ice/src/nomination/regularNomination.js.map +1 -0
- package/lib/ice/src/nomination/selectionReplacement.d.ts +138 -0
- package/lib/ice/src/nomination/selectionReplacement.js +371 -0
- package/lib/ice/src/nomination/selectionReplacement.js.map +1 -0
- package/lib/ice/src/provisional.d.ts +139 -0
- package/lib/ice/src/provisional.js +468 -0
- package/lib/ice/src/provisional.js.map +1 -0
- package/lib/ice/src/stun/protocol.d.ts +9 -2
- package/lib/ice/src/stun/protocol.js +16 -17
- package/lib/ice/src/stun/protocol.js.map +1 -1
- package/lib/ice/src/stun/tcpProtocol.d.ts +1 -1
- package/lib/ice/src/stun/tcpProtocol.js +7 -7
- package/lib/ice/src/stun/tcpProtocol.js.map +1 -1
- package/lib/ice/src/stun/transaction.js +4 -2
- package/lib/ice/src/stun/transaction.js.map +1 -1
- package/lib/ice/src/turn/protocol.d.ts +2 -2
- package/lib/ice/src/turn/protocol.js +6 -3
- package/lib/ice/src/turn/protocol.js.map +1 -1
- package/lib/ice/src/types/model.d.ts +16 -5
- package/lib/ice/src/types/model.js.map +1 -1
- package/lib/ice-server/src/stun/attributes.js +4 -0
- package/lib/ice-server/src/stun/attributes.js.map +1 -1
- package/lib/ice-server/src/stun/const.d.ts +20 -1
- package/lib/ice-server/src/stun/const.js +9 -1
- package/lib/ice-server/src/stun/const.js.map +1 -1
- package/lib/ice-server/src/stun/message.d.ts +28 -1
- package/lib/ice-server/src/stun/message.js +102 -15
- package/lib/ice-server/src/stun/message.js.map +1 -1
- package/lib/index.mjs +13394 -7732
- package/lib/nonstandard/index.mjs +680 -286
- package/lib/polyfill/dom.mjs +19605 -14243
- package/lib/polyfill/index.mjs +19605 -14243
- package/lib/rtp/src/index.d.ts +1 -0
- package/lib/rtp/src/index.js +1 -0
- package/lib/rtp/src/index.js.map +1 -1
- package/lib/rtp/src/rtp/continuity.d.ts +14 -1
- package/lib/rtp/src/rtp/continuity.js +24 -4
- package/lib/rtp/src/rtp/continuity.js.map +1 -1
- package/lib/rtp/src/rtp/timelineRewriter.d.ts +178 -0
- package/lib/rtp/src/rtp/timelineRewriter.js +417 -0
- package/lib/rtp/src/rtp/timelineRewriter.js.map +1 -0
- package/lib/sctp/src/sctp.d.ts +5 -0
- package/lib/sctp/src/sctp.js +81 -47
- package/lib/sctp/src/sctp.js.map +1 -1
- package/lib/webrtc/src/api/compatibilityOptions.d.ts +33 -0
- package/lib/webrtc/src/api/compatibilityOptions.js +33 -0
- package/lib/webrtc/src/api/compatibilityOptions.js.map +1 -0
- package/lib/webrtc/src/api/peerConfig.d.ts +348 -34
- package/lib/webrtc/src/api/peerConfig.js +90 -24
- package/lib/webrtc/src/api/peerConfig.js.map +1 -1
- package/lib/webrtc/src/api/peerConnectionEvents.d.ts +77 -1
- package/lib/webrtc/src/api/peerConnectionEvents.js +105 -1
- package/lib/webrtc/src/api/peerConnectionEvents.js.map +1 -1
- package/lib/webrtc/src/helper.d.ts +8 -0
- package/lib/webrtc/src/helper.js +40 -4
- package/lib/webrtc/src/helper.js.map +1 -1
- package/lib/webrtc/src/media/codecCompatibility.d.ts +87 -1
- package/lib/webrtc/src/media/codecCompatibility.js +338 -12
- package/lib/webrtc/src/media/codecCompatibility.js.map +1 -1
- package/lib/webrtc/src/media/receiver/nack.d.ts +43 -10
- package/lib/webrtc/src/media/receiver/nack.js +245 -88
- package/lib/webrtc/src/media/receiver/nack.js.map +1 -1
- package/lib/webrtc/src/media/router.d.ts +239 -51
- package/lib/webrtc/src/media/router.js +664 -237
- package/lib/webrtc/src/media/router.js.map +1 -1
- package/lib/webrtc/src/media/routing/pendingRoutes.d.ts +26 -0
- package/lib/webrtc/src/media/routing/pendingRoutes.js +48 -0
- package/lib/webrtc/src/media/routing/pendingRoutes.js.map +1 -0
- package/lib/webrtc/src/media/routing/ridRouting.d.ts +37 -0
- package/lib/webrtc/src/media/routing/ridRouting.js +74 -0
- package/lib/webrtc/src/media/routing/ridRouting.js.map +1 -0
- package/lib/webrtc/src/media/routing/routeTable.d.ts +60 -0
- package/lib/webrtc/src/media/routing/routeTable.js +95 -0
- package/lib/webrtc/src/media/routing/routeTable.js.map +1 -0
- package/lib/webrtc/src/media/routing/rtcpRouting.d.ts +34 -0
- package/lib/webrtc/src/media/routing/rtcpRouting.js +165 -0
- package/lib/webrtc/src/media/routing/rtcpRouting.js.map +1 -0
- package/lib/webrtc/src/media/routing/unknownSsrc.d.ts +55 -0
- package/lib/webrtc/src/media/routing/unknownSsrc.js +117 -0
- package/lib/webrtc/src/media/routing/unknownSsrc.js.map +1 -0
- package/lib/webrtc/src/media/rtpReceiver.d.ts +222 -0
- package/lib/webrtc/src/media/rtpReceiver.js +668 -28
- package/lib/webrtc/src/media/rtpReceiver.js.map +1 -1
- package/lib/webrtc/src/media/rtpSender.d.ts +7 -0
- package/lib/webrtc/src/media/rtpSender.js +9 -3
- package/lib/webrtc/src/media/rtpSender.js.map +1 -1
- package/lib/webrtc/src/media/rtpTransceiver.d.ts +18 -0
- package/lib/webrtc/src/media/rtpTransceiver.js +64 -2
- package/lib/webrtc/src/media/rtpTransceiver.js.map +1 -1
- package/lib/webrtc/src/media/sender/senderReportHistory.d.ts +51 -0
- package/lib/webrtc/src/media/sender/senderReportHistory.js +111 -0
- package/lib/webrtc/src/media/sender/senderReportHistory.js.map +1 -0
- package/lib/webrtc/src/media/sender/senderStats.d.ts +6 -5
- package/lib/webrtc/src/media/sender/senderStats.js +14 -19
- package/lib/webrtc/src/media/sender/senderStats.js.map +1 -1
- package/lib/webrtc/src/media/track.d.ts +9 -0
- package/lib/webrtc/src/media/track.js +9 -0
- package/lib/webrtc/src/media/track.js.map +1 -1
- package/lib/webrtc/src/negotiation/remoteMediaApplication.d.ts +23 -6
- package/lib/webrtc/src/negotiation/remoteMediaApplication.js +46 -22
- package/lib/webrtc/src/negotiation/remoteMediaApplication.js.map +1 -1
- package/lib/webrtc/src/negotiation/transceiverPairing.d.ts +1 -0
- package/lib/webrtc/src/negotiation/transceiverPairing.js +62 -0
- package/lib/webrtc/src/negotiation/transceiverPairing.js.map +1 -0
- package/lib/webrtc/src/negotiation/transportActivation.d.ts +8 -1
- package/lib/webrtc/src/negotiation/transportActivation.js +21 -0
- package/lib/webrtc/src/negotiation/transportActivation.js.map +1 -1
- package/lib/webrtc/src/negotiationTransaction.d.ts +35 -4
- package/lib/webrtc/src/negotiationTransaction.js +111 -8
- package/lib/webrtc/src/negotiationTransaction.js.map +1 -1
- package/lib/webrtc/src/peerConnection.d.ts +65 -6
- package/lib/webrtc/src/peerConnection.js +283 -28
- package/lib/webrtc/src/peerConnection.js.map +1 -1
- package/lib/webrtc/src/polyfill/globals.d.ts +2 -1
- package/lib/webrtc/src/polyfill/globals.js.map +1 -1
- package/lib/webrtc/src/polyfill/install.js +2 -0
- package/lib/webrtc/src/polyfill/install.js.map +1 -1
- package/lib/webrtc/src/sctpManager.js +4 -0
- package/lib/webrtc/src/sctpManager.js.map +1 -1
- package/lib/webrtc/src/sdp.d.ts +69 -0
- package/lib/webrtc/src/sdp.js +139 -14
- package/lib/webrtc/src/sdp.js.map +1 -1
- package/lib/webrtc/src/sdpManager.d.ts +85 -4
- package/lib/webrtc/src/sdpManager.js +214 -14
- package/lib/webrtc/src/sdpManager.js.map +1 -1
- package/lib/webrtc/src/secureTransportManager.d.ts +38 -1
- package/lib/webrtc/src/secureTransportManager.js +82 -7
- package/lib/webrtc/src/secureTransportManager.js.map +1 -1
- package/lib/webrtc/src/transceiverManager.d.ts +82 -4
- package/lib/webrtc/src/transceiverManager.js +231 -38
- package/lib/webrtc/src/transceiverManager.js.map +1 -1
- package/lib/webrtc/src/transport/dtls.d.ts +95 -1
- package/lib/webrtc/src/transport/dtls.js +324 -28
- package/lib/webrtc/src/transport/dtls.js.map +1 -1
- package/lib/webrtc/src/transport/ice.d.ts +61 -4
- package/lib/webrtc/src/transport/ice.js +180 -11
- package/lib/webrtc/src/transport/ice.js.map +1 -1
- package/lib/webrtc/src/transport/sctp.d.ts +23 -0
- package/lib/webrtc/src/transport/sctp.js +87 -2
- package/lib/webrtc/src/transport/sctp.js.map +1 -1
- package/lib/webrtc/src/utils.d.ts +33 -0
- package/lib/webrtc/src/utils.js +52 -3
- package/lib/webrtc/src/utils.js.map +1 -1
- package/package.json +2 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"iceBase.js","sourceRoot":"","sources":["../../../../ice/src/iceBase.ts"],"names":[],"mappings":";;;AAsQA,4DAYC;AAmJD,0DASC;AAED,gDAsBC;AAGD,sDAQC;AAED,4DA0CC;AAED,0CAKC;AA2CD,8DA+DC;AAQD,sDAkBC;AAUD,oDAEC;AAMD,sCAEC;AAUD,8EAYC;AAlrBD,mCAAoC;AACpC,2CAAgF;AAGhF,6CAM0B;AAC1B,wCAAgD;AAChD,4CAAyC;AAGzC,MAAM,GAAG,GAAG,IAAA,cAAK,EAAC,4CAA4C,CAAC,CAAC;AAyHhE,MAAa,aAAa;IAWxB,IAAI,KAAK;QACP,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;IAmBD,MAAM;QACJ,OAAO,IAAI,CAAC,IAAI,CAAC;IACnB,CAAC;IAED,IAAI,IAAI;QACN,OAAO;YACL,QAAQ,EAAE,IAAI,CAAC,QAAQ,CAAC,IAAI;YAC5B,cAAc,EAAE,IAAI,CAAC,cAAc,CAAC,KAAK,EAAE;YAC3C,eAAe,EAAE,IAAI,CAAC,eAAe,CAAC,KAAK,EAAE;SAC9C,CAAC;IACJ,CAAC;IAED,YACE,QAAkB,EAClB,eAA0B,EAC1B,cAAuB;QA9ClB;;;;;WAAmB;QACnB;;;;;WAA2B;QAC3B;;;;;WAAwB;QAEtB;;;;mBAAK,IAAA,mBAAU,GAAE,CAAC,QAAQ,EAAE;WAAC;QACtC;;;;;WAA0B;QAC1B;;;;mBAAY,KAAK;WAAC;QAClB;;;;mBAAkB,KAAK;WAAC;QACxB,2BAA2B;Q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a,CAAC,OAAwB;IACpD,OAAO,yBAAyB,CAAC,OAAO,CAAC,CAAC,WAAW,CAAC,MAAM,GAAG,CAAC,CAAC;AACnE,CAAC;AAED;;;;;;;GAOG;AACH,SAAgB,iCAAiC,CAC/C,SAAgD,EAChD,OAEiB;IAEjB,IAAI,SAAS,CAAC,IAAI,KAAK,OAAO;QAAE,OAAO,aAAa,CAAC,OAAO,CAAC,CAAC;IAC9D,IAAI,oBAAoB,CAAC,OAAO,CAAC;QAAE,OAAO,KAAK,CAAC;IAChD,IAAI,SAAS,CAAC,SAAS,CAAC,WAAW,EAAE,KAAK,KAAK,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC;QACnE,OAAO,KAAK,CAAC;IACf,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import { randomUUID } from \"crypto\";\nimport { Candidate, candidateFoundation, candidatePriority } from \"./candidate\";\nimport type { MdnsLookup } from \"./dns/lookup\";\nimport type { Cancelable } from \"./helper\";\nimport {\n type Address,\n debug,\n type Event,\n type InterfaceAddresses,\n type TlsConnectionOptions,\n} from \"./imports/common\";\nimport { classes, methods } from \"./stun/const\";\nimport { Message } from \"./stun/message\";\nimport type { Protocol } from \"./types/model\";\n\nconst log = debug(\"werift-ice : packages/ice/src/ice.ts : log\");\n\nexport interface IceConnection {\n iceLite: boolean;\n iceControlling: boolean;\n localUsername: string;\n localPassword: string;\n remotePassword: string;\n remoteUsername: string;\n remoteIsLite: boolean;\n checkList: CandidatePair[];\n localCandidates: Candidate[];\n remoteCandidates: Candidate[];\n candidatePairs: CandidatePair[];\n /**\n * STUN servers gathering queries, normalized from the options (see\n * {@link normalizeIceServerOptions}). Optional so that other\n * implementations of this interface keep compiling.\n */\n stunServers?: Address[];\n /** TURN servers gathering allocates on, each with its own credential. */\n turnServers?: TurnServerOptions[];\n /** @deprecated The first of {@link IceConnection.stunServers}. */\n stunServer?: Address;\n /** @deprecated The address of the first of {@link IceConnection.turnServers}. */\n turnServer?: Address;\n generation: number;\n options: IceOptions;\n remoteCandidatesEnd: boolean;\n localCandidatesEnd: boolean;\n state: IceState;\n lookup?: MdnsLookup;\n nominated?: CandidatePair;\n\n readonly onData: Event<[Buffer]>;\n readonly stateChanged: Event<[IceState]>;\n readonly onIceCandidate: Event<[Candidate]>;\n\n restart(): void;\n /**\n * Optional staged-restart and provisional-generation support. An\n * implementation without them still restarts ICE at the final answer, but\n * cannot answer or run checks for the new generation during pranswer.\n */\n /**\n * `gatherOptions`: the options the staged generation gathers with (an ICE\n * server update applied at the commit); its provisional checks use only\n * the sockets those options allow. Defaults to the current options.\n */\n stageLocalCredentials?(\n usernameFragment: string,\n password: string,\n gatherOptions?: Partial<IceOptions>,\n ): void;\n discardStagedLocalCredentials?(usernameFragment: string): void;\n commitLocalCredentials?(usernameFragment: string, password: string): void;\n /**\n * The remote side alone restarted (new remote credentials in an answer):\n * drop the remote generation and its checks, keep the local credentials\n * and gathered candidates.\n */\n restartRemote?(): void;\n setProvisionalRemoteParams?(params: {\n usernameFragment: string;\n password: string;\n }): void;\n addProvisionalRemoteCandidate?(\n candidate: Candidate | undefined,\n ): Promise<void>;\n startProvisionalChecks?(): void;\n readonly provisionalNominated?: CandidatePair;\n\n setIceServers(options: Partial<IceOptions>): void;\n\n setRemoteParams(params: {\n iceLite: boolean;\n usernameFragment: string;\n password: string;\n }): void;\n\n /**\n * Gather the current generation's candidates. After an ICE restart the\n * candidates the kept sockets advertised are re-advertised synchronously;\n * only server work (STUN, TURN) is awaited.\n */\n gatherCandidates(): Promise<void>;\n\n /** Whether gathering contacts a STUN or TURN server. */\n readonly gathersFromServers?: boolean;\n\n connect(): Promise<void>;\n\n close(): Promise<void>;\n\n addRemoteCandidate(remoteCandidate: Candidate | undefined): Promise<void>;\n\n send(data: Buffer): Promise<void>;\n\n getDefaultCandidate(): Candidate | undefined;\n resetNominatedPair(): void;\n /** Drop remote candidates and pairs that name another remote ufrag. */\n dropOtherRemoteGenerations?(usernameFragment: string): void;\n}\n\nexport interface CandidatePairStats {\n packetsSent: number;\n packetsReceived: number;\n bytesSent: number;\n bytesReceived: number;\n rtt?: number;\n totalRoundTripTime: number;\n roundTripTimeMeasurements: number;\n requestsReceived: number;\n requestsSent: number;\n responsesReceived: number;\n responsesSent: number;\n retransmissionsReceived: number;\n retransmissionsSent: number;\n consentRequestsSent: number;\n}\n\nexport class CandidatePair implements CandidatePairStats {\n public protocol: Protocol;\n public remoteCandidate: Candidate;\n public iceControlling: boolean;\n\n readonly id = randomUUID().toString();\n handle?: Cancelable<void>;\n nominated = false;\n remoteNominated = false;\n // 5.7.4. Computing States\n private _state: CandidatePairState = CandidatePairState.FROZEN;\n get state() {\n return this._state;\n }\n\n // Statistics tracking\n packetsSent = 0;\n packetsReceived = 0;\n bytesSent = 0;\n bytesReceived = 0;\n rtt?: number;\n totalRoundTripTime = 0;\n roundTripTimeMeasurements = 0;\n requestsReceived = 0;\n requestsSent = 0;\n responsesReceived = 0;\n responsesSent = 0;\n retransmissionsReceived = 0;\n retransmissionsSent = 0;\n consentRequestsSent = 0;\n private readonly requestTransactionIds = new Set<string>();\n\n toJSON() {\n return this.json;\n }\n\n get json() {\n return {\n protocol: this.protocol.type,\n localCandidate: this.localCandidate.toSdp(),\n remoteCandidate: this.remoteCandidate.toSdp(),\n };\n }\n\n constructor(\n protocol: Protocol,\n remoteCandidate: Candidate,\n iceControlling: boolean,\n ) {\n this.protocol = protocol;\n this.remoteCandidate = remoteCandidate;\n this.iceControlling = iceControlling;\n }\n\n updateState(state: CandidatePairState) {\n this._state = state;\n }\n\n get localCandidate() {\n if (!this.protocol.localCandidate) {\n throw new Error(\"localCandidate not exist\");\n }\n return this.protocol.localCandidate;\n }\n\n get remoteAddr(): Address {\n return [this.remoteCandidate.host, this.remoteCandidate.port];\n }\n\n get component() {\n return this.localCandidate.component;\n }\n\n get priority() {\n return candidatePairPriority(\n this.localCandidate,\n this.remoteCandidate,\n this.iceControlling,\n );\n }\n\n get foundation() {\n return this.localCandidate.foundation;\n }\n\n noteIncomingRequest(transactionId: string) {\n const isRetransmission = this.requestTransactionIds.has(transactionId);\n if (!isRetransmission) {\n this.requestTransactionIds.add(transactionId);\n return false;\n }\n this.retransmissionsReceived++;\n return true;\n }\n}\n\nexport const ICE_COMPLETED = 1 as const;\nexport const ICE_FAILED = 2 as const;\n\n/** Basic consent check period in seconds (RFC 7675). Actual interval is 0.8–1.2× this. */\nexport const CONSENT_INTERVAL = 5;\n\n/**\n * @deprecated Consent expiry is based on {@link CONSENT_TIMEOUT} (30s after the\n * last valid response), not a consecutive failure count. Kept for API compatibility.\n */\nexport const CONSENT_FAILURES = 6;\n\n/** RFC 7675: consent expires this many seconds after the last valid response. */\nexport const CONSENT_TIMEOUT = 30;\n\n/**\n * Default single-shot response wait for consent requests (ms) when RTT is unknown.\n * Independent of retransmission count. Downstream ICE-lite peers typically\n * answer in 150–300ms; 1s is a conservative default used by interop patches.\n */\nexport const CONSENT_RESPONSE_TIMEOUT = 1000;\n\n/** RFC 8445 §14.3: ICE RTO must not be less than 500ms. */\nexport const CONSENT_RESPONSE_TIMEOUT_MIN = 500;\n\n/**\n * Compute consent response wait from pair RTT (seconds).\n * Uses 2×RTT + 200ms jitter margin, floored at {@link CONSENT_RESPONSE_TIMEOUT_MIN}.\n * Falls back to {@link CONSENT_RESPONSE_TIMEOUT} when RTT is unavailable.\n */\nexport function consentResponseTimeoutMs(rttSeconds?: number): number {\n if (\n rttSeconds === undefined ||\n !Number.isFinite(rttSeconds) ||\n rttSeconds <= 0\n ) {\n return CONSENT_RESPONSE_TIMEOUT;\n }\n return Math.max(\n CONSENT_RESPONSE_TIMEOUT_MIN,\n Math.round(rttSeconds * 1000 * 2 + 200),\n );\n}\n\n/**\n * @enum\n */\nexport const CandidatePairState = {\n FROZEN: 0,\n WAITING: 1,\n IN_PROGRESS: 2,\n SUCCEEDED: 3,\n FAILED: 4,\n} as const;\nexport type CandidatePairState =\n (typeof CandidatePairState)[keyof typeof CandidatePairState];\n\nexport type IceState =\n | \"disconnected\"\n | \"closed\"\n | \"completed\"\n | \"new\"\n | \"connected\"\n | \"failed\";\n\n/** A TURN server and the credential and transport used for it. */\nexport type TurnServerOptions = {\n address: Address;\n username: string;\n password: string;\n /** Defaults to \"udp\" (with a TCP fallback when the UDP allocation fails). */\n transport?: \"udp\" | \"tcp\" | \"tls\";\n};\n\nexport interface IceOptions {\n /** Advertise and operate as an ICE lite agent. */\n iceLite: boolean;\n useTcp: boolean;\n /**\n * Gather passive TCP host candidates (opens a listening TCP server per\n * interface). Defaults to true. Send-only agents that never accept inbound\n * connections can set this false to avoid the listener while still gathering\n * active TCP candidates.\n */\n tcpPassive?: boolean;\n /**\n * Seconds to wait for server-reflexive candidates while gathering.\n * Defaults to 5. Where UDP is blocked these STUN queries are never answered,\n * so the wait always runs to the timeout; agents that must not stall on such\n * networks can lower it.\n */\n stunGatherTimeout?: number;\n /**\n * Seconds to wait for a TURN TCP/TLS connection to be established.\n * Defaults to 8.\n */\n turnConnectTimeout?: number;\n /**\n * STUN servers queried while gathering, in priority order. Every IPv4 UDP\n * host socket queries each of them in parallel; equal mappings are\n * advertised once, different ones (a NAT that maps per destination) each.\n * Gathering ends when the slowest server answers or `stunGatherTimeout`\n * runs out.\n *\n * Merged with the deprecated `stunServer`: the singular one comes first,\n * duplicates are dropped (see {@link normalizeIceServerOptions}).\n */\n stunServers?: Address[];\n /**\n * TURN servers allocated on while gathering, in priority order. Each one\n * gets its own allocation with its own credential and transport; one that\n * fails or times out does not stop the others. Gathering ends when the\n * slowest allocation completes or fails (`turnConnectTimeout` bounds a\n * TCP/TLS connection, the STUN transaction timeout an unanswered request).\n * `turnTlsOptions`, `turnUdpFamily`, `turnConnectTimeout`, `portRange` and\n * `interfaceAddresses` apply to every TURN server.\n *\n * Merged with the deprecated `turnServer` / `turnUsername` /\n * `turnPassword` / `turnTransport`: the singular one comes first,\n * duplicates are dropped and an entry without username / password is\n * ignored (see {@link normalizeIceServerOptions}).\n */\n turnServers?: TurnServerOptions[];\n /** @deprecated Use {@link IceOptions.stunServers}. Kept as their first entry. */\n stunServer?: Address;\n /**\n * Whether the built-in public STUN server (stun.l.google.com:19302) is used\n * when no STUN server is given. Defaults to true; false gathers no\n * server-reflexive candidate unless a STUN server is set.\n */\n useDefaultStunServer?: boolean;\n /** @deprecated Use {@link IceOptions.turnServers}. Kept as their first entry. */\n turnServer?: Address;\n /** @deprecated Use {@link TurnServerOptions.username} of {@link IceOptions.turnServers}. */\n turnUsername?: string;\n /** @deprecated Use {@link TurnServerOptions.password} of {@link IceOptions.turnServers}. */\n turnPassword?: string;\n /** @deprecated Use {@link TurnServerOptions.transport} of {@link IceOptions.turnServers}. */\n turnTransport?: \"udp\" | \"tcp\" | \"tls\";\n /** Applied to every TLS TURN server. */\n turnTlsOptions?: TlsConnectionOptions;\n /**\n * Preferred IP family of a TURN/UDP socket, applied (to every TURN server)\n * only when the server is a hostname. Ignored for an IP literal server,\n * whose own family always selects the socket. Defaults to 4.\n */\n turnUdpFamily?: 4 | 6;\n forceTurn?: boolean;\n localPasswordPrefix?: string;\n useIpv4: boolean;\n useIpv6: boolean;\n useLinkLocalAddress?: boolean;\n portRange?: [number, number];\n /**\n * Local addresses to bind the UDP host sockets to, per family.\n *\n * The address given for a family (`udp4` / `udp6`) is the only host\n * address of that family: its UDP host candidate advertises the address and\n * port the socket is actually bound to, even when the address is not among\n * the enumerated network interfaces (loopback, tun, ...), and its TCP host\n * candidates use it too. Other enumerated addresses of that family are not\n * gathered. If the bind fails, the family has no UDP host candidate.\n *\n * A family left unspecified while the other one is set gathers no\n * enumerated addresses (only its `additionalHostAddresses`). Without any\n * family set, every enumerated address is gathered over wildcard sockets.\n */\n interfaceAddresses?: InterfaceAddresses;\n /**\n * Host addresses gathered in addition to the enumerated ones. For a family\n * bound by `interfaceAddresses`, addresses other than the bound one are\n * ignored.\n */\n additionalHostAddresses?: string[];\n filterStunResponse?: (\n message: Message,\n addr: Address,\n protocol: Protocol,\n ) => boolean;\n filterCandidatePair?: (pair: CandidatePair) => boolean;\n}\n\nexport const defaultOptions: IceOptions = {\n iceLite: false,\n useTcp: false,\n useIpv4: true,\n useIpv6: true,\n};\n\nexport function validateRemoteCandidate(candidate: Candidate) {\n // \"\"\"\n // Check the remote candidate is supported.\n // \"\"\"\n if (![\"host\", \"relay\", \"srflx\"].includes(candidate.type))\n throw new Error(`Unexpected candidate type \"${candidate.type}\"`);\n\n // ipaddress.ip_address(candidate.host)\n return candidate;\n}\n\nexport function sortCandidatePairs(\n pairs: {\n localCandidate: Pick<Candidate, \"priority\">;\n remoteCandidate: Pick<Candidate, \"priority\">;\n }[],\n iceControlling: boolean,\n) {\n return pairs\n .sort(\n (a, b) =>\n candidatePairPriority(\n a.localCandidate,\n a.remoteCandidate,\n iceControlling,\n ) -\n candidatePairPriority(\n b.localCandidate,\n b.remoteCandidate,\n iceControlling,\n ),\n )\n .reverse();\n}\n\n// 5.7.2. Computing Pair Priority and Ordering Pairs\nexport function candidatePairPriority(\n local: Pick<Candidate, \"priority\">,\n remote: Pick<Candidate, \"priority\">,\n iceControlling: boolean,\n) {\n const G = (iceControlling && local.priority) || remote.priority;\n const D = (iceControlling && remote.priority) || local.priority;\n return (1 << 32) * Math.min(G, D) + 2 * Math.max(G, D) + (G > D ? 1 : 0);\n}\n\nexport async function serverReflexiveCandidate(\n protocol: Protocol,\n stunServer: Address,\n) {\n // \"\"\"\n // Query STUN server to obtain a server-reflexive candidate.\n // \"\"\"\n\n // # perform STUN query\n const request = new Message(methods.BINDING, classes.REQUEST);\n try {\n const [response] = await protocol.request(request, stunServer);\n\n const localCandidate = protocol.localCandidate;\n if (!localCandidate) {\n throw new Error(\"not exist\");\n }\n\n const candidate = new Candidate(\n candidateFoundation(\n \"srflx\",\n localCandidate.transport,\n localCandidate.host,\n ),\n localCandidate.component,\n localCandidate.transport,\n candidatePriority(\"srflx\", {\n transport: localCandidate.transport,\n tcptype: localCandidate.tcptype,\n }),\n response.getAttributeValue(\"XOR-MAPPED-ADDRESS\")[0],\n response.getAttributeValue(\"XOR-MAPPED-ADDRESS\")[1],\n \"srflx\",\n localCandidate.host,\n localCandidate.port,\n localCandidate.tcptype,\n );\n return candidate;\n } catch (error) {\n // todo fix\n log(\"error serverReflexiveCandidate\", error);\n }\n}\n\nexport function validateAddress(addr?: Address): Address | undefined {\n if (addr && Number.isNaN(addr[1])) {\n return [addr[0], 443];\n }\n return addr;\n}\n\n/** The STUN/TURN server fields of {@link IceOptions}, singular and plural. */\nexport type IceServerFields = Partial<\n Pick<\n IceOptions,\n | \"stunServer\"\n | \"stunServers\"\n | \"turnServer\"\n | \"turnServers\"\n | \"turnUsername\"\n | \"turnPassword\"\n | \"turnTransport\"\n >\n>;\n\n/** A STUN/TURN server address: validated (see {@link validateAddress}) or undefined. */\nfunction validServerAddress(addr: unknown): Address | undefined {\n if (!Array.isArray(addr)) return undefined;\n const validated = validateAddress(addr as unknown as Address);\n if (!validated) return undefined;\n const [host, port] = validated;\n if (typeof host !== \"string\" || host === \"\") return undefined;\n if (typeof port !== \"number\" || !Number.isFinite(port)) return undefined;\n return validated;\n}\n\nconst sameAddress = (a: Address, b: Address) => a[0] === b[0] && a[1] === b[1];\n\n/**\n * The STUN and TURN servers `options` configure, the one place the singular\n * (deprecated) and plural fields are merged:\n *\n * - order: the singular server first, then the plural list in its order;\n * - duplicates (the same STUN address; the same TURN address, transport and\n * credential) are kept once, at their first position;\n * - an invalid address (see {@link validateAddress}) is dropped, and so is a\n * TURN server without username or password (it cannot allocate);\n * - a TURN transport left unset is \"udp\".\n *\n * The built-in default STUN server is not added here; Connection falls back\n * to it when the result has no STUN server.\n */\nexport function normalizeIceServerOptions(options: IceServerFields): {\n stunServers: Address[];\n turnServers: Required<TurnServerOptions>[];\n} {\n const stunServers: Address[] = [];\n for (const server of [options.stunServer, ...(options.stunServers ?? [])]) {\n if (server === undefined) continue;\n const address = validServerAddress(server);\n if (!address) {\n log(\"invalid STUN server ignored\", server);\n continue;\n }\n if (stunServers.some((existing) => sameAddress(existing, address))) {\n continue;\n }\n stunServers.push(address);\n }\n\n const turnServers: Required<TurnServerOptions>[] = [];\n const configured: Partial<TurnServerOptions>[] = [\n ...(options.turnServer !== undefined\n ? [\n {\n address: options.turnServer,\n username: options.turnUsername,\n password: options.turnPassword,\n transport: options.turnTransport,\n },\n ]\n : []),\n ...(options.turnServers ?? []),\n ];\n for (const server of configured) {\n const address = validServerAddress(server?.address);\n if (!address) {\n log(\"invalid TURN server ignored\", server?.address);\n continue;\n }\n const { username, password } = server;\n if (!username || !password) {\n log(\"TURN server without username / credential ignored\", address);\n continue;\n }\n const entry: Required<TurnServerOptions> = {\n address,\n username,\n password,\n transport: server.transport ?? \"udp\",\n };\n if (\n turnServers.some(\n (existing) =>\n sameAddress(existing.address, entry.address) &&\n existing.transport === entry.transport &&\n existing.username === entry.username &&\n existing.password === entry.password,\n )\n ) {\n continue;\n }\n turnServers.push(entry);\n }\n return { stunServers, turnServers };\n}\n\n/**\n * `current` with an ICE server update applied (Connection.setIceServers): the\n * STUN/TURN fields, singular and plural, are replaced, an undefined one\n * included, so a STUN-only update cannot leave a previous TURN\n * host/credential behind; forceTurn and useTcp change only when given.\n */\nexport function mergeIceServerOptions<T extends Partial<IceOptions>>(\n current: T,\n update: Partial<IceOptions>,\n): T {\n return {\n ...current,\n stunServer: update.stunServer,\n stunServers: update.stunServers,\n turnServer: update.turnServer,\n turnServers: update.turnServers,\n turnUsername: update.turnUsername,\n turnPassword: update.turnPassword,\n turnTransport: update.turnTransport,\n turnTlsOptions: update.turnTlsOptions,\n turnUdpFamily: update.turnUdpFamily,\n forceTurn: update.forceTurn ?? current.forceTurn,\n useTcp: update.useTcp ?? current.useTcp,\n };\n}\n\n/**\n * Whether a generation gathered with `options` is relay-only: forceTurn (the\n * \"relay\" ICE transport policy). The policy holds whatever the TURN settings\n * are: without a usable TURN server / credential (or for an ICE-lite agent,\n * which gathers no relay candidate) the generation has no candidate at all\n * rather than falling back to host / server-reflexive ones, so the local and\n * public addresses are neither advertised nor used for checks.\n */\nexport function isRelayOnlyGathering(options: Pick<IceOptions, \"forceTurn\">) {\n return !!options.forceTurn;\n}\n\n/**\n * Whether `options` carry at least one usable TURN server with its\n * credential, the ones a gathering with them allocates relay candidates from.\n */\nexport function hasTurnServer(options: IceServerFields) {\n return normalizeIceServerOptions(options).turnServers.length > 0;\n}\n\n/**\n * Whether `candidate`, kept from an earlier generation (an ICE restart keeps\n * the sockets), may be advertised and paired in a generation gathered with\n * `options`. A fresh gathering with the same options would not have produced\n * a host / server-reflexive candidate for a relay-only policy, a TCP host\n * candidate without useTcp, nor a relay candidate without a TURN server;\n * the kept ones are held back the same way.\n */\nexport function isCandidateAllowedByGatherOptions(\n candidate: Pick<Candidate, \"type\" | \"transport\">,\n options: Pick<IceOptions, \"forceTurn\"> &\n Partial<Pick<IceOptions, \"useTcp\">> &\n IceServerFields,\n) {\n if (candidate.type === \"relay\") return hasTurnServer(options);\n if (isRelayOnlyGathering(options)) return false;\n if (candidate.transport.toLowerCase() === \"tcp\" && !options.useTcp) {\n return false;\n }\n return true;\n}\n"]}
|
|
1
|
+
{"version":3,"file":"iceBase.js","sourceRoot":"","sources":["../../../../ice/src/iceBase.ts"],"names":[],"mappings":";;;AA0TA,4DAYC;AAkRD,0DASC;AAED,gDAiBC;AAmBD,sDAOC;AAMD,oEAUC;AAQD,sEAmCC;AAOD,4DAYC;AAED,0CAKC;AA6CD,8DAsEC;AAQD,sDAmBC;AAUD,oDAEC;AAMD,sCAEC;AAUD,8EAYC;AA35BD,mCAAoC;AACpC,2CAAgF;AAChF,qDAI0B;AAG1B,6CAM0B;AAC1B,wCAA2E;AAC3E,4CAAyC;AAGzC,MAAM,GAAG,GAAG,IAAA,cAAK,EAAC,4CAA4C,CAAC,CAAC;AA4JhE,MAAa,aAAa;IAuBxB,IAAI,KAAK;QACP,OAAO,IAAI,CAAC,MAAM,CAAC;IACrB,CAAC;IAmBD,MAAM;QACJ,OAAO,IAAI,CAAC,IAAI,CAA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AAC,OAAO,CAAC;QAAE,OAAO,KAAK,CAAC;IAChD,IAAI,SAAS,CAAC,SAAS,CAAC,WAAW,EAAE,KAAK,KAAK,IAAI,CAAC,OAAO,CAAC,MAAM,EAAE,CAAC;QACnE,OAAO,KAAK,CAAC;IACf,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC","sourcesContent":["import { randomUUID } from \"crypto\";\nimport { Candidate, candidateFoundation, candidatePriority } from \"./candidate\";\nimport {\n type IceCandidateErrorInfo,\n type IceServerReachedInfo,\n MissingMappedAddressError,\n} from \"./candidateError\";\nimport type { MdnsLookup } from \"./dns/lookup\";\nimport type { Cancelable } from \"./helper\";\nimport {\n type Address,\n debug,\n type Event,\n type InterfaceAddresses,\n type TlsConnectionOptions,\n} from \"./imports/common\";\nimport { classes, type MessageIntegrityMode, methods } from \"./stun/const\";\nimport { Message } from \"./stun/message\";\nimport type { Protocol } from \"./types/model\";\n\nconst log = debug(\"werift-ice : packages/ice/src/ice.ts : log\");\n\nexport interface IceConnection {\n iceLite: boolean;\n iceControlling: boolean;\n localUsername: string;\n localPassword: string;\n remotePassword: string;\n remoteUsername: string;\n remoteIsLite: boolean;\n /**\n * The peer advertised `a=ice-options:renomination`. With\n * {@link IceOptions.renomination} the controlling agent then nominates with\n * the NOMINATION attribute (see `renomination`).\n */\n remoteRenomination?: boolean;\n /**\n * The remote `a=ice-options` tokens (RFC 8839 §5.6), e.g. `trickle`,\n * `ice2`. Informational: werift already follows RFC 8445, so no token\n * changes how checks or nomination run.\n */\n remoteIceOptions?: string[];\n /** The remote declared `ice2`: an RFC 8445 agent (RFC 8445 §10). */\n readonly remoteIce2?: boolean;\n checkList: CandidatePair[];\n localCandidates: Candidate[];\n remoteCandidates: Candidate[];\n candidatePairs: CandidatePair[];\n /**\n * STUN servers gathering queries, normalized from the options (see\n * {@link normalizeIceServerOptions}). Optional so that other\n * implementations of this interface keep compiling.\n */\n stunServers?: Address[];\n /** TURN servers gathering allocates on, each with its own credential. */\n turnServers?: TurnServerOptions[];\n /** @deprecated The first of {@link IceConnection.stunServers}. */\n stunServer?: Address;\n /** @deprecated The address of the first of {@link IceConnection.turnServers}. */\n turnServer?: Address;\n generation: number;\n options: IceOptions;\n remoteCandidatesEnd: boolean;\n localCandidatesEnd: boolean;\n /**\n * Resolves when `localCandidatesEnd` becomes true after `gatherCandidates()`\n * returned (server-reflexive queries that continue in the background), or\n * when the generation ends. Optional so that other implementations of this\n * interface keep compiling; without it gathering ends when\n * `gatherCandidates()` returns.\n */\n waitForLocalCandidatesEnd?(): Promise<void>;\n state: IceState;\n lookup?: MdnsLookup;\n nominated?: CandidatePair;\n\n readonly onData: Event<[Buffer]>;\n readonly stateChanged: Event<[IceState]>;\n readonly onIceCandidate: Event<[Candidate]>;\n /**\n * A STUN or TURN server of the current generation's gathering gave no\n * candidate (see {@link IceCandidateErrorInfo}). Optional so that other\n * implementations of this interface keep compiling.\n */\n readonly onIceCandidateError?: Event<[IceCandidateErrorInfo]>;\n /**\n * A STUN or TURN server of the current generation's gathering answered\n * (see {@link IceServerReachedInfo}). Optional like onIceCandidateError.\n */\n readonly onIceServerReached?: Event<[IceServerReachedInfo]>;\n\n restart(): void;\n /** Record the remote `a=ice-options` tokens (see remoteIceOptions). */\n setRemoteIceOptions?(options: string[]): void;\n /**\n * Optional staged-restart and provisional-generation support. An\n * implementation without them still restarts ICE at the final answer, but\n * cannot answer or run checks for the new generation during pranswer.\n */\n /**\n * `gatherOptions`: the options the staged generation gathers with (an ICE\n * server update applied at the commit); its provisional checks use only\n * the sockets those options allow. Defaults to the current options.\n */\n stageLocalCredentials?(\n usernameFragment: string,\n password: string,\n gatherOptions?: Partial<IceOptions>,\n ): void;\n discardStagedLocalCredentials?(usernameFragment: string): void;\n commitLocalCredentials?(usernameFragment: string, password: string): void;\n /**\n * The remote side alone restarted (new remote credentials in an answer):\n * drop the remote generation and its checks, keep the local credentials\n * and gathered candidates.\n */\n restartRemote?(): void;\n setProvisionalRemoteParams?(params: {\n usernameFragment: string;\n password: string;\n }): void;\n addProvisionalRemoteCandidate?(\n candidate: Candidate | undefined,\n ): Promise<void>;\n startProvisionalChecks?(): void;\n readonly provisionalNominated?: CandidatePair;\n\n setIceServers(options: Partial<IceOptions>): void;\n\n setRemoteParams(params: {\n iceLite: boolean;\n usernameFragment: string;\n password: string;\n }): void;\n\n /**\n * Gather the current generation's candidates. After an ICE restart the\n * candidates the kept sockets advertised are re-advertised synchronously;\n * only server work (STUN, TURN) is awaited.\n */\n gatherCandidates(): Promise<void>;\n\n /** Whether gathering contacts a STUN or TURN server. */\n readonly gathersFromServers?: boolean;\n\n connect(): Promise<void>;\n\n close(): Promise<void>;\n\n addRemoteCandidate(remoteCandidate: Candidate | undefined): Promise<void>;\n\n send(data: Buffer): Promise<void>;\n\n getDefaultCandidate(): Candidate | undefined;\n resetNominatedPair(): void;\n /** Drop remote candidates and pairs that name another remote ufrag. */\n dropOtherRemoteGenerations?(usernameFragment: string): void;\n}\n\nexport interface CandidatePairStats {\n packetsSent: number;\n packetsReceived: number;\n bytesSent: number;\n bytesReceived: number;\n rtt?: number;\n totalRoundTripTime: number;\n roundTripTimeMeasurements: number;\n requestsReceived: number;\n requestsSent: number;\n responsesReceived: number;\n responsesSent: number;\n retransmissionsReceived: number;\n retransmissionsSent: number;\n consentRequestsSent: number;\n}\n\nexport class CandidatePair implements CandidatePairStats {\n public protocol: Protocol;\n public remoteCandidate: Candidate;\n public iceControlling: boolean;\n\n readonly id = randomUUID().toString();\n handle?: Cancelable<void>;\n nominated = false;\n remoteNominated = false;\n /**\n * The largest nomination the peer sent for this pair while this agent was\n * controlled: the NOMINATION attribute's value (renomination), or 1 for\n * USE-CANDIDATE. The controlled agent selects the nominated pair with the\n * largest value, the higher-priority one between equal values.\n */\n remoteNomination = 0;\n /**\n * The NOMINATION value this agent (controlling, renomination) sent for the\n * pair and the peer answered; 0 when it did not renominate the pair.\n */\n nomination = 0;\n // 5.7.4. Computing States\n private _state: CandidatePairState = CandidatePairState.FROZEN;\n get state() {\n return this._state;\n }\n\n // Statistics tracking\n packetsSent = 0;\n packetsReceived = 0;\n bytesSent = 0;\n bytesReceived = 0;\n rtt?: number;\n totalRoundTripTime = 0;\n roundTripTimeMeasurements = 0;\n requestsReceived = 0;\n requestsSent = 0;\n responsesReceived = 0;\n responsesSent = 0;\n retransmissionsReceived = 0;\n retransmissionsSent = 0;\n consentRequestsSent = 0;\n private readonly requestTransactionIds = new Set<string>();\n\n toJSON() {\n return this.json;\n }\n\n get json() {\n return {\n protocol: this.protocol.type,\n localCandidate: this.localCandidate.toSdp(),\n remoteCandidate: this.remoteCandidate.toSdp(),\n };\n }\n\n constructor(\n protocol: Protocol,\n remoteCandidate: Candidate,\n iceControlling: boolean,\n ) {\n this.protocol = protocol;\n this.remoteCandidate = remoteCandidate;\n this.iceControlling = iceControlling;\n }\n\n updateState(state: CandidatePairState) {\n this._state = state;\n }\n\n get localCandidate() {\n if (!this.protocol.localCandidate) {\n throw new Error(\"localCandidate not exist\");\n }\n return this.protocol.localCandidate;\n }\n\n get remoteAddr(): Address {\n return [this.remoteCandidate.host, this.remoteCandidate.port];\n }\n\n get component() {\n return this.localCandidate.component;\n }\n\n get priority() {\n return candidatePairPriority(\n this.localCandidate,\n this.remoteCandidate,\n this.iceControlling,\n );\n }\n\n get foundation() {\n return this.localCandidate.foundation;\n }\n\n noteIncomingRequest(transactionId: string) {\n const isRetransmission = this.requestTransactionIds.has(transactionId);\n if (!isRetransmission) {\n this.requestTransactionIds.add(transactionId);\n return false;\n }\n this.retransmissionsReceived++;\n return true;\n }\n}\n\nexport const ICE_COMPLETED = 1 as const;\nexport const ICE_FAILED = 2 as const;\n\n/** Basic consent check period in seconds (RFC 7675). Actual interval is 0.8–1.2× this. */\nexport const CONSENT_INTERVAL = 5;\n\n/**\n * @deprecated Consent expiry is based on {@link CONSENT_TIMEOUT} (30s after the\n * last valid response), not a consecutive failure count. Kept for API compatibility.\n */\nexport const CONSENT_FAILURES = 6;\n\n/** RFC 7675: consent expires this many seconds after the last valid response. */\nexport const CONSENT_TIMEOUT = 30;\n\n/**\n * Default single-shot response wait for consent requests (ms) when RTT is unknown.\n * Independent of retransmission count. Downstream ICE-lite peers typically\n * answer in 150–300ms; 1s is a conservative default used by interop patches.\n */\nexport const CONSENT_RESPONSE_TIMEOUT = 1000;\n\n/** RFC 8445 §14.3: ICE RTO must not be less than 500ms. */\nexport const CONSENT_RESPONSE_TIMEOUT_MIN = 500;\n\n/**\n * Compute consent response wait from pair RTT (seconds).\n * Uses 2×RTT + 200ms jitter margin, floored at {@link CONSENT_RESPONSE_TIMEOUT_MIN}.\n * Falls back to {@link CONSENT_RESPONSE_TIMEOUT} when RTT is unavailable.\n */\nexport function consentResponseTimeoutMs(rttSeconds?: number): number {\n if (\n rttSeconds === undefined ||\n !Number.isFinite(rttSeconds) ||\n rttSeconds <= 0\n ) {\n return CONSENT_RESPONSE_TIMEOUT;\n }\n return Math.max(\n CONSENT_RESPONSE_TIMEOUT_MIN,\n Math.round(rttSeconds * 1000 * 2 + 200),\n );\n}\n\n/**\n * @enum\n */\nexport const CandidatePairState = {\n FROZEN: 0,\n WAITING: 1,\n IN_PROGRESS: 2,\n SUCCEEDED: 3,\n FAILED: 4,\n} as const;\nexport type CandidatePairState =\n (typeof CandidatePairState)[keyof typeof CandidatePairState];\n\nexport type IceState =\n | \"disconnected\"\n | \"closed\"\n | \"completed\"\n | \"new\"\n | \"connected\"\n | \"failed\";\n\n/** A TURN server and the credential and transport used for it. */\nexport type TurnServerOptions = {\n address: Address;\n username: string;\n password: string;\n /** Defaults to \"udp\" (with a TCP fallback when the UDP allocation fails). */\n transport?: \"udp\" | \"tcp\" | \"tls\";\n /**\n * The application's names (URLs) for this server. Metadata only: the\n * allocation does not use them. They are passed through unchanged to\n * {@link IceServerRef.urls} of `Connection.onIceCandidateError`, so a\n * failure can be matched to the configured server without exposing the\n * credential. Duplicates merged by {@link normalizeIceServerOptions} have\n * their urls merged.\n */\n urls?: string[];\n};\n\n/** A TURN server as gathering uses it (see {@link normalizeIceServerOptions}). */\nexport type NormalizedTurnServer = Required<Omit<TurnServerOptions, \"urls\">> &\n Pick<TurnServerOptions, \"urls\">;\n\n/**\n * The application's name (URL) of a STUN server, reported in\n * {@link IceServerRef.urls} of `Connection.onIceCandidateError`. Metadata\n * only; several entries may name the same address.\n */\nexport type StunServerUrl = { address: Address; url: string };\n\nexport interface IceOptions {\n /** Advertise and operate as an ICE lite agent. */\n iceLite: boolean;\n useTcp: boolean;\n /**\n * Gather passive TCP host candidates (opens a listening TCP server per\n * interface). Defaults to true. Send-only agents that never accept inbound\n * connections can set this false to avoid the listener while still gathering\n * active TCP candidates.\n */\n tcpPassive?: boolean;\n /**\n * Seconds to wait for server-reflexive candidates while gathering.\n * Defaults to 5. Where UDP is blocked these STUN queries are never answered,\n * so the wait always runs to the timeout; agents that must not stall on such\n * networks can lower it.\n *\n * `gatherCandidates()` waits only for the representative sockets' queries\n * (see `stunServers`); the other host sockets' queries continue up to this\n * timeout in the background and end-of-candidates follows them.\n */\n stunGatherTimeout?: number;\n /**\n * Seconds to wait for a TURN TCP/TLS connection to be established.\n * Defaults to 8.\n */\n turnConnectTimeout?: number;\n /**\n * With `nomination: \"regular\"`: milliseconds the controlling agent keeps\n * checking before it nominates (RFC 8445 §8.1.1 regular nomination). The\n * default semi-aggressive nomination does not wait. Counted from the later of the first\n * valid pair and the last pair added that outranks the best valid pair, so\n * a higher-priority candidate trickled shortly after a lower-priority one\n * succeeded can still be selected. Once both sides signalled\n * end-of-candidates and no higher-priority pair is still being checked, the\n * best valid pair is nominated at once. Defaults to 300; 0 nominates the\n * best valid pair as soon as one exists. A negative or non-finite value\n * falls back to the default.\n */\n nominationDelayMs?: number;\n /**\n * How the controlling agent nominates toward a full ICE peer when\n * renomination is not in use (see `renomination`).\n *\n * - `\"semi-aggressive\"` (default, as libwebrtc / Chrome): a check carries\n * USE-CANDIDATE while no pair is selected and for every pair that\n * outranks the selected one. The first pair whose check succeeds is\n * selected at once; checks of higher-priority pairs go on, and one that\n * succeeds later replaces the selection. Consent checks of the selected\n * pair carry USE-CANDIDATE as well.\n * - `\"regular\"`: RFC 8445 §8.1.1 regular nomination. Checks carry no\n * USE-CANDIDATE; after `nominationDelayMs` (or end-of-candidates) the\n * best valid pair is nominated once with a separate check and never\n * replaced.\n *\n * Toward an ICE-lite peer the first valid pair is nominated in either mode.\n */\n nomination?: \"semi-aggressive\" | \"regular\";\n /**\n * Renomination (draft-thatcher-ice-renomination, as libwebrtc implements\n * it). When enabled the agent advertises `a=ice-options:renomination`\n * (packages/webrtc). When the peer advertised it too, the controlling agent\n * nominates with the NOMINATION attribute (0xC001) and an increasing value\n * instead of USE-CANDIDATE: it nominates the first valid pair, keeps\n * checking higher-priority pairs and renominates a better one when its\n * check succeeds. This replaces `nomination` for that session.\n *\n * The controlled agent always honours the NOMINATION attribute: it selects\n * the pair with the largest value. Defaults to false.\n */\n renomination?: boolean;\n /**\n * STUN servers queried while gathering, in priority order. Every IPv4 UDP\n * host socket queries each of them in parallel; equal mappings are\n * advertised once, different ones (a NAT that maps per destination) each.\n *\n * Without `interfaceAddresses`, each family with a STUN server also gets a\n * UDP socket bound to the wildcard address that advertises no host\n * candidate: the OS picks its route (a full-tunnel VPN, an interface the\n * host sockets do not cover), and its server-reflexive candidates carry\n * the related address `0.0.0.0` / `::`. The IPv4 wildcard socket queries\n * every server, the IPv6 one only the IPv6 literal servers. It checks only\n * the remote candidates whose route leaves from an address no UDP host\n * socket is bound to, so a peer on a covered path learns no\n * peer-reflexive candidate from it.\n *\n * `gatherCandidates()` returns once the representative sockets answered or\n * `stunGatherTimeout` ran out: the wildcard sockets and the host socket of\n * the default-route address (every host socket when a family has neither).\n * The other host sockets' server-reflexive candidates trickle through\n * `onIceCandidate`, and `localCandidatesEnd` follows the last of them\n * (`waitForLocalCandidatesEnd()`), so an interface that cannot reach the\n * STUN server does not delay the description.\n *\n * Merged with the deprecated `stunServer`: the singular one comes first,\n * duplicates are dropped (see {@link normalizeIceServerOptions}).\n */\n stunServers?: Address[];\n /**\n * The application's names (URLs) of {@link IceOptions.stunServers}, by\n * address. Metadata only, reported in {@link IceServerRef.urls} of\n * `Connection.onIceCandidateError`; replaced together with the STUN\n * servers (see {@link mergeIceServerOptions}).\n */\n stunServerUrls?: StunServerUrl[];\n /**\n * TURN servers allocated on while gathering, in priority order. Each one\n * gets its own allocation with its own credential and transport; one that\n * fails or times out does not stop the others. Gathering ends when the\n * slowest allocation completes or fails (`turnConnectTimeout` bounds a\n * TCP/TLS connection, the STUN transaction timeout an unanswered request).\n * `turnTlsOptions`, `turnUdpFamily`, `turnConnectTimeout`, `portRange` and\n * `interfaceAddresses` apply to every TURN server.\n *\n * Merged with the deprecated `turnServer` / `turnUsername` /\n * `turnPassword` / `turnTransport`: the singular one comes first,\n * duplicates are dropped and an entry without username / password is\n * ignored (see {@link normalizeIceServerOptions}).\n */\n turnServers?: TurnServerOptions[];\n /** @deprecated Use {@link IceOptions.stunServers}. Kept as their first entry. */\n stunServer?: Address;\n /**\n * Whether the built-in public STUN server (stun.l.google.com:19302) is used\n * when no STUN server is given. Defaults to true; false gathers no\n * server-reflexive candidate unless a STUN server is set.\n */\n useDefaultStunServer?: boolean;\n /** @deprecated Use {@link IceOptions.turnServers}. Kept as their first entry. */\n turnServer?: Address;\n /** @deprecated Use {@link TurnServerOptions.username} of {@link IceOptions.turnServers}. */\n turnUsername?: string;\n /** @deprecated Use {@link TurnServerOptions.password} of {@link IceOptions.turnServers}. */\n turnPassword?: string;\n /** @deprecated Use {@link TurnServerOptions.transport} of {@link IceOptions.turnServers}. */\n turnTransport?: \"udp\" | \"tcp\" | \"tls\";\n /** Applied to every TLS TURN server. */\n turnTlsOptions?: TlsConnectionOptions;\n /**\n * Preferred IP family of a TURN/UDP socket, applied (to every TURN server)\n * only when the server is a hostname. Ignored for an IP literal server,\n * whose own family always selects the socket. Defaults to 4.\n */\n turnUdpFamily?: 4 | 6;\n forceTurn?: boolean;\n localPasswordPrefix?: string;\n useIpv4: boolean;\n useIpv6: boolean;\n useLinkLocalAddress?: boolean;\n portRange?: [number, number];\n /**\n * Local addresses to bind the UDP host sockets to, per family.\n *\n * The address given for a family (`udp4` / `udp6`) is the only host\n * address of that family: its UDP host candidate advertises the address and\n * port the socket is actually bound to, even when the address is not among\n * the enumerated network interfaces (loopback, tun, ...), and its TCP host\n * candidates use it too. Other enumerated addresses of that family are not\n * gathered. If the bind fails, the family has no UDP host candidate.\n *\n * A family left unspecified while the other one is set gathers no\n * enumerated addresses (only its `additionalHostAddresses`).\n *\n * Without any family set, every enumerated address gets its own UDP host\n * socket bound to that address (an IPv6 link-local one with its zone), so\n * the socket's packets leave from the advertised candidate address even on\n * a host with several network interfaces. An address whose bind fails, or\n * whose sends fail, loses only its own candidate; the other addresses are\n * unaffected. An `additionalHostAddresses` entry that is not assigned to a\n * local interface (a 1:1 NAT public address, for example) is gathered over\n * a wildcard socket. The enumerated addresses include costly networks (VPN\n * / tunnel interfaces: `ipsec`, `tun`, `utun`, `tap`) with a low local\n * preference; `vmnet` / `veth` interfaces are excluded. The default-route\n * address gets the highest local preference, so checks start with the path\n * the OS uses: the source address of the route to the first configured\n * STUN / TURN server that resolves in the family and has a route (UDP\n * `connect()`, no packet is sent). A family without such a server has no\n * default-route address: no other address (no public one) is probed in\n * its place, and its host candidates keep the gathering order. With a STUN\n * server, a wildcard socket per family maps the route the\n * OS picks (see `stunServers`).\n *\n * A family set to the wildcard address (`0.0.0.0` / `::`) gathers its\n * enumerated and additional addresses over wildcard sockets instead;\n * the wildcard address itself is never advertised.\n */\n interfaceAddresses?: InterfaceAddresses;\n /**\n * Host addresses gathered in addition to the enumerated ones. For a family\n * bound by `interfaceAddresses`, addresses other than the bound one are\n * ignored.\n */\n additionalHostAddresses?: string[];\n filterStunResponse?: (\n message: Message,\n addr: Address,\n protocol: Protocol,\n ) => boolean;\n filterCandidatePair?: (pair: CandidatePair) => boolean;\n /**\n * Integrity attributes of the connectivity checks and consent requests this\n * agent sends (short-term credentials, RFC 8489):\n * - `\"sha1\"` (default): MESSAGE-INTEGRITY only, what every browser accepts.\n * - `\"sha256\"`: MESSAGE-INTEGRITY-SHA256 only. A peer that does not know\n * the comprehension-required 0x001C attribute rejects such checks (420\n * or no answer), so use it only with a peer known to support it.\n * - `\"both\"`: MESSAGE-INTEGRITY followed by MESSAGE-INTEGRITY-SHA256.\n *\n * Received requests and responses are accepted with either algorithm, and\n * a response is always signed with the algorithm of its request\n * (MESSAGE-INTEGRITY-SHA256 when the request carried it, RFC 8489 §9.1.3).\n */\n messageIntegrity?: MessageIntegrityMode;\n}\n\nexport const defaultOptions: IceOptions = {\n iceLite: false,\n useTcp: false,\n useIpv4: true,\n useIpv6: true,\n};\n\nexport function validateRemoteCandidate(candidate: Candidate) {\n // \"\"\"\n // Check the remote candidate is supported.\n // \"\"\"\n if (![\"host\", \"relay\", \"srflx\"].includes(candidate.type))\n throw new Error(`Unexpected candidate type \"${candidate.type}\"`);\n\n // ipaddress.ip_address(candidate.host)\n return candidate;\n}\n\nexport function sortCandidatePairs(\n pairs: {\n localCandidate: Pick<Candidate, \"priority\">;\n remoteCandidate: Pick<Candidate, \"priority\">;\n }[],\n iceControlling: boolean,\n) {\n // Highest priority first; pairs of equal priority keep their order.\n return pairs.sort((a, b) =>\n compareCandidatePairPriority(\n b.localCandidate,\n b.remoteCandidate,\n a.localCandidate,\n a.remoteCandidate,\n iceControlling,\n ),\n );\n}\n\n/** RFC 8445 §6.1.2.3: G is the controlling agent's candidate priority, D the controlled one's. */\nfunction pairPriorityTerms(\n local: Pick<Candidate, \"priority\">,\n remote: Pick<Candidate, \"priority\">,\n iceControlling: boolean,\n) {\n const G = iceControlling ? local.priority : remote.priority;\n const D = iceControlling ? remote.priority : local.priority;\n return { min: Math.min(G, D), max: Math.max(G, D), tie: G > D ? 1 : 0 };\n}\n\n// 5.7.2. Computing Pair Priority and Ordering Pairs\n/**\n * `2^32 * MIN(G,D) + 2 * MAX(G,D) + (G > D ? 1 : 0)` (RFC 8445 §6.1.2.3).\n * The value can exceed `Number.MAX_SAFE_INTEGER`, so it is approximate;\n * order pairs with `compareCandidatePairPriority`, which is exact.\n */\nexport function candidatePairPriority(\n local: Pick<Candidate, \"priority\">,\n remote: Pick<Candidate, \"priority\">,\n iceControlling: boolean,\n) {\n const { min, max, tie } = pairPriorityTerms(local, remote, iceControlling);\n return 2 ** 32 * min + 2 * max + tie;\n}\n\n/**\n * Exact comparison of two pair priorities (RFC 8445 §6.1.2.3): negative\n * when pair `a` has the lower priority, positive when the higher, 0 when equal.\n */\nexport function compareCandidatePairPriority(\n aLocal: Pick<Candidate, \"priority\">,\n aRemote: Pick<Candidate, \"priority\">,\n bLocal: Pick<Candidate, \"priority\">,\n bRemote: Pick<Candidate, \"priority\">,\n iceControlling: boolean,\n) {\n const a = pairPriorityTerms(aLocal, aRemote, iceControlling);\n const b = pairPriorityTerms(bLocal, bRemote, iceControlling);\n return a.min - b.min || a.max - b.max || a.tie - b.tie;\n}\n\n/**\n * Query `stunServer` from `protocol` for a server-reflexive candidate.\n * Unlike {@link serverReflexiveCandidate} it rejects with the reason of a\n * failure. `base` is used for wildcard sockets that advertise no host\n * candidate themselves.\n */\nexport async function queryServerReflexiveCandidate(\n protocol: Protocol,\n stunServer: Address,\n base?: Pick<Candidate, \"host\" | \"port\" | \"transport\" | \"component\"> &\n Partial<Pick<Candidate, \"tcptype\">>,\n): Promise<Candidate> {\n const localCandidate = base ?? protocol.localCandidate;\n if (!localCandidate) {\n throw new Error(\"protocol has no local candidate\");\n }\n\n const request = new Message(methods.BINDING, classes.REQUEST);\n const [response] = await protocol.request(request, stunServer);\n const mapped = response.getAttributeValue(\"XOR-MAPPED-ADDRESS\") as\n | Address\n | undefined;\n if (!mapped) {\n throw new MissingMappedAddressError(stunServer);\n }\n\n return new Candidate(\n candidateFoundation(\"srflx\", localCandidate.transport, localCandidate.host),\n localCandidate.component,\n localCandidate.transport,\n candidatePriority(\"srflx\", {\n transport: localCandidate.transport,\n tcptype: localCandidate.tcptype,\n }),\n mapped[0],\n mapped[1],\n \"srflx\",\n localCandidate.host,\n localCandidate.port,\n localCandidate.tcptype,\n );\n}\n\n/**\n * Query a STUN server for a server-reflexive candidate. This compatibility\n * helper resolves `undefined` on failure; use\n * {@link queryServerReflexiveCandidate} when the failure reason is needed.\n */\nexport async function serverReflexiveCandidate(\n protocol: Protocol,\n stunServer: Address,\n base?: Pick<Candidate, \"host\" | \"port\" | \"transport\" | \"component\"> &\n Partial<Pick<Candidate, \"tcptype\">>,\n): Promise<Candidate | undefined> {\n return queryServerReflexiveCandidate(protocol, stunServer, base).catch(\n (error) => {\n log(\"error serverReflexiveCandidate\", error);\n return undefined;\n },\n );\n}\n\nexport function validateAddress(addr?: Address): Address | undefined {\n if (addr && Number.isNaN(addr[1])) {\n return [addr[0], 443];\n }\n return addr;\n}\n\n/** The STUN/TURN server fields of {@link IceOptions}, singular and plural. */\nexport type IceServerFields = Partial<\n Pick<\n IceOptions,\n | \"stunServer\"\n | \"stunServers\"\n | \"stunServerUrls\"\n | \"turnServer\"\n | \"turnServers\"\n | \"turnUsername\"\n | \"turnPassword\"\n | \"turnTransport\"\n >\n>;\n\n/** A STUN/TURN server address: validated (see {@link validateAddress}) or undefined. */\nfunction validServerAddress(addr: unknown): Address | undefined {\n if (!Array.isArray(addr)) return undefined;\n const validated = validateAddress(addr as unknown as Address);\n if (!validated) return undefined;\n const [host, port] = validated;\n if (typeof host !== \"string\" || host === \"\") return undefined;\n if (typeof port !== \"number\" || !Number.isFinite(port)) return undefined;\n return validated;\n}\n\nconst sameAddress = (a: Address, b: Address) => a[0] === b[0] && a[1] === b[1];\n\n/**\n * The STUN and TURN servers `options` configure, the one place the singular\n * (deprecated) and plural fields are merged:\n *\n * - order: the singular server first, then the plural list in its order;\n * - duplicates (the same STUN address; the same TURN address, transport and\n * credential) are kept once, at their first position;\n * - an invalid address (see {@link validateAddress}) is dropped, and so is a\n * TURN server without username or password (it cannot allocate);\n * - a TURN transport left unset is \"udp\";\n * - the `urls` of merged TURN duplicates are merged (in order, once each).\n *\n * The built-in default STUN server is not added here; Connection falls back\n * to it when the result has no STUN server.\n */\nexport function normalizeIceServerOptions(options: IceServerFields): {\n stunServers: Address[];\n turnServers: NormalizedTurnServer[];\n} {\n const stunServers: Address[] = [];\n for (const server of [options.stunServer, ...(options.stunServers ?? [])]) {\n if (server === undefined) continue;\n const address = validServerAddress(server);\n if (!address) {\n log(\"invalid STUN server ignored\", server);\n continue;\n }\n if (stunServers.some((existing) => sameAddress(existing, address))) {\n continue;\n }\n stunServers.push(address);\n }\n\n const turnServers: NormalizedTurnServer[] = [];\n const configured: Partial<TurnServerOptions>[] = [\n ...(options.turnServer !== undefined\n ? [\n {\n address: options.turnServer,\n username: options.turnUsername,\n password: options.turnPassword,\n transport: options.turnTransport,\n },\n ]\n : []),\n ...(options.turnServers ?? []),\n ];\n for (const server of configured) {\n const address = validServerAddress(server?.address);\n if (!address) {\n log(\"invalid TURN server ignored\", server?.address);\n continue;\n }\n const { username, password } = server;\n if (!username || !password) {\n log(\"TURN server without username / credential ignored\", address);\n continue;\n }\n const urls = Array.isArray(server.urls)\n ? server.urls.filter((url) => typeof url === \"string\")\n : undefined;\n const entry: NormalizedTurnServer = {\n address,\n username,\n password,\n transport: server.transport ?? \"udp\",\n ...(urls ? { urls: [...new Set(urls)] } : {}),\n };\n const existing = turnServers.find(\n (known) =>\n sameAddress(known.address, entry.address) &&\n known.transport === entry.transport &&\n known.username === entry.username &&\n known.password === entry.password,\n );\n if (existing) {\n // One allocation serves both: it answers to every name of them.\n if (entry.urls) {\n existing.urls = [...new Set([...(existing.urls ?? []), ...entry.urls])];\n }\n continue;\n }\n turnServers.push(entry);\n }\n return { stunServers, turnServers };\n}\n\n/**\n * `current` with an ICE server update applied (Connection.setIceServers): the\n * STUN/TURN fields, singular and plural, are replaced, an undefined one\n * included, so a STUN-only update cannot leave a previous TURN\n * host/credential behind; forceTurn and useTcp change only when given.\n */\nexport function mergeIceServerOptions<T extends Partial<IceOptions>>(\n current: T,\n update: Partial<IceOptions>,\n): T {\n return {\n ...current,\n stunServer: update.stunServer,\n stunServers: update.stunServers,\n stunServerUrls: update.stunServerUrls,\n turnServer: update.turnServer,\n turnServers: update.turnServers,\n turnUsername: update.turnUsername,\n turnPassword: update.turnPassword,\n turnTransport: update.turnTransport,\n turnTlsOptions: update.turnTlsOptions,\n turnUdpFamily: update.turnUdpFamily,\n forceTurn: update.forceTurn ?? current.forceTurn,\n useTcp: update.useTcp ?? current.useTcp,\n };\n}\n\n/**\n * Whether a generation gathered with `options` is relay-only: forceTurn (the\n * \"relay\" ICE transport policy). The policy holds whatever the TURN settings\n * are: without a usable TURN server / credential (or for an ICE-lite agent,\n * which gathers no relay candidate) the generation has no candidate at all\n * rather than falling back to host / server-reflexive ones, so the local and\n * public addresses are neither advertised nor used for checks.\n */\nexport function isRelayOnlyGathering(options: Pick<IceOptions, \"forceTurn\">) {\n return !!options.forceTurn;\n}\n\n/**\n * Whether `options` carry at least one usable TURN server with its\n * credential, the ones a gathering with them allocates relay candidates from.\n */\nexport function hasTurnServer(options: IceServerFields) {\n return normalizeIceServerOptions(options).turnServers.length > 0;\n}\n\n/**\n * Whether `candidate`, kept from an earlier generation (an ICE restart keeps\n * the sockets), may be advertised and paired in a generation gathered with\n * `options`. A fresh gathering with the same options would not have produced\n * a host / server-reflexive candidate for a relay-only policy, a TCP host\n * candidate without useTcp, nor a relay candidate without a TURN server;\n * the kept ones are held back the same way.\n */\nexport function isCandidateAllowedByGatherOptions(\n candidate: Pick<Candidate, \"type\" | \"transport\">,\n options: Pick<IceOptions, \"forceTurn\"> &\n Partial<Pick<IceOptions, \"useTcp\">> &\n IceServerFields,\n) {\n if (candidate.type === \"relay\") return hasTurnServer(options);\n if (isRelayOnlyGathering(options)) return false;\n if (candidate.transport.toLowerCase() === \"tcp\" && !options.useTcp) {\n return false;\n }\n return true;\n}\n"]}
|
package/lib/ice/src/index.d.ts
CHANGED
package/lib/ice/src/index.js
CHANGED
|
@@ -18,6 +18,7 @@ exports.randomPort = void 0;
|
|
|
18
18
|
var src_1 = require("../../common/src");
|
|
19
19
|
Object.defineProperty(exports, "randomPort", { enumerable: true, get: function () { return src_1.randomPort; } });
|
|
20
20
|
__exportStar(require("./candidate"), exports);
|
|
21
|
+
__exportStar(require("./candidateError"), exports);
|
|
21
22
|
__exportStar(require("./ice"), exports);
|
|
22
23
|
__exportStar(require("./iceBase"), exports);
|
|
23
24
|
__exportStar(require("./stun/const"), exports);
|
package/lib/ice/src/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../ice/src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,wCAA8C;AAArC,iGAAA,UAAU,OAAA;AACnB,8CAA4B;AAC5B,wCAAsB;AACtB,4CAA0B;AAC1B,+CAA6B;AAC7B,iDAA+B;AAC/B,kDAAgC;AAChC,kDAAgC;AAChC,qDAAmC;AACnC,kDAAgC;AAChC,gDAA8B;AAC9B,0CAAwB","sourcesContent":["export { randomPort } from \"../../common/src\";\nexport * from \"./candidate\";\nexport * from \"./ice\";\nexport * from \"./iceBase\";\nexport * from \"./stun/const\";\nexport * from \"./stun/message\";\nexport * from \"./stun/protocol\";\nexport * from \"./stun/tcpFrame\";\nexport * from \"./stun/tcpProtocol\";\nexport * from \"./turn/protocol\";\nexport * from \"./types/model\";\nexport * from \"./utils\";\n"]}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../ice/src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;AAAA,wCAA8C;AAArC,iGAAA,UAAU,OAAA;AACnB,8CAA4B;AAC5B,mDAAiC;AACjC,wCAAsB;AACtB,4CAA0B;AAC1B,+CAA6B;AAC7B,iDAA+B;AAC/B,kDAAgC;AAChC,kDAAgC;AAChC,qDAAmC;AACnC,kDAAgC;AAChC,gDAA8B;AAC9B,0CAAwB","sourcesContent":["export { randomPort } from \"../../common/src\";\nexport * from \"./candidate\";\nexport * from \"./candidateError\";\nexport * from \"./ice\";\nexport * from \"./iceBase\";\nexport * from \"./stun/const\";\nexport * from \"./stun/message\";\nexport * from \"./stun/protocol\";\nexport * from \"./stun/tcpFrame\";\nexport * from \"./stun/tcpProtocol\";\nexport * from \"./turn/protocol\";\nexport * from \"./types/model\";\nexport * from \"./utils\";\n"]}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { type Candidate } from "../candidate";
|
|
2
|
+
import { type MessageIntegrityMode } from "../stun/const";
|
|
3
|
+
import { Message } from "../stun/message";
|
|
4
|
+
/** STUN helpers of the connectivity checks (RFC 8445 §7.2, §7.3). */
|
|
5
|
+
/**
|
|
6
|
+
* Integrity attribute of a response to `request` (RFC 8489 §9.1.3): a request
|
|
7
|
+
* carrying MESSAGE-INTEGRITY-SHA256 is answered with MESSAGE-INTEGRITY-SHA256,
|
|
8
|
+
* any other with MESSAGE-INTEGRITY.
|
|
9
|
+
*/
|
|
10
|
+
export declare const responseIntegrityMode: (request: Message) => MessageIntegrityMode;
|
|
11
|
+
export declare const encodeTxUsername: ({ remoteUsername, localUsername, }: {
|
|
12
|
+
remoteUsername: string;
|
|
13
|
+
localUsername: string;
|
|
14
|
+
}) => string;
|
|
15
|
+
export declare const decodeTxUsername: (txUsername: string) => {
|
|
16
|
+
remoteUsername: string;
|
|
17
|
+
localUsername: string;
|
|
18
|
+
};
|
|
19
|
+
/** The peer answered with 487 (Role Conflict). */
|
|
20
|
+
export declare const isRoleConflict: (error: unknown) => boolean;
|
|
21
|
+
/**
|
|
22
|
+
* The nomination a peer's check carries: the NOMINATION value
|
|
23
|
+
* (renomination), else 1 for USE-CANDIDATE, else 0. A NOMINATION of 0 is
|
|
24
|
+
* invalid and nominates nothing (as in libwebrtc).
|
|
25
|
+
*/
|
|
26
|
+
export declare const receivedNomination: (message: Message) => number;
|
|
27
|
+
export type CheckRequestParams = {
|
|
28
|
+
/** USE-CANDIDATE (controlling only). */
|
|
29
|
+
nominate: boolean;
|
|
30
|
+
/** Renomination: the NOMINATION value to send (controlling only). */
|
|
31
|
+
nomination?: number;
|
|
32
|
+
remoteUsername: string;
|
|
33
|
+
localUsername: string;
|
|
34
|
+
iceControlling: boolean;
|
|
35
|
+
/** The local candidate of the pair: the PRIORITY of a peer-reflexive one. */
|
|
36
|
+
localCandidate?: Candidate;
|
|
37
|
+
/** ICE-CONTROLLING / ICE-CONTROLLED tie-breaker of the agent. */
|
|
38
|
+
tieBreaker: bigint;
|
|
39
|
+
};
|
|
40
|
+
/** A connectivity check (RFC 8445 §7.2.2): a Binding request of the agent. */
|
|
41
|
+
export declare const buildCheckRequest: ({ nominate, nomination, remoteUsername, localUsername, iceControlling, localCandidate, tieBreaker, }: CheckRequestParams) => Message;
|
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.buildCheckRequest = exports.receivedNomination = exports.isRoleConflict = exports.decodeTxUsername = exports.encodeTxUsername = exports.responseIntegrityMode = void 0;
|
|
4
|
+
const candidate_1 = require("../candidate");
|
|
5
|
+
const const_1 = require("../stun/const");
|
|
6
|
+
const message_1 = require("../stun/message");
|
|
7
|
+
/** STUN helpers of the connectivity checks (RFC 8445 §7.2, §7.3). */
|
|
8
|
+
/**
|
|
9
|
+
* Integrity attribute of a response to `request` (RFC 8489 §9.1.3): a request
|
|
10
|
+
* carrying MESSAGE-INTEGRITY-SHA256 is answered with MESSAGE-INTEGRITY-SHA256,
|
|
11
|
+
* any other with MESSAGE-INTEGRITY.
|
|
12
|
+
*/
|
|
13
|
+
const responseIntegrityMode = (request) => request.integrityAlgorithm === "sha256" ? "sha256" : "sha1";
|
|
14
|
+
exports.responseIntegrityMode = responseIntegrityMode;
|
|
15
|
+
const encodeTxUsername = ({ remoteUsername, localUsername, }) => {
|
|
16
|
+
return `${remoteUsername}:${localUsername}`;
|
|
17
|
+
};
|
|
18
|
+
exports.encodeTxUsername = encodeTxUsername;
|
|
19
|
+
const decodeTxUsername = (txUsername) => {
|
|
20
|
+
const [remoteUsername, localUsername] = txUsername.split(":");
|
|
21
|
+
return { remoteUsername, localUsername };
|
|
22
|
+
};
|
|
23
|
+
exports.decodeTxUsername = decodeTxUsername;
|
|
24
|
+
/** The peer answered with 487 (Role Conflict). */
|
|
25
|
+
const isRoleConflict = (error) => error?.response?.getAttributeValue("ERROR-CODE")?.[0] === 487;
|
|
26
|
+
exports.isRoleConflict = isRoleConflict;
|
|
27
|
+
/**
|
|
28
|
+
* The nomination a peer's check carries: the NOMINATION value
|
|
29
|
+
* (renomination), else 1 for USE-CANDIDATE, else 0. A NOMINATION of 0 is
|
|
30
|
+
* invalid and nominates nothing (as in libwebrtc).
|
|
31
|
+
*/
|
|
32
|
+
const receivedNomination = (message) => {
|
|
33
|
+
if (message.attributesKeys.includes("NOMINATION")) {
|
|
34
|
+
const value = message.getAttributeValue("NOMINATION");
|
|
35
|
+
return typeof value === "number" && value > 0 ? value : 0;
|
|
36
|
+
}
|
|
37
|
+
return message.attributesKeys.includes("USE-CANDIDATE") ? 1 : 0;
|
|
38
|
+
};
|
|
39
|
+
exports.receivedNomination = receivedNomination;
|
|
40
|
+
/** A connectivity check (RFC 8445 §7.2.2): a Binding request of the agent. */
|
|
41
|
+
const buildCheckRequest = ({ nominate, nomination, remoteUsername, localUsername, iceControlling, localCandidate, tieBreaker, }) => {
|
|
42
|
+
const txUsername = (0, exports.encodeTxUsername)({ remoteUsername, localUsername });
|
|
43
|
+
const request = new message_1.Message(const_1.methods.BINDING, const_1.classes.REQUEST);
|
|
44
|
+
request.setAttribute("USERNAME", txUsername).setAttribute("PRIORITY", (0, candidate_1.candidatePriority)("prflx", {
|
|
45
|
+
transport: localCandidate?.transport,
|
|
46
|
+
tcptype: localCandidate?.tcptype,
|
|
47
|
+
}));
|
|
48
|
+
if (iceControlling) {
|
|
49
|
+
request.setAttribute("ICE-CONTROLLING", tieBreaker);
|
|
50
|
+
if (nominate) {
|
|
51
|
+
request.setAttribute("USE-CANDIDATE", null);
|
|
52
|
+
}
|
|
53
|
+
if (nomination !== undefined) {
|
|
54
|
+
request.setAttribute("NOMINATION", nomination);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
else {
|
|
58
|
+
request.setAttribute("ICE-CONTROLLED", tieBreaker);
|
|
59
|
+
}
|
|
60
|
+
return request;
|
|
61
|
+
};
|
|
62
|
+
exports.buildCheckRequest = buildCheckRequest;
|
|
63
|
+
//# sourceMappingURL=checkMessages.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"checkMessages.js","sourceRoot":"","sources":["../../../../../ice/src/internal/checkMessages.ts"],"names":[],"mappings":";;;AAAA,4CAAiE;AAEjE,yCAA4E;AAC5E,6CAA0C;AAE1C,qEAAqE;AAErE;;;;GAIG;AACI,MAAM,qBAAqB,GAAG,CACnC,OAAgB,EACM,EAAE,CACxB,OAAO,CAAC,kBAAkB,KAAK,QAAQ,CAAC,CAAC,CAAC,QAAQ,CAAC,CAAC,CAAC,MAAM,CAAC;AAHjD,QAAA,qBAAqB,yBAG4B;AAEvD,MAAM,gBAAgB,GAAG,CAAC,EAC/B,cAAc,EACd,aAAa,GAId,EAAE,EAAE;IACH,OAAO,GAAG,cAAc,IAAI,aAAa,EAAE,CAAC;AAC9C,CAAC,CAAC;AARW,QAAA,gBAAgB,oBAQ3B;AAEK,MAAM,gBAAgB,GAAG,CAAC,UAAkB,EAAE,EAAE;IACrD,MAAM,CAAC,cAAc,EAAE,aAAa,CAAC,GAAG,UAAU,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;IAC9D,OAAO,EAAE,cAAc,EAAE,aAAa,EAAE,CAAC;AAC3C,CAAC,CAAC;AAHW,QAAA,gBAAgB,oBAG3B;AAEF,kDAAkD;AAC3C,MAAM,cAAc,GAAG,CAAC,KAAc,EAAE,EAAE,CAC9C,KAAsC,EAAE,QAAQ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ACpD,IAAI,QAAQ,EAAE,CAAC;YACb,OAAO,CAAC,YAAY,CAAC,eAAe,EAAE,IAAI,CAAC,CAAC;QAC9C,CAAC;QACD,IAAI,UAAU,KAAK,SAAS,EAAE,CAAC;YAC7B,OAAO,CAAC,YAAY,CAAC,YAAY,EAAE,UAAU,CAAC,CAAC;QACjD,CAAC;IACH,CAAC;SAAM,CAAC;QACN,OAAO,CAAC,YAAY,CAAC,gBAAgB,EAAE,UAAU,CAAC,CAAC;IACrD,CAAC;IACD,OAAO,OAAO,CAAC;AACjB,CAAC,CAAC;AA9BW,QAAA,iBAAiB,qBA8B5B","sourcesContent":["import { type Candidate, candidatePriority } from \"../candidate\";\nimport type { TransactionError } from \"../exceptions\";\nimport { classes, type MessageIntegrityMode, methods } from \"../stun/const\";\nimport { Message } from \"../stun/message\";\n\n/** STUN helpers of the connectivity checks (RFC 8445 §7.2, §7.3). */\n\n/**\n * Integrity attribute of a response to `request` (RFC 8489 §9.1.3): a request\n * carrying MESSAGE-INTEGRITY-SHA256 is answered with MESSAGE-INTEGRITY-SHA256,\n * any other with MESSAGE-INTEGRITY.\n */\nexport const responseIntegrityMode = (\n request: Message,\n): MessageIntegrityMode =>\n request.integrityAlgorithm === \"sha256\" ? \"sha256\" : \"sha1\";\n\nexport const encodeTxUsername = ({\n remoteUsername,\n localUsername,\n}: {\n remoteUsername: string;\n localUsername: string;\n}) => {\n return `${remoteUsername}:${localUsername}`;\n};\n\nexport const decodeTxUsername = (txUsername: string) => {\n const [remoteUsername, localUsername] = txUsername.split(\":\");\n return { remoteUsername, localUsername };\n};\n\n/** The peer answered with 487 (Role Conflict). */\nexport const isRoleConflict = (error: unknown) =>\n (error as TransactionError | undefined)?.response?.getAttributeValue(\n \"ERROR-CODE\",\n )?.[0] === 487;\n\n/**\n * The nomination a peer's check carries: the NOMINATION value\n * (renomination), else 1 for USE-CANDIDATE, else 0. A NOMINATION of 0 is\n * invalid and nominates nothing (as in libwebrtc).\n */\nexport const receivedNomination = (message: Message) => {\n if (message.attributesKeys.includes(\"NOMINATION\")) {\n const value = message.getAttributeValue(\"NOMINATION\");\n return typeof value === \"number\" && value > 0 ? value : 0;\n }\n return message.attributesKeys.includes(\"USE-CANDIDATE\") ? 1 : 0;\n};\n\nexport type CheckRequestParams = {\n /** USE-CANDIDATE (controlling only). */\n nominate: boolean;\n /** Renomination: the NOMINATION value to send (controlling only). */\n nomination?: number;\n remoteUsername: string;\n localUsername: string;\n iceControlling: boolean;\n /** The local candidate of the pair: the PRIORITY of a peer-reflexive one. */\n localCandidate?: Candidate;\n /** ICE-CONTROLLING / ICE-CONTROLLED tie-breaker of the agent. */\n tieBreaker: bigint;\n};\n\n/** A connectivity check (RFC 8445 §7.2.2): a Binding request of the agent. */\nexport const buildCheckRequest = ({\n nominate,\n nomination,\n remoteUsername,\n localUsername,\n iceControlling,\n localCandidate,\n tieBreaker,\n}: CheckRequestParams) => {\n const txUsername = encodeTxUsername({ remoteUsername, localUsername });\n const request = new Message(methods.BINDING, classes.REQUEST);\n request.setAttribute(\"USERNAME\", txUsername).setAttribute(\n \"PRIORITY\",\n candidatePriority(\"prflx\", {\n transport: localCandidate?.transport,\n tcptype: localCandidate?.tcptype,\n }),\n );\n if (iceControlling) {\n request.setAttribute(\"ICE-CONTROLLING\", tieBreaker);\n if (nominate) {\n request.setAttribute(\"USE-CANDIDATE\", null);\n }\n if (nomination !== undefined) {\n request.setAttribute(\"NOMINATION\", nomination);\n }\n } else {\n request.setAttribute(\"ICE-CONTROLLED\", tieBreaker);\n }\n return request;\n};\n"]}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The local address the OS sends from to reach `target` (the source address
|
|
3
|
+
* of its route), probed by `connect()` on a UDP socket. `undefined` without
|
|
4
|
+
* a route (package-private).
|
|
5
|
+
*/
|
|
6
|
+
export declare function getRouteSourceAddress(target: string): Promise<string | undefined>;
|
|
7
|
+
/**
|
|
8
|
+
* The local address the OS sends from to reach the first of `servers` (in
|
|
9
|
+
* priority order) that resolves in `family` and has a route; `undefined`
|
|
10
|
+
* when none does (package-private).
|
|
11
|
+
*/
|
|
12
|
+
export declare function getServerRouteAddress(family: 4 | 6, servers: string[]): Promise<string | undefined>;
|
|
13
|
+
/**
|
|
14
|
+
* The local address of each enabled family that gathering treats as its
|
|
15
|
+
* default route: the source address of the route to the configured STUN /
|
|
16
|
+
* TURN servers (`servers`, hostnames or IP literals in priority order). A
|
|
17
|
+
* family without such a server has none; no public address is probed in its
|
|
18
|
+
* place (package-private).
|
|
19
|
+
*/
|
|
20
|
+
export declare function getDefaultRouteAddresses(useIpv4: boolean, useIpv6: boolean, servers?: string[]): Promise<string[]>;
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.getRouteSourceAddress = getRouteSourceAddress;
|
|
37
|
+
exports.getServerRouteAddress = getServerRouteAddress;
|
|
38
|
+
exports.getDefaultRouteAddresses = getDefaultRouteAddresses;
|
|
39
|
+
const node_dgram_1 = require("node:dgram");
|
|
40
|
+
const dns = __importStar(require("node:dns/promises"));
|
|
41
|
+
const node_net_1 = require("node:net");
|
|
42
|
+
// The route probes `connect()` a UDP socket only to the addresses the agent
|
|
43
|
+
// talks to anyway (its STUN / TURN servers, a remote candidate): no packet is
|
|
44
|
+
// sent, and no other address (no public fallback) is probed.
|
|
45
|
+
const PROBE_TIMEOUT_MS = 1000;
|
|
46
|
+
/**
|
|
47
|
+
* The local address the OS sends from to reach `target` (the source address
|
|
48
|
+
* of its route), probed by `connect()` on a UDP socket. `undefined` without
|
|
49
|
+
* a route (package-private).
|
|
50
|
+
*/
|
|
51
|
+
function getRouteSourceAddress(target) {
|
|
52
|
+
return new Promise((resolve) => {
|
|
53
|
+
const socket = (0, node_dgram_1.createSocket)((0, node_net_1.isIPv6)(target) ? "udp6" : "udp4");
|
|
54
|
+
let settled = false;
|
|
55
|
+
const finish = (address) => {
|
|
56
|
+
if (settled)
|
|
57
|
+
return;
|
|
58
|
+
settled = true;
|
|
59
|
+
clearTimeout(timer);
|
|
60
|
+
try {
|
|
61
|
+
socket.close();
|
|
62
|
+
}
|
|
63
|
+
catch {
|
|
64
|
+
// already closed
|
|
65
|
+
}
|
|
66
|
+
resolve(address);
|
|
67
|
+
};
|
|
68
|
+
const timer = setTimeout(() => finish(), PROBE_TIMEOUT_MS);
|
|
69
|
+
socket.on("error", () => finish());
|
|
70
|
+
try {
|
|
71
|
+
socket.connect(9, target, () => {
|
|
72
|
+
try {
|
|
73
|
+
const address = socket.address().address.split("%")[0];
|
|
74
|
+
// Some kernels "connect" without a route and keep the wildcard.
|
|
75
|
+
finish(address === "0.0.0.0" || address === "::" ? undefined : address);
|
|
76
|
+
}
|
|
77
|
+
catch {
|
|
78
|
+
finish();
|
|
79
|
+
}
|
|
80
|
+
});
|
|
81
|
+
}
|
|
82
|
+
catch {
|
|
83
|
+
finish();
|
|
84
|
+
}
|
|
85
|
+
});
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* `host` as an address of `family`: an IP literal of that family as is, a
|
|
89
|
+
* hostname resolved within the probe timeout. `undefined` otherwise.
|
|
90
|
+
*/
|
|
91
|
+
async function resolveProbeTarget(host, family) {
|
|
92
|
+
const literal = (0, node_net_1.isIP)(host);
|
|
93
|
+
if (literal)
|
|
94
|
+
return literal === family ? host : undefined;
|
|
95
|
+
let timer;
|
|
96
|
+
const address = await Promise.race([
|
|
97
|
+
dns
|
|
98
|
+
.lookup(host, { family })
|
|
99
|
+
.then(({ address }) => address)
|
|
100
|
+
.catch(() => undefined),
|
|
101
|
+
new Promise((resolve) => {
|
|
102
|
+
timer = setTimeout(() => resolve(undefined), PROBE_TIMEOUT_MS);
|
|
103
|
+
}),
|
|
104
|
+
]);
|
|
105
|
+
clearTimeout(timer);
|
|
106
|
+
return address;
|
|
107
|
+
}
|
|
108
|
+
/**
|
|
109
|
+
* The local address the OS sends from to reach the first of `servers` (in
|
|
110
|
+
* priority order) that resolves in `family` and has a route; `undefined`
|
|
111
|
+
* when none does (package-private).
|
|
112
|
+
*/
|
|
113
|
+
async function getServerRouteAddress(family, servers) {
|
|
114
|
+
const targets = await Promise.all([...new Set(servers)].map((host) => resolveProbeTarget(host, family)));
|
|
115
|
+
const sources = await Promise.all(targets.map((target) => target === undefined ? undefined : getRouteSourceAddress(target)));
|
|
116
|
+
return sources.find((source) => source !== undefined);
|
|
117
|
+
}
|
|
118
|
+
/**
|
|
119
|
+
* The local address of each enabled family that gathering treats as its
|
|
120
|
+
* default route: the source address of the route to the configured STUN /
|
|
121
|
+
* TURN servers (`servers`, hostnames or IP literals in priority order). A
|
|
122
|
+
* family without such a server has none; no public address is probed in its
|
|
123
|
+
* place (package-private).
|
|
124
|
+
*/
|
|
125
|
+
async function getDefaultRouteAddresses(useIpv4, useIpv6, servers = []) {
|
|
126
|
+
if (servers.length === 0)
|
|
127
|
+
return [];
|
|
128
|
+
const [v4, v6] = await Promise.all([
|
|
129
|
+
useIpv4 ? getServerRouteAddress(4, servers) : undefined,
|
|
130
|
+
useIpv6 ? getServerRouteAddress(6, servers) : undefined,
|
|
131
|
+
]);
|
|
132
|
+
return [v4, v6].filter((address) => !!address);
|
|
133
|
+
}
|
|
134
|
+
//# sourceMappingURL=defaultRoute.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"defaultRoute.js","sourceRoot":"","sources":["../../../../../ice/src/internal/defaultRoute.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAeA,sDAmCC;AA+BD,sDAaC;AASD,4DAWC;AAlHD,2CAA0C;AAC1C,uDAAyC;AACzC,uCAAwC;AAExC,4EAA4E;AAC5E,8EAA8E;AAC9E,6DAA6D;AAE7D,MAAM,gBAAgB,GAAG,IAAI,CAAC;AAE9B;;;;GAIG;AACH,SAAgB,qBAAqB,CACnC,MAAc;IAEd,OAAO,IAAI,OAAO,CAAC,CAAC,OAAO,EAAE,EAAE;QAC7B,MAAM,MAAM,GAAG,IAAA,yBAAY,EAAC,IAAA,iBAAM,EAAC,MAAM,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC;QAC9D,IAAI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AChB,UAAoB,EAAE;IAEtB,IAAI,OAAO,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,EAAE,CAAC;IACpC,MAAM,CAAC,EAAE,EAAE,EAAE,CAAC,GAAG,MAAM,OAAO,CAAC,GAAG,CAAC;QACjC,OAAO,CAAC,CAAC,CAAC,qBAAqB,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,SAAS;QACvD,OAAO,CAAC,CAAC,CAAC,qBAAqB,CAAC,CAAC,EAAE,OAAO,CAAC,CAAC,CAAC,CAAC,SAAS;KACxD,CAAC,CAAC;IACH,OAAO,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC,MAAM,CAAC,CAAC,OAAO,EAAqB,EAAE,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC;AACpE,CAAC","sourcesContent":["import { createSocket } from \"node:dgram\";\nimport * as dns from \"node:dns/promises\";\nimport { isIP, isIPv6 } from \"node:net\";\n\n// The route probes `connect()` a UDP socket only to the addresses the agent\n// talks to anyway (its STUN / TURN servers, a remote candidate): no packet is\n// sent, and no other address (no public fallback) is probed.\n\nconst PROBE_TIMEOUT_MS = 1000;\n\n/**\n * The local address the OS sends from to reach `target` (the source address\n * of its route), probed by `connect()` on a UDP socket. `undefined` without\n * a route (package-private).\n */\nexport function getRouteSourceAddress(\n target: string,\n): Promise<string | undefined> {\n return new Promise((resolve) => {\n const socket = createSocket(isIPv6(target) ? \"udp6\" : \"udp4\");\n let settled = false;\n const finish = (address?: string) => {\n if (settled) return;\n settled = true;\n clearTimeout(timer);\n try {\n socket.close();\n } catch {\n // already closed\n }\n resolve(address);\n };\n const timer = setTimeout(() => finish(), PROBE_TIMEOUT_MS);\n socket.on(\"error\", () => finish());\n try {\n socket.connect(9, target, () => {\n try {\n const address = socket.address().address.split(\"%\")[0];\n // Some kernels \"connect\" without a route and keep the wildcard.\n finish(\n address === \"0.0.0.0\" || address === \"::\" ? undefined : address,\n );\n } catch {\n finish();\n }\n });\n } catch {\n finish();\n }\n });\n}\n\n/**\n * `host` as an address of `family`: an IP literal of that family as is, a\n * hostname resolved within the probe timeout. `undefined` otherwise.\n */\nasync function resolveProbeTarget(\n host: string,\n family: 4 | 6,\n): Promise<string | undefined> {\n const literal = isIP(host);\n if (literal) return literal === family ? host : undefined;\n let timer: ReturnType<typeof setTimeout> | undefined;\n const address = await Promise.race([\n dns\n .lookup(host, { family })\n .then(({ address }) => address)\n .catch(() => undefined),\n new Promise<undefined>((resolve) => {\n timer = setTimeout(() => resolve(undefined), PROBE_TIMEOUT_MS);\n }),\n ]);\n clearTimeout(timer);\n return address;\n}\n\n/**\n * The local address the OS sends from to reach the first of `servers` (in\n * priority order) that resolves in `family` and has a route; `undefined`\n * when none does (package-private).\n */\nexport async function getServerRouteAddress(\n family: 4 | 6,\n servers: string[],\n): Promise<string | undefined> {\n const targets = await Promise.all(\n [...new Set(servers)].map((host) => resolveProbeTarget(host, family)),\n );\n const sources = await Promise.all(\n targets.map((target) =>\n target === undefined ? undefined : getRouteSourceAddress(target),\n ),\n );\n return sources.find((source) => source !== undefined);\n}\n\n/**\n * The local address of each enabled family that gathering treats as its\n * default route: the source address of the route to the configured STUN /\n * TURN servers (`servers`, hostnames or IP literals in priority order). A\n * family without such a server has none; no public address is probed in its\n * place (package-private).\n */\nexport async function getDefaultRouteAddresses(\n useIpv4: boolean,\n useIpv6: boolean,\n servers: string[] = [],\n): Promise<string[]> {\n if (servers.length === 0) return [];\n const [v4, v6] = await Promise.all([\n useIpv4 ? getServerRouteAddress(4, servers) : undefined,\n useIpv6 ? getServerRouteAddress(6, servers) : undefined,\n ]);\n return [v4, v6].filter((address): address is string => !!address);\n}\n"]}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { type HostInterfaceAddress } from "./selectAddresses";
|
|
2
|
+
/**
|
|
3
|
+
* `getHostAddresses()` と同じ順序で、各アドレスの bind 用アドレス付きの
|
|
4
|
+
* 列挙結果を返す(package-private)。
|
|
5
|
+
*/
|
|
6
|
+
export declare function getHostInterfaceAddresses(useIpv4: boolean, useIpv6: boolean, options?: {
|
|
7
|
+
useLinkLocalAddress?: boolean;
|
|
8
|
+
}): HostInterfaceAddress[];
|
|
9
|
+
/**
|
|
10
|
+
* 候補列挙の除外条件(loopback / tun などの NIC、link-local の除外)を適用せず、
|
|
11
|
+
* ローカル NIC に割り当てられた全アドレスを返す(package-private)。
|
|
12
|
+
* `additionalHostAddresses` がローカル割り当てかどうかの判定に使う。
|
|
13
|
+
*/
|
|
14
|
+
export declare function getAssignedInterfaceAddresses(): {
|
|
15
|
+
address: string;
|
|
16
|
+
bindAddress: string;
|
|
17
|
+
}[];
|
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
36
|
+
exports.getHostInterfaceAddresses = getHostInterfaceAddresses;
|
|
37
|
+
exports.getAssignedInterfaceAddresses = getAssignedInterfaceAddresses;
|
|
38
|
+
const os = __importStar(require("node:os"));
|
|
39
|
+
const common_1 = require("../imports/common");
|
|
40
|
+
const utils_1 = require("../utils");
|
|
41
|
+
const selectAddresses_1 = require("./selectAddresses");
|
|
42
|
+
/**
|
|
43
|
+
* `getHostAddresses()` と同じ順序で、各アドレスの bind 用アドレス付きの
|
|
44
|
+
* 列挙結果を返す(package-private)。
|
|
45
|
+
*/
|
|
46
|
+
function getHostInterfaceAddresses(useIpv4, useIpv6, options = {}) {
|
|
47
|
+
const interfaces = os.networkInterfaces();
|
|
48
|
+
const addresses = [];
|
|
49
|
+
if (useIpv4) {
|
|
50
|
+
addresses.push(...(0, selectAddresses_1.selectHostInterfaces)(interfaces, 4, options, utils_1.isLinkLocalAddress));
|
|
51
|
+
}
|
|
52
|
+
if (useIpv6) {
|
|
53
|
+
addresses.push(...(0, selectAddresses_1.selectHostInterfaces)(interfaces, 6, options, utils_1.isLinkLocalAddress));
|
|
54
|
+
}
|
|
55
|
+
return addresses;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* 候補列挙の除外条件(loopback / tun などの NIC、link-local の除外)を適用せず、
|
|
59
|
+
* ローカル NIC に割り当てられた全アドレスを返す(package-private)。
|
|
60
|
+
* `additionalHostAddresses` がローカル割り当てかどうかの判定に使う。
|
|
61
|
+
*/
|
|
62
|
+
function getAssignedInterfaceAddresses() {
|
|
63
|
+
const result = [];
|
|
64
|
+
for (const [nic, infos] of Object.entries(os.networkInterfaces())) {
|
|
65
|
+
for (const info of infos ?? []) {
|
|
66
|
+
const isV6 = (0, common_1.normalizeFamilyNodeV18)(info.family) === 6;
|
|
67
|
+
result.push({
|
|
68
|
+
address: info.address,
|
|
69
|
+
bindAddress: isV6 && (0, utils_1.isLinkLocalAddress)(info)
|
|
70
|
+
? `${info.address}%${nic}`
|
|
71
|
+
: info.address,
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
return result;
|
|
76
|
+
}
|
|
77
|
+
//# sourceMappingURL=hostInterfaces.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"hostInterfaces.js","sourceRoot":"","sources":["../../../../../ice/src/internal/hostInterfaces.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAaA,8DAoBC;AAOD,sEAkBC;AA1DD,4CAA8B;AAE9B,8CAA2D;AAC3D,oCAA8C;AAC9C,uDAG2B;AAE3B;;;GAGG;AACH,SAAgB,yBAAyB,CACvC,OAAgB,EAChB,OAAgB,EAChB,UAEI,EAAE;IAEN,MAAM,UAAU,GAAG,EAAE,CAAC,iBAAiB,EAAE,CAAC;IAC1C,MAAM,SAAS,GAA2B,EAAE,CAAC;IAC7C,IAAI,OAAO,EAAE,CAAC;QACZ,SAAS,CAAC,IAAI,CACZ,GAAG,IAAA,sCAAoB,EAAC,UAAU,EAAE,CAAC,EAAE,OAAO,EAAE,0BAAkB,CAAC,CACpE,CAAC;IACJ,CAAC;IACD,IAAI,OAAO,EAAE,CAAC;QACZ,SAAS,CAAC,IAAI,CACZ,GAAG,IAAA,sCAAoB,EAAC,UAAU,EAAE,CAAC,EAAE,OAAO,EAAE,0BAAkB,CAAC,CACpE,CAAC;IACJ,CAAC;IACD,OAAO,SAAS,CAAC;AACnB,CAAC;AAED;;;;GAIG;AACH,SAAgB,6BAA6B;IAI3C,MAAM,MAAM,GAA+C,EAAE,CAAC;IAC9D,KAAK,MAAM,CAAC,GAAG,EAAE,KAAK,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,EAAE,CAAC,iBAAiB,EAAE,CAAC,EAAE,CAAC;QAClE,KAAK,MAAM,IAAI,IAAI,KAAK,IAAI,EAAE,EAAE,CAAC;YAC/B,MAAM,IAAI,GAAG,IAAA,+BAAsB,EAAC,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;YACvD,MAAM,CAAC,IAAI,CAAC;gBACV,OAAO,EAAE,IAAI,CAAC,OAAO;gBACrB,WAAW,EACT,IAAI,IAAI,IAAA,0BAAkB,EAAC,IAAI,CAAC;oBAC9B,CAAC,CAAC,GAAG,IAAI,CAAC,OAAO,IAAI,GAAG,EAAE;oBAC1B,CAAC,CAAC,IAAI,CAAC,OAAO;aACnB,CAAC,CAAC;QACL,CAAC;IACH,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC","sourcesContent":["import * as os from \"node:os\";\n\nimport { normalizeFamilyNodeV18 } from \"../imports/common\";\nimport { isLinkLocalAddress } from \"../utils\";\nimport {\n type HostInterfaceAddress,\n selectHostInterfaces,\n} from \"./selectAddresses\";\n\n/**\n * `getHostAddresses()` と同じ順序で、各アドレスの bind 用アドレス付きの\n * 列挙結果を返す(package-private)。\n */\nexport function getHostInterfaceAddresses(\n useIpv4: boolean,\n useIpv6: boolean,\n options: {\n useLinkLocalAddress?: boolean;\n } = {},\n): HostInterfaceAddress[] {\n const interfaces = os.networkInterfaces();\n const addresses: HostInterfaceAddress[] = [];\n if (useIpv4) {\n addresses.push(\n ...selectHostInterfaces(interfaces, 4, options, isLinkLocalAddress),\n );\n }\n if (useIpv6) {\n addresses.push(\n ...selectHostInterfaces(interfaces, 6, options, isLinkLocalAddress),\n );\n }\n return addresses;\n}\n\n/**\n * 候補列挙の除外条件(loopback / tun などの NIC、link-local の除外)を適用せず、\n * ローカル NIC に割り当てられた全アドレスを返す(package-private)。\n * `additionalHostAddresses` がローカル割り当てかどうかの判定に使う。\n */\nexport function getAssignedInterfaceAddresses(): {\n address: string;\n bindAddress: string;\n}[] {\n const result: { address: string; bindAddress: string }[] = [];\n for (const [nic, infos] of Object.entries(os.networkInterfaces())) {\n for (const info of infos ?? []) {\n const isV6 = normalizeFamilyNodeV18(info.family) === 6;\n result.push({\n address: info.address,\n bindAddress:\n isV6 && isLinkLocalAddress(info)\n ? `${info.address}%${nic}`\n : info.address,\n });\n }\n }\n return result;\n}\n"]}
|