@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.
@@ -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/dist/server.d.ts CHANGED
@@ -43,6 +43,8 @@ export interface BeagleServerOptions {
43
43
  /** How an exit is probed. Default: a TCP handshake to its :8888. Tests
44
44
  * inject a counter here. */
45
45
  exitProbe?: ProbeFn;
46
+ /** Clock for the exit prober (tests). Default Date.now. */
47
+ exitNow?: () => number;
46
48
  /** The swappable backend, so the UI can show which one is live and drive the
47
49
  * LAN handoff. Optional: a caller that pins one backend just omits it and
48
50
  * the network panel falls back to "no virtual LAN here". */
package/dist/server.js CHANGED
@@ -974,7 +974,48 @@ export function startBeagleServer(opts) {
974
974
  const exitProber = new ExitProber({
975
975
  path: opts.exitStatePath ?? join(dirname(opts.routesPath), "beagle-exit-state.json"),
976
976
  probe: opts.exitProbe,
977
+ now: opts.exitNow,
977
978
  });
979
+ const readRoutes = () => {
980
+ const none = { regions: [], default: "direct" };
981
+ if (!existsSync(opts.routesPath))
982
+ return none;
983
+ try {
984
+ return yaml.load(readFileSync(opts.routesPath, "utf-8")) ?? none;
985
+ }
986
+ catch {
987
+ return none;
988
+ }
989
+ };
990
+ const knownExitIps = (routes) => {
991
+ const known = new Set(DEFAULT_EXITS.flatMap((e) => (e.virtual_ip ? [e.virtual_ip] : [])));
992
+ for (const r of routes.regions ?? [])
993
+ for (const ip of r.exits ?? [])
994
+ known.add(ip);
995
+ return known;
996
+ };
997
+ const routeTargetOf = (routes) => routes.default && routes.default !== "direct" ? routes.default : null;
998
+ /** Routing goes through an exit: probe that route's exits once (an access),
999
+ * never again on a timer. */
1000
+ const probeRoute = async (routes) => {
1001
+ const target = routeTargetOf(routes);
1002
+ if (!target)
1003
+ return;
1004
+ await exitProber.refresh(exitsForTarget(target, routes.regions ?? [], DEFAULT_EXITS, knownExitIps(routes)));
1005
+ };
1006
+ /** A fallback to direct whose exits work again goes back to its route. */
1007
+ const restoreFallback = (routes) => {
1008
+ const fb = exitProber.fallback;
1009
+ if (!fb)
1010
+ return null;
1011
+ const fbIps = exitsForTarget(fb.from, routes.regions ?? [], DEFAULT_EXITS, knownExitIps(routes));
1012
+ if (!fbIps.some((ip) => exitProber.view(ip).reachable))
1013
+ return null;
1014
+ exitProber.setFallback(null);
1015
+ return (routes.default ?? "direct") === "direct" && writeRoutesDefault(opts.routesPath, fb.from) ? fb.from : null;
1016
+ };
1017
+ // Daemon start with routing through an exit = one access.
1018
+ void probeRoute(readRoutes()).catch(() => undefined);
978
1019
  const sendJson = (res, code, body) => {
979
1020
  res.writeHead(code, { "content-type": "application/json" });
980
1021
  res.end(JSON.stringify(body));
@@ -2263,16 +2304,16 @@ export function startBeagleServer(opts) {
2263
2304
  // announcing on the DHT — it does NOT mean IP packets get through (a
2264
2305
  // desynced/NAT-blocked exit shows "online" while `ping 10.86.x` times out,
2265
2306
  // e.g. GFAX). The proof is a TCP handshake to the exit's CONNECT-proxy
2266
- // port — but see exit-probe.ts: probes are cached and backed off, a dead
2267
- // exit goes `failed` after three tries and is never probed again on its
2268
- // own, and nothing is probed at all unless the network panel is open
2269
- // (?exits=1) or routing actually goes through an exit.
2307
+ // port — but see exit-probe.ts: nothing is probed on a timer. Opening
2308
+ // the network panel is one probe round (?exits=1&open=1, or the first
2309
+ // ?exits=1 after a long gap); the panel staying open costs nothing; a
2310
+ // dead exit goes `failed` after three failed accesses and only
2311
+ // Reconnect / Refresh touch it again.
2270
2312
  const allNodes = [...byRegion.values()].flat();
2271
2313
  const allIps = allNodes.map((n) => n.ip);
2272
2314
  const qs = new URL(req.url || "", "http://localhost").searchParams;
2273
- const panelOpen = qs.get("exits") === "1";
2274
- const routeTarget = routes.default && routes.default !== "direct" ? routes.default : null;
2275
- if (panelOpen || routeTarget)
2315
+ const routeTarget = routeTargetOf(routes);
2316
+ if (qs.get("exits") === "1" && exitProber.panelPoll(qs.get("open") === "1"))
2276
2317
  await exitProber.refresh(allIps);
2277
2318
  const views = new Map(allIps.map((ip) => [ip, exitProber.view(ip)]));
2278
2319
  for (const n of allNodes) {
@@ -2655,34 +2696,24 @@ export function startBeagleServer(opts) {
2655
2696
  // dial arbitrary hosts. {all:true} = every failed exit.
2656
2697
  if (req.method === "POST" && url === "/api/exits/reconnect") {
2657
2698
  const body = (await readBody(req));
2658
- let routes = { regions: [], default: "direct" };
2659
- if (existsSync(opts.routesPath)) {
2660
- try {
2661
- routes = yaml.load(readFileSync(opts.routesPath, "utf-8")) ?? routes;
2662
- }
2663
- catch { /* keep direct */ }
2664
- }
2665
- const known = new Set(DEFAULT_EXITS.flatMap((e) => (e.virtual_ip ? [e.virtual_ip] : [])));
2666
- for (const r of routes.regions ?? [])
2667
- for (const ip of r.exits ?? [])
2668
- known.add(ip);
2699
+ const routes = readRoutes();
2700
+ const known = knownExitIps(routes);
2669
2701
  const targets = body.all
2670
2702
  ? [...known].filter((ip) => exitProber.isFailed(ip))
2671
2703
  : typeof body.ip === "string" && known.has(body.ip) ? [body.ip] : [];
2672
2704
  if (!body.all && !targets.length)
2673
2705
  return sendJson(res, 400, { ok: false, error: "unknown exit" });
2674
2706
  const results = await Promise.all(targets.map((ip) => exitProber.reconnect(ip)));
2675
- // Routing that fell back to direct goes back once one of its exits works.
2676
- const fb = exitProber.fallback;
2677
- let restored = null;
2678
- if (fb) {
2679
- const fbIps = exitsForTarget(fb.from, routes.regions ?? [], DEFAULT_EXITS, known);
2680
- if (fbIps.some((ip) => exitProber.view(ip).reachable)) {
2681
- if ((routes.default ?? "direct") === "direct" && writeRoutesDefault(opts.routesPath, fb.from))
2682
- restored = fb.from;
2683
- exitProber.setFallback(null);
2684
- }
2685
- }
2707
+ const restored = restoreFallback(routes);
2708
+ sendJson(res, 200, { ok: true, exits: results, restored, available: exitProber.usable([...known]) });
2709
+ return;
2710
+ }
2711
+ // The panel's Refresh: every known exit once, now — failed ones too.
2712
+ if (req.method === "POST" && url === "/api/exits/refresh") {
2713
+ const routes = readRoutes();
2714
+ const known = knownExitIps(routes);
2715
+ const results = await exitProber.refreshAll([...known]);
2716
+ const restored = restoreFallback(routes);
2686
2717
  sendJson(res, 200, { ok: true, exits: results, restored, available: exitProber.usable([...known]) });
2687
2718
  return;
2688
2719
  }
@@ -2709,7 +2740,11 @@ export function startBeagleServer(opts) {
2709
2740
  const body = await readBody(req);
2710
2741
  try {
2711
2742
  const routes = JSON.parse(body.routes ?? "{}");
2743
+ const before = routeTargetOf(readRoutes());
2712
2744
  writeFileSync(opts.routesPath, yaml.dump(routes, { lineWidth: -1 }), "utf-8");
2745
+ // Routing just set to go through an exit = one access of its exits.
2746
+ if (routeTargetOf(routes) && routeTargetOf(routes) !== before)
2747
+ void probeRoute(routes).catch(() => undefined);
2713
2748
  sendJson(res, 200, { ok: true });
2714
2749
  }
2715
2750
  catch (err) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@decentnetwork/beagle",
3
- "version": "0.1.129",
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.37",
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"