@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.
@@ -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 {
@@ -2601,8 +2603,8 @@ export function startBeagleServer(opts) {
2601
2603
  return;
2602
2604
  }
2603
2605
  // 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.
2606
+ // RtcSignals here and polls for inbound ones. The daemon chooses the
2607
+ // transport and supplies ring-first events from RSP and the doorbell.
2606
2608
  if (req.method === "POST" && url === "/api/call-signal") {
2607
2609
  const { userid, data, page } = await readBody(req);
2608
2610
  // First claim wins: another page's answer / accept / decline for a
@@ -2646,6 +2648,35 @@ export function startBeagleServer(opts) {
2646
2648
  }
2647
2649
  return;
2648
2650
  }
2651
+ // TURN for a call about to start (peer-webrtc 0.3.3 CallEngineOptions
2652
+ // .turnServers): a short-term credential the RSP node mints for this
2653
+ // identity, else today's Carrier bootstrap TURN. The credential is
2654
+ // handed to this machine's own page only and never logged or stored
2655
+ // (rsp-turn.ts). STUN stays in the call's iceServers.
2656
+ if (req.method === "GET" && url === "/api/call-turn-servers") {
2657
+ if (!opts.callIce) {
2658
+ sendJson(res, 503, { ok: false, error: "call ICE not configured" });
2659
+ return;
2660
+ }
2661
+ if (!callTurn) {
2662
+ const { createCallTurnSource } = await import("./rsp-turn.js");
2663
+ const { buildCarrierCallIceServers } = await import("./call-ice.js");
2664
+ const callIce = opts.callIce;
2665
+ callTurn = createCallTurnSource({
2666
+ keyFile: callIce.keyFile,
2667
+ fallback: () => buildCarrierCallIceServers(callIce),
2668
+ log: (m) => console.log(m),
2669
+ });
2670
+ }
2671
+ // The identity's own credential goes only to a page on this machine;
2672
+ // anything else gets today's Carrier TURN, as /api/call-ice-servers gives it.
2673
+ const r = isLocalRequest(req)
2674
+ ? await callTurn.iceServers()
2675
+ : { source: "fallback", iceServers: (await import("./rsp-turn.js")).turnOnly(await (await import("./call-ice.js")).buildCarrierCallIceServers(opts.callIce).catch(() => [])) };
2676
+ res.setHeader("cache-control", "no-store");
2677
+ sendJson(res, 200, { ok: true, source: r.source, iceServers: r.iceServers });
2678
+ return;
2679
+ }
2649
2680
  if (req.method === "GET" && url === "/api/call-poll") {
2650
2681
  // The daemon holds this up to ~20s (long-poll). opts.call's own IPC
2651
2682
  // timeout is 30s, so it returns before that; on any error, resolve
@@ -2923,27 +2954,35 @@ export function startBeagleServer(opts) {
2923
2954
  log(`Could not start the web server: ${err.message}`);
2924
2955
  process.exit(1);
2925
2956
  });
2957
+ // `ready` resolves with the bound port. listenPort 0 asks the OS for a free
2958
+ // one (tests), and the ::1 listener then takes that same port.
2959
+ let resolveReady = () => undefined;
2960
+ const ready = new Promise((r) => { resolveReady = r; });
2926
2961
  server.listen(port, host === "localhost" ? "127.0.0.1" : host, () => {
2927
- log(`Beagle UI on http://${isLoopback ? "localhost" : host}:${port}`);
2962
+ const addr = server.address();
2963
+ const bound = addr && typeof addr === "object" ? addr.port : port;
2964
+ log(`Beagle UI on http://${isLoopback ? "localhost" : host}:${bound}`);
2965
+ if (isLoopback) {
2966
+ // Second server object on ::1: Node can't bind one listener to two
2967
+ // specific addresses, and binding :: instead would expose the UI on every
2968
+ // interface — the opposite of what a loopback default promises.
2969
+ v6 = http.createServer(handler);
2970
+ v6.on("error", (err) => {
2971
+ // A host with IPv6 disabled gives EADDRNOTAVAIL/EAFNOSUPPORT; the IPv4
2972
+ // listener above is already serving, so this is not fatal.
2973
+ if (err.code !== "EADDRINUSE")
2974
+ log(`(IPv6 loopback unavailable: ${err.code ?? err.message} — IPv4 still serving)`);
2975
+ });
2976
+ v6.listen(bound, "::1");
2977
+ }
2978
+ resolveReady(bound);
2928
2979
  });
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
2980
  return {
2943
2981
  stop: () => {
2944
2982
  server.close();
2945
2983
  v6?.close();
2946
2984
  },
2985
+ ready,
2947
2986
  };
2948
2987
  }
2949
2988
  const PAGE = `<!doctype html>
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@decentnetwork/beagle",
3
- "version": "0.1.147",
3
+ "version": "0.1.151",
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.49",
29
+ "@decentnetwork/beagle-ui": "^0.2.53",
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"