freertc 0.5.1 → 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
@@ -21,9 +21,11 @@ Usage:
21
21
  freertc install
22
22
  freertc relay:keygen
23
23
  freertc deploy [-- <deploy-args>]
24
- freertc dev [-- <dev-args>]
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,8 +111,14 @@ 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
- runInProject(process.execPath, [path.join(PACKAGE_ROOT, 'scripts', 'node-relay.mjs'), ...rest], { bootstrap: true });
119
+ // A relay on this machine (Node). It runs from the package's own files, so nothing is copied into the
120
+ // folder it is started from (the Worker's files are for deploy and dev:cf).
121
+ runInProject(process.execPath, [path.join(PACKAGE_ROOT, 'scripts', 'node-relay.mjs'), ...rest]);
114
122
  }
115
123
 
116
124
  if (subcommand === 'dev:cf' || subcommand === 'dev-cf') {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "freertc",
3
- "version": "0.5.1",
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",
package/public/app.js CHANGED
@@ -168,6 +168,13 @@ function normalizeText(value) {
168
168
 
169
169
  createApp({
170
170
  setup() {
171
+ // Light or dark (index.html picks it before the first paint; the switch in the top bar changes it).
172
+ const theme = ref(document.documentElement.dataset.theme === 'light' ? 'light' : 'dark');
173
+ const toggleTheme = () => {
174
+ theme.value = theme.value === 'dark' ? 'light' : 'dark';
175
+ document.documentElement.dataset.theme = theme.value;
176
+ try { localStorage.setItem('freertc:theme', theme.value); } catch (e) {}
177
+ };
171
178
  const host = window.location.host;
172
179
  const wsScheme = window.location.protocol === "https:" ? "wss" : "ws";
173
180
 
@@ -3168,7 +3175,9 @@ createApp({
3168
3175
  regenerateNetworkAndRoom,
3169
3176
  selectPeer,
3170
3177
  selectPeerFromUi,
3171
- handleSpecLinkClick
3178
+ handleSpecLinkClick,
3179
+ theme,
3180
+ toggleTheme
3172
3181
  };
3173
3182
  },
3174
3183
  template: `
@@ -3199,6 +3208,10 @@ createApp({
3199
3208
  <strong><a class="pill-link" :href="pspSpecUrl" target="_blank" rel="noopener noreferrer" @click="handleSpecLinkClick">{{ specPillLabel }}</a></strong>
3200
3209
  {{ specWarningCount > 0 ? specWarningCount + ' warning' + (specWarningCount === 1 ? '' : 's') : 'ok' }}
3201
3210
  </div>
3211
+ <button type="button" class="theme-switch" :aria-label="theme === 'dark' ? 'Switch to light mode' : 'Switch to dark mode'" :title="theme === 'dark' ? 'Light mode' : 'Dark mode'" @click="toggleTheme">
3212
+ <svg v-if="theme === 'dark'" viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="4.5" /><path d="M12 2.5v2.5M12 19v2.5M2.5 12H5M19 12h2.5M5.3 5.3l1.8 1.8M16.9 16.9l1.8 1.8M5.3 18.7l1.8-1.8M16.9 7.1l1.8-1.8" /></svg>
3213
+ <svg v-else viewBox="0 0 24 24" aria-hidden="true"><path d="M20 14.5A8 8 0 0 1 9.5 4a8 8 0 1 0 10.5 10.5z" /></svg>
3214
+ </button>
3202
3215
  </div>
3203
3216
  </section>
3204
3217
 
package/public/index.html CHANGED
@@ -4,6 +4,15 @@
4
4
  <meta charset="utf-8">
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1">
6
6
  <title>FreeRTC</title>
7
+ <script>
8
+ // The theme before the first paint: the one picked here last time, else the system's.
9
+ (function () {
10
+ var t = null;
11
+ try { t = localStorage.getItem('freertc:theme'); } catch (e) {}
12
+ if (t !== 'light' && t !== 'dark') t = window.matchMedia && matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark';
13
+ document.documentElement.dataset.theme = t;
14
+ })();
15
+ </script>
7
16
  <link rel="icon" type="image/svg+xml" href="/pigeonlogo.svg" />
8
17
  <link rel="icon" type="image/png" sizes="192x192" href="/icon-192.png" />
9
18
  <link rel="apple-touch-icon" sizes="180x180" href="/icon-180.png" />
@@ -36,6 +45,23 @@
36
45
  --success: var(--sheen);
37
46
  --warn: var(--warm);
38
47
  }
48
+ /* By day: Cruise, as peer.ooo, PigeonChess and PigeonFeed. */
49
+ html[data-theme='light'] {
50
+ color-scheme: light;
51
+ --night: #e8f6f9;
52
+ --night-2: #f5fbfc;
53
+ --line: #bee6ee;
54
+ --line-strong: #8aa7b3;
55
+ --bright: #2a3747;
56
+ --bone: #2a3747;
57
+ --bone-2: #46586e;
58
+ --bone-3: #5a7187;
59
+ --sheen: #237a50;
60
+ --info: #2f62a3;
61
+ --warm: #9a6a1f;
62
+ --bad: #b4423a;
63
+ --on-bone: #ffffff;
64
+ }
39
65
  *, *::before, *::after { box-sizing: border-box; }
40
66
  html, body { margin: 0; }
41
67
  body {
@@ -71,6 +97,10 @@
71
97
  .inline-link, .pill-link { color: var(--bone); text-decoration: underline; text-decoration-color: var(--line-strong); text-underline-offset: 3px; }
72
98
  .inline-link:hover, .pill-link:hover { text-decoration-color: var(--sheen); }
73
99
  .hero-status { display: flex; align-items: center; gap: 10px; min-width: 0; }
100
+ /* The theme switch, as on every PeerPigeon site: a bare line icon. */
101
+ button.theme-switch { display: grid; place-items: center; width: 36px; height: 36px; flex: none; padding: 0; border: 0; background: none; color: var(--bone-2); }
102
+ button.theme-switch:hover:not(:disabled) { color: var(--bright); }
103
+ .theme-switch svg { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; }
74
104
 
75
105
  /* Status and small labels: plain text with a dot, no pills. */
76
106
  .status-pill, .pill { display: inline-flex; align-items: center; gap: 8px; padding: 0; border: 0; background: none; color: var(--bone-2); font-size: 0.85rem; text-transform: none; letter-spacing: 0; border-radius: 0; }
@@ -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
@@ -227,17 +229,34 @@ setInterval(saveCredit, 60_000).unref();
227
229
  process.on('exit', saveCredit);
228
230
  // Punched connections need WebRTC in this process (werift, an optional dependency).
229
231
  const PUNCH = !isOff(process.env.FREERTC_PUNCH) && await punchOfferAvailable();
232
+ // The name it goes by until it has its own (src/node/relay-name.js) or RELAY_NAME: once it federates,
233
+ // freertc-<the first 16 hex of its node id>, the label its wss:// name will have; pages show it, so it
234
+ // is never its loopback address. A relay that does not federate keeps host and port (seen locally only).
235
+ async function defaultRelayName() {
236
+ if (federating) {
237
+ try {
238
+ const { publicKey, privateKey } = decodeRelayIdentitySecret(await relayIdentitySecret());
239
+ const { nodeId } = await createRelayIdentity(publicKey, privateKey);
240
+ if (/^[0-9a-f]{16}/i.test(nodeId)) return `freertc-${nodeId.slice(0, 16).toLowerCase()}`;
241
+ } catch { /* below */ }
242
+ }
243
+ return `freertc-node-${SELF_HOST}-${PORT}`;
244
+ }
230
245
  const env = {
231
246
  RELAY_KIND: process.env.RELAY_KIND === 'cloud' ? 'cloud' : 'local',
232
247
  ...(PUNCH ? { PUNCH_OFFER: 'on' } : {}),
233
248
  DB: meter.wrapD1(await openSqliteD1({ filename: path.resolve(process.env.DB_PATH || path.join(DATA_DIR, 'relay.sqlite')), migrationsDir: path.join(ROOT, 'migrations') })),
234
249
  RELAY_URL,
235
- RELAY_NAME: process.env.RELAY_NAME || `freertc-node-${SELF_HOST}-${PORT}`,
250
+ RELAY_NAME: process.env.RELAY_NAME || await defaultRelayName(),
236
251
  ...(process.env.FREERTC_VERBOSE ? { FREERTC_VERBOSE: process.env.FREERTC_VERBOSE } : {}),
237
252
  FREERTC_PUBLIC: PUBLIC ? 'true' : 'false',
238
253
  KADEMLIA_BOOTSTRAP_URLS: federating ? bootstrap.join(',') : '',
239
254
  // Without an identity the worker code runs no overlay at all: that is what off means.
240
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),
241
260
  ASSETS,
242
261
  };
243
262
  // Any Node relay can be a tunnel home for relays behind NAT, as a worker can.
@@ -387,6 +406,14 @@ const handler = async (req, res) => {
387
406
  return;
388
407
  }
389
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
+ }
390
417
  if (!statsAllowed({ mode: STATS_MODE, address: req.socket?.remoteAddress, encrypted: req.socket?.encrypted, host: req.headers.host, name: relayName?.name })) {
391
418
  res.writeHead(404, { 'Content-Type': 'text/plain' });
392
419
  res.end('Not found');
package/src/client.js CHANGED
@@ -2909,7 +2909,10 @@ export function createSignalingClient(options = {}) {
2909
2909
  lastSignalPingSentAt = 0
2910
2910
 
2911
2911
  send(pspEnvelope('announce', {
2912
- ttl_ms: 30000,
2912
+ // The same lease the heartbeat asks for. This asked for 30 s while the first heartbeat comes 40 s
2913
+ // later: every peer dropped out of the relay's list for those 10 s, each time it registered, and a
2914
+ // newcomer asking in that gap was not told of it (a storage server nobody could find, say).
2915
+ ttl_ms: ADVERTISE_TTL_MS,
2913
2916
  body: {
2914
2917
  instance_id: networkId,
2915
2918
  capabilities,
@@ -3176,7 +3179,7 @@ export function createSignalingClient(options = {}) {
3176
3179
  advertise(nextCapabilities) {
3177
3180
  if (!registered) return
3178
3181
  send(pspEnvelope('announce', {
3179
- ttl_ms: 30000,
3182
+ ttl_ms: ADVERTISE_TTL_MS,
3180
3183
  body: { instance_id: networkId, capabilities: nextCapabilities, hints: { wants_peers: true } },
3181
3184
  }))
3182
3185
  },
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.0";
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"]);
@@ -59,6 +60,8 @@ const FEDERATED_PEER_QUERY_TIMEOUT_MS = 2_500;
59
60
  // the local peers are sent alone if the federated lookup is still running.
60
61
  const DISCOVER_REPLY_DEADLINE_MS = 4_000;
61
62
  const MAX_TTL_MS = 120_000;
63
+ // The shortest lease an announcement is given (see upsertAnnouncement).
64
+ const MIN_ANNOUNCE_TTL_MS = 60_000;
62
65
  const MAX_MESSAGE_SIZE = 64 * 1024;
63
66
  const MAX_BATCH = 50;
64
67
  const RELAY_EXPIRY_MS = 5 * 60_000; // relay entry expires after 5 min without heartbeat
@@ -667,6 +670,13 @@ async function handleFetch(request, env, ctx) {
667
670
  }, 200);
668
671
  }
669
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
+
670
680
  if (url.pathname.startsWith("/api/v1/kad/")) {
671
681
  return handleKademliaRequest(request, env, {
672
682
  selfUrl: selfRelayUrl,
@@ -1465,7 +1475,9 @@ export function announcedRole(message) {
1465
1475
  export async function upsertAnnouncement(db, message) {
1466
1476
  await ensureRoleColumn(db);
1467
1477
  const now = Date.now();
1468
- const ttl = Math.min(message.ttl_ms || DEFAULT_TTL_MS, MAX_TTL_MS);
1478
+ // Never a lease shorter than a client's heartbeat (40 s): clients before 0.5.2 asked for 30 s when they
1479
+ // registered, and were gone from the list for 10 s before their first heartbeat renewed it.
1480
+ const ttl = Math.min(Math.max(message.ttl_ms || DEFAULT_TTL_MS, MIN_ANNOUNCE_TTL_MS), MAX_TTL_MS);
1469
1481
  const expiresAt = now + ttl;
1470
1482
 
1471
1483
  await db.prepare(`
@@ -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
+ }
@@ -9,6 +9,16 @@ export const STATS_PAGE = `<!doctype html>
9
9
  <meta charset="utf-8" />
10
10
  <meta name="viewport" content="width=device-width, initial-scale=1" />
11
11
  <meta name="theme-color" content="#1b2430" />
12
+ <script>
13
+ // The theme before the first paint: the one picked here last time, else the system's.
14
+ (function () {
15
+ var t = null;
16
+ try { t = localStorage.getItem('freertc:theme'); } catch (e) {}
17
+ if (t !== 'light' && t !== 'dark') t = window.matchMedia && matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark';
18
+ document.documentElement.dataset.theme = t;
19
+ if (t === 'light') document.querySelector('meta[name="theme-color"]').setAttribute('content', '#e8f6f9');
20
+ })();
21
+ </script>
12
22
  <title>Relay stats</title>
13
23
  <link rel="icon" type="image/svg+xml" href="/pigeonlogo.svg" />
14
24
  <link rel="icon" type="image/png" sizes="192x192" href="/icon-192.png" />
@@ -21,6 +31,19 @@ export const STATS_PAGE = `<!doctype html>
21
31
  --sheen: #7fd8a6; --info: #9cc3f5; --warn: #f2c879; --stop: #f29b91;
22
32
  color-scheme: dark;
23
33
  }
34
+ /* By day: Cruise, as peer.ooo, PigeonChess and PigeonFeed. */
35
+ html[data-theme='light'] {
36
+ --night: #e8f6f9; --night-2: #f5fbfc; --line: #bee6ee; --line-strong: #8aa7b3;
37
+ --bright: #2a3747; --bone: #2a3747; --bone-2: #46586e; --bone-3: #5a7187;
38
+ --sheen: #237a50; --info: #2f62a3; --warn: #9a6a1f; --stop: #b4423a;
39
+ color-scheme: light;
40
+ }
41
+ .top-right { display: flex; align-items: center; gap: 12px; }
42
+ /* The theme switch, as on every PeerPigeon site: a bare line icon. */
43
+ .theme-switch { display: grid; place-items: center; width: 36px; height: 36px; border: 0; background: none; color: var(--bone-2); cursor: pointer; }
44
+ .theme-switch:hover { color: var(--bright); }
45
+ .theme-switch svg { width: 18px; height: 18px; fill: none; stroke: currentColor; stroke-width: 1.8; stroke-linecap: round; stroke-linejoin: round; }
46
+ html[data-theme='dark'] .theme-switch .moon, html[data-theme='light'] .theme-switch .sun { display: none; }
24
47
  * { box-sizing: border-box; margin: 0; padding: 0; }
25
48
  body { background: var(--night); color: var(--bone); font: 14px/1.45 'Archivo', system-ui, -apple-system, 'Segoe UI', sans-serif; -webkit-font-smoothing: antialiased; }
26
49
  main { max-width: 1180px; margin: 0 auto; padding: 28px clamp(16px, 4vw, 40px) 56px; }
@@ -70,7 +93,10 @@ export const STATS_PAGE = `<!doctype html>
70
93
  <h1 id="name">Relay<small id="kind"></small></h1>
71
94
  <p class="where" id="url"></p>
72
95
  </div>
73
- <p class="live" id="live"><i></i><span>Connecting…</span></p>
96
+ <div class="top-right">
97
+ <p class="live" id="live"><i></i><span>Connecting…</span></p>
98
+ <button type="button" class="theme-switch" id="theme-switch" aria-label="Switch theme" title="Switch theme"><svg class="sun" viewBox="0 0 24 24" aria-hidden="true"><circle cx="12" cy="12" r="4.5" /><path d="M12 2.5v2.5M12 19v2.5M2.5 12H5M19 12h2.5M5.3 5.3l1.8 1.8M16.9 16.9l1.8 1.8M5.3 18.7l1.8-1.8M16.9 7.1l1.8-1.8" /></svg><svg class="moon" viewBox="0 0 24 24" aria-hidden="true"><path d="M20 14.5A8 8 0 0 1 9.5 4a8 8 0 1 0 10.5 10.5z" /></svg></button>
99
+ </div>
74
100
  </header>
75
101
 
76
102
  <div class="tiles">
@@ -79,7 +105,7 @@ export const STATS_PAGE = `<!doctype html>
79
105
  <div class="tile"><h2>Messages</h2><p class="big" id="msgs">–</p><p class="sub" id="msgs-sub"></p></div>
80
106
  <div class="tile"><h2>Bandwidth</h2><p class="big" id="bw">–</p><p class="sub" id="bw-sub"></p></div>
81
107
  <div class="tile"><h2>Pigeon Seeds</h2><p class="big" id="credit">–</p><p class="sub" id="credit-sub"></p></div>
82
- <div class="tile" id="acc-tile"><h2>Accounts kept</h2><p class="big" id="acc">–</p><p class="sub" id="acc-sub"></p></div>
108
+ <div class="tile" id="acc-tile" hidden><h2>Accounts kept</h2><p class="big" id="acc">–</p><p class="sub" id="acc-sub"></p></div>
83
109
  </div>
84
110
 
85
111
  <div class="charts">
@@ -93,7 +119,7 @@ export const STATS_PAGE = `<!doctype html>
93
119
  <div class="chart"><div class="chart-head"><h3>Memory (this relay)</h3><span id="c-mem"></span></div><svg id="g-mem" preserveAspectRatio="none"></svg></div>
94
120
  </div>
95
121
 
96
- <section id="acc-section">
122
+ <section id="acc-section" hidden>
97
123
  <h2>Accounts</h2>
98
124
  <div class="cols">
99
125
  <dl id="acc-browsers"></dl>
@@ -101,7 +127,7 @@ export const STATS_PAGE = `<!doctype html>
101
127
  </div>
102
128
  </section>
103
129
 
104
- <section id="events-section">
130
+ <section id="events-section" hidden>
105
131
  <h2>Account events between relays</h2>
106
132
  <ul class="relays" id="events"></ul>
107
133
  </section>
@@ -158,13 +184,20 @@ export const STATS_PAGE = `<!doctype html>
158
184
  if (values.length < 2) return '';
159
185
  const step = w / (values.length - 1);
160
186
  const points = values.map((v, j) => (j * step).toFixed(1) + ',' + (h - pad - (v / max) * (h - pad * 2)).toFixed(1)).join(' ');
161
- const area = i === 0 ? '<polygon points="0,' + h + ' ' + points + ' ' + w + ',' + h + '" fill="' + colors[i] + '" fill-opacity="0.08"/>' : '';
162
- return area + '<polyline points="' + points + '" fill="none" stroke="' + colors[i] + '" stroke-width="1.5" vector-effect="non-scaling-stroke" stroke-linejoin="round"/>';
187
+ const area = i === 0 ? '<polygon points="0,' + h + ' ' + points + ' ' + w + ',' + h + '" style="fill:' + colors[i] + '" fill-opacity="0.08"/>' : '';
188
+ return area + '<polyline points="' + points + '" fill="none" style="stroke:' + colors[i] + '" stroke-width="1.5" vector-effect="non-scaling-stroke" stroke-linejoin="round"/>';
163
189
  }).join('');
164
- svg.innerHTML = '<line x1="0" x2="' + w + '" y1="' + (h - 0.5) + '" y2="' + (h - 0.5) + '" stroke="#2c394a"/>' + lines;
190
+ svg.innerHTML = '<line x1="0" x2="' + w + '" y1="' + (h - 0.5) + '" y2="' + (h - 0.5) + '" style="stroke:var(--line)"/>' + lines;
165
191
  }
166
192
 
167
- const SHEEN = '#7fd8a6', BONE = '#9dbfc8';
193
+ const SHEEN = 'var(--sheen)', BONE = 'var(--bone-2)';
194
+
195
+ document.getElementById('theme-switch').addEventListener('click', () => {
196
+ const t = document.documentElement.dataset.theme === 'dark' ? 'light' : 'dark';
197
+ document.documentElement.dataset.theme = t;
198
+ document.querySelector('meta[name="theme-color"]').setAttribute('content', t === 'dark' ? '#1b2430' : '#e8f6f9');
199
+ try { localStorage.setItem('freertc:theme', t); } catch (e) {}
200
+ });
168
201
  let lastOk = 0;
169
202
 
170
203
  async function refresh() {
@@ -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
+ }