@decentnetwork/beagle 0.1.148 → 0.1.153

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,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
+ };
@@ -0,0 +1,118 @@
1
+ // Short-term TURN credentials from the RSP node for this app's calls
2
+ // (decent-hq, 2026-11-25; @decentnetwork/peer-webrtc 0.3.3 RspTurnCredentials,
3
+ // RSP-TURN/1 = webrtc-signaling-node docs/PROTOCOL.md §10, rsp-v0.3.4).
4
+ //
5
+ // The node mints a credential for THIS Carrier identity, valid 4 h, instead of
6
+ // every client sharing one static coturn password. The proof is the same one
7
+ // the RSP/2 call bridge makes (lan's src/carrier/rsp-profile.ts):
8
+ // carrierSigner over x25519 with the node key + HMAC-SHA256, from the Carrier
9
+ // key file Peer already created. The secret is read only while proving and
10
+ // wiped afterwards; this module never creates or replaces the identity.
11
+ //
12
+ // The credential lives in memory only (RspTurnCredentials' cache). It is never
13
+ // logged or written anywhere: log lines carry the reason only.
14
+ import { readFileSync } from "node:fs";
15
+ import { base58ToBytes, carrierIdFromPublicKey, createCarrierRendezvousAuthProof } from "@decentnetwork/peer";
16
+ import { RspTurnCredentials } from "@decentnetwork/peer-webrtc";
17
+ import { carrierSigner } from "@decentnetwork/peer-webrtc/rsp";
18
+ export const RSP_TURN_NODE_DEFAULT = "https://rsp.beagle.chat";
19
+ function readKey(keyFile) {
20
+ return JSON.parse(readFileSync(keyFile, "utf-8"));
21
+ }
22
+ /** The RSP/2 bridge's signer for the identity in `keyFile` (lan rsp-profile.ts). */
23
+ export function rspCarrierSigner(keyFile) {
24
+ const key = readKey(keyFile);
25
+ if (key.format !== "decent-peer-tox-keypair-v1" || !/^[a-fA-F0-9]{64}$/.test(key.publicKey ?? "")) {
26
+ throw new Error("unsupported Carrier key file");
27
+ }
28
+ const publicKey = key.publicKey;
29
+ const userid = carrierIdFromPublicKey(Buffer.from(publicKey, "hex"));
30
+ const prove = (serverPublicKey, transcript) => {
31
+ const stored = readKey(keyFile);
32
+ if (stored.publicKey !== publicKey || stored.format !== key.format || !/^[a-fA-F0-9]{64}$/.test(stored.secretKey ?? "")) {
33
+ throw new Error("Carrier identity changed");
34
+ }
35
+ const secret = Buffer.from(stored.secretKey, "hex");
36
+ try {
37
+ return createCarrierRendezvousAuthProof(secret, base58ToBytes(serverPublicKey), transcript);
38
+ }
39
+ finally {
40
+ secret.fill(0);
41
+ }
42
+ };
43
+ return { userid, signer: carrierSigner({ userid, createProof: (a) => prove(a.serverPublicKey, a.transcript) }) };
44
+ }
45
+ /** Only the TURN entries of an ICE list (STUN stays in the call's iceServers). */
46
+ export function turnOnly(list) {
47
+ const isTurn = (u) => /^turns?:/i.test(u);
48
+ const out = [];
49
+ for (const e of list || []) {
50
+ const urls = (Array.isArray(e.urls) ? e.urls : [e.urls]).filter((u) => typeof u === "string" && isTurn(u));
51
+ if (urls.length)
52
+ out.push({ ...e, urls: Array.isArray(e.urls) ? urls : urls[0] });
53
+ }
54
+ return out;
55
+ }
56
+ /**
57
+ * TURN entries for a call about to start: the RSP credential (cached while
58
+ * valid for 10 more minutes), else `fallback()`. Never rejects. `source` says
59
+ * which, for the UI's diagnostics — never the credential itself.
60
+ */
61
+ export function createCallTurnSource(opts) {
62
+ const nodeUrl = (opts.nodeUrl || process.env.BEAGLE_RSP_NODE_URL || RSP_TURN_NODE_DEFAULT).replace(/\/+$/, "");
63
+ const log = opts.log ?? (() => { });
64
+ let rsp = null;
65
+ let setupError = "";
66
+ try {
67
+ const { signer } = rspCarrierSigner(opts.keyFile);
68
+ // No library fallback: ours is computed per call (Carrier TURN is minted
69
+ // too), and an empty answer is how we know the node did not mint.
70
+ rsp = new RspTurnCredentials({
71
+ nodeUrl,
72
+ signer,
73
+ fallback: [],
74
+ log: (m) => log(`[rsp-turn] ${m}`),
75
+ ...(opts.fetch ? { fetch: opts.fetch } : {}),
76
+ });
77
+ }
78
+ catch (e) {
79
+ setupError = e.message;
80
+ log(`[rsp-turn] disabled: ${setupError}`);
81
+ }
82
+ // Say once per switch which TURN calls use. RspTurnCredentials' own line
83
+ // reads "no fallback configured" because ours is applied here instead.
84
+ let lastSource = "";
85
+ const note = (source, count) => {
86
+ if (source === lastSource)
87
+ return;
88
+ lastSource = source;
89
+ log(source === "rsp"
90
+ ? `[rsp-turn] calls use the RSP node's TURN credential (${nodeUrl})`
91
+ : `[rsp-turn] calls use today's Carrier bootstrap TURN (${count} entr${count === 1 ? "y" : "ies"})`);
92
+ };
93
+ return {
94
+ async iceServers() {
95
+ if (rsp) {
96
+ try {
97
+ const minted = turnOnly((await rsp.iceServers()));
98
+ if (minted.length) {
99
+ note("rsp", minted.length);
100
+ return { source: "rsp", iceServers: minted };
101
+ }
102
+ }
103
+ catch {
104
+ /* RspTurnCredentials never rejects; belt and braces */
105
+ }
106
+ }
107
+ try {
108
+ const list = turnOnly(await opts.fallback());
109
+ note("fallback", list.length);
110
+ return { source: "fallback", iceServers: list };
111
+ }
112
+ catch {
113
+ note("fallback", 0);
114
+ return { source: "fallback", iceServers: [] };
115
+ }
116
+ },
117
+ };
118
+ }
package/dist/server.d.ts CHANGED
@@ -86,4 +86,5 @@ export interface BeagleServerOptions {
86
86
  }
87
87
  export declare function startBeagleServer(opts: BeagleServerOptions): {
88
88
  stop: () => void;
89
+ ready: Promise<number>;
89
90
  };
package/dist/server.js CHANGED
@@ -279,6 +279,8 @@ async function ensPublicByUserid(maxWaitMs = 300) {
279
279
  const UPDATE_TTL_MS = 6 * 3600_000;
280
280
  const BEAGLE_PKG = "@decentnetwork/beagle";
281
281
  let updateCache = null;
282
+ /** The call TURN source (rsp-turn.ts), made on first use; holds the RSP credential in memory. */
283
+ let callTurn = null;
282
284
  const BEAGLE_ROOT = join(dirname(fileURLToPath(import.meta.url)), "..");
283
285
  function beagleVersion() {
284
286
  try {
@@ -2248,6 +2250,16 @@ export function startBeagleServer(opts) {
2248
2250
  // The client they advertised with their profile, for the UI.
2249
2251
  platform: f.platform ?? stamp?.platform ?? null,
2250
2252
  appVersion: f.appVersion ?? stamp?.appVersion ?? null,
2253
+ // The rest of their pushed profile, for the friend card (what the
2254
+ // phone apps show). From the SDK's store: the daemon's
2255
+ // friends-list does not carry these.
2256
+ osVersion: f.osVersion ?? stamp?.osVersion ?? null,
2257
+ description: f.description || f.descr || stamp?.description || null,
2258
+ profileUrl: stamp?.profileUrl ?? null,
2259
+ ensClaim: stamp?.ens ?? null,
2260
+ pushedAvatarUrl: stamp?.avatarUrl ?? null,
2261
+ rspProtocol: stamp?.rspProtocol ?? null,
2262
+ lastSessionAt: stamp?.sessionAt ?? null,
2251
2263
  };
2252
2264
  });
2253
2265
  const pend = pending.ok ? (pending.data?.pending ?? []) : [];
@@ -2601,8 +2613,8 @@ export function startBeagleServer(opts) {
2601
2613
  return;
2602
2614
  }
2603
2615
  // WebRTC call signaling (peer-webrtc). The browser CallEngine sends
2604
- // RtcSignals here and long-polls call-poll for inbound ones; the daemon
2605
- // relays both over the Carrier "carrier" invite extension.
2616
+ // RtcSignals here and polls for inbound ones. The daemon chooses the
2617
+ // transport and supplies ring-first events from RSP and the doorbell.
2606
2618
  if (req.method === "POST" && url === "/api/call-signal") {
2607
2619
  const { userid, data, page } = await readBody(req);
2608
2620
  // First claim wins: another page's answer / accept / decline for a
@@ -2646,6 +2658,35 @@ export function startBeagleServer(opts) {
2646
2658
  }
2647
2659
  return;
2648
2660
  }
2661
+ // TURN for a call about to start (peer-webrtc 0.3.3 CallEngineOptions
2662
+ // .turnServers): a short-term credential the RSP node mints for this
2663
+ // identity, else today's Carrier bootstrap TURN. The credential is
2664
+ // handed to this machine's own page only and never logged or stored
2665
+ // (rsp-turn.ts). STUN stays in the call's iceServers.
2666
+ if (req.method === "GET" && url === "/api/call-turn-servers") {
2667
+ if (!opts.callIce) {
2668
+ sendJson(res, 503, { ok: false, error: "call ICE not configured" });
2669
+ return;
2670
+ }
2671
+ if (!callTurn) {
2672
+ const { createCallTurnSource } = await import("./rsp-turn.js");
2673
+ const { buildCarrierCallIceServers } = await import("./call-ice.js");
2674
+ const callIce = opts.callIce;
2675
+ callTurn = createCallTurnSource({
2676
+ keyFile: callIce.keyFile,
2677
+ fallback: () => buildCarrierCallIceServers(callIce),
2678
+ log: (m) => console.log(m),
2679
+ });
2680
+ }
2681
+ // The identity's own credential goes only to a page on this machine;
2682
+ // anything else gets today's Carrier TURN, as /api/call-ice-servers gives it.
2683
+ const r = isLocalRequest(req)
2684
+ ? await callTurn.iceServers()
2685
+ : { source: "fallback", iceServers: (await import("./rsp-turn.js")).turnOnly(await (await import("./call-ice.js")).buildCarrierCallIceServers(opts.callIce).catch(() => [])) };
2686
+ res.setHeader("cache-control", "no-store");
2687
+ sendJson(res, 200, { ok: true, source: r.source, iceServers: r.iceServers });
2688
+ return;
2689
+ }
2649
2690
  if (req.method === "GET" && url === "/api/call-poll") {
2650
2691
  // The daemon holds this up to ~20s (long-poll). opts.call's own IPC
2651
2692
  // timeout is 30s, so it returns before that; on any error, resolve
@@ -2923,27 +2964,35 @@ export function startBeagleServer(opts) {
2923
2964
  log(`Could not start the web server: ${err.message}`);
2924
2965
  process.exit(1);
2925
2966
  });
2967
+ // `ready` resolves with the bound port. listenPort 0 asks the OS for a free
2968
+ // one (tests), and the ::1 listener then takes that same port.
2969
+ let resolveReady = () => undefined;
2970
+ const ready = new Promise((r) => { resolveReady = r; });
2926
2971
  server.listen(port, host === "localhost" ? "127.0.0.1" : host, () => {
2927
- log(`Beagle UI on http://${isLoopback ? "localhost" : host}:${port}`);
2972
+ const addr = server.address();
2973
+ const bound = addr && typeof addr === "object" ? addr.port : port;
2974
+ log(`Beagle UI on http://${isLoopback ? "localhost" : host}:${bound}`);
2975
+ if (isLoopback) {
2976
+ // Second server object on ::1: Node can't bind one listener to two
2977
+ // specific addresses, and binding :: instead would expose the UI on every
2978
+ // interface — the opposite of what a loopback default promises.
2979
+ v6 = http.createServer(handler);
2980
+ v6.on("error", (err) => {
2981
+ // A host with IPv6 disabled gives EADDRNOTAVAIL/EAFNOSUPPORT; the IPv4
2982
+ // listener above is already serving, so this is not fatal.
2983
+ if (err.code !== "EADDRINUSE")
2984
+ log(`(IPv6 loopback unavailable: ${err.code ?? err.message} — IPv4 still serving)`);
2985
+ });
2986
+ v6.listen(bound, "::1");
2987
+ }
2988
+ resolveReady(bound);
2928
2989
  });
2929
- if (isLoopback) {
2930
- // Second server object on ::1: Node can't bind one listener to two
2931
- // specific addresses, and binding :: instead would expose the UI on every
2932
- // interface — the opposite of what a loopback default promises.
2933
- v6 = http.createServer(handler);
2934
- v6.on("error", (err) => {
2935
- // A host with IPv6 disabled gives EADDRNOTAVAIL/EAFNOSUPPORT; the IPv4
2936
- // listener above is already serving, so this is not fatal.
2937
- if (err.code !== "EADDRINUSE")
2938
- log(`(IPv6 loopback unavailable: ${err.code ?? err.message} — IPv4 still serving)`);
2939
- });
2940
- v6.listen(port, "::1");
2941
- }
2942
2990
  return {
2943
2991
  stop: () => {
2944
2992
  server.close();
2945
2993
  v6?.close();
2946
2994
  },
2995
+ ready,
2947
2996
  };
2948
2997
  }
2949
2998
  const PAGE = `<!doctype html>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@decentnetwork/beagle",
3
- "version": "0.1.148",
3
+ "version": "0.1.153",
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.50",
29
+ "@decentnetwork/beagle-ui": "^0.2.55",
30
30
  "@decentnetwork/chat-components": "^0.1.3",
31
31
  "@decentnetwork/lan": "^0.1.316",
32
32
  "@decentnetwork/peer": "^0.1.178",
33
- "@decentnetwork/peer-webrtc": "^0.2.21",
33
+ "@decentnetwork/peer-webrtc": "^0.3.3",
34
34
  "js-yaml": "^4.1.0",
35
35
  "ws": "^8.21.1",
36
36
  "yargs": "^17.7.2"