@decentnetwork/beagle 0.1.129 → 0.1.131

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.
@@ -322,11 +322,17 @@ var PeerWebRTC = (() => {
322
322
  var ICE_RESTART_MAX = 3;
323
323
  var ICE_DISCONNECT_GRACE_MS = 4e3;
324
324
  var ICE_FAILED_GRACE_MS = 12e4;
325
- var _opts, _iceServers, _sessions, _restartOffersEnabled, _setOutgoingVideoTrack, setOutgoingVideoTrack_fn, _renegotiate, renegotiate_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, _flushLocalCandidates, flushLocalCandidates_fn, _drainRemoteCandidates, drainRemoteCandidates_fn, _send, send_fn, _sendByeSafe, sendByeSafe_fn, _cleanup, cleanup_fn, _setState, setState_fn, _normId, normId_fn, _toInfo, _newCallId, newCallId_fn, _log, log_fn;
325
+ var DEFAULT_RING_TIMEOUT_MS = 6e4;
326
+ var ENDED_CALL_MEMORY_MS = 12e4;
327
+ var _opts, _iceServers, _sessions, _restartOffersEnabled, _endedCalls, _placeCall, placeCall_fn, _startRingTimer, startRingTimer_fn, _clearRingTimer, clearRingTimer_fn, _setOutgoingVideoTrack, setOutgoingVideoTrack_fn, _renegotiate, renegotiate_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, _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;
326
328
  var CallEngine = class extends Emitter {
327
329
  constructor(opts) {
328
330
  var _a, _b;
329
331
  super();
332
+ __privateAdd(this, _placeCall);
333
+ /** Start the caller's ring timer (see CallEngineOptions.ringTimeoutMs). */
334
+ __privateAdd(this, _startRingTimer);
335
+ __privateAdd(this, _clearRingTimer);
330
336
  /** Point the outgoing video sender at `track` (replaceTrack, no renegotiation
331
337
  * needed if a sender exists), flip the transceiver to send, and refresh the
332
338
  * local-preview stream. `track === null` removes the outgoing video. */
@@ -395,6 +401,8 @@ var PeerWebRTC = (() => {
395
401
  __privateAdd(this, _send);
396
402
  __privateAdd(this, _sendByeSafe);
397
403
  __privateAdd(this, _cleanup);
404
+ __privateAdd(this, _rememberEnded);
405
+ __privateAdd(this, _recentlyEnded);
398
406
  __privateAdd(this, _setState);
399
407
  /** Canonical session key. callId is a UUID; iOS re-serializes it UPPERCASE
400
408
  * (it parses our lowercase UUID into a `UUID` and echoes `.uuidString`), so
@@ -410,6 +418,8 @@ var PeerWebRTC = (() => {
410
418
  __privateAdd(this, _sessions, /* @__PURE__ */ new Map());
411
419
  /** See CallEngineOptions.iceRestartOffers — off by default for native-app safety. */
412
420
  __privateAdd(this, _restartOffersEnabled, void 0);
421
+ /** Normalized callId → time it ended (see ENDED_CALL_MEMORY_MS). */
422
+ __privateAdd(this, _endedCalls, /* @__PURE__ */ new Map());
413
423
  __privateAdd(this, _toInfo, (session) => ({
414
424
  callId: session.callId,
415
425
  peerId: session.peerId,
@@ -448,43 +458,23 @@ var PeerWebRTC = (() => {
448
458
  * "remoteStream"/"ended" as the call progresses.
449
459
  */
450
460
  async call(peerId, kinds = {}) {
451
- var _a, _b, _c, _d, _e;
461
+ var _a, _b, _c;
452
462
  const audio = (_a = kinds.audio) != null ? _a : true;
453
463
  const video = (_b = kinds.video) != null ? _b : false;
454
464
  const data = (_c = kinds.data) != null ? _c : false;
455
465
  const callId = __privateMethod(this, _newCallId, newCallId_fn).call(this);
456
466
  const session = __privateMethod(this, _createSession, createSession_fn).call(this, callId, peerId, "outgoing", { audio, video, data });
457
- await __privateMethod(this, _attachLocalMedia, attachLocalMedia_fn).call(this, session);
458
- if (audio && !((_d = session.localStream) == null ? void 0 : _d.getAudioTracks().length)) {
459
- try {
460
- session.pc.addTransceiver("audio", { direction: "recvonly" });
461
- } catch {
462
- }
463
- }
464
- if (video && !((_e = session.localStream) == null ? void 0 : _e.getVideoTracks().length)) {
465
- try {
466
- session.pc.addTransceiver("video", { direction: "recvonly" });
467
- } catch {
467
+ __privateMethod(this, _startRingTimer, startRingTimer_fn).call(this, session);
468
+ try {
469
+ await __privateMethod(this, _placeCall, placeCall_fn).call(this, session);
470
+ } catch (err) {
471
+ if (!session.closed) {
472
+ const unreachable = (err == null ? void 0 : err.sendFailed) === true;
473
+ __privateMethod(this, _setState, setState_fn).call(this, session, unreachable ? "unreachable" : "failed");
474
+ __privateMethod(this, _cleanup, cleanup_fn).call(this, session, "close", unreachable ? "unreachable" : "failed");
468
475
  }
476
+ throw err;
469
477
  }
470
- const offer = await __privateMethod(this, _createOffer, createOffer_fn).call(this, session);
471
- await session.pc.setLocalDescription(offer);
472
- const options = [];
473
- if (audio)
474
- options.push("audio");
475
- if (video)
476
- options.push("video");
477
- if (data)
478
- options.push("data");
479
- await __privateMethod(this, _send, send_fn).call(this, peerId, {
480
- type: "offer",
481
- sdp: offer.sdp,
482
- options,
483
- callId,
484
- event: void 0
485
- });
486
- __privateMethod(this, _setState, setState_fn).call(this, session, "ringing");
487
- __privateMethod(this, _log, log_fn).call(this, `call \u2192 ${peerId} callId=${callId} audio=${audio} video=${video}`);
488
478
  return callId;
489
479
  }
490
480
  /**
@@ -621,6 +611,78 @@ var PeerWebRTC = (() => {
621
611
  _iceServers = new WeakMap();
622
612
  _sessions = new WeakMap();
623
613
  _restartOffersEnabled = new WeakMap();
614
+ _endedCalls = new WeakMap();
615
+ _placeCall = new WeakSet();
616
+ placeCall_fn = async function(session) {
617
+ var _a, _b;
618
+ const { callId, peerId, audio, video, data } = session;
619
+ await __privateMethod(this, _attachLocalMedia, attachLocalMedia_fn).call(this, session);
620
+ if (session.closed)
621
+ throw new Error(`call ${callId} ended before the offer was sent`);
622
+ if (audio && !((_a = session.localStream) == null ? void 0 : _a.getAudioTracks().length)) {
623
+ try {
624
+ session.pc.addTransceiver("audio", { direction: "recvonly" });
625
+ } catch {
626
+ }
627
+ }
628
+ if (video && !((_b = session.localStream) == null ? void 0 : _b.getVideoTracks().length)) {
629
+ try {
630
+ session.pc.addTransceiver("video", { direction: "recvonly" });
631
+ } catch {
632
+ }
633
+ }
634
+ const offer = await __privateMethod(this, _createOffer, createOffer_fn).call(this, session);
635
+ await session.pc.setLocalDescription(offer);
636
+ const options = [];
637
+ if (audio)
638
+ options.push("audio");
639
+ if (video)
640
+ options.push("video");
641
+ if (data)
642
+ options.push("data");
643
+ try {
644
+ await __privateMethod(this, _send, send_fn).call(this, peerId, {
645
+ type: "offer",
646
+ sdp: offer.sdp,
647
+ options,
648
+ callId,
649
+ event: void 0
650
+ });
651
+ } catch (err) {
652
+ const e = err instanceof Error ? err : new Error(String(err));
653
+ e.sendFailed = true;
654
+ throw e;
655
+ }
656
+ if (session.closed)
657
+ return;
658
+ if (!session.hasReceivedSdp)
659
+ __privateMethod(this, _setState, setState_fn).call(this, session, session.remoteRang ? "remoteRinging" : "ringing");
660
+ __privateMethod(this, _log, log_fn).call(this, `call \u2192 ${peerId} callId=${callId} audio=${audio} video=${video}`);
661
+ };
662
+ _startRingTimer = new WeakSet();
663
+ startRingTimer_fn = function(session) {
664
+ var _a, _b, _c;
665
+ const ms = (_a = __privateGet(this, _opts).ringTimeoutMs) != null ? _a : DEFAULT_RING_TIMEOUT_MS;
666
+ if (!(ms > 0))
667
+ return;
668
+ session.ringTimer = setTimeout(() => {
669
+ session.ringTimer = void 0;
670
+ if (session.closed || session.hasReceivedSdp)
671
+ return;
672
+ __privateMethod(this, _log, log_fn).call(this, `no answer from ${session.peerId} in ${ms}ms \u2014 ending call ${session.callId}`);
673
+ __privateMethod(this, _setState, setState_fn).call(this, session, "noAnswer");
674
+ void __privateMethod(this, _sendByeSafe, sendByeSafe_fn).call(this, session, "normal");
675
+ __privateMethod(this, _cleanup, cleanup_fn).call(this, session, "normal", "noAnswer");
676
+ }, ms);
677
+ (_c = (_b = session.ringTimer).unref) == null ? void 0 : _c.call(_b);
678
+ };
679
+ _clearRingTimer = new WeakSet();
680
+ clearRingTimer_fn = function(session) {
681
+ if (session.ringTimer) {
682
+ clearTimeout(session.ringTimer);
683
+ session.ringTimer = void 0;
684
+ }
685
+ };
624
686
  _setOutgoingVideoTrack = new WeakSet();
625
687
  setOutgoingVideoTrack_fn = async function(session, track, stream) {
626
688
  var _a, _b, _c, _d;
@@ -787,11 +849,19 @@ var PeerWebRTC = (() => {
787
849
  existing.pendingOffer = signal.sdp;
788
850
  return;
789
851
  }
852
+ if (__privateMethod(this, _recentlyEnded, recentlyEnded_fn).call(this, signal.callId)) {
853
+ __privateMethod(this, _log, log_fn).call(this, `dropping offer for ended call ${signal.callId} from ${peerId}`);
854
+ return;
855
+ }
790
856
  const audio = signal.options ? signal.options.includes("audio") : true;
791
857
  const video = signal.options ? signal.options.includes("video") : false;
792
858
  const data = signal.options ? signal.options.includes("data") : false;
793
859
  const session = __privateMethod(this, _createSession, createSession_fn).call(this, signal.callId, peerId, "incoming", { audio, video, data });
794
860
  session.pendingOffer = signal.sdp;
861
+ if (__privateGet(this, _opts).sendRinging !== false) {
862
+ void __privateMethod(this, _send, send_fn).call(this, peerId, { type: "event", event: "ringing", callId: signal.callId }).catch(() => {
863
+ });
864
+ }
795
865
  this.emit("incomingCall", __privateGet(this, _toInfo).call(this, session));
796
866
  __privateMethod(this, _log, log_fn).call(this, `incoming call from ${peerId} callId=${signal.callId} audio=${audio} video=${video}`);
797
867
  };
@@ -823,6 +893,7 @@ var PeerWebRTC = (() => {
823
893
  try {
824
894
  await session.pc.setRemoteDescription({ type: "answer", sdp: __privateMethod(this, _cleanInbound, cleanInbound_fn).call(this, signal.sdp, "answer") });
825
895
  session.hasReceivedSdp = true;
896
+ __privateMethod(this, _clearRingTimer, clearRingTimer_fn).call(this, session);
826
897
  if (session.state !== "connected")
827
898
  __privateMethod(this, _setState, setState_fn).call(this, session, "connecting");
828
899
  await __privateMethod(this, _drainRemoteCandidates, drainRemoteCandidates_fn).call(this, session);
@@ -869,10 +940,17 @@ var PeerWebRTC = (() => {
869
940
  if (!session)
870
941
  return;
871
942
  if (signal.type === "event") {
872
- if (signal.event === "ringing")
873
- __privateMethod(this, _setState, setState_fn).call(this, session, "remoteRinging");
874
- else if (signal.event === "online")
875
- __privateMethod(this, _setState, setState_fn).call(this, session, "remoteOnline");
943
+ const preAnswer = session.direction === "outgoing" && !session.hasReceivedSdp;
944
+ if (signal.event === "ringing") {
945
+ if (!preAnswer)
946
+ return;
947
+ session.remoteRang = true;
948
+ if (session.state === "ringing")
949
+ __privateMethod(this, _setState, setState_fn).call(this, session, "remoteRinging");
950
+ } else if (signal.event === "online") {
951
+ if (preAnswer && session.state === "ringing")
952
+ __privateMethod(this, _setState, setState_fn).call(this, session, "remoteOnline");
953
+ }
876
954
  } else if (signal.type === "action") {
877
955
  if (signal.action === "reject") {
878
956
  __privateMethod(this, _setState, setState_fn).call(this, session, "declined");
@@ -1008,6 +1086,15 @@ var PeerWebRTC = (() => {
1008
1086
  }
1009
1087
  }
1010
1088
  }
1089
+ if (stream && session.closed) {
1090
+ for (const t of stream.getTracks()) {
1091
+ try {
1092
+ t.stop();
1093
+ } catch {
1094
+ }
1095
+ }
1096
+ return;
1097
+ }
1011
1098
  if (!stream) {
1012
1099
  __privateMethod(this, _log, log_fn).call(this, `no local media for ${session.callId}; connecting receive-only`);
1013
1100
  return;
@@ -1064,6 +1151,8 @@ var PeerWebRTC = (() => {
1064
1151
  if (session.closed)
1065
1152
  return;
1066
1153
  session.closed = true;
1154
+ __privateMethod(this, _clearRingTimer, clearRingTimer_fn).call(this, session);
1155
+ __privateMethod(this, _rememberEnded, rememberEnded_fn).call(this, session.callId);
1067
1156
  if (session.restartTimer) {
1068
1157
  clearTimeout(session.restartTimer);
1069
1158
  session.restartTimer = void 0;
@@ -1087,6 +1176,20 @@ var PeerWebRTC = (() => {
1087
1176
  }
1088
1177
  this.emit("ended", session.callId, endedReason != null ? endedReason : reason);
1089
1178
  };
1179
+ _rememberEnded = new WeakSet();
1180
+ rememberEnded_fn = function(callId) {
1181
+ const now = Date.now();
1182
+ for (const [id, at] of __privateGet(this, _endedCalls)) {
1183
+ if (now - at > ENDED_CALL_MEMORY_MS)
1184
+ __privateGet(this, _endedCalls).delete(id);
1185
+ }
1186
+ __privateGet(this, _endedCalls).set(__privateMethod(this, _normId, normId_fn).call(this, callId), now);
1187
+ };
1188
+ _recentlyEnded = new WeakSet();
1189
+ recentlyEnded_fn = function(callId) {
1190
+ const at = __privateGet(this, _endedCalls).get(__privateMethod(this, _normId, normId_fn).call(this, callId));
1191
+ return at !== void 0 && Date.now() - at <= ENDED_CALL_MEMORY_MS;
1192
+ };
1090
1193
  _setState = new WeakSet();
1091
1194
  setState_fn = function(session, state) {
1092
1195
  if (session.state === state)
@@ -15,6 +15,7 @@ import { mkdir, readFile, writeFile, unlink } from "node:fs/promises";
15
15
  import { basename, resolve } from "node:path";
16
16
  import { CarrierNode } from "./carrier-node.js";
17
17
  import { MessageStore } from "./message-store.js";
18
+ import { parseGroupFile, withoutFileData } from "./group-file.js";
18
19
  import { FriendMetaStore } from "./friend-meta.js";
19
20
  import { Logger } from "./logger.js";
20
21
  import { acquireIdentityLock } from "./identity-lock.js";
@@ -203,9 +204,18 @@ export class EmbeddedHost {
203
204
  // No status on an inbound message — MessageStore's status field tracks
204
205
  // OUR delivery state (queued|sent|failed). `via` is the inbound signal:
205
206
  // whether it arrived live or was pulled from offline storage.
206
- this.#messages.append(pubkey, "in", text, Date.now(), undefined, via);
207
- this.#meta.ensure(pubkey);
208
- this.#events.emit("event", { type: "chat", userid: pubkey, dir: "in" });
207
+ // A file posted in a group we are an agent of: CGP1 with the bytes as
208
+ // message.file.data_base64 (group-file.ts). Saved as a received file in
209
+ // the group's thread, from its real sender; never stored as base64 text.
210
+ const gf = parseGroupFile(text);
211
+ if (gf?.data) {
212
+ void this.#saveGroupFile(pubkey, gf, text, via);
213
+ }
214
+ else {
215
+ this.#messages.append(pubkey, "in", gf ? withoutFileData(text) : text, Date.now(), undefined, via);
216
+ this.#meta.ensure(pubkey);
217
+ this.#events.emit("event", { type: "chat", userid: pubkey, dir: "in" });
218
+ }
209
219
  // Hearing from them proves the session carries traffic — better
210
220
  // evidence than any status flag, so use it.
211
221
  void this.#chainFlush(pubkey);
@@ -310,6 +320,35 @@ export class EmbeddedHost {
310
320
  this.#activeSends.delete(p.fileId);
311
321
  });
312
322
  }
323
+ /** A group file that came with its bytes: downloads/<name> (a different
324
+ * file of the same name gets "-2", "-3"…), de-duplicated by SHA-256 in the
325
+ * group's thread, attributed to the sender. On failure the description is
326
+ * kept as text so the message is not lost. */
327
+ async #saveGroupFile(pubkey, f, text, via) {
328
+ try {
329
+ if (f.sha256 && this.#messages.hasFileSha(pubkey, f.sha256))
330
+ return;
331
+ await mkdir(this.downloadsDir, { recursive: true });
332
+ const safe = sanitizeFileName(f.name);
333
+ const dot = safe.lastIndexOf(".");
334
+ let name = safe;
335
+ for (let i = 2; i < 1000; i++) {
336
+ const existing = await readFile(resolve(this.downloadsDir, name)).catch(() => undefined);
337
+ if (!existing || existing.equals(f.data))
338
+ break;
339
+ name = dot > 0 ? `${safe.slice(0, dot)}-${i}${safe.slice(dot)}` : `${safe}-${i}`;
340
+ }
341
+ await writeFile(resolve(this.downloadsDir, name), f.data);
342
+ this.#messages.appendFile(pubkey, "in", { name, size: f.data.length, sha256: f.sha256 }, Date.now(), { origin: { userid: f.origin.userid, nickname: f.origin.nickname }, via });
343
+ this.#logger.info(`saved group file "${name}" (${f.data.length}B) from ${f.origin.nickname || "member"} in ${pubkey.slice(0, 8)}`);
344
+ }
345
+ catch (e) {
346
+ this.#logger.warn(`could not save group file: ${e.message}`);
347
+ this.#messages.append(pubkey, "in", withoutFileData(text), Date.now(), undefined, via);
348
+ }
349
+ this.#meta.ensure(pubkey);
350
+ this.#events.emit("event", { type: "chat", userid: pubkey, dir: "in" });
351
+ }
313
352
  /** Persist a received file under downloads/ and log it in the thread. */
314
353
  async #saveIncoming(pubkey, name, data) {
315
354
  const safe = sanitizeFileName(name);
@@ -2,11 +2,12 @@ export declare const EXIT_PROBE_PORT = 8888;
2
2
  export declare const EXIT_PROBE_TIMEOUT_MS = 2000;
3
3
  /** Consecutive failed probes after which an exit is `failed`. */
4
4
  export declare const EXIT_MAX_FAILS = 3;
5
- /** Wait after the 1st and 2nd failure before the next automatic try. */
6
- export declare const EXIT_RETRY_BACKOFF_MS: number[];
7
- /** How long a successful probe is trusted before the next one. */
8
- export declare const EXIT_OK_CACHE_MS = 60000;
9
- export type ExitStatus = "unknown" | "ok" | "retrying" | "failed";
5
+ /** Panel polls (?exits=1) closer together than this are one panel visit, so
6
+ * they cost one probe round, not one per poll. Long, because a background
7
+ * browser tab is throttled to a poll a minute and must not count as
8
+ * re-opening the panel each time. Re-opening the tab says so explicitly. */
9
+ export declare const EXIT_PANEL_SESSION_GAP_MS: number;
10
+ export type ExitStatus = "unknown" | "ok" | "down" | "failed";
10
11
  export interface ExitRecord {
11
12
  /** Consecutive failed probes (reset by a success). */
12
13
  fails: number;
@@ -14,8 +15,6 @@ export interface ExitRecord {
14
15
  reachable: boolean;
15
16
  ping: number | null;
16
17
  lastProbeAt: number;
17
- /** No automatic probe before this time. */
18
- nextProbeAt: number;
19
18
  }
20
19
  export interface ExitView {
21
20
  ip: string;
@@ -54,14 +53,20 @@ export declare class ExitProber {
54
53
  /** True while at least one of `ips` is not failed — i.e. there is an exit
55
54
  * the route/proxy feature could still use. None configured = false. */
56
55
  usable(ips: string[]): boolean;
57
- /** Is an automatic probe of `ip` due now? Failed exits never are. */
58
- due(ip: string): boolean;
59
- /** Probe every exit in `ips` that is due (never a failed one, never one
60
- * already being probed). Resolves when those probes are done. */
56
+ /** A network-panel poll arrived (?exits=1). True when it is a new visit —
57
+ * `opened` (the UI's first poll after the tab opens) or the first poll
58
+ * after a long gap — and so earns one probe round. Every other poll of
59
+ * the same visit is false: an open panel costs nothing. */
60
+ panelPoll(opened: boolean): boolean;
61
+ /** One access: probe every exit in `ips` once — never a failed one, never
62
+ * one already being probed. Resolves when those probes are done. */
61
63
  refresh(ips: string[]): Promise<void>;
62
64
  /** The Reconnect button: one probe now, whatever the state. Success makes
63
65
  * the exit normal again; a failure leaves a failed exit failed. */
64
66
  reconnect(ip: string): Promise<ExitView>;
67
+ /** The Refresh button: every exit once, failed ones included (with
68
+ * Reconnect's rule: a failed one that fails again stays failed). */
69
+ refreshAll(ips: string[]): Promise<ExitView[]>;
65
70
  get fallback(): RouteFallback | null;
66
71
  setFallback(f: RouteFallback | null): void;
67
72
  }
@@ -7,22 +7,25 @@
7
7
  // of SYNs to seven hosts that never answered — whether or not routing used an
8
8
  // exit and whether or not anyone was looking at the panel.
9
9
  //
10
- // The rules this file holds:
11
- // - a probe result is cached (a good one for OK_CACHE_MS, a bad one until
12
- // its backoff runs out);
13
- // - an exit that fails MAX_FAILS probes in a row is `failed` and is never
14
- // probed automatically again — only `reconnect()` (a button press) does;
15
- // - the record lives on disk, so a restart does not start the loop over.
10
+ // The rules this file holds (Weili 2026-11-05: "有访问的时候再查,联系失败后停止查询"
11
+ // — check when something is accessed, stop checking once contact fails):
12
+ // - nothing here runs on a timer. An exit is probed only on an access: the
13
+ // network panel being OPENED (not while it stays open — see panelPoll),
14
+ // a Refresh / Reconnect press, or routing being set to go through it;
15
+ // - each failed access is one failure; MAX_FAILS in a row and the exit is
16
+ // `failed` and only Reconnect / Refresh probes it again. A success resets;
17
+ // - the record lives on disk, so a restart does not start over.
16
18
  import net from "node:net";
17
19
  import { existsSync, readFileSync, writeFileSync, renameSync } from "node:fs";
18
20
  export const EXIT_PROBE_PORT = 8888;
19
21
  export const EXIT_PROBE_TIMEOUT_MS = 2000;
20
22
  /** Consecutive failed probes after which an exit is `failed`. */
21
23
  export const EXIT_MAX_FAILS = 3;
22
- /** Wait after the 1st and 2nd failure before the next automatic try. */
23
- export const EXIT_RETRY_BACKOFF_MS = [30_000, 120_000];
24
- /** How long a successful probe is trusted before the next one. */
25
- export const EXIT_OK_CACHE_MS = 60_000;
24
+ /** Panel polls (?exits=1) closer together than this are one panel visit, so
25
+ * they cost one probe round, not one per poll. Long, because a background
26
+ * browser tab is throttled to a poll a minute and must not count as
27
+ * re-opening the panel each time. Re-opening the tab says so explicitly. */
28
+ export const EXIT_PANEL_SESSION_GAP_MS = 5 * 60_000;
26
29
  /** One TCP handshake to the exit's CONNECT-proxy port. A completed handshake
27
30
  * proves the mesh path and the exit process are both live. ECONNREFUSED means
28
31
  * the host answered (L3 reachable) but nothing listens — still reachable for
@@ -62,6 +65,7 @@ export class ExitProber {
62
65
  #exits = new Map();
63
66
  #fallback = null;
64
67
  #inFlight = new Map();
68
+ #lastPanelPoll = -Infinity;
65
69
  constructor(opts = {}) {
66
70
  this.#path = opts.path;
67
71
  this.#probe = opts.probe ?? ((ip) => tcpProbe(ip));
@@ -82,7 +86,6 @@ export class ExitProber {
82
86
  reachable: !!r.reachable,
83
87
  ping: typeof r.ping === "number" ? r.ping : null,
84
88
  lastProbeAt: Number(r.lastProbeAt) || 0,
85
- nextProbeAt: Number(r.nextProbeAt) || 0,
86
89
  });
87
90
  }
88
91
  this.#fallback = f?.fallback && typeof f.fallback.from === "string" ? f.fallback : null;
@@ -107,7 +110,7 @@ export class ExitProber {
107
110
  #record(ip) {
108
111
  let r = this.#exits.get(ip);
109
112
  if (!r) {
110
- r = { fails: 0, failed: false, reachable: false, ping: null, lastProbeAt: 0, nextProbeAt: 0 };
113
+ r = { fails: 0, failed: false, reachable: false, ping: null, lastProbeAt: 0 };
111
114
  this.#exits.set(ip, r);
112
115
  }
113
116
  return r;
@@ -117,7 +120,7 @@ export class ExitProber {
117
120
  if (!r || !r.lastProbeAt) {
118
121
  return { ip, status: r?.failed ? "failed" : "unknown", reachable: false, ping: null, fails: r?.fails ?? 0, checkedAt: null };
119
122
  }
120
- const status = r.failed ? "failed" : r.reachable ? "ok" : r.fails > 0 ? "retrying" : "unknown";
123
+ const status = r.failed ? "failed" : r.reachable ? "ok" : r.fails > 0 ? "down" : "unknown";
121
124
  return { ip, status, reachable: !r.failed && r.reachable, ping: r.failed ? null : r.ping, fails: r.fails, checkedAt: r.lastProbeAt };
122
125
  }
123
126
  isFailed(ip) {
@@ -128,14 +131,15 @@ export class ExitProber {
128
131
  usable(ips) {
129
132
  return ips.some((ip) => !this.isFailed(ip));
130
133
  }
131
- /** Is an automatic probe of `ip` due now? Failed exits never are. */
132
- due(ip) {
133
- const r = this.#exits.get(ip);
134
- if (!r)
135
- return true;
136
- if (r.failed)
137
- return false;
138
- return this.#now() >= r.nextProbeAt;
134
+ /** A network-panel poll arrived (?exits=1). True when it is a new visit —
135
+ * `opened` (the UI's first poll after the tab opens) or the first poll
136
+ * after a long gap — and so earns one probe round. Every other poll of
137
+ * the same visit is false: an open panel costs nothing. */
138
+ panelPoll(opened) {
139
+ const now = this.#now();
140
+ const fresh = opened || now - this.#lastPanelPoll > EXIT_PANEL_SESSION_GAP_MS;
141
+ this.#lastPanelPoll = now;
142
+ return fresh;
139
143
  }
140
144
  #apply(ip, ok, ping, manual) {
141
145
  const r = this.#record(ip);
@@ -146,7 +150,6 @@ export class ExitProber {
146
150
  r.failed = false;
147
151
  r.reachable = true;
148
152
  r.ping = ping;
149
- r.nextProbeAt = now + EXIT_OK_CACHE_MS;
150
153
  }
151
154
  else {
152
155
  r.reachable = false;
@@ -159,7 +162,6 @@ export class ExitProber {
159
162
  if (r.fails >= EXIT_MAX_FAILS)
160
163
  r.failed = true;
161
164
  }
162
- r.nextProbeAt = r.failed ? Number.MAX_SAFE_INTEGER : now + EXIT_RETRY_BACKOFF_MS[Math.min(r.fails - 1, EXIT_RETRY_BACKOFF_MS.length - 1)];
163
165
  }
164
166
  this.#save();
165
167
  }
@@ -174,11 +176,11 @@ export class ExitProber {
174
176
  this.#inFlight.set(ip, p);
175
177
  return p;
176
178
  }
177
- /** Probe every exit in `ips` that is due (never a failed one, never one
178
- * already being probed). Resolves when those probes are done. */
179
+ /** One access: probe every exit in `ips` once — never a failed one, never
180
+ * one already being probed. Resolves when those probes are done. */
179
181
  async refresh(ips) {
180
- const due = [...new Set(ips)].filter((ip) => !this.#inFlight.has(ip) && this.due(ip));
181
- await Promise.all(due.map((ip) => this.#run(ip, false)));
182
+ const todo = [...new Set(ips)].filter((ip) => !this.#inFlight.has(ip) && !this.isFailed(ip));
183
+ await Promise.all(todo.map((ip) => this.#run(ip, false)));
182
184
  }
183
185
  /** The Reconnect button: one probe now, whatever the state. Success makes
184
186
  * the exit normal again; a failure leaves a failed exit failed. */
@@ -186,10 +188,14 @@ export class ExitProber {
186
188
  const running = this.#inFlight.get(ip);
187
189
  if (running)
188
190
  await running;
189
- if (!this.view(ip).reachable)
190
- await this.#run(ip, true);
191
+ await this.#run(ip, true);
191
192
  return this.view(ip);
192
193
  }
194
+ /** The Refresh button: every exit once, failed ones included (with
195
+ * Reconnect's rule: a failed one that fails again stays failed). */
196
+ async refreshAll(ips) {
197
+ return Promise.all([...new Set(ips)].map((ip) => this.reconnect(ip)));
198
+ }
193
199
  get fallback() {
194
200
  return this.#fallback;
195
201
  }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * A file posted in a CarrierGroup, as an AGENT member receives it: a CGP1
3
+ * envelope whose message.file describes the file and, since the group service
4
+ * commit b6a3cb5 (2026-11-05), carries the bytes as `data_base64` (RFC 4648,
5
+ * padded) whenever the whole message fits in 5 MiB. Bigger files arrive as a
6
+ * description only. Spec: agentnet-v2 group/docs/GROUP_FILE_MESSAGE.md.
7
+ *
8
+ * The desktop Beagle is registered as an agent in its groups (to learn real
9
+ * sender userids), so before this a voice note from a phone showed as the text
10
+ * "[file] voice-….m4a (31639 bytes)" and could not be played.
11
+ *
12
+ * Pure (no fs, no network). Same module as @decentnetwork/lan src/daemon/group-file.ts
13
+ * (the daemon backend); unit-tested in test/group-file.test.ts.
14
+ */
15
+ export interface GroupFile {
16
+ group: {
17
+ userid?: string;
18
+ address?: string;
19
+ nickname?: string;
20
+ };
21
+ origin: {
22
+ userid?: string;
23
+ nickname?: string;
24
+ };
25
+ name: string;
26
+ contentType: string;
27
+ /** Declared size (the description). */
28
+ size: number;
29
+ /** Microseconds, as the service sends message.timestamp. */
30
+ timestampUs?: number;
31
+ /** The bytes, when the envelope carried them and they decode to `size`. */
32
+ data?: Buffer;
33
+ /** SHA-256 hex of `data`. */
34
+ sha256?: string;
35
+ }
36
+ /** The group file in a CGP1 text, or null when the text is anything else.
37
+ * Never throws: a peer wrote it. */
38
+ export declare function parseGroupFile(text: string): GroupFile | null;
39
+ /** The same CGP1 text without `message.file.data_base64`: what gets stored
40
+ * when the bytes could not be saved, so messages.json never holds megabytes
41
+ * of base64. Returns the input unchanged when it is not a CGP1 file. */
42
+ export declare function withoutFileData(text: string): string;
43
+ /** Does a stored CGP1 description describe this same file (same group, same
44
+ * name, same post time)? Used to replace the "not delivered" card when the
45
+ * bytes arrive later for the same message. */
46
+ export declare function sameGroupFile(storedText: string, f: GroupFile): boolean;