werift 0.15.0-alpha.1 → 0.15.2

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.
Files changed (59) hide show
  1. package/lib/common/src/index.d.ts +1 -0
  2. package/lib/common/src/index.js +1 -0
  3. package/lib/common/src/index.js.map +1 -1
  4. package/lib/common/src/network.d.ts +5 -0
  5. package/lib/common/src/network.js +41 -0
  6. package/lib/common/src/network.js.map +1 -0
  7. package/lib/dtls/src/context/cipher.js +1 -4
  8. package/lib/dtls/src/context/cipher.js.map +1 -1
  9. package/lib/ice/src/exceptions.d.ts +4 -1
  10. package/lib/ice/src/exceptions.js +5 -3
  11. package/lib/ice/src/exceptions.js.map +1 -1
  12. package/lib/ice/src/ice.d.ts +1 -1
  13. package/lib/ice/src/ice.js +74 -28
  14. package/lib/ice/src/ice.js.map +1 -1
  15. package/lib/ice/src/stun/attributes.d.ts +16 -3
  16. package/lib/ice/src/stun/attributes.js +33 -1
  17. package/lib/ice/src/stun/attributes.js.map +1 -1
  18. package/lib/ice/src/stun/const.d.ts +1 -1
  19. package/lib/ice/src/stun/const.js +5 -2
  20. package/lib/ice/src/stun/const.js.map +1 -1
  21. package/lib/ice/src/stun/message.d.ts +6 -10
  22. package/lib/ice/src/stun/message.js +23 -17
  23. package/lib/ice/src/stun/message.js.map +1 -1
  24. package/lib/ice/src/stun/protocol.js +0 -1
  25. package/lib/ice/src/stun/protocol.js.map +1 -1
  26. package/lib/ice/src/stun/transaction.d.ts +0 -2
  27. package/lib/ice/src/stun/transaction.js +1 -1
  28. package/lib/ice/src/stun/transaction.js.map +1 -1
  29. package/lib/ice/src/transport.js +2 -2
  30. package/lib/ice/src/transport.js.map +1 -1
  31. package/lib/ice/src/turn/protocol.d.ts +8 -6
  32. package/lib/ice/src/turn/protocol.js +73 -71
  33. package/lib/ice/src/turn/protocol.js.map +1 -1
  34. package/lib/ice/src/utils.d.ts +0 -5
  35. package/lib/ice/src/utils.js +1 -38
  36. package/lib/ice/src/utils.js.map +1 -1
  37. package/lib/rtp/src/processor/webm.js +1 -2
  38. package/lib/rtp/src/processor/webm.js.map +1 -1
  39. package/lib/webrtc/src/dataChannel.js +3 -2
  40. package/lib/webrtc/src/dataChannel.js.map +1 -1
  41. package/lib/webrtc/src/media/parameters.d.ts +4 -0
  42. package/lib/webrtc/src/media/parameters.js.map +1 -1
  43. package/lib/webrtc/src/media/rtpTransceiver.d.ts +1 -1
  44. package/lib/webrtc/src/media/rtpTransceiver.js +3 -1
  45. package/lib/webrtc/src/media/rtpTransceiver.js.map +1 -1
  46. package/lib/webrtc/src/nonstandard/userMedia.js +1 -1
  47. package/lib/webrtc/src/nonstandard/userMedia.js.map +1 -1
  48. package/lib/webrtc/src/peerConnection.d.ts +5 -1
  49. package/lib/webrtc/src/peerConnection.js +37 -25
  50. package/lib/webrtc/src/peerConnection.js.map +1 -1
  51. package/lib/webrtc/src/transport/dtls.js +2 -6
  52. package/lib/webrtc/src/transport/dtls.js.map +1 -1
  53. package/package.json +1 -1
  54. package/src/dataChannel.ts +4 -2
  55. package/src/media/parameters.ts +4 -0
  56. package/src/media/rtpTransceiver.ts +5 -1
  57. package/src/nonstandard/userMedia.ts +1 -1
  58. package/src/peerConnection.ts +108 -85
  59. package/src/transport/dtls.ts +2 -6
@@ -1,3 +1,4 @@
1
1
  export * from "./binary";
2
2
  export * from "./number";
3
3
  export * from "./promise";
4
+ export * from "./network";
@@ -13,4 +13,5 @@ Object.defineProperty(exports, "__esModule", { value: true });
13
13
  __exportStar(require("./binary"), exports);
14
14
  __exportStar(require("./number"), exports);
15
15
  __exportStar(require("./promise"), exports);
16
+ __exportStar(require("./network"), exports);
16
17
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../common/src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,2CAAyB;AACzB,2CAAyB;AACzB,4CAA0B","sourcesContent":["export * from \"./binary\";\nexport * from \"./number\";\nexport * from \"./promise\";\n"]}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../../../common/src/index.ts"],"names":[],"mappings":";;;;;;;;;;;;AAAA,2CAAyB;AACzB,2CAAyB;AACzB,4CAA0B;AAC1B,4CAA0B","sourcesContent":["export * from \"./binary\";\nexport * from \"./number\";\nexport * from \"./promise\";\nexport * from \"./network\";\n"]}
@@ -0,0 +1,5 @@
1
+ /// <reference types="node" />
2
+ import { SocketType } from "dgram";
3
+ export declare function randomPort(protocol?: SocketType): Promise<number>;
4
+ export declare function randomPorts(num: number, protocol?: SocketType): Promise<number[]>;
5
+ export declare function findPort(min: number, max: number, protocol?: SocketType): Promise<number>;
@@ -0,0 +1,41 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.findPort = exports.randomPorts = exports.randomPort = void 0;
4
+ const dgram_1 = require("dgram");
5
+ async function randomPort(protocol = "udp4") {
6
+ const socket = (0, dgram_1.createSocket)(protocol);
7
+ setImmediate(() => socket.bind(0));
8
+ await new Promise((r) => {
9
+ socket.once("error", r);
10
+ socket.once("listening", r);
11
+ });
12
+ const port = socket.address()?.port;
13
+ await new Promise((r) => socket.close(() => r()));
14
+ return port;
15
+ }
16
+ exports.randomPort = randomPort;
17
+ async function randomPorts(num, protocol = "udp4") {
18
+ return Promise.all([...Array(num)].map(() => randomPort(protocol)));
19
+ }
20
+ exports.randomPorts = randomPorts;
21
+ async function findPort(min, max, protocol = "udp4") {
22
+ let port;
23
+ for (let i = min; i <= max; i++) {
24
+ const socket = (0, dgram_1.createSocket)(protocol);
25
+ setImmediate(() => socket.bind(i));
26
+ await new Promise((r) => {
27
+ socket.once("error", r);
28
+ socket.once("listening", r);
29
+ });
30
+ port = socket.address()?.port;
31
+ await new Promise((r) => socket.close(() => r()));
32
+ if (min <= port && port <= max) {
33
+ break;
34
+ }
35
+ }
36
+ if (!port)
37
+ throw new Error("port not found");
38
+ return port;
39
+ }
40
+ exports.findPort = findPort;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,QAAQ,CAAC,CAAC;QAEtC,YAAY,CAAC,GAAG,EAAE,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,CAAC;QAEnC,MAAM,IAAI,OAAO,CAAO,CAAC,CAAC,EAAE,EAAE;YAC5B,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC;YACxB,MAAM,CAAC,IAAI,CAAC,WAAW,EAAE,CAAC,CAAC,CAAC;QAC9B,CAAC,CAAC,CAAC;QAEH,IAAI,GAAG,MAAM,CAAC,OAAO,EAAE,EAAE,IAAI,CAAC;QAC9B,MAAM,IAAI,OAAO,CAAO,CAAC,CAAC,EAAE,EAAE,CAAC,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,CAAC,EAAE,CAAC,CAAC,CAAC;QACxD,IAAI,GAAG,IAAI,IAAI,IAAI,IAAI,IAAI,GAAG,EAAE;YAC9B,MAAM;SACP;KACF;IAED,IAAI,CAAC,IAAI;QAAE,MAAM,IAAI,KAAK,CAAC,gBAAgB,CAAC,CAAC;IAE7C,OAAO,IAAI,CAAC;AACd,CAAC;AA3BD,4BA2BC","sourcesContent":["import { createSocket, SocketType } from \"dgram\";\n\nexport async function randomPort(protocol: SocketType = \"udp4\") {\n const socket = createSocket(protocol);\n\n setImmediate(() => socket.bind(0));\n\n await new Promise<void>((r) => {\n socket.once(\"error\", r);\n socket.once(\"listening\", r);\n });\n\n const port = socket.address()?.port;\n await new Promise<void>((r) => socket.close(() => r()));\n return port;\n}\n\nexport async function randomPorts(num: number, protocol: SocketType = \"udp4\") {\n return Promise.all([...Array(num)].map(() => randomPort(protocol)));\n}\n\nexport async function findPort(\n min: number,\n max: number,\n protocol: SocketType = \"udp4\"\n) {\n let port: number | undefined;\n\n for (let i = min; i <= max; i++) {\n const socket = createSocket(protocol);\n\n setImmediate(() => socket.bind(i));\n\n await new Promise<void>((r) => {\n socket.once(\"error\", r);\n socket.once(\"listening\", r);\n });\n\n port = socket.address()?.port;\n await new Promise<void>((r) => socket.close(() => r()));\n if (min <= port && port <= max) {\n break;\n }\n }\n\n if (!port) throw new Error(\"port not found\");\n\n return port;\n}\n"]}
@@ -159,10 +159,7 @@ CipherContext.createSelfSignedCertificateWithKey = async (signatureHash, namedCu
159
159
  };
160
160
  }
161
161
  })();
162
- const keys = (await crypto.subtle.generateKey(alg, true, [
163
- "sign",
164
- "verify",
165
- ]));
162
+ const keys = await crypto.subtle.generateKey(alg, true, ["sign", "verify"]);
166
163
  const cert = await x509.X509CertificateGenerator.createSelfSigned({
167
164
  serialNumber: "01",
168
165
  name: "C=AU, ST=Some-State, O=Internet Widgits Pty Ltd",
@@ -1 +1 @@
1
- {"version":3,"file":"cipher.js","sourceRoot":"","sources":["../../../../../dtls/src/context/cipher.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,qCAAqD;AACrD,mDAA6C;AAC7C,qDAAuC;AACvC,6CAAoD;AACpD,mCAAoC;AACpC,iEAAyC;AAEzC,2CAQyB;AAEzB,uCAAyE;AACzE,wDAAsE;AAEtE,gDAAsD;AAItD,MAAM,MAAM,GAAG,IAAI,kBAAM,EAAE,CAAC;AAC5B,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,MAAa,CAAC,CAAC;AAEvC,MAAa,aAAa;IAcxB,YACS,WAAyB,EACzB,OAAgB,EAChB,MAAe,EACtB,sBAAsC;QAH/B,gBAAW,GAAX,WAAW,CAAc;QACzB,YAAO,GAAP,OAAO,CAAS;QAChB,WAAM,GAAN,MAAM,CAAS;QAGtB,IAAI,OAAO,IAAI,MAAM,IAAI,sBAAsB,EAAE;YAC/C,IAAI,CAAC,SAAS,CAAC,OAAO,EAAE,MAAM,EAAE,sBAAsB,CAAC,CAAC;SACzD;IACH,CAAC;IA8ED,aAAa,CAAC,GAAkB;QAC9B,MAAM,MAAM,GAAG,GAAG,CAAC,iBAAiB,CAAC;QACrC,MAAM,GAAG,GAAG,IAAI,CAAC,MAAM,CAAC,OA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,EAAE,CAAC;QAClC,gBAAgB,EAAE,GAAG;QACrB,IAAI;KACL,CAAC,CAAC;IAEH,MAAM,OAAO,GAAG,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;IACrC,MAAM,MAAM,GAAG,IAAI,CAAC,YAAY,CAAC,MAAM,CACrC,MAAM,MAAM,CAAC,MAAM,CAAC,SAAS,CAAC,OAAO,EAAE,IAAI,CAAC,UAAiB,CAAC,EAC9D,aAAa,CACd,CAAC;IAEF,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,CAAC;AAC5C,CAAE,CAAA","sourcesContent":["import { Certificate, PrivateKey } from \"@fidm/x509\";\nimport { Crypto } from \"@peculiar/webcrypto\";\nimport * as x509 from \"@peculiar/x509\";\nimport { decode, encode, types } from \"binary-data\";\nimport { createSign } from \"crypto\";\nimport addYears from \"date-fns/addYears\";\n\nimport {\n CipherSuites,\n CurveType,\n HashAlgorithm,\n NamedCurveAlgorithm,\n NamedCurveAlgorithms,\n SignatureAlgorithm,\n SignatureHash,\n} from \"../cipher/const\";\nimport { NamedCurveKeyPair } from \"../cipher/namedCurve\";\nimport { prfVerifyDataClient, prfVerifyDataServer } from \"../cipher/prf\";\nimport { SessionType, SessionTypes } from \"../cipher/suites/abstract\";\nimport AEADCipher from \"../cipher/suites/aead\";\nimport { ProtocolVersion } from \"../handshake/binary\";\nimport { DtlsRandom } from \"../handshake/random\";\nimport { DtlsPlaintext } from \"../record/message/plaintext\";\n\nconst crypto = new Crypto();\nx509.cryptoProvider.set(crypto as any);\n\nexport class CipherContext {\n localRandom!: DtlsRandom;\n remoteRandom!: DtlsRandom;\n cipherSuite!: CipherSuites;\n remoteCertificate?: Buffer;\n remoteKeyPair!: Partial<NamedCurveKeyPair>;\n localKeyPair!: NamedCurveKeyPair;\n masterSecret!: Buffer;\n cipher!: AEADCipher;\n namedCurve!: NamedCurveAlgorithms;\n signatureHashAlgorithm?: SignatureHash;\n localCert!: Buffer;\n localPrivateKey!: PrivateKey;\n\n constructor(\n public sessionType: SessionTypes,\n public certPem?: string,\n public keyPem?: string,\n signatureHashAlgorithm?: SignatureHash\n ) {\n if (certPem && keyPem && signatureHashAlgorithm) {\n this.parseX509(certPem, keyPem, signatureHashAlgorithm);\n }\n }\n\n /**\n *\n * @param signatureHash\n * @param namedCurveAlgorithm necessary when use ecdsa\n */\n static createSelfSignedCertificateWithKey = async (\n signatureHash: SignatureHash,\n namedCurveAlgorithm?: NamedCurveAlgorithms\n ) => {\n const signatureAlgorithmName = (() => {\n switch (signatureHash.signature) {\n case SignatureAlgorithm.rsa_1:\n return \"RSASSA-PKCS1-v1_5\";\n case SignatureAlgorithm.ecdsa_3:\n return \"ECDSA\";\n }\n })();\n const hash = (() => {\n switch (signatureHash.hash) {\n case HashAlgorithm.sha256_4:\n return \"SHA-256\";\n }\n })();\n const namedCurve = (() => {\n switch (namedCurveAlgorithm) {\n case NamedCurveAlgorithm.secp256r1_23:\n return \"P-256\";\n case NamedCurveAlgorithm.x25519_29:\n // todo fix (X25519 not supported with ECDSA)\n if (signatureAlgorithmName === \"ECDSA\") {\n return \"P-256\";\n }\n return \"X25519\";\n default: {\n if (signatureAlgorithmName === \"ECDSA\") return \"P-256\";\n if (signatureAlgorithmName === \"RSASSA-PKCS1-v1_5\") return \"X25519\";\n }\n }\n })();\n const alg = (() => {\n switch (signatureAlgorithmName) {\n case \"ECDSA\":\n return { name: signatureAlgorithmName, hash, namedCurve };\n case \"RSASSA-PKCS1-v1_5\":\n return {\n name: signatureAlgorithmName,\n hash,\n publicExponent: new Uint8Array([1, 0, 1]),\n modulusLength: 2048,\n };\n }\n })();\n\n const keys = (await crypto.subtle.generateKey(alg, true, [\n \"sign\",\n \"verify\",\n ])) as any;\n\n const cert = await x509.X509CertificateGenerator.createSelfSigned({\n serialNumber: \"01\",\n name: \"C=AU, ST=Some-State, O=Internet Widgits Pty Ltd\",\n notBefore: new Date(),\n notAfter: addYears(Date.now(), 10),\n signingAlgorithm: alg,\n keys,\n });\n\n const certPem = cert.toString(\"pem\");\n const keyPem = x509.PemConverter.encode(\n await crypto.subtle.exportKey(\"pkcs8\", keys.privateKey as any),\n \"private key\"\n );\n\n return { certPem, keyPem, signatureHash };\n };\n\n encryptPacket(pkt: DtlsPlaintext) {\n const header = pkt.recordLayerHeader;\n const enc = this.cipher.encrypt(this.sessionType, pkt.fragment, {\n type: header.contentType,\n version: decode(\n Buffer.from(encode(header.protocolVersion, ProtocolVersion).slice()),\n { version: types.uint16be }\n ).version,\n epoch: header.epoch,\n sequenceNumber: header.sequenceNumber,\n });\n pkt.fragment = enc;\n pkt.recordLayerHeader.contentLen = enc.length;\n return pkt;\n }\n\n decryptPacket(pkt: DtlsPlaintext) {\n const header = pkt.recordLayerHeader;\n const dec = this.cipher.decrypt(this.sessionType, pkt.fragment, {\n type: header.contentType,\n version: decode(\n Buffer.from(encode(header.protocolVersion, ProtocolVersion).slice()),\n { version: types.uint16be }\n ).version,\n epoch: header.epoch,\n sequenceNumber: header.sequenceNumber,\n });\n return dec;\n }\n\n verifyData(buf: Buffer) {\n if (this.sessionType === SessionType.CLIENT)\n return prfVerifyDataClient(this.masterSecret, buf);\n else return prfVerifyDataServer(this.masterSecret, buf);\n }\n\n signatureData(data: Buffer, hash: string) {\n const signature = createSign(hash).update(data);\n const key = this.localPrivateKey.toPEM().toString();\n const signed = signature.sign(key);\n return signed;\n }\n\n generateKeySignature(hashAlgorithm: string) {\n const clientRandom =\n this.sessionType === SessionType.CLIENT\n ? this.localRandom\n : this.remoteRandom;\n const serverRandom =\n this.sessionType === SessionType.SERVER\n ? this.localRandom\n : this.remoteRandom;\n\n const sig = this.valueKeySignature(\n clientRandom.serialize(),\n serverRandom.serialize(),\n this.localKeyPair.publicKey,\n this.namedCurve\n );\n\n const enc = this.localPrivateKey.sign(sig, hashAlgorithm);\n return enc;\n }\n\n parseX509(certPem: string, keyPem: string, signatureHash: SignatureHash) {\n const cert = Certificate.fromPEM(Buffer.from(certPem));\n const sec = PrivateKey.fromPEM(Buffer.from(keyPem));\n this.localCert = cert.raw;\n this.localPrivateKey = sec;\n this.signatureHashAlgorithm = signatureHash;\n }\n\n private valueKeySignature(\n clientRandom: Buffer,\n serverRandom: Buffer,\n publicKey: Buffer,\n namedCurve: number\n ) {\n const serverParams = Buffer.from(\n encode(\n {\n type: CurveType.named_curve_3,\n curve: namedCurve,\n len: publicKey.length,\n },\n { type: types.uint8, curve: types.uint16be, len: types.uint8 }\n ).slice()\n );\n return Buffer.concat([clientRandom, serverRandom, serverParams, publicKey]);\n }\n}\n"]}
1
+ {"version":3,"file":"cipher.js","sourceRoot":"","sources":["../../../../../dtls/src/context/cipher.ts"],"names":[],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAAA,qCAAqD;AACrD,mDAA6C;AAC7C,qDAAuC;AACvC,6CAAoD;AACpD,mCAAoC;AACpC,iEAAyC;AAEzC,2CAQyB;AAEzB,uCAAyE;AACzE,wDAAsE;AAEtE,gDAAsD;AAItD,MAAM,MAAM,GAAG,IAAI,kBAAM,EAAE,CAAC;AAC5B,IAAI,CAAC,cAAc,CAAC,GAAG,CAAC,MAAa,CAAC,CAAC;AAEvC,MAAa,aAAa;IAcxB,YACS,WAAyB,EACzB,OAAgB,EAChB,MAAe,EACtB,sBAAsC;QAH/B,gBAAW,GAAX,WAAW,CAAc;QACzB,YAAO,GAAP,OAAO,CAAS;QAChB,WAAM,GAAN,MAAM,CAAS;QAGtB,IAAI,OAAO,IAAI,MAAM,IAAI,sBAAsB,EAAE;YAC/C,IAAI,CAAC,SAAS,CAAC,OAAO,EAAE,MAAM,EAAE,sBAAsB,CAAC,CAAC;SACzD;IACH,CAAC;IA2ED,aAAa,CAAC,GAAkB;QAC9B,MAAM,MAAM,GAAG,GAAG,CAAC,iBAAiB,CAAC;QACrC,MAAM,GAAG,GAAG,IAAI,CAAC,MAAM,CAAC,OAAO,CAAC,IAAI,CAAC,WAAW,EAAE,GAAG,CAAC,QAAQ,EAAE;YAC9D,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AAM,OAAO,GAAG,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC;IACrC,MAAM,MAAM,GAAG,IAAI,CAAC,YAAY,CAAC,MAAM,CACrC,MAAM,MAAM,CAAC,MAAM,CAAC,SAAS,CAAC,OAAO,EAAE,IAAI,CAAC,UAAiB,CAAC,EAC9D,aAAa,CACd,CAAC;IAEF,OAAO,EAAE,OAAO,EAAE,MAAM,EAAE,aAAa,EAAE,CAAC;AAC5C,CAAE,CAAA","sourcesContent":["import { Certificate, PrivateKey } from \"@fidm/x509\";\nimport { Crypto } from \"@peculiar/webcrypto\";\nimport * as x509 from \"@peculiar/x509\";\nimport { decode, encode, types } from \"binary-data\";\nimport { createSign } from \"crypto\";\nimport addYears from \"date-fns/addYears\";\n\nimport {\n CipherSuites,\n CurveType,\n HashAlgorithm,\n NamedCurveAlgorithm,\n NamedCurveAlgorithms,\n SignatureAlgorithm,\n SignatureHash,\n} from \"../cipher/const\";\nimport { NamedCurveKeyPair } from \"../cipher/namedCurve\";\nimport { prfVerifyDataClient, prfVerifyDataServer } from \"../cipher/prf\";\nimport { SessionType, SessionTypes } from \"../cipher/suites/abstract\";\nimport AEADCipher from \"../cipher/suites/aead\";\nimport { ProtocolVersion } from \"../handshake/binary\";\nimport { DtlsRandom } from \"../handshake/random\";\nimport { DtlsPlaintext } from \"../record/message/plaintext\";\n\nconst crypto = new Crypto();\nx509.cryptoProvider.set(crypto as any);\n\nexport class CipherContext {\n localRandom!: DtlsRandom;\n remoteRandom!: DtlsRandom;\n cipherSuite!: CipherSuites;\n remoteCertificate?: Buffer;\n remoteKeyPair!: Partial<NamedCurveKeyPair>;\n localKeyPair!: NamedCurveKeyPair;\n masterSecret!: Buffer;\n cipher!: AEADCipher;\n namedCurve!: NamedCurveAlgorithms;\n signatureHashAlgorithm?: SignatureHash;\n localCert!: Buffer;\n localPrivateKey!: PrivateKey;\n\n constructor(\n public sessionType: SessionTypes,\n public certPem?: string,\n public keyPem?: string,\n signatureHashAlgorithm?: SignatureHash\n ) {\n if (certPem && keyPem && signatureHashAlgorithm) {\n this.parseX509(certPem, keyPem, signatureHashAlgorithm);\n }\n }\n\n /**\n *\n * @param signatureHash\n * @param namedCurveAlgorithm necessary when use ecdsa\n */\n static createSelfSignedCertificateWithKey = async (\n signatureHash: SignatureHash,\n namedCurveAlgorithm?: NamedCurveAlgorithms\n ) => {\n const signatureAlgorithmName = (() => {\n switch (signatureHash.signature) {\n case SignatureAlgorithm.rsa_1:\n return \"RSASSA-PKCS1-v1_5\";\n case SignatureAlgorithm.ecdsa_3:\n return \"ECDSA\";\n }\n })();\n const hash = (() => {\n switch (signatureHash.hash) {\n case HashAlgorithm.sha256_4:\n return \"SHA-256\";\n }\n })();\n const namedCurve = (() => {\n switch (namedCurveAlgorithm) {\n case NamedCurveAlgorithm.secp256r1_23:\n return \"P-256\";\n case NamedCurveAlgorithm.x25519_29:\n // todo fix (X25519 not supported with ECDSA)\n if (signatureAlgorithmName === \"ECDSA\") {\n return \"P-256\";\n }\n return \"X25519\";\n default: {\n if (signatureAlgorithmName === \"ECDSA\") return \"P-256\";\n if (signatureAlgorithmName === \"RSASSA-PKCS1-v1_5\") return \"X25519\";\n }\n }\n })();\n const alg = (() => {\n switch (signatureAlgorithmName) {\n case \"ECDSA\":\n return { name: signatureAlgorithmName, hash, namedCurve };\n case \"RSASSA-PKCS1-v1_5\":\n return {\n name: signatureAlgorithmName,\n hash,\n publicExponent: new Uint8Array([1, 0, 1]),\n modulusLength: 2048,\n };\n }\n })();\n\n const keys = await crypto.subtle.generateKey(alg, true, [\"sign\", \"verify\"]);\n\n const cert = await x509.X509CertificateGenerator.createSelfSigned({\n serialNumber: \"01\",\n name: \"C=AU, ST=Some-State, O=Internet Widgits Pty Ltd\",\n notBefore: new Date(),\n notAfter: addYears(Date.now(), 10),\n signingAlgorithm: alg,\n keys,\n });\n\n const certPem = cert.toString(\"pem\");\n const keyPem = x509.PemConverter.encode(\n await crypto.subtle.exportKey(\"pkcs8\", keys.privateKey as any),\n \"private key\"\n );\n\n return { certPem, keyPem, signatureHash };\n };\n\n encryptPacket(pkt: DtlsPlaintext) {\n const header = pkt.recordLayerHeader;\n const enc = this.cipher.encrypt(this.sessionType, pkt.fragment, {\n type: header.contentType,\n version: decode(\n Buffer.from(encode(header.protocolVersion, ProtocolVersion).slice()),\n { version: types.uint16be }\n ).version,\n epoch: header.epoch,\n sequenceNumber: header.sequenceNumber,\n });\n pkt.fragment = enc;\n pkt.recordLayerHeader.contentLen = enc.length;\n return pkt;\n }\n\n decryptPacket(pkt: DtlsPlaintext) {\n const header = pkt.recordLayerHeader;\n const dec = this.cipher.decrypt(this.sessionType, pkt.fragment, {\n type: header.contentType,\n version: decode(\n Buffer.from(encode(header.protocolVersion, ProtocolVersion).slice()),\n { version: types.uint16be }\n ).version,\n epoch: header.epoch,\n sequenceNumber: header.sequenceNumber,\n });\n return dec;\n }\n\n verifyData(buf: Buffer) {\n if (this.sessionType === SessionType.CLIENT)\n return prfVerifyDataClient(this.masterSecret, buf);\n else return prfVerifyDataServer(this.masterSecret, buf);\n }\n\n signatureData(data: Buffer, hash: string) {\n const signature = createSign(hash).update(data);\n const key = this.localPrivateKey.toPEM().toString();\n const signed = signature.sign(key);\n return signed;\n }\n\n generateKeySignature(hashAlgorithm: string) {\n const clientRandom =\n this.sessionType === SessionType.CLIENT\n ? this.localRandom\n : this.remoteRandom;\n const serverRandom =\n this.sessionType === SessionType.SERVER\n ? this.localRandom\n : this.remoteRandom;\n\n const sig = this.valueKeySignature(\n clientRandom.serialize(),\n serverRandom.serialize(),\n this.localKeyPair.publicKey,\n this.namedCurve\n );\n\n const enc = this.localPrivateKey.sign(sig, hashAlgorithm);\n return enc;\n }\n\n parseX509(certPem: string, keyPem: string, signatureHash: SignatureHash) {\n const cert = Certificate.fromPEM(Buffer.from(certPem));\n const sec = PrivateKey.fromPEM(Buffer.from(keyPem));\n this.localCert = cert.raw;\n this.localPrivateKey = sec;\n this.signatureHashAlgorithm = signatureHash;\n }\n\n private valueKeySignature(\n clientRandom: Buffer,\n serverRandom: Buffer,\n publicKey: Buffer,\n namedCurve: number\n ) {\n const serverParams = Buffer.from(\n encode(\n {\n type: CurveType.named_curve_3,\n curve: namedCurve,\n len: publicKey.length,\n },\n { type: types.uint8, curve: types.uint16be, len: types.uint8 }\n ).slice()\n );\n return Buffer.concat([clientRandom, serverRandom, serverParams, publicKey]);\n }\n}\n"]}
@@ -1,10 +1,13 @@
1
1
  import { Message } from "./stun/message";
2
+ import { Address } from "./types/model";
2
3
  export declare class TransactionError extends Error {
3
4
  response?: Message;
5
+ addr?: Address;
4
6
  }
5
7
  export declare class TransactionFailed extends TransactionError {
6
8
  response: Message;
7
- constructor(response: Message);
9
+ addr: Address;
10
+ constructor(response: Message, addr: Address);
8
11
  get str(): string;
9
12
  }
10
13
  export declare class TransactionTimeout extends TransactionError {
@@ -5,14 +5,16 @@ class TransactionError extends Error {
5
5
  }
6
6
  exports.TransactionError = TransactionError;
7
7
  class TransactionFailed extends TransactionError {
8
- constructor(response) {
8
+ constructor(response, addr) {
9
9
  super();
10
10
  this.response = response;
11
+ this.addr = addr;
11
12
  }
12
13
  get str() {
13
14
  let out = "STUN transaction failed";
14
- if (Object.keys(this.response.attributes).includes("ERROR-CODE")) {
15
- const [code, msg] = this.response.attributes["ERROR-CODE"];
15
+ const attribute = this.response.getAttributeValue("ERROR-CODE");
16
+ if (attribute) {
17
+ const [code, msg] = attribute;
16
18
  out += ` (${code} - ${msg})`;
17
19
  }
18
20
  return out;
@@ -1 +1 @@
1
- {"version":3,"file":"exceptions.js","sourceRoot":"","sources":["../../../../ice/src/exceptions.ts"],"names":[],"mappings":";;;AAEA,MAAa,gBAAiB,SAAQ,KAAK;CAE1C;AAFD,4CAEC;AAED,MAAa,iBAAkB,SAAQ,gBAAgB;IACrD,YAAmB,QAAiB;QAClC,KAAK,EAAE,CAAC;QADS,aAAQ,GAAR,QAAQ,CAAS;IAEpC,CAAC;IAED,IAAI,GAAG;QACL,IAAI,GAAG,GAAG,yBAAyB,CAAC;QACpC,IAAI,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,UAAU,CAAC,CAAC,QAAQ,CAAC,YAAY,CAAC,EAAE;YAChE,MAAM,CAAC,IAAI,EAAE,GAAG,CAAC,GAAG,IAAI,CAAC,QAAQ,CAAC,UAAU,CAAC,YAAY,CAAC,CAAC;YAC3D,GAAG,IAAI,KAAK,IAAI,MAAM,GAAG,GAAG,CAAC;SAC9B;QACD,OAAO,GAAG,CAAC;IACb,CAAC;CACF;AAbD,8CAaC;AAED,MAAa,kBAAmB,SAAQ,gBAAgB;IACtD,IAAI,GAAG;QACL,OAAO,4BAA4B,CAAC;IACtC,CAAC;CACF;AAJD,gDAIC","sourcesContent":["import { Message } from \"./stun/message\";\n\nexport class TransactionError extends Error {\n response?: Message;\n}\n\nexport class TransactionFailed extends TransactionError {\n constructor(public response: Message) {\n super();\n }\n\n get str() {\n let out = \"STUN transaction failed\";\n if (Object.keys(this.response.attributes).includes(\"ERROR-CODE\")) {\n const [code, msg] = this.response.attributes[\"ERROR-CODE\"];\n out += ` (${code} - ${msg})`;\n }\n return out;\n }\n}\n\nexport class TransactionTimeout extends TransactionError {\n get str() {\n return \"STUN transaction timed out\";\n }\n}\n"]}
1
+ {"version":3,"file":"exceptions.js","sourceRoot":"","sources":["../../../../ice/src/exceptions.ts"],"names":[],"mappings":";;;AAGA,MAAa,gBAAiB,SAAQ,KAAK;CAG1C;AAHD,4CAGC;AAED,MAAa,iBAAkB,SAAQ,gBAAgB;IACrD,YAAmB,QAAiB,EAAS,IAAa;QACxD,KAAK,EAAE,CAAC;QADS,aAAQ,GAAR,QAAQ,CAAS;QAAS,SAAI,GAAJ,IAAI,CAAS;IAE1D,CAAC;IAED,IAAI,GAAG;QACL,IAAI,GAAG,GAAG,yBAAyB,CAAC;QACpC,MAAM,SAAS,GAAG,IAAI,CAAC,QAAQ,CAAC,iBAAiB,CAAC,YAAY,CAAC,CAAC;QAChE,IAAI,SAAS,EAAE;YACb,MAAM,CAAC,IAAI,EAAE,GAAG,CAAC,GAAG,SAAS,CAAC;YAC9B,GAAG,IAAI,KAAK,IAAI,MAAM,GAAG,GAAG,CAAC;SAC9B;QACD,OAAO,GAAG,CAAC;IACb,CAAC;CACF;AAdD,8CAcC;AAED,MAAa,kBAAmB,SAAQ,gBAAgB;IACtD,IAAI,GAAG;QACL,OAAO,4BAA4B,CAAC;IACtC,CAAC;CACF;AAJD,gDAIC","sourcesContent":["import { Message } from \"./stun/message\";\nimport { Address } from \"./types/model\";\n\nexport class TransactionError extends Error {\n response?: Message;\n addr?: Address;\n}\n\nexport class TransactionFailed extends TransactionError {\n constructor(public response: Message, public addr: Address) {\n super();\n }\n\n get str() {\n let out = \"STUN transaction failed\";\n const attribute = this.response.getAttributeValue(\"ERROR-CODE\");\n if (attribute) {\n const [code, msg] = attribute;\n out += ` (${code} - ${msg})`;\n }\n return out;\n }\n}\n\nexport class TransactionTimeout extends TransactionError {\n get str() {\n return \"STUN transaction timed out\";\n }\n}\n"]}
@@ -103,7 +103,7 @@ export interface IceOptions {
103
103
  export declare function validateRemoteCandidate(candidate: Candidate): Candidate;
104
104
  export declare function sortCandidatePairs(pairs: CandidatePair[], iceControlling: boolean): void;
105
105
  export declare function candidatePairPriority(local: Candidate, remote: Candidate, iceControlling: boolean): number;
106
- export declare function getHostAddress(useIpv4: boolean, useIpv6: boolean): string[];
106
+ export declare function getHostAddresses(useIpv4: boolean, useIpv6: boolean): string[];
107
107
  export declare function serverReflexiveCandidate(protocol: Protocol, stunServer: Address): Promise<Candidate | undefined>;
108
108
  export declare function validateAddress(addr?: Address): Address | undefined;
109
109
  export {};
@@ -22,7 +22,7 @@ var __importDefault = (this && this.__importDefault) || function (mod) {
22
22
  return (mod && mod.__esModule) ? mod : { "default": mod };
23
23
  };
24
24
  Object.defineProperty(exports, "__esModule", { value: true });
25
- exports.validateAddress = exports.serverReflexiveCandidate = exports.getHostAddress = exports.candidatePairPriority = exports.sortCandidatePairs = exports.validateRemoteCandidate = exports.CandidatePairState = exports.CandidatePair = exports.Connection = void 0;
25
+ exports.validateAddress = exports.serverReflexiveCandidate = exports.getHostAddresses = exports.candidatePairPriority = exports.sortCandidatePairs = exports.validateRemoteCandidate = exports.CandidatePairState = exports.CandidatePair = exports.Connection = void 0;
26
26
  const crypto_1 = require("crypto");
27
27
  const debug_1 = __importDefault(require("debug"));
28
28
  const dns_1 = __importDefault(require("dns"));
@@ -31,6 +31,7 @@ const nodeIp = __importStar(require("ip"));
31
31
  const isEqual_1 = __importDefault(require("lodash/isEqual"));
32
32
  const range_1 = __importDefault(require("lodash/range"));
33
33
  const net_1 = require("net");
34
+ const os_1 = __importDefault(require("os"));
34
35
  const p_cancelable_1 = __importDefault(require("p-cancelable"));
35
36
  const rx_mini_1 = require("rx.mini");
36
37
  const promises_1 = __importDefault(require("timers/promises"));
@@ -94,6 +95,7 @@ class Connection {
94
95
  }
95
96
  }
96
97
  catch (error) {
98
+ log("no stun response");
97
99
  failures++;
98
100
  this.setState("disconnected");
99
101
  }
@@ -129,7 +131,7 @@ class Connection {
129
131
  const request = this.buildRequest(pair, nominate);
130
132
  const result = {};
131
133
  try {
132
- const [response, addr] = await pair.protocol.request(request, pair.remoteAddr, Buffer.from(this.remotePassword, "utf8"));
134
+ const [response, addr] = await pair.protocol.request(request, pair.remoteAddr, Buffer.from(this.remotePassword, "utf8"), 4);
133
135
  log("response", response, addr);
134
136
  result.response = response;
135
137
  result.addr = addr;
@@ -138,7 +140,7 @@ class Connection {
138
140
  const exc = error;
139
141
  // 7.1.3.1. Failure Cases
140
142
  log("failure case", exc.response);
141
- if (exc.response?.attributes["ERROR-CODE"][0] === 487) {
143
+ if (exc.response?.getAttributeValue("ERROR-CODE")[0] === 487) {
142
144
  if (request.attributesKeys.includes("ICE-CONTROLLED")) {
143
145
  this.switchRole(true);
144
146
  }
@@ -218,7 +220,7 @@ class Connection {
218
220
  if (!this.localCandidatesStart) {
219
221
  this.localCandidatesStart = true;
220
222
  this.promiseGatherCandidates = new rx_mini_1.Event();
221
- const address = getHostAddress(this.useIpv4, this.useIpv6);
223
+ const address = getHostAddresses(this.useIpv4, this.useIpv6);
222
224
  for (const component of this._components) {
223
225
  const candidates = await this.getComponentCandidates(component, address, 5, cb);
224
226
  this.localCandidates = [...this.localCandidates, ...candidates];
@@ -292,7 +294,7 @@ class Connection {
292
294
  // This coroutine returns if a candidate pair was successfully nominated
293
295
  // and raises an exception otherwise.
294
296
  // """
295
- log("start connect ice");
297
+ log("start connect ice", this.localCandidates);
296
298
  if (!this._localCandidatesEnd) {
297
299
  if (!this.localCandidatesStart)
298
300
  throw new Error("Local candidates gathering was not performed");
@@ -317,7 +319,13 @@ class Connection {
317
319
  await promises_1.default.setTimeout(20);
318
320
  }
319
321
  // # wait for completion
320
- const res = this.checkList.length > 0 ? await this.checkListState.get() : ICE_FAILED;
322
+ let res;
323
+ if (this.checkList.length > 0) {
324
+ res = await this.checkListState.get();
325
+ }
326
+ else {
327
+ res = ICE_FAILED;
328
+ }
321
329
  // # cancel remaining checks
322
330
  this.checkList.forEach((check) => check.handle?.cancel());
323
331
  if (res !== ICE_COMPLETED) {
@@ -394,7 +402,9 @@ class Connection {
394
402
  }
395
403
  // # stop check list
396
404
  if (this.checkList && !this.checkListDone) {
397
- this.checkListState.put(new Promise((r) => r(ICE_FAILED)));
405
+ this.checkListState.put(new Promise((r) => {
406
+ r(ICE_FAILED);
407
+ }));
398
408
  }
399
409
  this.nominated = {};
400
410
  for (const protocol of this.protocols) {
@@ -443,6 +453,7 @@ class Connection {
443
453
  catch (error) {
444
454
  return;
445
455
  }
456
+ log("addRemoteCandidate", remoteCandidate);
446
457
  this.remoteCandidates.push(remoteCandidate);
447
458
  this.pairRemoteCandidate(remoteCandidate);
448
459
  this.sortCheckList();
@@ -477,7 +488,7 @@ class Connection {
477
488
  (0, message_1.parseMessage)(rawData, Buffer.from(this.localPassword, "utf8"));
478
489
  if (!this.remoteUsername) {
479
490
  const rxUsername = `${this.localUserName}:${this.remoteUsername}`;
480
- if (message.attributes["USERNAME"] != rxUsername)
491
+ if (message.getAttributeValue("USERNAME") != rxUsername)
481
492
  throw new Error("Wrong username");
482
493
  }
483
494
  }
@@ -488,7 +499,7 @@ class Connection {
488
499
  const { iceControlling } = this;
489
500
  // 7.2.1.1. Detecting and Repairing Role Conflicts
490
501
  if (iceControlling && message.attributesKeys.includes("ICE-CONTROLLING")) {
491
- if (this._tieBreaker >= message.attributes["ICE-CONTROLLING"]) {
502
+ if (this._tieBreaker >= message.getAttributeValue("ICE-CONTROLLING")) {
492
503
  this.respondError(message, addr, protocol, [487, "Role Conflict"]);
493
504
  return;
494
505
  }
@@ -498,7 +509,7 @@ class Connection {
498
509
  }
499
510
  else if (!iceControlling &&
500
511
  message.attributesKeys.includes("ICE-CONTROLLED")) {
501
- if (this._tieBreaker < message.attributes["ICE-CONTROLLED"]) {
512
+ if (this._tieBreaker < message.getAttributeValue("ICE-CONTROLLED")) {
502
513
  this.respondError(message, addr, protocol, [487, "Role Conflict"]);
503
514
  }
504
515
  else {
@@ -508,9 +519,10 @@ class Connection {
508
519
  }
509
520
  // # send binding response
510
521
  const response = new message_1.Message(const_1.methods.BINDING, const_1.classes.RESPONSE, message.transactionId);
511
- response.attributes["XOR-MAPPED-ADDRESS"] = addr;
512
- response.addMessageIntegrity(Buffer.from(this.localPassword, "utf8"));
513
- response.addFingerprint();
522
+ response
523
+ .setAttribute("XOR-MAPPED-ADDRESS", addr)
524
+ .addMessageIntegrity(Buffer.from(this.localPassword, "utf8"))
525
+ .addFingerprint();
514
526
  protocol.sendStun(response, addr);
515
527
  // todo fix
516
528
  // if (this.checkList.length === 0) {
@@ -614,7 +626,9 @@ class Connection {
614
626
  }
615
627
  if (!this.checkListDone) {
616
628
  log("ICE failed");
617
- this.checkListState.put(new Promise((r) => r(ICE_FAILED)));
629
+ this.checkListState.put(new Promise((r) => {
630
+ r(ICE_FAILED);
631
+ }));
618
632
  this.checkListDone = true;
619
633
  }
620
634
  }
@@ -640,7 +654,7 @@ class Connection {
640
654
  }
641
655
  if (!remoteCandidate) {
642
656
  // 7.2.1.3. Learning Peer Reflexive Candidates
643
- remoteCandidate = new candidate_1.Candidate((0, helper_1.randomString)(10), component, "udp", message.attributes["PRIORITY"], host, port, "prflx");
657
+ remoteCandidate = new candidate_1.Candidate((0, helper_1.randomString)(10), component, "udp", message.getAttributeValue("PRIORITY"), host, port, "prflx");
644
658
  this.remoteCandidates.push(remoteCandidate);
645
659
  }
646
660
  // find pair
@@ -668,24 +682,26 @@ class Connection {
668
682
  buildRequest(pair, nominate) {
669
683
  const txUsername = `${this.remoteUsername}:${this.localUserName}`;
670
684
  const request = new message_1.Message(const_1.methods.BINDING, const_1.classes.REQUEST);
671
- request.attributes["USERNAME"] = txUsername;
672
- request.attributes["PRIORITY"] = (0, candidate_1.candidatePriority)(pair.component, "prflx");
685
+ request
686
+ .setAttribute("USERNAME", txUsername)
687
+ .setAttribute("PRIORITY", (0, candidate_1.candidatePriority)(pair.component, "prflx"));
673
688
  if (this.iceControlling) {
674
- request.attributes["ICE-CONTROLLING"] = this._tieBreaker;
689
+ request.setAttribute("ICE-CONTROLLING", this._tieBreaker);
675
690
  if (nominate) {
676
- request.attributes["USE-CANDIDATE"] = null;
691
+ request.setAttribute("USE-CANDIDATE", null);
677
692
  }
678
693
  }
679
694
  else {
680
- request.attributes["ICE-CONTROLLED"] = this._tieBreaker;
695
+ request.setAttribute("ICE-CONTROLLED", this._tieBreaker);
681
696
  }
682
697
  return request;
683
698
  }
684
699
  respondError(request, addr, protocol, errorCode) {
685
700
  const response = new message_1.Message(request.messageMethod, const_1.classes.ERROR, request.transactionId);
686
- response.attributes["ERROR-CODE"] = errorCode;
687
- response.addMessageIntegrity(Buffer.from(this.localPassword, "utf8"));
688
- response.addFingerprint();
701
+ response
702
+ .setAttribute("ERROR-CODE", errorCode)
703
+ .addMessageIntegrity(Buffer.from(this.localPassword, "utf8"))
704
+ .addFingerprint();
689
705
  protocol.sendStun(response, addr);
690
706
  }
691
707
  }
@@ -751,15 +767,45 @@ function candidatePairPriority(local, remote, iceControlling) {
751
767
  return (1 << 32) * Math.min(G, D) + 2 * Math.max(G, D) + (G > D ? 1 : 0);
752
768
  }
753
769
  exports.candidatePairPriority = candidatePairPriority;
754
- function getHostAddress(useIpv4, useIpv6) {
770
+ function nodeIpAddress(family) {
771
+ // https://chromium.googlesource.com/external/webrtc/+/master/rtc_base/network.cc#236
772
+ const costlyNetworks = ["ipsec", "tun", "utun", "tap"];
773
+ const interfaces = os_1.default.networkInterfaces();
774
+ const all = Object.keys(interfaces)
775
+ .map((nic) => {
776
+ for (const costly of costlyNetworks) {
777
+ if (nic.startsWith(costly)) {
778
+ return {
779
+ nic,
780
+ addresses: [],
781
+ };
782
+ }
783
+ }
784
+ const addresses = interfaces[nic].filter((details) => details.family.toLowerCase() === family &&
785
+ !nodeIp.isLoopback(details.address));
786
+ return {
787
+ nic,
788
+ addresses: addresses.map((address) => address.address),
789
+ };
790
+ })
791
+ .filter((address) => !!address);
792
+ // os.networkInterfaces doesn't actually return addresses in a good order.
793
+ // have seen instances where en0 (ethernet) is after en1 (wlan), etc.
794
+ // eth0 > eth1
795
+ all.sort((a, b) => a.nic.localeCompare(b.nic));
796
+ return Object.values(all)
797
+ .map((entry) => entry.addresses)
798
+ .flat();
799
+ }
800
+ function getHostAddresses(useIpv4, useIpv6) {
755
801
  const address = [];
756
802
  if (useIpv4)
757
- address.push(nodeIp.address("", "ipv4"));
803
+ address.push(...nodeIpAddress("ipv4"));
758
804
  if (useIpv6)
759
- address.push(nodeIp.address("", "ipv6"));
805
+ address.push(...nodeIpAddress("ipv6"));
760
806
  return address;
761
807
  }
762
- exports.getHostAddress = getHostAddress;
808
+ exports.getHostAddresses = getHostAddresses;
763
809
  async function serverReflexiveCandidate(protocol, stunServer) {
764
810
  // """
765
811
  // Query STUN server to obtain a server-reflexive candidate.
@@ -771,7 +817,7 @@ async function serverReflexiveCandidate(protocol, stunServer) {
771
817
  const localCandidate = protocol.localCandidate;
772
818
  if (!localCandidate)
773
819
  throw new Error("not exist");
774
- return new candidate_1.Candidate((0, candidate_1.candidateFoundation)("srflx", "udp", localCandidate.host), localCandidate.component, localCandidate.transport, (0, candidate_1.candidatePriority)(localCandidate.component, "srflx"), response.attributes["XOR-MAPPED-ADDRESS"][0], response.attributes["XOR-MAPPED-ADDRESS"][1], "srflx", localCandidate.host, localCandidate.port);
820
+ return new candidate_1.Candidate((0, candidate_1.candidateFoundation)("srflx", "udp", localCandidate.host), localCandidate.component, localCandidate.transport, (0, candidate_1.candidatePriority)(localCandidate.component, "srflx"), response.getAttributeValue("XOR-MAPPED-ADDRESS")[0], response.getAttributeValue("XOR-MAPPED-ADDRESS")[1], "srflx", localCandidate.host, localCandidate.port);
775
821
  }
776
822
  catch (error) {
777
823
  // todo fix