freertc 0.1.33 → 0.5.0

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.
Files changed (60) hide show
  1. package/README.md +205 -13
  2. package/bin/freertc.mjs +38 -633
  3. package/migrations/0001_initial.sql +43 -0
  4. package/migrations/0002_kademlia_overlay.sql +32 -0
  5. package/migrations/0003_announcement_role.sql +4 -0
  6. package/package.json +44 -17
  7. package/public/app.js +746 -172
  8. package/public/icon-180.png +0 -0
  9. package/public/icon-192.png +0 -0
  10. package/public/index.html +200 -799
  11. package/public/pigeonlogo.svg +51 -0
  12. package/scripts/d1-schema.sql +36 -0
  13. package/scripts/deploy-cloudflare.mjs +190 -0
  14. package/scripts/dev-server.mjs +54 -7
  15. package/scripts/generate-relay-identity.mjs +14 -0
  16. package/scripts/name-setup.mjs +332 -0
  17. package/scripts/node-relay.mjs +1128 -0
  18. package/scripts/project-bootstrap.mjs +13 -6
  19. package/scripts/wrangler-install-wizard.mjs +21 -11
  20. package/src/client.js +3468 -0
  21. package/src/direct/cert.js +95 -0
  22. package/src/direct/common.js +187 -0
  23. package/src/direct/dial.js +47 -0
  24. package/src/direct/directory.js +230 -0
  25. package/src/direct/listener.js +201 -0
  26. package/src/direct/lookup.js +75 -0
  27. package/src/direct/names.js +150 -0
  28. package/src/direct/node-relay-direct.js +170 -0
  29. package/src/direct/portmap.js +214 -0
  30. package/src/direct/reachable.js +40 -0
  31. package/src/direct/record.js +188 -0
  32. package/src/index.js +1401 -199
  33. package/src/kademlia.js +133 -0
  34. package/src/node/account-sync.js +98 -0
  35. package/src/node/cost-meter.js +92 -0
  36. package/src/node/d1-sqlite.js +108 -0
  37. package/src/node/data-dir.js +66 -0
  38. package/src/node/durable-object.js +58 -0
  39. package/src/node/lan-beacon.js +55 -0
  40. package/src/node/link-crypto.js +99 -0
  41. package/src/node/relay-links.js +385 -0
  42. package/src/node/relay-name.js +193 -0
  43. package/src/node/relay-pq.js +68 -0
  44. package/src/node/relay-stats.js +276 -0
  45. package/src/node/stats-page.js +281 -0
  46. package/src/node/websocket-pair.js +117 -0
  47. package/src/punch/offer.js +143 -0
  48. package/src/punch/rendezvous.js +124 -0
  49. package/src/punch/transport.js +257 -0
  50. package/src/relay-fetch.js +131 -0
  51. package/src/relay-id.js +74 -0
  52. package/src/relay-identity.js +298 -0
  53. package/src/relay-overlay.js +857 -0
  54. package/src/tunnel/client.js +276 -0
  55. package/src/tunnel/frames.js +64 -0
  56. package/src/tunnel/home.js +271 -0
  57. package/wrangler.template.jsonc +34 -9
  58. package/wrangler.workers-dev.jsonc +20 -3
  59. package/scripts/non-cloudflare-server.mjs +0 -433
  60. package/scripts/postinstall-message.mjs +0 -133
@@ -0,0 +1,1128 @@
1
+ #!/usr/bin/env node
2
+ // A freertc relay under Node that runs the SAME relay code as the Cloudflare
3
+ // worker (src/index.js): announcements, discovery, forwarding and Kademlia
4
+ // federation, with D1 on a local SQLite file and WebSockets through `ws`.
5
+ // One process is one relay, so the worker's single-isolate mode applies and
6
+ // no Durable Object is needed.
7
+ //
8
+ // Environment:
9
+ // FREERTC_FEDERATION on (default) | off — off runs a standalone relay
10
+ // FREERTC_PUBLIC true (default) | false — a public relay joins the
11
+ // public relays and never federates a loopback or
12
+ // private address, its own or another's; false is a
13
+ // private/LAN mesh where local addresses are allowed
14
+ // PORT, HOST where to listen (default 0.0.0.0:8788: this machine and its LAN;
15
+ // HOST=127.0.0.1 keeps it to this machine)
16
+ // RELAY_URL this relay's ws(s):// URL as others reach it
17
+ // (default wss://PROD_DOMAIN/ws, else ws://HOST:PORT/ws, with 127.0.0.1 for 0.0.0.0)
18
+ // RELAY_NAME display name
19
+ // KADEMLIA_BOOTSTRAP_URLS comma-separated relays to join through (public
20
+ // default: the public relays; private default: none)
21
+ // RELAY_IDENTITY_SECRET signing identity; generated and kept in the data dir if unset
22
+ // FREERTC_DATA_DIR where the database, identity and name live (default ~/.freertc-relay,
23
+ // the same wherever the relay starts; an earlier one is carried there)
24
+ // DB_PATH database file (default <data dir>/relay.sqlite)
25
+ // TLS_CERT_PATH, TLS_KEY_PATH serve HTTPS/WSS with this certificate
26
+ // PROD_DOMAIN host[:port] this relay is served as
27
+ // FREERTC_TUNNEL on (default) | off — a public relay whose own address is
28
+ // loopback/private (behind NAT) gets a public one through a
29
+ // tunnel to a public relay: wss://<home>/t/<node id>/ws
30
+ // FREERTC_TUNNEL_HOMES comma-separated relays to tunnel through, tried in order
31
+ // (default: the bootstrap relays)
32
+ // FREERTC_DIRECT on (default) | off — accept direct WebRTC connections from browsers
33
+ // on a UDP port the router forwards (UPnP / NAT-PMP), listed in the
34
+ // DNS relay directory (needs node-datachannel 0.33+)
35
+ // FREERTC_DIRECT_PORT UDP port for direct connections (default 9443)
36
+ // FREERTC_DIRECT_PUBLIC_IP this machine's public address, when no router needs asking
37
+ // FREERTC_DIRECTORY_URL the cloud relay that keeps the directory (default: the tunnel home)
38
+ // FREERTC_PUNCH on (default) | off — accept punched connections: a client posts
39
+ // its offer to POST /api/v1/punch/offer (through the tunnel when
40
+ // behind NAT) and talks to this relay over a direct data channel;
41
+ // needs WebRTC (the optional werift dependency)
42
+ // RELAY_KIND local (default) | cloud — what this relay tells clients it is
43
+ // FREERTC_IDP on (default) | off — keep PigeonIdP accounts for the browsers on this
44
+ // relay, in <data dir>/identities.json (needs the pigeonidp package),
45
+ // shared with the other local relays it federates with
46
+ // FREERTC_LINKS on (default) | off — link to other local relays (punched data
47
+ // channels, or the LAN) and send federation calls to them over the
48
+ // link instead of out through a cloud tunnel home
49
+ // FREERTC_STATS local (default) | private | public | off — the relay's dashboard
50
+ // at /stats (and /api/v1/stats): local answers this machine, its
51
+ // network (loopback and private addresses), and anyone through the
52
+ // relay's own https name; private only this machine and its network.
53
+ // Account numbers only ever go to this machine itself
54
+ // FREERTC_PQ on (default) | off — give this relay a post-quantum (ML-DSA-65) key
55
+ // next to its P-256 one (<data dir>/relay-pq.json): links to other
56
+ // local relays need a hybrid proof, pinned per relay on first sight
57
+ // (<data dir>/relay-pins.json), and the directory pins it too
58
+ // FREERTC_LAN on (default) | off — find relays on this network by UDP broadcast
59
+ // (only when HOST is a LAN address, e.g. 0.0.0.0; never loopback)
60
+ // FREERTC_LAN_PORT UDP port for LAN beacons (default 41235)
61
+ // PUNCH_RENDEZVOUS_URL also accept hole-punched connections through this rendezvous
62
+ // PUNCH_LISTENER_ID the id to register there
63
+ import { createServer } from 'node:http';
64
+ import { createServer as createTlsServer } from 'node:https';
65
+ import { existsSync, readFileSync, writeFileSync, mkdirSync, statSync, createReadStream, appendFileSync, renameSync } from 'node:fs';
66
+ import os from 'node:os';
67
+ import path from 'node:path';
68
+ import { fileURLToPath } from 'node:url';
69
+ import WsClient, { WebSocketServer } from 'ws';
70
+ import { installWebSocketPair, serverSocketOf } from '../src/node/websocket-pair.js';
71
+ import { openSqliteD1 } from '../src/node/d1-sqlite.js';
72
+ import { resolveDataDir } from '../src/node/data-dir.js';
73
+ import { createCostMeter } from '../src/node/cost-meter.js';
74
+ import { createRelayStats, isLocalAddress, statsAllowed, statsFor } from '../src/node/relay-stats.js';
75
+ import { STATS_PAGE } from '../src/node/stats-page.js';
76
+ import { ACCOUNT_SYNC_ACTION, ACCOUNT_SYNC_EVERY_MS, createAccountSync, createSyncRequest, verifySyncRequest } from '../src/node/account-sync.js';
77
+ import { PUNCH_OFFER_PATH, createPunchOfferHandler, punchOfferAvailable } from '../src/punch/offer.js';
78
+ import { DataChannelSocket } from '../src/punch/transport.js';
79
+ import { LINK_CHANNEL_LABEL, LINK_PATH, createRelayLinks } from '../src/node/relay-links.js';
80
+ import { hasLanAddress, startLanBeacon, DEFAULT_LAN_PORT } from '../src/node/lan-beacon.js';
81
+ import { nodeDurableNamespace } from '../src/node/durable-object.js';
82
+ import { createRelayIdentity, createSignedNodeRecord, decodeRelayIdentitySecret, isPrivateRelayUrl, tunnelNodeIdOf } from '../src/relay-identity.js';
83
+ import { heartbeatKademlia, isPublicRelay, listKnownRelays, relayReachOf } from '../src/relay-overlay.js';
84
+ import { RelayTunnel } from '../src/tunnel/home.js';
85
+ import { loadNameSettings } from '../src/node/relay-name.js';
86
+
87
+ // The relay runs as a child of this process, which restarts it when the
88
+ // machine moves to another network (exit code NETWORK_CHANGED_EXIT): a new
89
+ // LAN address, router and public address mean new port forwards, a new
90
+ // directory entry and new federation, which a running relay cannot redo in
91
+ // place. Signals are passed on, so Ctrl-C still stops it; node:sqlite gets
92
+ // --experimental-sqlite where this Node needs it (before 22.13).
93
+ const NETWORK_CHANGED_EXIT = 75;
94
+ if (!process.env.FREERTC_RELAY_CHILD) {
95
+ const { spawn } = await import('node:child_process');
96
+ let needsFlag = false;
97
+ try { await import('node:sqlite'); } catch { needsFlag = !process.execArgv.includes('--experimental-sqlite'); }
98
+ const args = [...(needsFlag ? ['--experimental-sqlite', '--no-warnings'] : []), ...process.execArgv, fileURLToPath(import.meta.url), ...process.argv.slice(2)];
99
+ let child = null;
100
+ let stopping = false;
101
+ let signalled = 0;
102
+ const start = () => {
103
+ child = spawn(process.execPath, args, { stdio: 'inherit', env: { ...process.env, FREERTC_RELAY_CHILD: '1' } });
104
+ child.on('exit', (code, signal) => {
105
+ if (!stopping && code === NETWORK_CHANGED_EXIT) {
106
+ console.log('[node-relay] restarting on the new network');
107
+ start();
108
+ return;
109
+ }
110
+ process.exit(code ?? (signal ? 1 : 0));
111
+ });
112
+ };
113
+ // A second Ctrl-C ends the child at once, whatever it is doing.
114
+ for (const signal of ['SIGINT', 'SIGTERM', 'SIGHUP']) {
115
+ process.on(signal, () => { stopping = true; signalled += 1; child?.kill(signalled > 1 ? 'SIGKILL' : signal); });
116
+ }
117
+ start();
118
+ await new Promise(() => {});
119
+ }
120
+ try {
121
+ await import('node:sqlite');
122
+ } catch {
123
+ console.error('[node-relay] this Node has no node:sqlite; use Node 22.5 or later');
124
+ process.exit(1);
125
+ }
126
+
127
+ installWebSocketPair();
128
+ const { default: worker, relayLogCounts } = await import('../src/index.js');
129
+
130
+ const ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..');
131
+ const HOST = process.env.HOST || '0.0.0.0';
132
+ // Listening on every interface lets other machines on the LAN use this relay.
133
+ // It still names itself by loopback, so its relay URL and name stay what they
134
+ // were, and a private address is never announced to public relays.
135
+ const SELF_HOST = ['0.0.0.0', '::'].includes(HOST) ? '127.0.0.1' : HOST;
136
+ const PORT = Number(process.env.PORT || 8788);
137
+ // One folder per user (~/.freertc-relay), wherever it starts from: it keeps its id and name (src/node/data-dir.js).
138
+ const DATA_DIR = resolveDataDir({ log: (line) => console.log(`[node-relay] ${line}`) });
139
+ const PUBLIC_DIR = path.join(ROOT, 'public');
140
+ mkdirSync(DATA_DIR, { recursive: true });
141
+
142
+ async function relayIdentitySecret() {
143
+ if (process.env.RELAY_IDENTITY_SECRET) return process.env.RELAY_IDENTITY_SECRET;
144
+ const file = path.join(DATA_DIR, 'relay-identity.json');
145
+ if (existsSync(file)) return readFileSync(file, 'utf8').trim();
146
+ const { generateRandomPair } = await import('unsea');
147
+ const { encodeRelayIdentitySecret } = await import('../src/relay-identity.js');
148
+ const pair = await generateRandomPair();
149
+ const secret = encodeRelayIdentitySecret(pair.pub, pair.priv);
150
+ writeFileSync(file, secret, { mode: 0o600 });
151
+ return secret;
152
+ }
153
+
154
+ const MIME = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json', '.svg': 'image/svg+xml', '.png': 'image/png' };
155
+ const ASSETS = {
156
+ async fetch(request) {
157
+ const pathname = decodeURIComponent(new URL(request.url).pathname);
158
+ const file = path.join(PUBLIC_DIR, pathname.endsWith('/') ? `${pathname}index.html` : pathname);
159
+ if (!file.startsWith(PUBLIC_DIR) || !existsSync(file) || !statSync(file).isFile()) return new Response('Not Found', { status: 404 });
160
+ return new Response(readFileSync(file), { headers: { 'Content-Type': MIME[path.extname(file)] ?? 'application/octet-stream' } });
161
+ },
162
+ };
163
+
164
+ // The public relays a public relay joins through when none are configured.
165
+ const PUBLIC_BOOTSTRAP_URLS = ['wss://peer.ooo/ws', 'wss://decentralize.ooo/ws', 'wss://oooooooooooooooooooooooooooo.ooo/ws'];
166
+ const TLS_CERT_PATH = process.env.TLS_CERT_PATH;
167
+ const TLS_KEY_PATH = process.env.TLS_KEY_PATH;
168
+ const TLS = Boolean(TLS_CERT_PATH && TLS_KEY_PATH && existsSync(TLS_CERT_PATH) && existsSync(TLS_KEY_PATH));
169
+ const isOff = (value, fallback = 'on') => ['off', 'false', '0', 'no'].includes(String(value ?? fallback).trim().toLowerCase());
170
+ const FEDERATION = !isOff(process.env.FREERTC_FEDERATION);
171
+ const TUNNEL = !isOff(process.env.FREERTC_TUNNEL);
172
+ const PUBLIC = isPublicRelay(process.env);
173
+ // Federate on this machine's public address, through a port the router
174
+ // forwards, instead of a tunnel (FREERTC_OPEN_PORT=off for the tunnel only).
175
+ const OPEN_PORT = !isOff(process.env.FREERTC_OPEN_PORT) && !process.env.RELAY_URL && !process.env.PROD_DOMAIN;
176
+ const RELAY_URL = process.env.RELAY_URL
177
+ || (process.env.PROD_DOMAIN ? `${TLS ? 'wss' : 'ws'}://${process.env.PROD_DOMAIN}/ws` : `${TLS ? 'wss' : 'ws'}://${SELF_HOST}:${PORT}/ws`);
178
+ const configuredBootstrap = String(process.env.KADEMLIA_BOOTSTRAP_URLS ?? '').split(',').map((url) => url.trim()).filter(Boolean);
179
+ // A public relay never federates a loopback or private address, so it never
180
+ // joins through one either.
181
+ const bootstrap = (configuredBootstrap.length ? configuredBootstrap : (PUBLIC ? PUBLIC_BOOTSTRAP_URLS : []))
182
+ .filter((url) => !(PUBLIC && isPrivateRelayUrl(url)));
183
+
184
+ const tunnelHomes = (String(process.env.FREERTC_TUNNEL_HOMES ?? '').split(',').map((url) => url.trim()).filter(Boolean).length
185
+ ? String(process.env.FREERTC_TUNNEL_HOMES).split(',').map((url) => url.trim()).filter(Boolean)
186
+ : bootstrap).filter((url) => !isPrivateRelayUrl(url));
187
+
188
+ let federationNote;
189
+ let federating = FEDERATION;
190
+ let tunneling = false;
191
+ if (!FEDERATION) {
192
+ federationNote = 'off (FREERTC_FEDERATION=off)';
193
+ } else if (PUBLIC && isPrivateRelayUrl(RELAY_URL) && TUNNEL && tunnelHomes.length) {
194
+ // Behind NAT: public relays can't reach ws://127.0.0.1 or a LAN address.
195
+ // First ask the router to forward this port (OPEN_PORT below); if it won't,
196
+ // or relays still can't reach it, take a public address through a tunnel.
197
+ // Federation starts once there is a public address.
198
+ tunneling = true;
199
+ federationNote = OPEN_PORT
200
+ ? `public: asking the router to forward tcp ${PORT} so relays reach this one with no tunnel (a tunnel through ${tunnelHomes.join(', ')} if not), joining through ${bootstrap.join(', ')}`
201
+ : `public, through a tunnel (${RELAY_URL} is loopback/private; homes: ${tunnelHomes.join(', ')}), joining through ${bootstrap.join(', ')}`;
202
+ } else if (PUBLIC && isPrivateRelayUrl(RELAY_URL)) {
203
+ // Announcing ws://127.0.0.1 or a LAN address to public relays would send them
204
+ // to an address that reaches nobody. Stay out until there is a public one.
205
+ federating = false;
206
+ federationNote = `off: ${RELAY_URL} is a loopback/private address and this is a public relay${TUNNEL ? ' with no public relay to tunnel through' : ' and FREERTC_TUNNEL=off'}; set RELAY_URL to a public address, or FREERTC_PUBLIC=false for a private mesh`;
207
+ } else {
208
+ federationNote = `${PUBLIC ? 'public' : 'private mesh'}, joining through ${bootstrap.length ? bootstrap.join(', ') : '(no bootstrap: others join through this relay)'}`;
209
+ }
210
+
211
+ // What this relay would cost as a Cloudflare worker (src/node/cost-meter.js); GET /debug/cost.
212
+ const meter = createCostMeter();
213
+ // The relay's own numbers for its dashboard (src/node/relay-stats.js); GET /stats.
214
+ const STATS_MODE = ['public', 'private', 'off'].includes(String(process.env.FREERTC_STATS || '').trim().toLowerCase())
215
+ ? String(process.env.FREERTC_STATS).trim().toLowerCase()
216
+ : 'local';
217
+ // Credit (what this relay has served) is kept in <data dir>/credit.json across restarts.
218
+ const CREDIT_FILE = path.join(DATA_DIR, 'credit.json');
219
+ const stats = createRelayStats({ credit: (() => { try { return JSON.parse(readFileSync(CREDIT_FILE, 'utf8')); } catch { return null; } })() });
220
+ const saveCredit = () => {
221
+ try {
222
+ writeFileSync(`${CREDIT_FILE}.tmp`, JSON.stringify(stats.creditState()));
223
+ renameSync(`${CREDIT_FILE}.tmp`, CREDIT_FILE);
224
+ } catch {}
225
+ };
226
+ setInterval(saveCredit, 60_000).unref();
227
+ process.on('exit', saveCredit);
228
+ // Punched connections need WebRTC in this process (werift, an optional dependency).
229
+ const PUNCH = !isOff(process.env.FREERTC_PUNCH) && await punchOfferAvailable();
230
+ const env = {
231
+ RELAY_KIND: process.env.RELAY_KIND === 'cloud' ? 'cloud' : 'local',
232
+ ...(PUNCH ? { PUNCH_OFFER: 'on' } : {}),
233
+ DB: meter.wrapD1(await openSqliteD1({ filename: path.resolve(process.env.DB_PATH || path.join(DATA_DIR, 'relay.sqlite')), migrationsDir: path.join(ROOT, 'migrations') })),
234
+ RELAY_URL,
235
+ RELAY_NAME: process.env.RELAY_NAME || `freertc-node-${SELF_HOST}-${PORT}`,
236
+ ...(process.env.FREERTC_VERBOSE ? { FREERTC_VERBOSE: process.env.FREERTC_VERBOSE } : {}),
237
+ FREERTC_PUBLIC: PUBLIC ? 'true' : 'false',
238
+ KADEMLIA_BOOTSTRAP_URLS: federating ? bootstrap.join(',') : '',
239
+ // Without an identity the worker code runs no overlay at all: that is what off means.
240
+ ...(federating ? { RELAY_IDENTITY_SECRET: await relayIdentitySecret() } : {}),
241
+ ASSETS,
242
+ };
243
+ // Any Node relay can be a tunnel home for relays behind NAT, as a worker can.
244
+ env.RELAY_TUNNEL = nodeDurableNamespace(RelayTunnel, env);
245
+ // Relays behind NAT reached through this one, as their federation URLs:
246
+ // always asked for a room's peers, like linked relays (src/index.js).
247
+ env.HOSTED_RELAY_URLS = () => {
248
+ const urls = [];
249
+ let base = null;
250
+ try { base = new URL(String(env.RELAY_URL)); } catch { return urls; }
251
+ for (const [nodeId, object] of env.RELAY_TUNNEL.instances) {
252
+ if (!/^[0-9a-f]{64}$/.test(nodeId) || !object?.tunnelSocket?.()) continue;
253
+ urls.push(`${base.protocol}//${base.host}/t/${nodeId}/ws`);
254
+ }
255
+ return urls;
256
+ };
257
+ // No peer is connected to a relay that has just started: forget the room
258
+ // announcements the last run left in its database. Kept, they were listed
259
+ // to other relays (and so to browsers) as present until they expired, and
260
+ // browsers dialled dozens of peers that were gone before the live ones.
261
+ try {
262
+ const cleared = await env.DB.prepare('DELETE FROM psp_announcements').run();
263
+ const n = Number(cleared?.meta?.changes ?? cleared?.changes ?? 0);
264
+ if (n) console.log(`[node-relay] forgot ${n} peer announcement${n === 1 ? '' : 's'} left from the last run`);
265
+ } catch {
266
+ // a new database has no table yet
267
+ }
268
+ let accountsShared = false;
269
+ let accountStore = null;
270
+ // What happened with accounts between relays, for the dashboard and for
271
+ // whoever has to find out why an account did not arrive: kept in memory and
272
+ // appended to <data dir>/relay-events.log (rolled over at 1 MB).
273
+ const EVENTS_FILE = path.join(DATA_DIR, 'relay-events.log');
274
+ const relayEvents = [];
275
+ function relayEvent(text) {
276
+ const line = `${new Date().toISOString()} ${text}`;
277
+ relayEvents.push(line);
278
+ if (relayEvents.length > 200) relayEvents.shift();
279
+ try {
280
+ if (existsSync(EVENTS_FILE) && statSync(EVENTS_FILE).size > 1_048_576) renameSync(EVENTS_FILE, `${EVENTS_FILE}.1`);
281
+ appendFileSync(EVENTS_FILE, `${line}\n`);
282
+ } catch { /* the log is a convenience */ }
283
+ }
284
+ stats.setEvents(() => relayEvents.slice(-60));
285
+ // Accounts: a local relay is a PigeonIdP server for the browsers connected to
286
+ // it, keeping signed account records in DATA_DIR/identities.json so they
287
+ // survive restarts (pigeonidp/relay). On unless FREERTC_IDP=off.
288
+ if (!isOff(process.env.FREERTC_IDP)) {
289
+ try {
290
+ const { createRelayIdentityStore } = await import('pigeonidp/relay');
291
+ const store = await createRelayIdentityStore({
292
+ dataDir: DATA_DIR,
293
+ log: (line) => console.log(`[node-relay:accounts] ${line}`),
294
+ onEvent: (text) => relayEvent(`accounts: ${text}`),
295
+ // Shared with the other local relays this one federates with (never
296
+ // the cloud relays): their POST /api/v1/idp. Looked up on each use, as
297
+ // federation comes up after this; fetch is the relay's own, so linked
298
+ // relays are reached over their link.
299
+ fetch: (url, init) => {
300
+ try { stats.accountOutbound(JSON.parse(String(init?.body ?? '{}'))); } catch { /* not ours to count */ }
301
+ return globalThis.fetch(url, init);
302
+ },
303
+ otherRelays: federating
304
+ ? async () => (await listKnownRelays(env, env.RELAY_URL).catch(() => []))
305
+ .filter((relay) => relay.relay_kind === 'local' && relay.url && relay.url !== env.RELAY_URL)
306
+ .map((relay) => relay.url.replace(/^ws(s?):\/\//, 'http$1://').replace(/\/ws$/, ''))
307
+ : null,
308
+ });
309
+ // Counted for the dashboard: requests from browsers and other relays, and
310
+ // what this store asks of other relays.
311
+ env.RELAY_REQUEST_HANDLER = async (body) => {
312
+ if (body?.action === ACCOUNT_SYNC_ACTION) return answerSyncRequest(body);
313
+ const result = await store.handle(body);
314
+ stats.account(body, result);
315
+ return result;
316
+ };
317
+ stats.setAccountCount(() => store.size());
318
+ accountStore = store;
319
+ relayEvent(`accounts: started with ${store.size()} kept`);
320
+ accountsShared = federating;
321
+ console.log(`[node-relay] accounts: kept for browsers on this relay in ${store.file.startsWith(process.cwd() + path.sep) ? path.relative(process.cwd(), store.file) : store.file.replace(os.homedir(), '~')} (${store.size()} so far)`);
322
+ } catch (error) {
323
+ console.log(`[node-relay] accounts: off (${error?.code === 'ERR_MODULE_NOT_FOUND' ? 'pigeonidp is not installed: npm install' : error?.message || error})`);
324
+ }
325
+ } else {
326
+ console.log('[node-relay] accounts: off (FREERTC_IDP=off)');
327
+ }
328
+ const ctx = { waitUntil: (work) => { Promise.resolve(work).catch((error) => console.error('[node-relay] background task failed:', error?.message || error)); } };
329
+
330
+ // This relay calling itself at its own public address (a relay reached
331
+ // through it, ws://<public ip>:<port>/t/<id>/..., or its own federation
332
+ // URL) goes to localhost instead. Few routers loop a public address back
333
+ // inside, so those calls failed, and the failed forwards went round through
334
+ // the cloud relays instead: thousands of Worker and Durable Object requests.
335
+ {
336
+ const outsideFetch = globalThis.fetch;
337
+ globalThis.fetch = (input, init) => {
338
+ try {
339
+ const own = String(env.RELAY_URL || '');
340
+ if (!TLS && own.startsWith('ws://') && !tunnelNodeIdOf(own)) {
341
+ const self = new URL(own.replace(/^ws/, 'http'));
342
+ const target = new URL(typeof input === 'string' || input instanceof URL ? String(input) : input.url);
343
+ if (target.host === self.host && (target.protocol === 'http:' || target.protocol === 'ws:')) {
344
+ target.protocol = 'http:';
345
+ target.host = `127.0.0.1:${PORT}`;
346
+ return outsideFetch(typeof input === 'string' || input instanceof URL ? target.toString() : new Request(target.toString(), input), init);
347
+ }
348
+ }
349
+ } catch {}
350
+ return outsideFetch(input, init);
351
+ };
352
+ }
353
+
354
+ function toRequest(req, body) {
355
+ const headers = new Headers();
356
+ for (const [name, value] of Object.entries(req.headers)) {
357
+ if (Array.isArray(value)) for (const item of value) headers.append(name, item);
358
+ else if (value !== undefined) headers.set(name, value);
359
+ }
360
+ return new Request(`http://${req.headers.host || `${HOST}:${PORT}`}${req.url}`, {
361
+ method: req.method,
362
+ headers,
363
+ body: req.method === 'GET' || req.method === 'HEAD' ? undefined : body,
364
+ });
365
+ }
366
+
367
+ async function writeResponse(res, response) {
368
+ const headers = {};
369
+ response.headers.forEach((value, name) => { headers[name] = value; });
370
+ res.writeHead(response.status, headers);
371
+ const body = Buffer.from(await response.arrayBuffer());
372
+ res.end(body);
373
+ return body.length;
374
+ }
375
+
376
+ // Set once acceptSocket exists (below); requests can't arrive before the server listens.
377
+ let handlePunchOffer = null;
378
+
379
+ const handler = async (req, res) => {
380
+ try {
381
+ const pathname = new URL(req.url, 'http://x').pathname;
382
+ if (pathname === PUNCH_OFFER_PATH && handlePunchOffer) {
383
+ meter.request(req.method, pathname, false);
384
+ const chunks = [];
385
+ for await (const chunk of req) chunks.push(chunk);
386
+ await writeResponse(res, await handlePunchOffer(toRequest(req, chunks.length ? Buffer.concat(chunks) : undefined)));
387
+ return;
388
+ }
389
+ if ((pathname === '/stats' || pathname === '/api/v1/stats') && req.method === 'GET' && STATS_MODE !== 'off') {
390
+ if (!statsAllowed({ mode: STATS_MODE, address: req.socket?.remoteAddress, encrypted: req.socket?.encrypted, host: req.headers.host, name: relayName?.name })) {
391
+ res.writeHead(404, { 'Content-Type': 'text/plain' });
392
+ res.end('Not found');
393
+ return;
394
+ }
395
+ if (pathname === '/stats') {
396
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8', 'Cache-Control': 'no-store' });
397
+ res.end(STATS_PAGE);
398
+ } else {
399
+ res.writeHead(200, { 'Content-Type': 'application/json', 'Cache-Control': 'no-store' });
400
+ res.end(JSON.stringify(statsFor(stats.snapshot(), req.socket?.remoteAddress))); // accounts: this machine only
401
+ }
402
+ return;
403
+ }
404
+ if (pathname === '/debug/cost' && req.method === 'GET') {
405
+ res.writeHead(200, { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' });
406
+ res.end(JSON.stringify({ ok: true, relay: env.RELAY_URL, name: env.RELAY_NAME, cost: meter.snapshot() }));
407
+ return;
408
+ }
409
+ meter.request(req.method, pathname, false);
410
+ const chunks = [];
411
+ for await (const chunk of req) chunks.push(chunk);
412
+ const bodyIn = chunks.length ? Buffer.concat(chunks) : undefined;
413
+ const response = await worker.fetch(toRequest(req, bodyIn), env, ctx);
414
+ stats.http(bodyIn?.length ?? 0, await writeResponse(res, response));
415
+ } catch (error) {
416
+ // A client that hung up mid-request is not a relay error: count it.
417
+ if (error?.message === 'aborted' || error?.code === 'ECONNRESET') {
418
+ noteTrouble('requests the client abandoned');
419
+ return;
420
+ }
421
+ console.error('[node-relay] request failed:', error?.stack || error);
422
+ if (!res.headersSent) res.writeHead(500, { 'Content-Type': 'application/json' });
423
+ res.end(JSON.stringify({ ok: false, error: 'Relay error' }));
424
+ }
425
+ };
426
+ const server = TLS
427
+ ? createTlsServer({ cert: readFileSync(TLS_CERT_PATH), key: readFileSync(TLS_KEY_PATH) }, handler)
428
+ : createServer(handler);
429
+
430
+ const wss = new WebSocketServer({ noServer: true });
431
+
432
+ // A peer that vanishes without closing (a killed process, a sleeping laptop,
433
+ // a router that drops the connection) leaves a socket the system may not
434
+ // report closed for minutes, and the relay kept counting and routing to it.
435
+ // Ping every socket; one that has not answered within LIVENESS_TIMEOUT_MS is
436
+ // closed, which removes the peer from its room at once.
437
+ const LIVENESS_PING_MS = 15_000;
438
+ const LIVENESS_TIMEOUT_MS = 30_000;
439
+ const watchedSockets = new Set();
440
+ function watchLiveness(ws) {
441
+ ws.lastHeardAt = Date.now();
442
+ const heard = () => { ws.lastHeardAt = Date.now(); };
443
+ ws.on('pong', heard);
444
+ ws.on('message', heard);
445
+ ws.on('close', () => watchedSockets.delete(ws));
446
+ watchedSockets.add(ws);
447
+ }
448
+ setInterval(() => {
449
+ const now = Date.now();
450
+ for (const ws of watchedSockets) {
451
+ if (now - ws.lastHeardAt > LIVENESS_TIMEOUT_MS) {
452
+ watchedSockets.delete(ws);
453
+ try { ws.terminate(); } catch {}
454
+ continue;
455
+ }
456
+ try { ws.ping(); } catch {}
457
+ }
458
+ }, LIVENESS_PING_MS).unref();
459
+ const onUpgrade = async (req, socket, head) => {
460
+ try {
461
+ if (new URL(req.url, 'http://x').pathname === LINK_PATH) {
462
+ if (!relayLinks) { socket.end('HTTP/1.1 404 No links here\r\n\r\n'); return; }
463
+ wss.handleUpgrade(req, socket, head, (ws) => relayLinks.accept(ws, { via: 'lan' }));
464
+ return;
465
+ }
466
+ meter.request(req.method, new URL(req.url, 'http://x').pathname, true);
467
+ const response = await worker.fetch(toRequest(req), env, ctx);
468
+ const serverSocket = serverSocketOf(response);
469
+ if (!serverSocket) {
470
+ noteTrouble(`upgrades refused (${response.status})`);
471
+ socket.end(`HTTP/1.1 ${response.status} ${response.statusText || 'Error'}\r\nConnection: close\r\n\r\n`);
472
+ return;
473
+ }
474
+ wss.handleUpgrade(req, socket, head, (ws) => {
475
+ ws.on('message', (data) => meter.wsMessage(data));
476
+ watchLiveness(ws);
477
+ stats.watchSocket(ws);
478
+ serverSocket.attach(ws);
479
+ });
480
+ } catch (error) {
481
+ noteTrouble('upgrades failed');
482
+ console.error('[node-relay] upgrade failed:', error?.stack || error);
483
+ socket.destroy();
484
+ }
485
+ };
486
+ server.on('upgrade', onUpgrade);
487
+
488
+ /**
489
+ * Hand a socket that did not arrive as an HTTP upgrade (a hole-punched channel,
490
+ * a WebSocket carried through the tunnel) to the worker exactly as an upgrade
491
+ * would be, so it gets the same relay, discovery and federation.
492
+ */
493
+ async function acceptSocket(socket, pathname = '/ws', headers = []) {
494
+ const upgrade = new Request(new URL(pathname, env.RELAY_URL.replace(/^ws/, 'http')), { headers });
495
+ upgrade.headers.set('Upgrade', 'websocket');
496
+ const response = await worker.fetch(upgrade, env, ctx);
497
+ const serverSocket = serverSocketOf(response);
498
+ if (serverSocket) serverSocket.attach(stats.watchSocket(socket));
499
+ else socket.close(1011, `Relay answered ${response.status}`);
500
+ }
501
+
502
+ // This relay's post-quantum key (src/node/relay-pq.js), when it federates.
503
+ const PQ = federating && !isOff(process.env.FREERTC_PQ);
504
+ let relayPq = null;
505
+ if (PQ) {
506
+ const { loadRelayPqIdentity, loadRelayPins } = await import('../src/node/relay-pq.js');
507
+ const { publicKey, privateKey } = decodeRelayIdentitySecret(env.RELAY_IDENTITY_SECRET);
508
+ const { nodeId } = await createRelayIdentity(publicKey, privateKey);
509
+ relayPq = { identity: loadRelayPqIdentity(DATA_DIR, { publicKey, privateKey, nodeId }), pins: loadRelayPins(DATA_DIR), required: true };
510
+ console.log(`[node-relay] post-quantum key: ML-DSA-65 with P-256 (hybrid) for links to other local relays and the directory${relayPq.pins.size() ? ` (${relayPq.pins.size()} relay${relayPq.pins.size() === 1 ? '' : 's'} pinned)` : ''}`);
511
+ }
512
+
513
+ // The same without a link, over the ordinary federation path: this relay asks
514
+ // every local relay it knows for its whole store (signed with its own keys),
515
+ // 15 s after it starts, whenever it meets a local relay it has not synced with
516
+ // in the last 5 minutes, and every 5 minutes; and answers such requests from
517
+ // local relays it knows. So an account reaches every local relay without
518
+ // anyone having to log in.
519
+ const PULL_EVERY_MS = 5 * 60_000;
520
+ const lastPulled = new Map(); // node id -> when
521
+ async function localRelayRecords() {
522
+ return (await listKnownRelays(env, env.RELAY_URL).catch(() => []))
523
+ .filter((relay) => relay.relay_kind === 'local' && relay.url && relay.url !== env.RELAY_URL && relay.node_id);
524
+ }
525
+ async function answerSyncRequest(body) {
526
+ if (!accountStore) return { ok: false, error: 'no accounts here' };
527
+ if (body?.from_relay !== true) return { ok: false, error: 'only between relays' };
528
+ const verdict = await verifySyncRequest(body, {
529
+ selfUrl: env.RELAY_URL,
530
+ knownLocalNodeIds: async () => new Set((await localRelayRecords()).map((relay) => relay.node_id)),
531
+ pinnedPqKey: (nodeId) => relayPq?.pins?.get(nodeId) ?? null,
532
+ });
533
+ const who = `relay ${String(body?.node_id || '?').slice(0, 8)}`;
534
+ if (!verdict.ok) {
535
+ relayEvent(`accounts: refused ${who} its sync (${verdict.error})`);
536
+ return { ok: false, error: verdict.error };
537
+ }
538
+ // Its post-quantum key is remembered on first sight, as a link would.
539
+ if (typeof body.pq_public_key === 'string' && relayPq?.pins && !relayPq.pins.get(body.node_id)) relayPq.pins.set(body.node_id, body.pq_public_key);
540
+ relayEvent(`accounts: gave ${who} all ${accountStore.size()}`);
541
+ return { ok: true, records: accountStore.exportRecords() };
542
+ }
543
+ let syncIdentity = null;
544
+ async function pullAccountsFrom(relay) {
545
+ syncIdentity ??= await (async () => {
546
+ const { publicKey, privateKey } = decodeRelayIdentitySecret(env.RELAY_IDENTITY_SECRET);
547
+ return createRelayIdentity(publicKey, privateKey);
548
+ })();
549
+ const who = (() => { try { return new URL(relay.url).host; } catch { return relay.url; } })();
550
+ lastPulled.set(relay.node_id, Date.now());
551
+ try {
552
+ const base = relay.url.replace(/^ws(s?):\/\//, 'http$1://').replace(/\/ws$/, '');
553
+ const body = await createSyncRequest({ identity: syncIdentity, pqIdentity: relayPq?.identity ?? null, target: relay.url });
554
+ const response = await globalThis.fetch(`${base}/api/v1/idp`, {
555
+ method: 'POST',
556
+ headers: { 'Content-Type': 'application/json' },
557
+ body: JSON.stringify(body),
558
+ signal: AbortSignal.timeout(15_000),
559
+ });
560
+ const answer = await response.json().catch(() => null);
561
+ if (!response.ok || !answer?.ok) {
562
+ relayEvent(`accounts: ${who}: no sync (${answer?.error || `answered ${response.status}`})`);
563
+ return;
564
+ }
565
+ const { stored } = await accountStore.importRecords(answer.records, { from: who });
566
+ if (stored) console.log(`[node-relay] accounts: ${stored} from ${who}`);
567
+ } catch (error) {
568
+ relayEvent(`accounts: ${who}: no sync (${error?.name === 'TimeoutError' ? 'no answer' : error?.message || error})`);
569
+ }
570
+ }
571
+ async function pullAccounts({ onlyNew = false } = {}) {
572
+ if (!accountStore || !federating || !env.RELAY_IDENTITY_SECRET) return;
573
+ for (const relay of await localRelayRecords()) {
574
+ if (onlyNew && Date.now() - (lastPulled.get(relay.node_id) ?? 0) < PULL_EVERY_MS) continue;
575
+ await pullAccountsFrom(relay);
576
+ }
577
+ }
578
+ if (federating) {
579
+ setTimeout(() => { pullAccounts().catch(() => {}); }, 15_000).unref();
580
+ // A relay met for the first time (or again after a while) is synced within 30 s.
581
+ setInterval(() => { pullAccounts({ onlyNew: true }).catch(() => {}); }, 30_000).unref();
582
+ }
583
+
584
+ // Accounts between linked relays (src/node/account-sync.js): each side takes
585
+ // the other's whole store when a link opens and every 10 minutes.
586
+ const accountSync = createAccountSync({
587
+ store: () => accountStore,
588
+ event: relayEvent,
589
+ log: (line) => console.log(`[node-relay] ${line}`),
590
+ });
591
+
592
+ // Links to other local relays (src/node/relay-links.js): federation calls to
593
+ // a linked relay go over the link, not out through a cloud tunnel home.
594
+ let relayLinks = null;
595
+ const LINKS = federating && !isOff(process.env.FREERTC_LINKS);
596
+ if (LINKS) {
597
+ const { publicKey, privateKey } = decodeRelayIdentitySecret(env.RELAY_IDENTITY_SECRET);
598
+ const linkIdentity = await createRelayIdentity(publicKey, privateKey);
599
+ const directFetch = globalThis.fetch;
600
+ const PeerConnection = PUNCH ? (await import('werift')).RTCPeerConnection : null;
601
+ const { punchRelayChannel } = await import('../src/client.js');
602
+ relayLinks = createRelayLinks({
603
+ identity: linkIdentity,
604
+ nodeRecord: () => createSignedNodeRecord(linkIdentity, {
605
+ url: env.RELAY_URL,
606
+ name: env.RELAY_NAME,
607
+ relayKind: env.RELAY_KIND,
608
+ reach: relayReachOf(env, env.RELAY_URL),
609
+ }),
610
+ // Only a linked relay (proved, and encrypted with post-quantum keys) can
611
+ // ask for the whole account store.
612
+ handleRequest: (request) => accountSync.handleLinkRequest(request) ?? worker.fetch(request, env, ctx),
613
+ onLinked: (nodeId, link) => accountSync.syncOver(nodeId, link),
614
+ dialPunch: PeerConnection
615
+ ? async (offerUrl) => {
616
+ const { pc, channel } = await punchRelayChannel(offerUrl, {
617
+ PeerConnection,
618
+ iceServers: [{ urls: 'stun:stun.l.google.com:19302' }, { urls: 'stun:stun.cloudflare.com:3478' }],
619
+ fetchImpl: directFetch,
620
+ label: LINK_CHANNEL_LABEL,
621
+ });
622
+ return new DataChannelSocket(channel, pc, { link: true });
623
+ }
624
+ : null,
625
+ dialLan: (url) => new Promise((resolve, reject) => {
626
+ const ws = new WsClient(url);
627
+ ws.once('open', () => resolve(ws));
628
+ ws.once('error', reject);
629
+ }),
630
+ listRelays: () => listKnownRelays(env, env.RELAY_URL),
631
+ log: (line) => console.log(`[node-relay:links] ${line}`),
632
+ pq: relayPq,
633
+ });
634
+ globalThis.fetch = relayLinks.wrapFetch(directFetch);
635
+ setInterval(() => {
636
+ for (const [nodeId, link] of relayLinks.links) if (link.open) accountSync.syncOver(nodeId, link);
637
+ }, ACCOUNT_SYNC_EVERY_MS).unref();
638
+ env.LINKED_RELAY_URLS = () => relayLinks.linkedRelayUrls();
639
+ setTimeout(() => relayLinks.maintain().catch(() => {}), 5_000).unref();
640
+ const lanHost = !['127.0.0.1', 'localhost', '::1'].includes(HOST);
641
+ if (!isOff(process.env.FREERTC_LAN) && lanHost && hasLanAddress()) {
642
+ startLanBeacon({
643
+ nodeId: linkIdentity.nodeId,
644
+ port: PORT,
645
+ lanPort: Number(process.env.FREERTC_LAN_PORT || DEFAULT_LAN_PORT),
646
+ onRelay: (nodeId, url) => relayLinks.lanSeen(nodeId, url),
647
+ log: (line) => console.log(`[node-relay:links] ${line}`),
648
+ });
649
+ }
650
+ }
651
+
652
+ if (PUNCH) {
653
+ handlePunchOffer = createPunchOfferHandler({
654
+ onSocket: (socket) => (socket.channel?.label === LINK_CHANNEL_LABEL && relayLinks
655
+ ? relayLinks.accept(socket, { via: 'punch' })
656
+ : acceptSocket(socket)),
657
+ log: (line) => console.log(`[node-relay:punch] ${line}`),
658
+ });
659
+ }
660
+
661
+ // The worker only heartbeats when a request comes in; a relay behind NAT may
662
+ // see none for a while, so keep its federation alive from here too.
663
+ // Say whether federation actually holds: which relays answered this relay's
664
+ // announcement, logged whenever that changes.
665
+ let federationState = null;
666
+ stats.setLinks(() => {
667
+ const relays = relayLinks?.linkedRelayUrls?.() ?? [];
668
+ return { linked: relays.length, relays };
669
+ });
670
+ stats.setReach(() => ({
671
+ // Its own name and wss:// address once it has them (src/node/relay-name.js).
672
+ name: relayName?.name || env.RELAY_NAME,
673
+ kind: env.RELAY_KIND,
674
+ url: servingWss || env.RELAY_URL,
675
+ federation: federating ? (federationState || federationNote) : federationNote,
676
+ postQuantum: Boolean(relayPq),
677
+ accountsShared,
678
+ }));
679
+ // Say plainly what this relay's public address costs.
680
+ function howReached(url) {
681
+ if (!tunnelNodeIdOf(url)) return ' (open port, no tunnel)';
682
+ let host = url;
683
+ try { host = new URL(url).host; } catch {}
684
+ return String(url).startsWith('wss:')
685
+ ? ` (through a cloud tunnel on ${host}: works, but every message through it counts against Cloudflare's requests)`
686
+ : ` (reached through the relay at ${host}, no cloud)`;
687
+ }
688
+ async function heartbeat() {
689
+ if (!federating) return;
690
+ // Not federated yet: still getting a public address (open port or tunnel).
691
+ if (PUBLIC && isPrivateRelayUrl(env.RELAY_URL)) return;
692
+ const result = await heartbeatKademlia(env, env.RELAY_URL)
693
+ .catch((error) => ({ error: error?.message || String(error) }));
694
+ const hosts = (urls) => urls.map((url) => { try { return new URL(url).host; } catch { return url; } }).sort();
695
+ const state = result?.error
696
+ ? `not federated: heartbeat failed (${result.error})`
697
+ : !result?.enabled
698
+ ? 'not federated: federation is off for this address'
699
+ : result.confirmed_by.length
700
+ ? `federated as ${env.RELAY_URL}${howReached(env.RELAY_URL)}: known to ${hosts(result.confirmed_by).join(', ')}`
701
+ : `not federated: no relay answered (asked ${hosts(result.asked).join(', ') || 'none'})`;
702
+ if (state !== federationState) {
703
+ federationState = state;
704
+ console.log(`[node-relay] ${state}`);
705
+ }
706
+ }
707
+
708
+ /**
709
+ * Relays with an open port that this relay can be reached through (not this
710
+ * one): those in the DNS directory, and those it already knows from
711
+ * federation at a bare public address (found sooner than DNS, which caches
712
+ * for minutes).
713
+ */
714
+ async function directoryHomeUrls(selfNodeId) {
715
+ if (isOff(process.env.FREERTC_DIRECTORY_HOMES)) return [];
716
+ // Relays this one was last reached through, remembered across restarts:
717
+ // they do not depend on DNS or on the cloud relays being up.
718
+ const urls = [...rememberedHomes()];
719
+ try {
720
+ const { lookupDirectRelays } = await import('../src/direct/lookup.js');
721
+ const records = await lookupDirectRelays({ useCache: false });
722
+ for (const record of records) if (record.ws && record.node_id !== selfNodeId) urls.push(record.ws);
723
+ } catch {}
724
+ try {
725
+ for (const relay of await listKnownRelays(env, env.RELAY_URL)) {
726
+ const url = String(relay.url || '');
727
+ if (relay.node_id === selfNodeId || !/^ws:\/\/\d{1,3}(\.\d{1,3}){3}:\d{1,5}\/ws$/.test(url) || isPrivateRelayUrl(url)) continue;
728
+ urls.push(url);
729
+ }
730
+ } catch {}
731
+ return [...new Set(urls)].slice(0, 3);
732
+ }
733
+
734
+ const HOMES_FILE = path.join(DATA_DIR, 'homes.json');
735
+ function rememberedHomes() {
736
+ try {
737
+ const list = JSON.parse(readFileSync(HOMES_FILE, 'utf8'));
738
+ return Array.isArray(list) ? list.filter((url) => typeof url === 'string' && url.startsWith('ws://')).slice(0, 3) : [];
739
+ } catch {
740
+ return [];
741
+ }
742
+ }
743
+ function rememberHome(url) {
744
+ try {
745
+ const home = String(url).replace(/\/t\/[0-9a-f]{64}\/ws$/, '/ws');
746
+ if (!home.startsWith('ws://')) return;
747
+ writeFileSync(HOMES_FILE, JSON.stringify([home, ...rememberedHomes().filter((h) => h !== home)].slice(0, 3)));
748
+ } catch {}
749
+ }
750
+
751
+ let tunnelStarted = false;
752
+ async function openTunnel() {
753
+ if (tunnelStarted) return;
754
+ tunnelStarted = true;
755
+ const { startTunnel } = await import('../src/tunnel/client.js');
756
+ const { publicKey, privateKey } = decodeRelayIdentitySecret(env.RELAY_IDENTITY_SECRET);
757
+ const identity = await createRelayIdentity(publicKey, privateKey);
758
+ // Relays with an open port from the DNS directory first: reached through
759
+ // one of them, this relay's federation and peers' signaling go with no
760
+ // cloud relay in the way. The cloud homes come after, for when none
761
+ // answers; every frame through them counts against Cloudflare's limit.
762
+ const directoryHomes = await directoryHomeUrls(identity.nodeId);
763
+ if (directoryHomes.length) console.log(`[node-relay] can be reached through these relays with an open port: ${directoryHomes.join(", ")} (cloud only if none answers)`);
764
+ startHomeTunnel(startTunnel, identity, directoryHomes);
765
+ // Reached through the cloud (no open-port relay answered, or one came up
766
+ // after this relay did): look again every 30 s and move as soon as one is
767
+ // up, so it does not matter which relay starts first. The lookups cost no
768
+ // Worker requests (DNS-over-HTTPS, and this relay's own federation table).
769
+ let checking = false;
770
+ setInterval(async () => {
771
+ if (checking) return;
772
+ checking = true;
773
+ try { await moveOffCloud(); } finally { checking = false; }
774
+ }, 30_000).unref();
775
+ async function moveOffCloud() {
776
+ const url = tunnelHandle?.url;
777
+ // On a relay with an open port already: nothing to do. Through the cloud,
778
+ // or not reached at all (every home refusing): look for one.
779
+ if (url && !url.startsWith('wss:')) return;
780
+ const homes = await directoryHomeUrls(identity.nodeId);
781
+ for (const home of homes) {
782
+ const up = await fetch(home.replace(/^ws/, 'http').replace(/\/ws$/, '/health'), { signal: AbortSignal.timeout(5_000) }).then((r) => r.ok).catch(() => false);
783
+ if (!up) continue;
784
+ console.log(`[node-relay] ${home} is up (a relay with an open port): reaching this relay through it instead of the cloud`);
785
+ tunnelHandle.close();
786
+ startHomeTunnel(startTunnel, identity, homes);
787
+ return;
788
+ }
789
+ }
790
+ }
791
+
792
+ let tunnelHandle = null;
793
+ function startHomeTunnel(startTunnel, identity, directoryHomes) {
794
+ tunnelHandle = startTunnel({
795
+ homes: [...directoryHomes, ...tunnelHomes],
796
+ identity,
797
+ name: env.RELAY_NAME,
798
+ handleRequest: (request) => (handlePunchOffer && new URL(request.url).pathname === PUNCH_OFFER_PATH
799
+ ? handlePunchOffer(request)
800
+ : worker.fetch(request, env, ctx)),
801
+ handleStream: (socket, { path: streamPath, headers }) => acceptSocket(socket, new URL(streamPath, 'http://x').pathname, headers),
802
+ onUrl: (url) => {
803
+ env.RELAY_URL = url ?? RELAY_URL;
804
+ if (url) rememberHome(url);
805
+ if (url) setTimeout(() => directRelay?.republish().catch(() => {}), 2_000).unref();
806
+ console.log(url ? `[node-relay] joining federation as ${url}` : `[node-relay] tunnel lost; out of federation until it is back`);
807
+ heartbeat();
808
+ if (url) setTimeout(() => relayLinks?.maintain().catch(() => {}), 5_000).unref();
809
+ },
810
+ log: (line) => console.log(`${new Date().toLocaleTimeString([], { hour12: false })} [node-relay:tunnel] ${line}`),
811
+ });
812
+ }
813
+
814
+ // The open port: forward tcp PORT on the router, check that a public relay can
815
+ // call this relay there, and federate as ws://<public ip>:<port>/ws. Relays
816
+ // call it straight (from a Worker, over a TCP socket); no tunnel is opened.
817
+ let openPortMapping = null;
818
+ let openPortUrl = null; // ws://<public ip>:<port>/ws, kept to fall back to
819
+
820
+ // Federate as wss://<name>:<tls port>/ws once the TLS listener is up, when this
821
+ // relay is reached through its open port (the same router forwards both).
822
+ // If no relay accepts that address, go back to the bare ws:// one.
823
+ async function federateUnderName() {
824
+ if (!servingWss || !openPortMapping || env.RELAY_URL === servingWss) return;
825
+ const before = env.RELAY_URL;
826
+ env.RELAY_URL = servingWss;
827
+ console.log(`[node-relay] federating under its name: ${servingWss}`);
828
+ await heartbeat();
829
+ if (!String(federationState || '').startsWith('federated as') && openPortUrl) {
830
+ console.log(`[node-relay] no relay took ${servingWss}; back to ${openPortUrl}`);
831
+ env.RELAY_URL = before || openPortUrl;
832
+ await heartbeat();
833
+ return;
834
+ }
835
+ setTimeout(() => directRelay?.republish().catch(() => {}), 2_000).unref();
836
+ }
837
+ async function openPublicPort() {
838
+ const log = (line) => console.log(`${new Date().toLocaleTimeString([], { hour12: false })} [node-relay:open-port] ${line}`);
839
+ const { mapTcpPort, isNonPublicIPv4 } = await import('../src/direct/portmap.js');
840
+ const { REACHABLE_PATH } = await import('../src/direct/reachable.js');
841
+ const mapping = await mapTcpPort({ internalPort: PORT, externalPort: PORT, description: `freertc relay ${PORT}`, log });
842
+ if (!mapping) { log('no router answered UPnP or NAT-PMP; using a tunnel'); return false; }
843
+ if (isNonPublicIPv4(mapping.externalIp)) {
844
+ log(`the router's own address ${mapping.externalIp} is not public (carrier-grade NAT or a second router); using a tunnel`);
845
+ await mapping.close().catch(() => {});
846
+ return false;
847
+ }
848
+ const url = `ws://${mapping.externalIp}:${mapping.externalPort}/ws`;
849
+ const { publicKey, privateKey } = decodeRelayIdentitySecret(env.RELAY_IDENTITY_SECRET);
850
+ const { nodeId } = await createRelayIdentity(publicKey, privateKey);
851
+ for (const home of tunnelHomes) {
852
+ try {
853
+ const response = await fetch(new URL(REACHABLE_PATH, home.replace(/^ws/, 'http')), {
854
+ method: 'POST',
855
+ headers: { 'Content-Type': 'application/json' },
856
+ body: JSON.stringify({ port: mapping.externalPort, node_id: nodeId }),
857
+ signal: AbortSignal.timeout(10_000),
858
+ });
859
+ const result = await response.json().catch(() => null);
860
+ if (!response.ok || !result) continue; // that relay can't check yet; ask the next
861
+ if (result.ip && result.ip !== mapping.externalIp) {
862
+ log(`relays see this machine at ${result.ip}, the router says ${mapping.externalIp}; using a tunnel`);
863
+ break;
864
+ }
865
+ if (!result.reachable) {
866
+ log(`router forwards tcp ${mapping.externalIp}:${mapping.externalPort}, but ${new URL(home).host} could not reach it (${result.why || 'no answer'}); a firewall on this machine may be blocking port ${PORT}. Using a tunnel`);
867
+ break;
868
+ }
869
+ openPortMapping = mapping;
870
+ openPortUrl = url;
871
+ // A relay with its own name and certificate federates under that name.
872
+ env.RELAY_URL = servingWss || url;
873
+ log(`router forwards tcp ${mapping.externalIp}:${mapping.externalPort} here (${mapping.method}) and ${new URL(home).host} reached it: no tunnel`);
874
+ setTimeout(() => directRelay?.republish().catch(() => {}), 2_000).unref();
875
+ console.log(`[node-relay] joining federation as ${env.RELAY_URL}`);
876
+ heartbeat();
877
+ setTimeout(() => relayLinks?.maintain().catch(() => {}), 5_000).unref();
878
+ return true;
879
+ } catch (error) {
880
+ log(`${new URL(home).host}: ${error?.message || error}`);
881
+ }
882
+ }
883
+ await mapping.close().catch(() => {});
884
+ return false;
885
+ }
886
+
887
+ if (federating) setInterval(heartbeat, 2 * 60_000).unref();
888
+
889
+ // One line a minute instead of one per message passed on (FREERTC_VERBOSE=1
890
+ // for every message).
891
+ // How busy the relay is: the longest it took to get back to its event loop
892
+ // this minute (a relay that stalls cannot accept connections), and
893
+ // connections that failed before or during the upgrade.
894
+ let maxLoopLagMs = 0;
895
+ let lastLoopTick = Date.now();
896
+ setInterval(() => {
897
+ const now = Date.now();
898
+ maxLoopLagMs = Math.max(maxLoopLagMs, now - lastLoopTick - 100);
899
+ lastLoopTick = now;
900
+ }, 100).unref();
901
+ const connectionTrouble = new Map();
902
+ const noteTrouble = (what) => connectionTrouble.set(what, (connectionTrouble.get(what) ?? 0) + 1);
903
+
904
+ setInterval(async () => {
905
+ const lag = maxLoopLagMs;
906
+ maxLoopLagMs = 0;
907
+ for (const [what, count] of connectionTrouble) relayLogCounts.set(what, count);
908
+ connectionTrouble.clear();
909
+ if (lag > 1_000) relayLogCounts.set(`ms longest stall`, lag);
910
+ if (!relayLogCounts?.size) return;
911
+ const parts = [...relayLogCounts].map(([what, count]) => `${count} ${what}`);
912
+ relayLogCounts.clear();
913
+ const health = await worker.fetch(new Request(`http://${SELF_HOST}:${PORT}/health`), env, ctx).then((r) => r.json()).catch(() => null);
914
+ console.log(`${new Date().toLocaleTimeString([], { hour12: false })} [node-relay] last minute: ${parts.join(', ')}${health ? `; ${health.peers} peers connected` : ''}`);
915
+ }, 60_000).unref();
916
+
917
+ // On a terminal, one status line that redraws in place every few seconds
918
+ // while the relay is healthy (it never adds lines); anything else the relay
919
+ // prints goes above it. Piped or redirected output gets no status line.
920
+ if (process.stdout.isTTY) {
921
+ let status = '';
922
+ const clear = () => { if (status) process.stdout.write('\r\x1b[2K'); };
923
+ const draw = () => { if (status) process.stdout.write(status.slice(0, Math.max(20, (process.stdout.columns || 120) - 1))); };
924
+ for (const method of ['log', 'info', 'warn', 'error']) {
925
+ const original = console[method].bind(console);
926
+ console[method] = (...args) => { clear(); original(...args); draw(); };
927
+ }
928
+ let stallMs = 0;
929
+ setInterval(() => { stallMs = Math.max(stallMs, maxLoopLagMs); }, 100).unref();
930
+ setInterval(async () => {
931
+ const health = await worker.fetch(new Request(`http://${SELF_HOST}:${PORT}/health`), env, ctx).then((r) => r.json()).catch(() => null);
932
+ const time = new Date().toLocaleTimeString([], { hour12: false });
933
+ const stall = stallMs > 1_000 ? `, stalled ${stallMs} ms` : '';
934
+ stallMs = 0;
935
+ clear();
936
+ status = health
937
+ ? `${time} [node-relay] ${health.peers ?? 0} peers connected${stall ? stall : ', healthy'}`
938
+ : `${time} [node-relay] not answering its own health check`;
939
+ draw();
940
+ }, 5_000).unref();
941
+ }
942
+
943
+ // Direct connections (src/direct): browsers reach this relay with a WebRTC data
944
+ // channel on a UDP port the router forwards, found through the DNS relay
945
+ // directory, with no cloud relay in the way. Needs node-datachannel 0.33+.
946
+ let directRelay = null;
947
+ let relayName = null; // src/node/relay-name.js: this relay's own name and certificate
948
+ let tlsServer = null;
949
+ let servingWss = null; // wss://<name>:<port>/ws once the TLS listener is up
950
+ // On exit, withdraw from the directory and remove the router's port forwards.
951
+ // Ctrl-C always ends the relay: the cleanup gets 3 s (a router or the
952
+ // directory that does not answer must not keep it running), and a second
953
+ // Ctrl-C ends it at once.
954
+ let stopping = false;
955
+ let stoppingAt = 0;
956
+ for (const signal of ['SIGINT', 'SIGTERM']) {
957
+ process.on(signal, () => {
958
+ // Ctrl-C reaches this process twice (from the terminal and passed on by
959
+ // the parent): only a second press, not the echo, stops it at once.
960
+ if (stopping && Date.now() - stoppingAt > 500) process.kill(process.pid, 'SIGKILL');
961
+ if (stopping) return;
962
+ stopping = true;
963
+ stoppingAt = Date.now();
964
+ console.log('[node-relay] stopping (Ctrl-C again to stop at once)');
965
+ saveCredit();
966
+ setTimeout(() => process.exit(0), 3_000);
967
+ Promise.all([directRelay?.stop().catch(() => {}), openPortMapping?.close().catch(() => {})])
968
+ .finally(() => process.exit(0));
969
+ });
970
+ }
971
+ // Moved to another network (the machine's IPv4 addresses changed: new
972
+ // Wi-Fi, a hotspot, a VPN): clean up as on Ctrl-C and exit with
973
+ // NETWORK_CHANGED_EXIT, and the parent starts the relay again, which redoes
974
+ // the port forwards, the directory entry and federation for the new network.
975
+ if (process.env.FREERTC_RELAY_CHILD) {
976
+ const { networkInterfaces } = await import('node:os');
977
+ const addresses = () => Object.values(networkInterfaces()).flat()
978
+ .filter((entry) => entry && !entry.internal && entry.family === 'IPv4' && !entry.address.startsWith('169.254.'))
979
+ .map((entry) => entry.address).sort().join(',');
980
+ const startedOn = addresses();
981
+ setInterval(() => {
982
+ const now = addresses();
983
+ if (now === startedOn || stopping) return;
984
+ stopping = true;
985
+ stoppingAt = Date.now();
986
+ console.log(`[node-relay] the network changed (${startedOn || 'none'} -> ${now || 'none'}); restarting`);
987
+ setTimeout(() => process.exit(NETWORK_CHANGED_EXIT), 3_000);
988
+ Promise.all([directRelay?.stop().catch(() => {}), openPortMapping?.close().catch(() => {})])
989
+ .finally(() => process.exit(NETWORK_CHANGED_EXIT));
990
+ }, 10_000).unref();
991
+ }
992
+ // The direct (WebRTC) listener can stop answering while the rest of the
993
+ // relay keeps working: browsers then fail on the address the directory
994
+ // lists, and nothing said so. Every minute the relay opens a direct channel
995
+ // to itself on loopback; after two failures in a row it restarts (the parent
996
+ // starts it again), which brings the listener back.
997
+ function watchDirectListener(port, fingerprint) {
998
+ let failures = 0;
999
+ const check = async () => {
1000
+ if (stopping) return;
1001
+ let pc = null;
1002
+ try {
1003
+ const { RTCPeerConnection } = await import('node-datachannel/polyfill');
1004
+ const { directRelayChannel } = await import('../src/direct/dial.js');
1005
+ const opened = await directRelayChannel(`webrtc-direct://127.0.0.1:${port}/sha256/${fingerprint}`, { PeerConnection: RTCPeerConnection, timeoutMs: 8_000 });
1006
+ pc = opened.pc;
1007
+ failures = 0;
1008
+ if (process.env.FREERTC_VERBOSE === '1') console.log('[node-relay:direct] self-check: direct listener answered');
1009
+ } catch (error) {
1010
+ failures += 1;
1011
+ console.log(`${new Date().toLocaleTimeString([], { hour12: false })} [node-relay:direct] self-check: direct listener did not answer (${error?.message || error})${failures >= 2 ? '; restarting' : ''}`);
1012
+ if (failures >= 2 && !stopping) {
1013
+ stopping = true;
1014
+ stoppingAt = Date.now();
1015
+ setTimeout(() => process.exit(NETWORK_CHANGED_EXIT), 3_000);
1016
+ Promise.all([directRelay?.stop().catch(() => {}), openPortMapping?.close().catch(() => {})])
1017
+ .finally(() => process.exit(NETWORK_CHANGED_EXIT));
1018
+ }
1019
+ } finally {
1020
+ try { pc?.close(); } catch {}
1021
+ }
1022
+ };
1023
+ setInterval(() => { check().catch(() => {}); }, Number(process.env.FREERTC_DIRECT_SELFCHECK_MS || 60_000)).unref();
1024
+ }
1025
+
1026
+ if (!isOff(process.env.FREERTC_DIRECT)) {
1027
+ // Set up in the background: asking the router takes a few seconds and the
1028
+ // relay serves its own address meanwhile.
1029
+ (async () => {
1030
+ const { startDirectRelay } = await import('../src/direct/node-relay-direct.js');
1031
+ // The identity signs the directory entry. A relay that does not federate is
1032
+ // not listed, so any identity will do there.
1033
+ const { publicKey, privateKey } = env.RELAY_IDENTITY_SECRET
1034
+ ? decodeRelayIdentitySecret(env.RELAY_IDENTITY_SECRET)
1035
+ : await (async () => { const { generateRandomPair } = await import('unsea'); const pair = await generateRandomPair(); return { publicKey: pair.pub, privateKey: pair.priv }; })();
1036
+ const home = process.env.FREERTC_DIRECTORY_URL || (tunnelHomes[0] || bootstrap[0] || '').replace(/^ws/, 'http').replace(/\/ws$/, '');
1037
+ directRelay = await startDirectRelay({
1038
+ identity: await createRelayIdentity(publicKey, privateKey),
1039
+ dataDir: DATA_DIR,
1040
+ port: Number(process.env.FREERTC_DIRECT_PORT || 9443),
1041
+ // Listed in the directory only when this relay federates publicly.
1042
+ directoryUrl: federating && PUBLIC ? (home || null) : null,
1043
+ publicIp: process.env.FREERTC_DIRECT_PUBLIC_IP || null,
1044
+ tunnelUrl: () => (tunnelNodeIdOf(env.RELAY_URL) && String(env.RELAY_URL).startsWith('wss:') ? env.RELAY_URL : null),
1045
+ // Listed with its open TCP port, so relays behind NAT can make it their home.
1046
+ wsUrl: () => (openPortMapping ? env.RELAY_URL : null),
1047
+ // Its wss:// name once it has one (src/node/relay-name.js), so browsers can use TLS.
1048
+ name: () => relayName?.wssUrl || env.RELAY_NAME,
1049
+ acceptSocket: (socket) => acceptSocket(socket),
1050
+ pqIdentity: relayPq?.identity ?? null,
1051
+ log: (line) => console.log(`${new Date().toLocaleTimeString([], { hour12: false })} [node-relay:direct] ${line}`),
1052
+ });
1053
+ if (directRelay && process.env.FREERTC_RELAY_CHILD) watchDirectListener(Number(process.env.FREERTC_DIRECT_PORT || 9443), directRelay.fingerprint);
1054
+ })().catch((error) => console.log(`[node-relay:direct] direct connections: off (${error?.message || error})`));
1055
+ }
1056
+
1057
+ // A name and a Let's Encrypt certificate on the owner's own domain, kept by
1058
+ // the owner's Worker (src/node/relay-name.js), once `npx freertc name` has
1059
+ // registered this relay there. Then it also serves wss:// (and https) on
1060
+ // FREERTC_TLS_PORT (default 8443), forwarded by the router.
1061
+ const nameSettings = isOff(process.env.FREERTC_NAMES) ? null : loadNameSettings(DATA_DIR);
1062
+ if (nameSettings) {
1063
+ (async () => {
1064
+ const { startRelayName } = await import('../src/node/relay-name.js');
1065
+ const { mapTcpPort } = await import('../src/direct/portmap.js');
1066
+ const log = (line) => console.log(`${new Date().toLocaleTimeString([], { hour12: false })} [node-relay:name] ${line}`);
1067
+ const TLS_PORT = Number(process.env.FREERTC_TLS_PORT || 8443);
1068
+ const { publicKey, privateKey } = decodeRelayIdentitySecret(await relayIdentitySecret());
1069
+ relayName = await startRelayName({
1070
+ identity: await createRelayIdentity(publicKey, privateKey),
1071
+ dataDir: DATA_DIR,
1072
+ worker: nameSettings.worker,
1073
+ tlsPort: TLS_PORT,
1074
+ staging: process.env.FREERTC_ACME_STAGING === '1',
1075
+ mapPort: (port) => mapTcpPort({ internalPort: port, externalPort: port, description: `freertc relay tls ${port}`, log }),
1076
+ onCertificate: ({ key, cert, name }) => {
1077
+ if (tlsServer) { tlsServer.setSecureContext({ key, cert }); log('serving the renewed certificate'); return; }
1078
+ tlsServer = createTlsServer({ key, cert }, handler);
1079
+ tlsServer.on('upgrade', onUpgrade);
1080
+ tlsServer.on('clientError', (error, socket) => { noteTrouble(`tls connection errors (${error?.code || 'client'})`); try { socket.destroy(); } catch {} });
1081
+ tlsServer.on('error', (error) => log(`tls server: ${error?.code || error?.message || error}`));
1082
+ tlsServer.listen(TLS_PORT, HOST, () => {
1083
+ servingWss = `wss://${name}:${TLS_PORT}/ws`;
1084
+ log(`serving ${servingWss} and https://${name}:${TLS_PORT}/stats`);
1085
+ federateUnderName().catch((error) => log(`federating under the name: ${error?.message || error}`));
1086
+ });
1087
+ },
1088
+ onAddress: (url) => {
1089
+ if (url) log(`directory: listing ${url}`);
1090
+ directRelay?.republish?.().catch?.(() => {});
1091
+ },
1092
+ log,
1093
+ });
1094
+ })().catch((error) => console.log(`[node-relay:name] names: off (${error?.message || error})`));
1095
+ }
1096
+
1097
+ if (process.env.PUNCH_RENDEZVOUS_URL) {
1098
+ const { listenForPunches } = await import('../src/punch/transport.js');
1099
+ const listenerId = process.env.PUNCH_LISTENER_ID || `freertc-${crypto.randomUUID()}`;
1100
+ listenForPunches({
1101
+ rendezvousUrl: process.env.PUNCH_RENDEZVOUS_URL,
1102
+ listenerId,
1103
+ name: env.RELAY_NAME,
1104
+ log: (line) => console.log(`[node-relay:punch] ${line}`),
1105
+ onSocket: (socket) => acceptSocket(socket),
1106
+ });
1107
+ console.log(`[node-relay] accepting punched connections as ${listenerId}`);
1108
+ }
1109
+
1110
+ server.on('clientError', (error, socket) => {
1111
+ noteTrouble(`connection errors (${error?.code || 'client'})`);
1112
+ try { socket.destroy(); } catch {}
1113
+ });
1114
+ server.on('error', (error) => noteTrouble(`server errors (${error?.code || 'unknown'})`));
1115
+ server.listen(PORT, HOST, () => {
1116
+ console.log(`[node-relay] ${env.RELAY_NAME} on ${TLS ? 'https' : 'http'}://${HOST}:${PORT} (relay ${env.RELAY_URL})`);
1117
+ if (STATS_MODE !== 'off') {
1118
+ console.log(`[node-relay] stats: ${TLS ? 'https' : 'http'}://${['0.0.0.0', '::'].includes(HOST) ? 'localhost' : HOST}:${PORT}/stats (${STATS_MODE === 'public' ? 'open to anyone' : STATS_MODE === 'private' ? 'this machine and its network only' : "this machine, its network, and anyone through the relay's own https name"})`);
1119
+ }
1120
+ console.log(`[node-relay] federation: ${federationNote}; data in ${DATA_DIR}`);
1121
+ console.log(`[node-relay] punched connections: ${PUNCH ? `accepted when a peer asks for one, introduced through this relay's public address (POST ${PUNCH_OFFER_PATH})` : (isOff(process.env.FREERTC_PUNCH) ? 'off (FREERTC_PUNCH=off)' : 'off: no WebRTC here (npm install werift)')}`);
1122
+ heartbeat();
1123
+ if (tunneling) {
1124
+ (OPEN_PORT ? openPublicPort() : Promise.resolve(false))
1125
+ .catch((error) => { console.log(`[node-relay:open-port] ${error?.message || error}; using a tunnel`); return false; })
1126
+ .then((open) => (open ? null : openTunnel()));
1127
+ }
1128
+ });