@decentnetwork/beagle 0.1.130 → 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);
@@ -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;
@@ -0,0 +1,92 @@
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
+ import { createHash } from "crypto";
16
+ const B64_RE = /^[A-Za-z0-9+/]*={0,2}$/;
17
+ const str = (v) => (typeof v === "string" && v ? v : undefined);
18
+ /** The group file in a CGP1 text, or null when the text is anything else.
19
+ * Never throws: a peer wrote it. */
20
+ export function parseGroupFile(text) {
21
+ const t = String(text ?? "").replace(/\0+$/u, "").trim();
22
+ if (!t.startsWith("CGP1 "))
23
+ return null;
24
+ let j;
25
+ try {
26
+ j = JSON.parse(t.slice(5));
27
+ }
28
+ catch {
29
+ return null;
30
+ }
31
+ if (!j || j.type !== "carrier_group_message" || j.chat_type !== "group")
32
+ return null;
33
+ const f = j.message?.file;
34
+ if (!f || typeof f !== "object")
35
+ return null;
36
+ const name = str(f.filename);
37
+ if (!name)
38
+ return null;
39
+ const declared = Number(f.size);
40
+ const out = {
41
+ group: { userid: str(j.group?.userid), address: str(j.group?.address), nickname: str(j.group?.nickname) },
42
+ origin: {
43
+ userid: str(j.origin?.userid) ?? str(j.origin?.friendid),
44
+ nickname: str(j.origin?.nickname) ?? str(j.origin?.user_info?.name),
45
+ },
46
+ name,
47
+ contentType: str(f.contentType) ?? "application/octet-stream",
48
+ size: Number.isFinite(declared) && declared >= 0 ? declared : 0,
49
+ timestampUs: typeof j.message?.timestamp === "number" ? j.message.timestamp : undefined,
50
+ };
51
+ const b64 = typeof f.data_base64 === "string" ? f.data_base64.replace(/\s+/g, "") : "";
52
+ if (b64 && b64.length % 4 === 0 && B64_RE.test(b64)) {
53
+ const data = Buffer.from(b64, "base64");
54
+ // A size mismatch means a truncated or damaged copy: keep the description.
55
+ if (data.length > 0 && (!out.size || data.length === out.size)) {
56
+ out.data = data;
57
+ out.size = data.length;
58
+ out.sha256 = createHash("sha256").update(data).digest("hex");
59
+ }
60
+ }
61
+ return out;
62
+ }
63
+ /** The same CGP1 text without `message.file.data_base64`: what gets stored
64
+ * when the bytes could not be saved, so messages.json never holds megabytes
65
+ * of base64. Returns the input unchanged when it is not a CGP1 file. */
66
+ export function withoutFileData(text) {
67
+ const t = String(text ?? "").replace(/\0+$/u, "").trim();
68
+ if (!t.startsWith("CGP1 "))
69
+ return text;
70
+ try {
71
+ const j = JSON.parse(t.slice(5));
72
+ if (j?.message?.file && "data_base64" in j.message.file) {
73
+ delete j.message.file.data_base64;
74
+ return "CGP1 " + JSON.stringify(j);
75
+ }
76
+ }
77
+ catch { /* not ours to fix */ }
78
+ return text;
79
+ }
80
+ /** Does a stored CGP1 description describe this same file (same group, same
81
+ * name, same post time)? Used to replace the "not delivered" card when the
82
+ * bytes arrive later for the same message. */
83
+ export function sameGroupFile(storedText, f) {
84
+ const d = parseGroupFile(storedText);
85
+ if (!d || d.name !== f.name)
86
+ return false;
87
+ if (d.group.userid && f.group.userid && d.group.userid !== f.group.userid)
88
+ return false;
89
+ if (d.timestampUs !== undefined && f.timestampUs !== undefined)
90
+ return d.timestampUs === f.timestampUs;
91
+ return d.size === f.size;
92
+ }
@@ -43,6 +43,13 @@ export interface ChatMessage {
43
43
  durationMs?: number;
44
44
  avgKbps?: number;
45
45
  kbps?: number;
46
+ sha256?: string;
47
+ };
48
+ /** The real sender of a file relayed by a group (the thread is the group's
49
+ * userid), from the CGP1 envelope (group-file.ts). */
50
+ origin?: {
51
+ userid?: string;
52
+ nickname?: string;
46
53
  };
47
54
  }
48
55
  export declare class MessageStore {
@@ -90,7 +97,13 @@ export declare class MessageStore {
90
97
  size: number;
91
98
  status?: "queued" | "sending" | "sent" | "failed" | "cancelled";
92
99
  sent?: number;
93
- }, ts?: number): ChatMessage;
100
+ sha256?: string;
101
+ }, ts?: number, extra?: {
102
+ origin?: ChatMessage["origin"];
103
+ via?: "online" | "offline";
104
+ }): ChatMessage;
105
+ /** True when this peer's thread already holds a file with these bytes. */
106
+ hasFileSha(peer: string, sha256: string): boolean;
94
107
  /** Patch an existing file message's transfer fields (status / sent bytes).
95
108
  * No-op if the id isn't found. Returns true if it patched. */
96
109
  patchFile(peer: string, id: string, patch: {
@@ -120,8 +120,17 @@ export class MessageStore {
120
120
  return arr.filter((m) => m.dir === "out" && (m.status === "queued" || m.file?.status === "queued"));
121
121
  }
122
122
  /** Append a file-transfer entry (shown as a file chip in the UI). */
123
- appendFile(peer, dir, file, ts = Date.now()) {
124
- return this.push(peer, { dir, text: "", ts, id: `${ts}-${this.seq++}`, file });
123
+ appendFile(peer, dir, file, ts = Date.now(), extra = {}) {
124
+ const msg = { dir, text: "", ts, id: `${ts}-${this.seq++}`, file };
125
+ if (extra.origin)
126
+ msg.origin = extra.origin;
127
+ if (extra.via)
128
+ msg.via = extra.via;
129
+ return this.push(peer, msg);
130
+ }
131
+ /** True when this peer's thread already holds a file with these bytes. */
132
+ hasFileSha(peer, sha256) {
133
+ return (this.history(peer)[peer] ?? []).some((m) => m.file?.sha256 === sha256);
125
134
  }
126
135
  /** Patch an existing file message's transfer fields (status / sent bytes).
127
136
  * No-op if the id isn't found. Returns true if it patched. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@decentnetwork/beagle",
3
- "version": "0.1.130",
3
+ "version": "0.1.131",
4
4
  "description": "Beagle — P2P chat, file transfer and calls for regular users, on the Decent Network. No admin privilege required.",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -26,11 +26,11 @@
26
26
  "start": "node dist/cli.js"
27
27
  },
28
28
  "dependencies": {
29
- "@decentnetwork/beagle-ui": "^0.2.38",
29
+ "@decentnetwork/beagle-ui": "^0.2.40",
30
30
  "@decentnetwork/chat-components": "^0.1.3",
31
- "@decentnetwork/lan": "^0.1.313",
32
- "@decentnetwork/peer": "^0.1.170",
33
- "@decentnetwork/peer-webrtc": "^0.2.17",
31
+ "@decentnetwork/lan": "^0.1.315",
32
+ "@decentnetwork/peer": "^0.1.172",
33
+ "@decentnetwork/peer-webrtc": "^0.2.18",
34
34
  "js-yaml": "^4.1.0",
35
35
  "ws": "^8.21.1",
36
36
  "yargs": "^17.7.2"