freertc 0.5.2 → 0.5.3

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.
package/README.md CHANGED
@@ -191,6 +191,27 @@ Worker without running `freertc name`. A Worker with `NAMES_OPEN=1` names any
191
191
  relay (a public naming service). The Worker side is `src/direct/names.js`; the
192
192
  relay side `src/node/relay-name.js`; the command `scripts/name-setup.mjs`.
193
193
 
194
+ ### Your relay in the PeerPigeon console
195
+
196
+ [console.peerpigeon.io](https://console.peerpigeon.io) lists the relays you run.
197
+ Sign in there, copy your account key from Relays → Add, and on the relay's
198
+ machine run:
199
+
200
+ ```bash
201
+ npx freertc claim <account key>
202
+ ```
203
+
204
+ For a FreeRTC Worker, name it instead: `npx freertc claim <account key> --worker <name>`
205
+ (it sets the Worker's `RELAY_OWNER` secret with wrangler).
206
+ `npx freertc claim --remove` undoes it.
207
+
208
+ The relay then answers `GET /api/v1/owner?nonce=<16-64 characters>` with its
209
+ owner, signed by the relay's own key for that nonce, so the console can tell the
210
+ relay names you now. A Node relay also lets its owner read `/api/v1/stats` from
211
+ anywhere, by a request the owner signs (`?at=<ms>&sig=<signature>`); the account
212
+ numbers are left out. The relay keeps nothing about the owner but the key, in
213
+ `owner.json` in its data folder. The code is in `src/relay-owner.js`.
214
+
194
215
  ## Kademlia relay overlay
195
216
 
196
217
  FreeRTC uses Kademlia between federated relays—not between browser peers. Relay IDs, scope keys, and exact-peer keys are deterministic 256-bit SHA-256 values produced by UnSEA. Relay and provider records are signed with stable UnSEA P-256 identities before they are accepted or replicated.
package/bin/freertc.mjs CHANGED
@@ -24,6 +24,8 @@ Usage:
24
24
  freertc dev (a relay on this machine: ws://127.0.0.1:8788/ws)
25
25
  freertc dev:cf [-- <dev-args>]
26
26
  freertc name [--domain example.com] [--worker <name>]
27
+ freertc claim <account key> [--worker <name>] (the relay is yours, in console.peerpigeon.io)
28
+ freertc claim --remove [--worker <name>]
27
29
 
28
30
  Examples:
29
31
  npx freertc
@@ -109,6 +111,10 @@ if (subcommand === 'name') {
109
111
  runInProject(process.execPath, [path.join(PACKAGE_ROOT, 'scripts', 'name-setup.mjs'), ...rest]);
110
112
  }
111
113
 
114
+ if (subcommand === 'claim') {
115
+ runInProject(process.execPath, [path.join(PACKAGE_ROOT, 'scripts', 'claim.mjs'), ...rest]);
116
+ }
117
+
112
118
  if (subcommand === 'dev') {
113
119
  // A relay on this machine (Node). It runs from the package's own files, so nothing is copied into the
114
120
  // folder it is started from (the Worker's files are for deploy and dev:cf).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "freertc",
3
- "version": "0.5.2",
3
+ "version": "0.5.3",
4
4
  "description": "WebRTC browser client and Cloudflare Worker signaling relay with D1 storage.",
5
5
  "keywords": [
6
6
  "webrtc",
@@ -37,6 +37,7 @@
37
37
  "scripts/d1-schema.sql",
38
38
  "scripts/deploy-cloudflare.mjs",
39
39
  "scripts/name-setup.mjs",
40
+ "scripts/claim.mjs",
40
41
  "scripts/dev-server.mjs",
41
42
  "scripts/generate-relay-identity.mjs",
42
43
  "scripts/project-bootstrap.mjs",
@@ -48,6 +49,7 @@
48
49
  "src/relay-fetch.js",
49
50
  "src/relay-identity.js",
50
51
  "src/relay-overlay.js",
52
+ "src/relay-owner.js",
51
53
  "wrangler.template.jsonc",
52
54
  "wrangler.workers-dev.jsonc",
53
55
  "scripts/node-relay.mjs",
@@ -0,0 +1,61 @@
1
+ #!/usr/bin/env node
2
+ // npx freertc claim <account key> this machine's relay is yours
3
+ // npx freertc claim <account key> --worker <n> your FreeRTC Worker <n> is yours (a Worker secret)
4
+ // npx freertc claim --remove [--worker <n>] nobody's
5
+ //
6
+ // The key is your PigeonIdP account's signing key, shown on console.peerpigeon.io
7
+ // under Relays → Add. The relay then answers GET /api/v1/owner with it, signed
8
+ // by the relay (src/relay-owner.js), and the console lists the relay as yours.
9
+ // A running Node relay picks it up at once; a Worker takes it with its next request.
10
+ import { spawnSync } from 'node:child_process';
11
+ import { existsSync, mkdirSync, readFileSync } from 'node:fs';
12
+ import path from 'node:path';
13
+ import { resolveDataDir } from '../src/node/data-dir.js';
14
+ import { removeOwnerFile, writeOwnerFile } from '../src/node/owner-file.js';
15
+ import { createRelayIdentity, decodeRelayIdentitySecret } from '../src/relay-identity.js';
16
+ import { isOwnerKey } from '../src/relay-owner.js';
17
+
18
+ const say = (line) => console.log(`[freertc claim] ${line}`);
19
+ const args = process.argv.slice(2);
20
+ const remove = args.includes('--remove');
21
+ const workerAt = args.indexOf('--worker');
22
+ const worker = workerAt >= 0 ? args[workerAt + 1] : null;
23
+ const key = args.find((a, i) => !a.startsWith('--') && (workerAt < 0 || i !== workerAt + 1));
24
+
25
+ if (workerAt >= 0 && !worker) {
26
+ say('--worker needs the Worker\'s name (as in its wrangler.jsonc).');
27
+ process.exit(1);
28
+ }
29
+ if (!remove && !isOwnerKey(key)) {
30
+ say('Give the account key the console shows (Relays → Add): npx freertc claim <key>');
31
+ process.exit(1);
32
+ }
33
+
34
+ if (worker) {
35
+ const wrangler = (secretArgs, input) => spawnSync('npx', ['wrangler', 'secret', ...secretArgs, '--name', worker], { input, stdio: [input === undefined ? 'inherit' : 'pipe', 'inherit', 'inherit'] });
36
+ const result = remove ? wrangler(['delete', 'RELAY_OWNER']) : wrangler(['put', 'RELAY_OWNER'], `${key}\n`);
37
+ if (result.status !== 0) {
38
+ say(`wrangler could not ${remove ? 'remove' : 'set'} the Worker's RELAY_OWNER secret.`);
39
+ process.exit(result.status ?? 1);
40
+ }
41
+ say(remove ? `${worker} has no owner now.` : `${worker} is yours. Back in the console, press Check.`);
42
+ process.exit(0);
43
+ }
44
+
45
+ const dataDir = resolveDataDir({ log: say });
46
+ if (remove) {
47
+ say(removeOwnerFile(dataDir) ? 'This relay has no owner now.' : 'This relay had no owner.');
48
+ process.exit(0);
49
+ }
50
+ mkdirSync(dataDir, { recursive: true });
51
+ writeOwnerFile(dataDir, key);
52
+ let nodeId = null;
53
+ try {
54
+ const file = path.join(dataDir, 'relay-identity.json');
55
+ if (existsSync(file)) {
56
+ const { publicKey, privateKey } = decodeRelayIdentitySecret(readFileSync(file, 'utf8').trim());
57
+ ({ nodeId } = await createRelayIdentity(publicKey, privateKey));
58
+ }
59
+ } catch { /* shown without it */ }
60
+ say(`This relay${nodeId ? ` (${nodeId.slice(0, 16)}…)` : ''} is yours (${path.join(dataDir, 'owner.json')}).`);
61
+ say(nodeId ? 'Back in the console, press Check.' : 'Start it (npx freertc dev), then press Check in the console.');
@@ -83,6 +83,8 @@ import { createRelayIdentity, createSignedNodeRecord, decodeRelayIdentitySecret,
83
83
  import { heartbeatKademlia, isPublicRelay, listKnownRelays, relayReachOf } from '../src/relay-overlay.js';
84
84
  import { RelayTunnel } from '../src/tunnel/home.js';
85
85
  import { loadNameSettings } from '../src/node/relay-name.js';
86
+ import { readOwnerFile } from '../src/node/owner-file.js';
87
+ import { ownerAsked } from '../src/relay-owner.js';
86
88
 
87
89
  // The relay runs as a child of this process, which restarts it when the
88
90
  // machine moves to another network (exit code NETWORK_CHANGED_EXIT): a new
@@ -251,6 +253,10 @@ const env = {
251
253
  KADEMLIA_BOOTSTRAP_URLS: federating ? bootstrap.join(',') : '',
252
254
  // Without an identity the worker code runs no overlay at all: that is what off means.
253
255
  ...(federating ? { RELAY_IDENTITY_SECRET: await relayIdentitySecret() } : {}),
256
+ // Who runs this relay (src/relay-owner.js): the key `freertc claim` wrote, read on each ask so a claim
257
+ // needs no restart. The relay answers for it with its identity even when federation is off.
258
+ OWNER_IDENTITY_SECRET: await relayIdentitySecret(),
259
+ RELAY_OWNER: () => process.env.FREERTC_OWNER || readOwnerFile(DATA_DIR),
254
260
  ASSETS,
255
261
  };
256
262
  // Any Node relay can be a tunnel home for relays behind NAT, as a worker can.
@@ -400,6 +406,14 @@ const handler = async (req, res) => {
400
406
  return;
401
407
  }
402
408
  if ((pathname === '/stats' || pathname === '/api/v1/stats') && req.method === 'GET' && STATS_MODE !== 'off') {
409
+ // The relay's owner, signed in to console.peerpigeon.io, reads the numbers from anywhere (src/relay-owner.js).
410
+ const query = new URL(req.url, 'http://relay').searchParams;
411
+ const byOwner = pathname === '/api/v1/stats' && query.has('sig') && await ownerAsked(env, query.get('at'), query.get('sig'));
412
+ if (byOwner) {
413
+ res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store', 'Access-Control-Allow-Origin': '*' });
414
+ res.end(JSON.stringify(statsFor(stats.snapshot(), null)));
415
+ return;
416
+ }
403
417
  if (!statsAllowed({ mode: STATS_MODE, address: req.socket?.remoteAddress, encrypted: req.socket?.encrypted, host: req.headers.host, name: relayName?.name })) {
404
418
  res.writeHead(404, { 'Content-Type': 'text/plain' });
405
419
  res.end('Not found');
package/src/index.js CHANGED
@@ -15,6 +15,7 @@ import {
15
15
  relayNodeIdOf,
16
16
  } from "./relay-overlay.js";
17
17
  import { relayPeerIdFor } from "./relay-id.js";
18
+ import { ownerProof } from "./relay-owner.js";
18
19
  import { tunnelRoute } from "./tunnel/frames.js";
19
20
  import { DIRECTORY_PATH, directoryEnabled, handleDirectoryRequest } from "./direct/directory.js";
20
21
  import { NAMES_PATH, handleNameRequest } from "./direct/names.js";
@@ -36,7 +37,7 @@ function relayLog(what, line) {
36
37
  export { RelayTunnel } from "./tunnel/home.js";
37
38
 
38
39
  const PSP_VERSION = "1.0";
39
- const WORKER_VERSION = "0.5.2";
40
+ const WORKER_VERSION = "0.5.3";
40
41
 
41
42
  const DISCOVERY_TYPES = new Set(["announce", "withdraw", "discover", "peer_list", "redirect"]);
42
43
  const NEGOTIATION_TYPES = new Set(["connect_request", "connect_accept", "connect_reject", "offer", "answer", "ice_candidate", "ice_end", "renegotiate"]);
@@ -669,6 +670,13 @@ async function handleFetch(request, env, ctx) {
669
670
  }, 200);
670
671
  }
671
672
 
673
+ // Who runs this relay (src/relay-owner.js), signed by the relay for the asker's nonce.
674
+ if (url.pathname === "/api/v1/owner") {
675
+ if (request.method !== "GET") return jsonResponse({ ok: false, error: "Method not allowed" }, 405);
676
+ const { status, body } = await ownerProof(env, url.searchParams.get("nonce"));
677
+ return jsonResponse(body, status);
678
+ }
679
+
672
680
  if (url.pathname.startsWith("/api/v1/kad/")) {
673
681
  return handleKademliaRequest(request, env, {
674
682
  selfUrl: selfRelayUrl,
@@ -0,0 +1,28 @@
1
+ // A Node relay's owner (src/relay-owner.js), kept in <data dir>/owner.json:
2
+ // { "v": 1, "owner": "<account signing key>", "at": <ms> }.
3
+ import { existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
4
+ import path from 'node:path';
5
+ import { isOwnerKey } from '../relay-owner.js';
6
+
7
+ const FILE = 'owner.json';
8
+
9
+ export function readOwnerFile(dataDir) {
10
+ try {
11
+ const parsed = JSON.parse(readFileSync(path.join(dataDir, FILE), 'utf8'));
12
+ return isOwnerKey(parsed?.owner) ? parsed.owner : null;
13
+ } catch {
14
+ return null;
15
+ }
16
+ }
17
+
18
+ export function writeOwnerFile(dataDir, owner, now = Date.now()) {
19
+ if (!isOwnerKey(owner)) throw new TypeError('not an account key');
20
+ writeFileSync(path.join(dataDir, FILE), `${JSON.stringify({ v: 1, owner, at: now }, null, 2)}\n`, { mode: 0o600 });
21
+ }
22
+
23
+ export function removeOwnerFile(dataDir) {
24
+ const file = path.join(dataDir, FILE);
25
+ if (!existsSync(file)) return false;
26
+ rmSync(file);
27
+ return true;
28
+ }
@@ -0,0 +1,88 @@
1
+ // Who runs this relay, for the PeerPigeon console (console.peerpigeon.io).
2
+ //
3
+ // An owner is the signing key of a PigeonIdP account. Whoever controls the
4
+ // relay names it: `npx freertc claim <key>` writes it to the relay's data
5
+ // folder (<data dir>/owner.json), and a Worker takes it from its RELAY_OWNER
6
+ // secret. Anyone can then ask the relay who owns it:
7
+ //
8
+ // GET /api/v1/owner?nonce=<16-64 characters>
9
+ // -> { ok, node_id, relay_pub, owner, nonce, signature }
10
+ //
11
+ // The relay signs [ 'freertc-owner', 1, node_id, owner, nonce ] with its own
12
+ // signing key, so the answer proves the relay with that node id names that
13
+ // owner now: a stale answer cannot be replayed (the asker picks the nonce), and
14
+ // nobody but the relay's operator can change the owner. The relay keeps no
15
+ // account, password or anything else about the owner: just the key it was told.
16
+ import { signMessage, verifyMessage } from 'unsea';
17
+ import { canonicalJson, relayNodeId } from './kademlia.js';
18
+ import { createRelayIdentity, decodeRelayIdentitySecret } from './relay-identity.js';
19
+
20
+ const NONCE_RE = /^[\w-]{16,64}$/;
21
+ // An unsea public key: base64url halves joined by a dot (P-256 x.y).
22
+ const OWNER_RE = /^[\w-]{20,100}\.[\w-]{20,100}$/;
23
+
24
+ export const isOwnerKey = (value) => typeof value === 'string' && OWNER_RE.test(value);
25
+ export const ownerText = (nodeId, owner, nonce) => canonicalJson(['freertc-owner', 1, nodeId, owner, nonce]);
26
+
27
+ const identities = new WeakMap();
28
+
29
+ async function identityOf(env) {
30
+ const secret = env?.RELAY_IDENTITY_SECRET || env?.OWNER_IDENTITY_SECRET;
31
+ const keys = secret
32
+ ? decodeRelayIdentitySecret(secret)
33
+ : env?.RELAY_SIGNING_PUBLIC_KEY && env?.RELAY_SIGNING_PRIVATE_KEY
34
+ ? { publicKey: env.RELAY_SIGNING_PUBLIC_KEY, privateKey: env.RELAY_SIGNING_PRIVATE_KEY }
35
+ : null;
36
+ if (!keys) return null;
37
+ if (!identities.has(env)) identities.set(env, createRelayIdentity(keys.publicKey, keys.privateKey));
38
+ return identities.get(env);
39
+ }
40
+
41
+ /** The owner this relay was told, or null. RELAY_OWNER is a key, or (a Node relay) a function reading one. */
42
+ export async function configuredOwner(env) {
43
+ const value = typeof env?.RELAY_OWNER === 'function' ? await env.RELAY_OWNER() : env?.RELAY_OWNER;
44
+ const owner = typeof value === 'string' ? value.trim() : '';
45
+ return isOwnerKey(owner) ? owner : null;
46
+ }
47
+
48
+ /** The answer to GET /api/v1/owner. */
49
+ export async function ownerProof(env, nonce) {
50
+ if (typeof nonce !== 'string' || !NONCE_RE.test(nonce)) return { status: 400, body: { ok: false, error: 'nonce: 16 to 64 letters, digits, - or _' } };
51
+ let identity = null;
52
+ try { identity = await identityOf(env); } catch { identity = null; }
53
+ if (!identity) return { status: 200, body: { ok: false, error: 'no identity' } };
54
+ const owner = await configuredOwner(env);
55
+ if (!owner) return { status: 200, body: { ok: true, node_id: identity.nodeId, owner: null } };
56
+ const signature = await signMessage(ownerText(identity.nodeId, owner, nonce), identity.privateKey);
57
+ return { status: 200, body: { ok: true, node_id: identity.nodeId, relay_pub: identity.publicKey, owner, nonce, signature } };
58
+ }
59
+
60
+ /**
61
+ * Whether an answer proves that the relay with `nodeId` names `owner`, for the nonce the asker sent.
62
+ * Used by the console; here so both sides share one definition.
63
+ */
64
+ export async function verifyOwnerProof(proof, { nonce, nodeId, owner }) {
65
+ if (!proof?.ok || proof.nonce !== nonce || proof.owner !== owner || !isOwnerKey(owner)) return false;
66
+ if (typeof proof.relay_pub !== 'string' || typeof proof.signature !== 'string') return false;
67
+ if (await relayNodeId(proof.relay_pub) !== proof.node_id) return false;
68
+ if (nodeId && proof.node_id !== nodeId) return false;
69
+ try { return await verifyMessage(ownerText(proof.node_id, owner, nonce), proof.signature, proof.relay_pub); } catch { return false; }
70
+ }
71
+
72
+ /**
73
+ * What an owner signs to read the relay's numbers from elsewhere (GET /api/v1/stats?at=<ms>&sig=<sig>, a
74
+ * Node relay): good for this relay only, for five minutes.
75
+ */
76
+ export const ownerStatsText = (nodeId, at) => canonicalJson(['freertc-owner-stats', 1, nodeId, at]);
77
+ const OWNER_ASK_SKEW_MS = 5 * 60_000;
78
+
79
+ /** Whether `sig` is this relay's owner asking, at `at` (ms), recently. */
80
+ export async function ownerAsked(env, at, sig, now = Date.now()) {
81
+ const when = Number(at);
82
+ if (!Number.isFinite(when) || Math.abs(now - when) > OWNER_ASK_SKEW_MS || typeof sig !== 'string' || sig.length > 4096) return false;
83
+ const owner = await configuredOwner(env);
84
+ let identity = null;
85
+ try { identity = await identityOf(env); } catch { identity = null; }
86
+ if (!owner || !identity) return false;
87
+ try { return await verifyMessage(ownerStatsText(identity.nodeId, when), sig, owner); } catch { return false; }
88
+ }