@decentnetwork/beagle 0.1.147 → 0.1.151

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.
@@ -3,6 +3,7 @@ var PeerWebRTC = (() => {
3
3
  var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
4
4
  var __getOwnPropNames = Object.getOwnPropertyNames;
5
5
  var __hasOwnProp = Object.prototype.hasOwnProperty;
6
+ var __defNormalProp = (obj, key, value) => key in obj ? __defProp(obj, key, { enumerable: true, configurable: true, writable: true, value }) : obj[key] = value;
6
7
  var __export = (target, all) => {
7
8
  for (var name in all)
8
9
  __defProp(target, name, { get: all[name], enumerable: true });
@@ -16,6 +17,10 @@ var PeerWebRTC = (() => {
16
17
  return to;
17
18
  };
18
19
  var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
20
+ var __publicField = (obj, key, value) => {
21
+ __defNormalProp(obj, typeof key !== "symbol" ? key + "" : key, value);
22
+ return value;
23
+ };
19
24
  var __accessCheck = (obj, member, msg) => {
20
25
  if (!member.has(obj))
21
26
  throw TypeError("Cannot " + msg);
@@ -48,6 +53,7 @@ var PeerWebRTC = (() => {
48
53
  CallEngine: () => CallEngine,
49
54
  CarrierSignaling: () => CarrierSignaling,
50
55
  Emitter: () => Emitter,
56
+ RspTurnCredentials: () => RspTurnCredentials,
51
57
  SocketIoSignaling: () => SocketIoSignaling,
52
58
  byteLength: () => byteLength,
53
59
  decodeSignal: () => decodeSignal,
@@ -331,10 +337,10 @@ var PeerWebRTC = (() => {
331
337
  var LEAN_VIDEO_CODECS = /^video\/(H264|VP8|rtx|red|ulpfec)$/i;
332
338
  var ICE_RESTART_MAX = 3;
333
339
  var ICE_DISCONNECT_GRACE_MS = 4e3;
334
- var ICE_FAILED_GRACE_MS = 12e4;
340
+ var ICE_MEDIA_LOSS_GRACE_MS = 12e4;
335
341
  var DEFAULT_RING_TIMEOUT_MS = 6e4;
336
342
  var ENDED_CALL_MEMORY_MS = 12e4;
337
- var _opts, _iceServers, _sessions, _restartOffersEnabled, _endedCalls, _placeCall, placeCall_fn, _startRingTimer, startRingTimer_fn, _clearRingTimer, clearRingTimer_fn, _setOutgoingVideoTrack, setOutgoingVideoTrack_fn, _renegotiate, renegotiate_fn, _sendRenegotiationOffer, sendRenegotiationOffer_fn, _createOffer, createOffer_fn, _createAnswer, createAnswer_fn, _cleanOutbound, cleanOutbound_fn, _cleanInbound, cleanInbound_fn, _preferLeanVideoCodecs, preferLeanVideoCodecs_fn, _restartIce, restartIce_fn, _handleSignal, handleSignal_fn, _onOffer, onOffer_fn, _answerRenegotiation, answerRenegotiation_fn, _negotiationFailed, negotiationFailed_fn, _onAnswer, onAnswer_fn, _onCandidate, onCandidate_fn, _onBye, onBye_fn, _onAuxiliary, onAuxiliary_fn, _createSession, createSession_fn, _wirePeerConnection, wirePeerConnection_fn, _ensureRemoteStream, ensureRemoteStream_fn, _attachLocalMedia, attachLocalMedia_fn, _canTrickle, canTrickle_fn, _localSdpSent, localSdpSent_fn, _flushLocalCandidates, flushLocalCandidates_fn, _drainRemoteCandidates, drainRemoteCandidates_fn, _send, send_fn, _sendByeSafe, sendByeSafe_fn, _cleanup, cleanup_fn, _rememberEnded, rememberEnded_fn, _recentlyEnded, recentlyEnded_fn, _setState, setState_fn, _normId, normId_fn, _toInfo, _newCallId, newCallId_fn, _log, log_fn;
343
+ var _opts, _iceServers, _sessions, _restartOffersEnabled, _endedCalls, _placeCall, placeCall_fn, _startRingTimer, startRingTimer_fn, _clearRingTimer, clearRingTimer_fn, _iceServersForCall, iceServersForCall_fn, _iceServersNow, iceServersNow_fn, _refreshIceServers, refreshIceServers_fn, _setOutgoingVideoTrack, setOutgoingVideoTrack_fn, _renegotiate, renegotiate_fn, _sendRenegotiationOffer, sendRenegotiationOffer_fn, _createOffer, createOffer_fn, _createAnswer, createAnswer_fn, _cleanOutbound, cleanOutbound_fn, _cleanInbound, cleanInbound_fn, _preferLeanVideoCodecs, preferLeanVideoCodecs_fn, _restartIce, restartIce_fn, _handleSignal, handleSignal_fn, _onOffer, onOffer_fn, _answerRenegotiation, answerRenegotiation_fn, _negotiationFailed, negotiationFailed_fn, _onAnswer, onAnswer_fn, _onCandidate, onCandidate_fn, _onBye, onBye_fn, _onAuxiliary, onAuxiliary_fn, _createSession, createSession_fn, _wirePeerConnection, wirePeerConnection_fn, _armMediaLoss, armMediaLoss_fn, _ensureRemoteStream, ensureRemoteStream_fn, _attachLocalMedia, attachLocalMedia_fn, _canTrickle, canTrickle_fn, _localSdpSent, localSdpSent_fn, _flushLocalCandidates, flushLocalCandidates_fn, _drainRemoteCandidates, drainRemoteCandidates_fn, _send, send_fn, _sendByeSafe, sendByeSafe_fn, _cleanup, cleanup_fn, _rememberEnded, rememberEnded_fn, _recentlyEnded, recentlyEnded_fn, _setState, setState_fn, _normId, normId_fn, _toInfo, _newCallId, newCallId_fn, _log, log_fn;
338
344
  var CallEngine = class extends Emitter {
339
345
  constructor(opts) {
340
346
  var _a, _b;
@@ -343,6 +349,14 @@ var PeerWebRTC = (() => {
343
349
  /** Start the caller's ring timer (see CallEngineOptions.ringTimeoutMs). */
344
350
  __privateAdd(this, _startRingTimer);
345
351
  __privateAdd(this, _clearRingTimer);
352
+ /** ICE servers for a call about to start: the configured ones plus TURN. */
353
+ __privateAdd(this, _iceServersForCall);
354
+ /** The same, without waiting: cached TURN credential or the fallback. */
355
+ __privateAdd(this, _iceServersNow);
356
+ /** Incoming call: its RTCPeerConnection was made when the offer arrived,
357
+ * with whatever TURN credential was cached. Before the answer (so before
358
+ * ICE gathering) give it a fresh one if that changed anything. */
359
+ __privateAdd(this, _refreshIceServers);
346
360
  /** Point the outgoing video sender at `track` (replaceTrack, no renegotiation
347
361
  * needed if a sender exists), flip the transceiver to send, and refresh the
348
362
  * local-preview stream. `track === null` removes the outgoing video. */
@@ -405,6 +419,7 @@ var PeerWebRTC = (() => {
405
419
  __privateAdd(this, _onAuxiliary);
406
420
  __privateAdd(this, _createSession);
407
421
  __privateAdd(this, _wirePeerConnection);
422
+ __privateAdd(this, _armMediaLoss);
408
423
  __privateAdd(this, _ensureRemoteStream);
409
424
  __privateAdd(this, _attachLocalMedia);
410
425
  /** May a local candidate go out now? Only once
@@ -485,7 +500,8 @@ var PeerWebRTC = (() => {
485
500
  const video = (_b = kinds.video) != null ? _b : false;
486
501
  const data = (_c = kinds.data) != null ? _c : false;
487
502
  const callId = __privateMethod(this, _newCallId, newCallId_fn).call(this);
488
- const session = __privateMethod(this, _createSession, createSession_fn).call(this, callId, peerId, "outgoing", { audio, video, data });
503
+ const iceServers = await __privateMethod(this, _iceServersForCall, iceServersForCall_fn).call(this);
504
+ const session = __privateMethod(this, _createSession, createSession_fn).call(this, callId, peerId, "outgoing", { audio, video, data }, iceServers);
489
505
  __privateMethod(this, _startRingTimer, startRingTimer_fn).call(this, session);
490
506
  try {
491
507
  await __privateMethod(this, _placeCall, placeCall_fn).call(this, session);
@@ -509,6 +525,7 @@ var PeerWebRTC = (() => {
509
525
  throw new Error(`accept: no pending incoming call ${callId}`);
510
526
  }
511
527
  await __privateMethod(this, _attachLocalMedia, attachLocalMedia_fn).call(this, session);
528
+ await __privateMethod(this, _refreshIceServers, refreshIceServers_fn).call(this, session);
512
529
  await session.pc.setRemoteDescription({ type: "offer", sdp: __privateMethod(this, _cleanInbound, cleanInbound_fn).call(this, session.pendingOffer, "offer") });
513
530
  session.hasReceivedSdp = true;
514
531
  session.pendingOffer = void 0;
@@ -715,6 +732,42 @@ var PeerWebRTC = (() => {
715
732
  session.ringTimer = void 0;
716
733
  }
717
734
  };
735
+ _iceServersForCall = new WeakSet();
736
+ iceServersForCall_fn = async function() {
737
+ const turn = __privateGet(this, _opts).turnServers;
738
+ if (!turn)
739
+ return __privateGet(this, _iceServers);
740
+ let extra = [];
741
+ try {
742
+ extra = await turn.iceServers();
743
+ } catch {
744
+ extra = turn.currentIceServers();
745
+ }
746
+ return [...__privateGet(this, _iceServers), ...extra];
747
+ };
748
+ _iceServersNow = new WeakSet();
749
+ iceServersNow_fn = function() {
750
+ const turn = __privateGet(this, _opts).turnServers;
751
+ return turn ? [...__privateGet(this, _iceServers), ...turn.currentIceServers()] : __privateGet(this, _iceServers);
752
+ };
753
+ _refreshIceServers = new WeakSet();
754
+ refreshIceServers_fn = async function(session) {
755
+ var _a;
756
+ if (!__privateGet(this, _opts).turnServers)
757
+ return;
758
+ const iceServers = await __privateMethod(this, _iceServersForCall, iceServersForCall_fn).call(this);
759
+ const pc = session.pc;
760
+ if (typeof pc.setConfiguration !== "function")
761
+ return;
762
+ const current = typeof pc.getConfiguration === "function" ? pc.getConfiguration() : {};
763
+ if (sameIceServers((_a = current.iceServers) != null ? _a : [], iceServers))
764
+ return;
765
+ try {
766
+ pc.setConfiguration({ ...current, iceServers });
767
+ } catch (err) {
768
+ __privateMethod(this, _log, log_fn).call(this, `accept ${session.callId}: could not update ICE servers (${err.message}); keeping the cached/static ones`);
769
+ }
770
+ };
718
771
  _setOutgoingVideoTrack = new WeakSet();
719
772
  setOutgoingVideoTrack_fn = async function(session, track, stream) {
720
773
  var _a, _b, _c, _d;
@@ -902,8 +955,10 @@ var PeerWebRTC = (() => {
902
955
  const audio = signal.options ? signal.options.includes("audio") : true;
903
956
  const video = signal.options ? signal.options.includes("video") : false;
904
957
  const data = signal.options ? signal.options.includes("data") : false;
905
- const session = __privateMethod(this, _createSession, createSession_fn).call(this, signal.callId, peerId, "incoming", { audio, video, data });
958
+ const session = __privateMethod(this, _createSession, createSession_fn).call(this, signal.callId, peerId, "incoming", { audio, video, data }, __privateMethod(this, _iceServersNow, iceServersNow_fn).call(this));
906
959
  session.pendingOffer = signal.sdp;
960
+ if (__privateGet(this, _opts).turnServers)
961
+ void __privateGet(this, _opts).turnServers.iceServers();
907
962
  if (__privateGet(this, _opts).sendRinging !== false) {
908
963
  void __privateMethod(this, _send, send_fn).call(this, peerId, { type: "event", event: "ringing", callId: signal.callId }).catch(() => {
909
964
  });
@@ -1010,8 +1065,8 @@ var PeerWebRTC = (() => {
1010
1065
  }
1011
1066
  };
1012
1067
  _createSession = new WeakSet();
1013
- createSession_fn = function(callId, peerId, direction, kinds) {
1014
- const pc = __privateGet(this, _opts).createPeerConnection({ iceServers: __privateGet(this, _iceServers) });
1068
+ createSession_fn = function(callId, peerId, direction, kinds, iceServers = __privateGet(this, _iceServers)) {
1069
+ const pc = __privateGet(this, _opts).createPeerConnection({ iceServers });
1015
1070
  const session = {
1016
1071
  callId,
1017
1072
  peerId,
@@ -1066,11 +1121,14 @@ var PeerWebRTC = (() => {
1066
1121
  clearTimeout(session.restartTimer);
1067
1122
  session.restartTimer = void 0;
1068
1123
  }
1124
+ clearTimeout(session.mediaLossTimer);
1125
+ session.mediaLossTimer = void 0;
1069
1126
  session.restartAttempts = 0;
1070
1127
  __privateMethod(this, _setState, setState_fn).call(this, session, "connected");
1071
1128
  break;
1072
1129
  case "disconnected":
1073
1130
  __privateMethod(this, _setState, setState_fn).call(this, session, "disconnected");
1131
+ __privateMethod(this, _armMediaLoss, armMediaLoss_fn).call(this, session);
1074
1132
  if (__privateGet(this, _restartOffersEnabled) && session.direction === "outgoing" && !session.restartTimer && session.restartAttempts < ICE_RESTART_MAX) {
1075
1133
  session.restartTimer = setTimeout(() => {
1076
1134
  session.restartTimer = void 0;
@@ -1085,15 +1143,7 @@ var PeerWebRTC = (() => {
1085
1143
  __privateMethod(this, _setState, setState_fn).call(this, session, "disconnected");
1086
1144
  if (__privateGet(this, _restartOffersEnabled) && session.direction === "outgoing")
1087
1145
  void __privateMethod(this, _restartIce, restartIce_fn).call(this, session);
1088
- if (session.restartTimer)
1089
- clearTimeout(session.restartTimer);
1090
- session.restartTimer = setTimeout(() => {
1091
- session.restartTimer = void 0;
1092
- if (!session.closed && pc.iceConnectionState === "failed") {
1093
- __privateMethod(this, _setState, setState_fn).call(this, session, "failed");
1094
- __privateMethod(this, _cleanup, cleanup_fn).call(this, session, "close", "failed");
1095
- }
1096
- }, ICE_FAILED_GRACE_MS);
1146
+ __privateMethod(this, _armMediaLoss, armMediaLoss_fn).call(this, session);
1097
1147
  } else {
1098
1148
  __privateMethod(this, _setState, setState_fn).call(this, session, "failed");
1099
1149
  __privateMethod(this, _cleanup, cleanup_fn).call(this, session, "close", "failed");
@@ -1108,6 +1158,22 @@ var PeerWebRTC = (() => {
1108
1158
  }
1109
1159
  };
1110
1160
  };
1161
+ _armMediaLoss = new WeakSet();
1162
+ armMediaLoss_fn = function(session) {
1163
+ if (session.mediaLossTimer)
1164
+ return;
1165
+ session.mediaLossTimer = setTimeout(() => {
1166
+ var _a;
1167
+ session.mediaLossTimer = void 0;
1168
+ if (session.closed)
1169
+ return;
1170
+ const state = (_a = session.pc) == null ? void 0 : _a.iceConnectionState;
1171
+ if (state === "connected" || state === "completed")
1172
+ return;
1173
+ __privateMethod(this, _setState, setState_fn).call(this, session, "failed");
1174
+ __privateMethod(this, _cleanup, cleanup_fn).call(this, session, "close", "failed");
1175
+ }, ICE_MEDIA_LOSS_GRACE_MS);
1176
+ };
1111
1177
  _ensureRemoteStream = new WeakSet();
1112
1178
  ensureRemoteStream_fn = function(session, track) {
1113
1179
  if (!session.remoteStream)
@@ -1225,6 +1291,8 @@ var PeerWebRTC = (() => {
1225
1291
  clearTimeout(session.restartTimer);
1226
1292
  session.restartTimer = void 0;
1227
1293
  }
1294
+ clearTimeout(session.mediaLossTimer);
1295
+ session.mediaLossTimer = void 0;
1228
1296
  try {
1229
1297
  session.pc.onicecandidate = null;
1230
1298
  session.pc.ontrack = null;
@@ -1288,6 +1356,320 @@ var PeerWebRTC = (() => {
1288
1356
  var _a, _b;
1289
1357
  (_b = (_a = __privateGet(this, _opts)).logger) == null ? void 0 : _b.call(_a, `[peer-webrtc] ${msg}`);
1290
1358
  };
1359
+ function sameIceServers(a, b) {
1360
+ const key = (s) => {
1361
+ var _a;
1362
+ return `${[s.urls].flat().join(",")}|${(_a = s.username) != null ? _a : ""}`;
1363
+ };
1364
+ if (a.length !== b.length)
1365
+ return false;
1366
+ return a.every((s, i) => key(s) === key(b[i]));
1367
+ }
1368
+
1369
+ // node_modules/@decentnetwork/rendezvous-protocol/src/index.js
1370
+ var IDENTITY_METHODS = Object.freeze([
1371
+ "carrier-x25519",
1372
+ "ethereum-eip191",
1373
+ "solana-ed25519"
1374
+ ]);
1375
+ var PROOF_TYPES = Object.freeze([
1376
+ "carrier-x25519-hmac-sha256",
1377
+ "ethereum-eip191",
1378
+ "solana-ed25519"
1379
+ ]);
1380
+ var SIGNAL_TYPES = Object.freeze([
1381
+ "call.ringing",
1382
+ "call.accept",
1383
+ "call.reject",
1384
+ "call.cancel",
1385
+ "call.connected",
1386
+ "call.hangup",
1387
+ "webrtc.offer",
1388
+ "webrtc.answer",
1389
+ "webrtc.candidate",
1390
+ "webrtc.ice-restart"
1391
+ ]);
1392
+ var SIGNAL_ENCODINGS = Object.freeze(["json", "ciphertext.base64url"]);
1393
+ var SAFE_FIELD = /^[^\r\n\0]{1,512}$/;
1394
+ var CARRIER_ID = /^[1-9A-HJ-NP-Za-km-z]{32,52}$/;
1395
+ var ETHEREUM_ID = /^eip155:([1-9][0-9]*):(0x[0-9a-fA-F]{40})$/;
1396
+ var TURN_NONCE = /^[A-Za-z0-9_-]{16,128}$/;
1397
+ var SOLANA_ID = /^solana:([A-Za-z0-9_-]{1,32}):([1-9A-HJ-NP-Za-km-z]{32,50})$/;
1398
+ function safeField(value, name) {
1399
+ if (typeof value !== "string" || !SAFE_FIELD.test(value))
1400
+ throw new TypeError(`${name} is invalid`);
1401
+ return value;
1402
+ }
1403
+ function validateIdentity(identity) {
1404
+ if (!identity || typeof identity !== "object" || Array.isArray(identity))
1405
+ throw new TypeError("identity must be an object");
1406
+ const keys = Object.keys(identity).sort();
1407
+ if (keys.length !== 2 || keys[0] !== "id" || keys[1] !== "method")
1408
+ throw new TypeError("identity fields are invalid");
1409
+ if (!IDENTITY_METHODS.includes(identity.method))
1410
+ throw new TypeError("identity method is unsupported");
1411
+ safeField(identity.id, "identity id");
1412
+ if (identity.method === "carrier-x25519" && !CARRIER_ID.test(identity.id))
1413
+ throw new TypeError("Carrier userid is invalid");
1414
+ if (identity.method === "ethereum-eip191" && !ETHEREUM_ID.test(identity.id))
1415
+ throw new TypeError("Ethereum account id is invalid");
1416
+ if (identity.method === "solana-ed25519" && !SOLANA_ID.test(identity.id))
1417
+ throw new TypeError("Solana account id is invalid");
1418
+ return { method: identity.method, id: identity.id };
1419
+ }
1420
+ function canonicalIdentity(identity) {
1421
+ const checked = validateIdentity(identity);
1422
+ return `${checked.method}:${checked.id}`;
1423
+ }
1424
+ var TURN_AUTH_DOMAIN = "RSP-TURN/1";
1425
+ function turnCredentialSigningText({ nodeUrl, carrierServerKey = "", self, timestamp, nonce }) {
1426
+ if (!Number.isSafeInteger(timestamp) || timestamp < 0)
1427
+ throw new TypeError("timestamp is invalid");
1428
+ if (typeof nonce !== "string" || !TURN_NONCE.test(nonce))
1429
+ throw new TypeError("nonce is invalid");
1430
+ return [
1431
+ TURN_AUTH_DOMAIN,
1432
+ safeField(nodeUrl, "nodeUrl"),
1433
+ carrierServerKey === "" ? "" : safeField(carrierServerKey, "carrierServerKey"),
1434
+ canonicalIdentity(self),
1435
+ String(timestamp),
1436
+ nonce
1437
+ ].join("\n");
1438
+ }
1439
+
1440
+ // node_modules/@decentnetwork/peer-webrtc/dist/turn.js
1441
+ var DEFAULT_MIN_VALIDITY_MS = 10 * 6e4;
1442
+ var DEFAULT_TIMEOUT_MS = 8e3;
1443
+ var DEFAULT_RETRY_AFTER_FAILURE_MS = 6e4;
1444
+ var ROUTE = "/v1/turn-credentials";
1445
+ var TurnFetchError = class extends Error {
1446
+ constructor(reason, status, code, serverTime, retryAfterMs) {
1447
+ super(reason);
1448
+ __publicField(this, "reason");
1449
+ __publicField(this, "status");
1450
+ __publicField(this, "code");
1451
+ __publicField(this, "serverTime");
1452
+ __publicField(this, "retryAfterMs");
1453
+ this.reason = reason;
1454
+ this.status = status;
1455
+ this.code = code;
1456
+ this.serverTime = serverTime;
1457
+ this.retryAfterMs = retryAfterMs;
1458
+ }
1459
+ };
1460
+ var _opts2, _base, _minValidityMs, _cached, _inflight, _clockOffsetMs, _quietUntil, _mint, mint_fn, _discover, discover_fn, _post, post_fn, _fetch, fetch_fn, _now, now_fn, _log2, log_fn2;
1461
+ var RspTurnCredentials = class {
1462
+ constructor(opts) {
1463
+ __privateAdd(this, _mint);
1464
+ __privateAdd(this, _discover);
1465
+ __privateAdd(this, _post);
1466
+ __privateAdd(this, _fetch);
1467
+ __privateAdd(this, _now);
1468
+ __privateAdd(this, _log2);
1469
+ __privateAdd(this, _opts2, void 0);
1470
+ __privateAdd(this, _base, void 0);
1471
+ __privateAdd(this, _minValidityMs, void 0);
1472
+ __privateAdd(this, _cached, void 0);
1473
+ __privateAdd(this, _inflight, void 0);
1474
+ /** Our clock minus the node's, learned from a 401 invalid_timestamp. */
1475
+ __privateAdd(this, _clockOffsetMs, 0);
1476
+ /** No new fetch before this time (after a failure). */
1477
+ __privateAdd(this, _quietUntil, 0);
1478
+ var _a;
1479
+ if (!(opts == null ? void 0 : opts.nodeUrl))
1480
+ throw new TypeError("nodeUrl is required");
1481
+ if (!opts.signer || typeof opts.signer.descriptor !== "function" || typeof opts.signer.signChallenge !== "function") {
1482
+ throw new TypeError("signer must implement descriptor() and signChallenge()");
1483
+ }
1484
+ __privateSet(this, _opts2, opts);
1485
+ __privateSet(this, _base, opts.nodeUrl.replace(/\/+$/, ""));
1486
+ __privateSet(this, _minValidityMs, (_a = opts.minValidityMs) != null ? _a : DEFAULT_MIN_VALIDITY_MS);
1487
+ }
1488
+ currentIceServers() {
1489
+ var _a;
1490
+ const c = __privateGet(this, _cached);
1491
+ if (c && c.expiresAt - __privateMethod(this, _now, now_fn).call(this) >= __privateGet(this, _minValidityMs))
1492
+ return [toIceServer(c)];
1493
+ return [...(_a = __privateGet(this, _opts2).fallback) != null ? _a : []];
1494
+ }
1495
+ async iceServers() {
1496
+ var _a, _b, _c;
1497
+ const c = __privateGet(this, _cached);
1498
+ if (c && c.expiresAt - __privateMethod(this, _now, now_fn).call(this) >= __privateGet(this, _minValidityMs))
1499
+ return [toIceServer(c)];
1500
+ if (__privateMethod(this, _now, now_fn).call(this) < __privateGet(this, _quietUntil))
1501
+ return [...(_a = __privateGet(this, _opts2).fallback) != null ? _a : []];
1502
+ (_b = __privateGet(this, _inflight)) != null ? _b : __privateSet(this, _inflight, __privateMethod(this, _mint, mint_fn).call(this).then((fresh) => {
1503
+ __privateSet(this, _cached, fresh);
1504
+ return fresh;
1505
+ }, (err) => {
1506
+ var _a2, _b2, _c2, _d;
1507
+ const reason = err instanceof TurnFetchError ? err.reason : `error: ${(_a2 = err == null ? void 0 : err.name) != null ? _a2 : "Error"}`;
1508
+ const backoff = Math.max((_b2 = __privateGet(this, _opts2).retryAfterFailureMs) != null ? _b2 : DEFAULT_RETRY_AFTER_FAILURE_MS, err instanceof TurnFetchError ? (_c2 = err.retryAfterMs) != null ? _c2 : 0 : 0);
1509
+ __privateSet(this, _quietUntil, __privateMethod(this, _now, now_fn).call(this) + backoff);
1510
+ const fallback = (_d = __privateGet(this, _opts2).fallback) != null ? _d : [];
1511
+ __privateMethod(this, _log2, log_fn2).call(this, `TURN credentials from ${__privateGet(this, _base)} unavailable (${reason}); ${fallback.length ? "using the static TURN entry" : "no fallback configured"}, next try in ${Math.round(backoff / 1e3)} s`);
1512
+ throw err;
1513
+ }).finally(() => {
1514
+ __privateSet(this, _inflight, void 0);
1515
+ }));
1516
+ try {
1517
+ return [toIceServer(await __privateGet(this, _inflight))];
1518
+ } catch {
1519
+ return [...(_c = __privateGet(this, _opts2).fallback) != null ? _c : []];
1520
+ }
1521
+ }
1522
+ /** Forget the cached credential (e.g. after the user switched identity). */
1523
+ clear() {
1524
+ __privateSet(this, _cached, void 0);
1525
+ __privateSet(this, _quietUntil, 0);
1526
+ }
1527
+ };
1528
+ _opts2 = new WeakMap();
1529
+ _base = new WeakMap();
1530
+ _minValidityMs = new WeakMap();
1531
+ _cached = new WeakMap();
1532
+ _inflight = new WeakMap();
1533
+ _clockOffsetMs = new WeakMap();
1534
+ _quietUntil = new WeakMap();
1535
+ _mint = new WeakSet();
1536
+ mint_fn = async function() {
1537
+ let staleRetried = false;
1538
+ let clockRetried = false;
1539
+ for (; ; ) {
1540
+ const discovery = await __privateMethod(this, _discover, discover_fn).call(this);
1541
+ try {
1542
+ return await __privateMethod(this, _post, post_fn).call(this, discovery);
1543
+ } catch (err) {
1544
+ if (!(err instanceof TurnFetchError))
1545
+ throw err;
1546
+ if (err.code === "stale_server_key" && !staleRetried) {
1547
+ staleRetried = true;
1548
+ continue;
1549
+ }
1550
+ if (err.code === "invalid_timestamp" && !clockRetried && err.serverTime !== void 0) {
1551
+ clockRetried = true;
1552
+ __privateSet(this, _clockOffsetMs, __privateMethod(this, _now, now_fn).call(this) - err.serverTime);
1553
+ __privateMethod(this, _log2, log_fn2).call(this, `TURN credentials: local clock off by ${Math.round(__privateGet(this, _clockOffsetMs) / 1e3)} s; retrying with the node's time`);
1554
+ continue;
1555
+ }
1556
+ throw err;
1557
+ }
1558
+ }
1559
+ };
1560
+ _discover = new WeakSet();
1561
+ discover_fn = async function() {
1562
+ const res = await __privateMethod(this, _fetch, fetch_fn).call(this, `${__privateGet(this, _base)}${ROUTE}`, { method: "GET", headers: { accept: "application/json" } });
1563
+ const body = await readJson(res);
1564
+ if (!res.ok)
1565
+ throw httpError("GET", res, body);
1566
+ const nodeUrl = body == null ? void 0 : body.nodeUrl;
1567
+ const carrierServerKey = body == null ? void 0 : body.carrierServerKey;
1568
+ if (typeof nodeUrl !== "string" || !nodeUrl || typeof carrierServerKey !== "string") {
1569
+ throw new TurnFetchError("GET: discovery reply is malformed", res.status);
1570
+ }
1571
+ return { nodeUrl, carrierServerKey };
1572
+ };
1573
+ _post = new WeakSet();
1574
+ post_fn = async function(discovery) {
1575
+ var _a, _b, _c;
1576
+ const self = await __privateGet(this, _opts2).signer.descriptor();
1577
+ const carrierServerKey = self.method === "carrier-x25519" ? discovery.carrierServerKey : "";
1578
+ const timestamp = __privateMethod(this, _now, now_fn).call(this) - __privateGet(this, _clockOffsetMs);
1579
+ const nonce = (_c = (_b = (_a = __privateGet(this, _opts2)).nonce) == null ? void 0 : _b.call(_a)) != null ? _c : randomNonce();
1580
+ const message = turnCredentialSigningText({ nodeUrl: discovery.nodeUrl, carrierServerKey, self, timestamp, nonce });
1581
+ const signed = await __privateGet(this, _opts2).signer.signChallenge({
1582
+ message,
1583
+ bytes: new TextEncoder().encode(message),
1584
+ hello: { carrierServerKey: discovery.carrierServerKey, nodeUrl: discovery.nodeUrl },
1585
+ request: { route: ROUTE }
1586
+ });
1587
+ if (!signed || typeof signed.type !== "string")
1588
+ throw new TurnFetchError("signer returned no proof");
1589
+ const proof = { type: signed.type, value: proofValue(signed.value) };
1590
+ const body = { self, timestamp, nonce, proof };
1591
+ if (carrierServerKey)
1592
+ body.carrierServerKey = carrierServerKey;
1593
+ const res = await __privateMethod(this, _fetch, fetch_fn).call(this, `${__privateGet(this, _base)}${ROUTE}`, {
1594
+ method: "POST",
1595
+ headers: { "content-type": "application/json", accept: "application/json" },
1596
+ body: JSON.stringify(body)
1597
+ });
1598
+ const reply = await readJson(res);
1599
+ if (!res.ok)
1600
+ throw httpError("POST", res, reply);
1601
+ const { urls, username, credential, expiresAt } = reply != null ? reply : {};
1602
+ if (!Array.isArray(urls) || urls.length === 0 || !urls.every((u) => typeof u === "string") || typeof username !== "string" || typeof credential !== "string" || !Number.isSafeInteger(expiresAt)) {
1603
+ throw new TurnFetchError("POST: credential reply is malformed", res.status);
1604
+ }
1605
+ return { urls: [...urls], username, credential, expiresAt };
1606
+ };
1607
+ _fetch = new WeakSet();
1608
+ fetch_fn = async function(url, init) {
1609
+ var _a, _b, _c;
1610
+ const f = (_a = __privateGet(this, _opts2).fetch) != null ? _a : globalThis.fetch;
1611
+ if (typeof f !== "function")
1612
+ throw new TurnFetchError("no fetch available");
1613
+ const controller = typeof AbortController === "function" ? new AbortController() : void 0;
1614
+ const timer = controller ? setTimeout(() => controller.abort(), (_b = __privateGet(this, _opts2).timeoutMs) != null ? _b : DEFAULT_TIMEOUT_MS) : void 0;
1615
+ try {
1616
+ return await f(url, { ...init, signal: controller == null ? void 0 : controller.signal, cache: "no-store" });
1617
+ } catch (err) {
1618
+ const aborted = (err == null ? void 0 : err.name) === "AbortError";
1619
+ throw new TurnFetchError(`${init.method}: ${aborted ? "timed out" : `network error (${(_c = err == null ? void 0 : err.name) != null ? _c : "Error"})`}`);
1620
+ } finally {
1621
+ if (timer)
1622
+ clearTimeout(timer);
1623
+ }
1624
+ };
1625
+ _now = new WeakSet();
1626
+ now_fn = function() {
1627
+ var _a, _b, _c;
1628
+ return (_c = (_b = (_a = __privateGet(this, _opts2)).now) == null ? void 0 : _b.call(_a)) != null ? _c : Date.now();
1629
+ };
1630
+ _log2 = new WeakSet();
1631
+ log_fn2 = function(message) {
1632
+ var _a, _b;
1633
+ try {
1634
+ (_b = (_a = __privateGet(this, _opts2)).log) == null ? void 0 : _b.call(_a, message);
1635
+ } catch {
1636
+ }
1637
+ };
1638
+ function toIceServer(c) {
1639
+ return { urls: [...c.urls], username: c.username, credential: c.credential };
1640
+ }
1641
+ async function readJson(res) {
1642
+ try {
1643
+ return await res.json();
1644
+ } catch {
1645
+ return void 0;
1646
+ }
1647
+ }
1648
+ function httpError(method, res, body) {
1649
+ var _a, _b, _c, _d, _e;
1650
+ const code = typeof ((_a = body == null ? void 0 : body.error) == null ? void 0 : _a.code) === "string" ? body.error.code : void 0;
1651
+ const header = Number((_c = (_b = res.headers) == null ? void 0 : _b.get) == null ? void 0 : _c.call(_b, "x-server-time"));
1652
+ const retryAfter = Number((_e = (_d = res.headers) == null ? void 0 : _d.get) == null ? void 0 : _e.call(_d, "retry-after"));
1653
+ return new TurnFetchError(`${method}: HTTP ${res.status}${code ? ` ${code}` : ""}`, res.status, code, Number.isSafeInteger(header) && header > 0 ? header : void 0, Number.isFinite(retryAfter) && retryAfter > 0 ? Math.min(retryAfter, 3600) * 1e3 : void 0);
1654
+ }
1655
+ function proofValue(value) {
1656
+ if (typeof value === "string")
1657
+ return value;
1658
+ if (value instanceof Uint8Array)
1659
+ return base64url(value);
1660
+ throw new TurnFetchError("signer proof must be a string or Uint8Array");
1661
+ }
1662
+ function randomNonce() {
1663
+ const bytes = new Uint8Array(24);
1664
+ globalThis.crypto.getRandomValues(bytes);
1665
+ return base64url(bytes);
1666
+ }
1667
+ function base64url(bytes) {
1668
+ let s = "";
1669
+ for (const b of bytes)
1670
+ s += String.fromCharCode(b);
1671
+ return btoa(s).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
1672
+ }
1291
1673
 
1292
1674
  // node_modules/@decentnetwork/peer-webrtc/dist/signaling/broadcast.js
1293
1675
  var _selfId, _channel, _handler;
@@ -1522,14 +1904,14 @@ var PeerWebRTC = (() => {
1522
1904
  "https://www.callpass.cn/push-api/push-message",
1523
1905
  "https://tokyo.fi.chat:3004/push-api/push-message"
1524
1906
  ];
1525
- var _appKey, _appName, _endpoints, _fetch, _gateway, _env, _sendDirect, sendDirect_fn;
1907
+ var _appKey, _appName, _endpoints, _fetch2, _gateway, _env, _sendDirect, sendDirect_fn;
1526
1908
  var BeaglePushClient = class {
1527
1909
  constructor(opts) {
1528
1910
  __privateAdd(this, _sendDirect);
1529
1911
  __privateAdd(this, _appKey, void 0);
1530
1912
  __privateAdd(this, _appName, void 0);
1531
1913
  __privateAdd(this, _endpoints, void 0);
1532
- __privateAdd(this, _fetch, void 0);
1914
+ __privateAdd(this, _fetch2, void 0);
1533
1915
  __privateAdd(this, _gateway, void 0);
1534
1916
  __privateAdd(this, _env, void 0);
1535
1917
  var _a, _b, _c;
@@ -1543,7 +1925,7 @@ var PeerWebRTC = (() => {
1543
1925
  const f = (_c = opts.fetch) != null ? _c : globalThis.fetch;
1544
1926
  if (!f && __privateGet(this, _appKey))
1545
1927
  throw new Error("BeaglePushClient: no fetch available \u2014 pass opts.fetch");
1546
- __privateSet(this, _fetch, f);
1928
+ __privateSet(this, _fetch2, f);
1547
1929
  }
1548
1930
  /**
1549
1931
  * Ring an offline peer. `calleeUserId` is the destination (their Carrier user
@@ -1608,13 +1990,13 @@ var PeerWebRTC = (() => {
1608
1990
  _appKey = new WeakMap();
1609
1991
  _appName = new WeakMap();
1610
1992
  _endpoints = new WeakMap();
1611
- _fetch = new WeakMap();
1993
+ _fetch2 = new WeakMap();
1612
1994
  _gateway = new WeakMap();
1613
1995
  _env = new WeakMap();
1614
1996
  _sendDirect = new WeakSet();
1615
1997
  sendDirect_fn = async function(calleeUserId, payload, appKey) {
1616
1998
  var _a;
1617
- const fetchFn = __privateGet(this, _fetch);
1999
+ const fetchFn = __privateGet(this, _fetch2);
1618
2000
  if (!fetchFn)
1619
2001
  return false;
1620
2002
  const params = new URLSearchParams({
@@ -0,0 +1,34 @@
1
+ import { carrierSigner } from "@decentnetwork/peer-webrtc/rsp";
2
+ export declare const RSP_TURN_NODE_DEFAULT = "https://rsp.beagle.chat";
3
+ export interface TurnEntry {
4
+ urls: string | string[];
5
+ username?: string;
6
+ credential?: string;
7
+ }
8
+ /** The RSP/2 bridge's signer for the identity in `keyFile` (lan rsp-profile.ts). */
9
+ export declare function rspCarrierSigner(keyFile: string): {
10
+ userid: string;
11
+ signer: ReturnType<typeof carrierSigner>;
12
+ };
13
+ /** Only the TURN entries of an ICE list (STUN stays in the call's iceServers). */
14
+ export declare function turnOnly(list: TurnEntry[]): TurnEntry[];
15
+ export interface CallTurnSourceOptions {
16
+ keyFile: string;
17
+ /** RSP node; BEAGLE_RSP_NODE_URL overrides, e.g. to test the fallback. */
18
+ nodeUrl?: string;
19
+ /** Today's TURN entries, used when the node cannot mint (Carrier bootstrap TURN). */
20
+ fallback: () => Promise<TurnEntry[]>;
21
+ log?: (message: string) => void;
22
+ fetch?: typeof fetch;
23
+ }
24
+ /**
25
+ * TURN entries for a call about to start: the RSP credential (cached while
26
+ * valid for 10 more minutes), else `fallback()`. Never rejects. `source` says
27
+ * which, for the UI's diagnostics — never the credential itself.
28
+ */
29
+ export declare function createCallTurnSource(opts: CallTurnSourceOptions): {
30
+ iceServers(): Promise<{
31
+ source: "rsp" | "fallback";
32
+ iceServers: TurnEntry[];
33
+ }>;
34
+ };