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,131 @@
1
+ // How one relay calls another over HTTP.
2
+ //
3
+ // A relay at a bare public IP (a local relay whose router forwards its TCP
4
+ // port, see scripts/node-relay.mjs) is reached with no tunnel. A Cloudflare
5
+ // Worker cannot fetch() a bare IP address, but it can open a TCP connection
6
+ // to one (cloudflare:sockets), so there this speaks HTTP/1.1 itself. The
7
+ // calls carry only signed or public data, so they need no TLS.
8
+ //
9
+ // Everywhere else (named hosts, and Node) it is plain fetch().
10
+
11
+ const IPV4 = /^\d{1,3}(\.\d{1,3}){3}$/;
12
+ const MAX_RESPONSE_BYTES = 4 * 1024 * 1024;
13
+
14
+ export function isIpLiteralHost(hostname) {
15
+ return IPV4.test(hostname) || hostname.startsWith('[');
16
+ }
17
+
18
+ function inWorker() {
19
+ return typeof navigator !== 'undefined' && navigator.userAgent === 'Cloudflare-Workers';
20
+ }
21
+
22
+ let socketsModule = null;
23
+ async function sockets() {
24
+ socketsModule ??= import('cloudflare:sockets');
25
+ return socketsModule;
26
+ }
27
+
28
+ export async function relayFetch(url, init = {}) {
29
+ const target = new URL(url);
30
+ if (target.protocol !== 'http:' || !isIpLiteralHost(target.hostname) || !inWorker()) {
31
+ return fetch(url, init);
32
+ }
33
+ return fetchOverTcp(target, init);
34
+ }
35
+
36
+ function indexOfCrlfCrlf(bytes, from = 0) {
37
+ for (let i = from; i + 3 < bytes.length; i += 1) {
38
+ if (bytes[i] === 13 && bytes[i + 1] === 10 && bytes[i + 2] === 13 && bytes[i + 3] === 10) return i;
39
+ }
40
+ return -1;
41
+ }
42
+
43
+ function concat(chunks, total) {
44
+ const out = new Uint8Array(total);
45
+ let offset = 0;
46
+ for (const chunk of chunks) { out.set(chunk, offset); offset += chunk.length; }
47
+ return out;
48
+ }
49
+
50
+ /** Decode a chunked transfer-encoded body. */
51
+ export function dechunk(bytes) {
52
+ const decoder = new TextDecoder();
53
+ const parts = [];
54
+ let total = 0;
55
+ let i = 0;
56
+ while (i < bytes.length) {
57
+ let lineEnd = i;
58
+ while (lineEnd + 1 < bytes.length && !(bytes[lineEnd] === 13 && bytes[lineEnd + 1] === 10)) lineEnd += 1;
59
+ const size = parseInt(decoder.decode(bytes.subarray(i, lineEnd)).split(';')[0].trim(), 16);
60
+ if (!Number.isFinite(size)) throw new Error('bad chunked body');
61
+ if (size === 0) break;
62
+ const start = lineEnd + 2;
63
+ parts.push(bytes.subarray(start, start + size));
64
+ total += size;
65
+ i = start + size + 2;
66
+ }
67
+ return concat(parts, total);
68
+ }
69
+
70
+ /** Parse a complete HTTP/1.1 response (headers and body, read until close). */
71
+ export function parseHttpResponse(bytes) {
72
+ const headerEnd = indexOfCrlfCrlf(bytes);
73
+ if (headerEnd < 0) throw new Error('incomplete HTTP response');
74
+ const lines = new TextDecoder().decode(bytes.subarray(0, headerEnd)).split('\r\n');
75
+ const status = Number(/^HTTP\/1\.[01] (\d{3})/.exec(lines[0])?.[1]);
76
+ if (!status) throw new Error('bad HTTP status line');
77
+ const headers = new Headers();
78
+ for (const line of lines.slice(1)) {
79
+ const colon = line.indexOf(':');
80
+ if (colon > 0) headers.append(line.slice(0, colon).trim(), line.slice(colon + 1).trim());
81
+ }
82
+ let body = bytes.subarray(headerEnd + 4);
83
+ if (/chunked/i.test(headers.get('transfer-encoding') || '')) body = dechunk(body);
84
+ else if (headers.has('content-length')) body = body.subarray(0, Number(headers.get('content-length')));
85
+ headers.delete('transfer-encoding');
86
+ const nullBody = status === 204 || status === 304 || (status >= 100 && status < 200);
87
+ return new Response(nullBody ? null : body, { status, headers });
88
+ }
89
+
90
+ async function fetchOverTcp(target, init) {
91
+ const { connect } = await sockets();
92
+ const method = String(init.method || 'GET').toUpperCase();
93
+ const body = init.body == null ? null
94
+ : typeof init.body === 'string' ? new TextEncoder().encode(init.body)
95
+ : new Uint8Array(init.body);
96
+ const headers = new Headers(init.headers || {});
97
+ headers.set('Host', target.host);
98
+ headers.set('Connection', 'close');
99
+ headers.set('User-Agent', 'freertc-relay');
100
+ if (body) headers.set('Content-Length', String(body.length));
101
+ let head = `${method} ${target.pathname}${target.search} HTTP/1.1\r\n`;
102
+ for (const [name, value] of headers) head += `${name}: ${value}\r\n`;
103
+ head += '\r\n';
104
+
105
+ const socket = connect({ hostname: target.hostname.replace(/^\[|\]$/g, ''), port: Number(target.port || 80) });
106
+ const abort = () => { try { socket.close(); } catch {} };
107
+ if (init.signal?.aborted) { abort(); throw new DOMException('aborted', 'AbortError'); }
108
+ init.signal?.addEventListener?.('abort', abort, { once: true });
109
+ try {
110
+ const writer = socket.writable.getWriter();
111
+ await writer.write(new TextEncoder().encode(head));
112
+ if (body) await writer.write(body);
113
+ writer.releaseLock();
114
+
115
+ const reader = socket.readable.getReader();
116
+ const chunks = [];
117
+ let total = 0;
118
+ for (;;) {
119
+ const { value, done } = await reader.read();
120
+ if (done) break;
121
+ chunks.push(value);
122
+ total += value.length;
123
+ if (total > MAX_RESPONSE_BYTES) throw new Error('response too large');
124
+ }
125
+ if (init.signal?.aborted) throw new DOMException('aborted', 'AbortError');
126
+ return parseHttpResponse(concat(chunks, total));
127
+ } finally {
128
+ init.signal?.removeEventListener?.('abort', abort);
129
+ abort();
130
+ }
131
+ }
@@ -0,0 +1,74 @@
1
+ // A relay's peer ID is the SHA-256 of the domain it is deployed on, as 64 lowercase hex
2
+ // characters. It is derived, never configured: two relays can only share an ID by sharing a
3
+ // domain. Synchronous on purpose, so every PSP message can carry it without awaiting.
4
+
5
+ const K = new Uint32Array([
6
+ 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
7
+ 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
8
+ 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
9
+ 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
10
+ 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
11
+ 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
12
+ 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
13
+ 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2,
14
+ ]);
15
+
16
+ export function sha256Hex(text) {
17
+ const bytes = new TextEncoder().encode(String(text));
18
+ const length = bytes.length;
19
+ const blocks = Math.ceil((length + 9) / 64);
20
+ const padded = new Uint8Array(blocks * 64);
21
+ padded.set(bytes);
22
+ padded[length] = 0x80;
23
+ const view = new DataView(padded.buffer);
24
+ view.setUint32(padded.length - 8, Math.floor(length / 0x20000000));
25
+ view.setUint32(padded.length - 4, (length << 3) >>> 0);
26
+
27
+ const h = new Uint32Array([
28
+ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19,
29
+ ]);
30
+ const w = new Uint32Array(64);
31
+ const rotr = (x, n) => (x >>> n) | (x << (32 - n));
32
+
33
+ for (let offset = 0; offset < padded.length; offset += 64) {
34
+ for (let i = 0; i < 16; i++) w[i] = view.getUint32(offset + i * 4);
35
+ for (let i = 16; i < 64; i++) {
36
+ const s0 = rotr(w[i - 15], 7) ^ rotr(w[i - 15], 18) ^ (w[i - 15] >>> 3);
37
+ const s1 = rotr(w[i - 2], 17) ^ rotr(w[i - 2], 19) ^ (w[i - 2] >>> 10);
38
+ w[i] = (w[i - 16] + s0 + w[i - 7] + s1) >>> 0;
39
+ }
40
+ let [a, b, c, d, e, f, g, hh] = h;
41
+ for (let i = 0; i < 64; i++) {
42
+ const t1 = (hh + (rotr(e, 6) ^ rotr(e, 11) ^ rotr(e, 25)) + ((e & f) ^ (~e & g)) + K[i] + w[i]) >>> 0;
43
+ const t2 = ((rotr(a, 2) ^ rotr(a, 13) ^ rotr(a, 22)) + ((a & b) ^ (a & c) ^ (b & c))) >>> 0;
44
+ hh = g; g = f; f = e; e = (d + t1) >>> 0;
45
+ d = c; c = b; b = a; a = (t1 + t2) >>> 0;
46
+ }
47
+ h[0] += a; h[1] += b; h[2] += c; h[3] += d; h[4] += e; h[5] += f; h[6] += g; h[7] += hh;
48
+ }
49
+ return Array.from(h, (word) => word.toString(16).padStart(8, "0")).join("");
50
+ }
51
+
52
+ const cache = new Map();
53
+
54
+ // The domain a relay is deployed on, from its relay URL (wss://peer.ooo/ws → peer.ooo).
55
+ // Lowercased, without port, so the same deployment always hashes the same way.
56
+ export function relayDomain(relayUrl) {
57
+ try {
58
+ const hostname = new URL(relayUrl).hostname.toLowerCase().replace(/\.$/, "");
59
+ return hostname || null;
60
+ } catch {
61
+ return null;
62
+ }
63
+ }
64
+
65
+ // A relay with no public URL yet (local development) is "localhost".
66
+ export function relayPeerIdFor(relayUrl) {
67
+ const domain = relayDomain(relayUrl) || "localhost";
68
+ let id = cache.get(domain);
69
+ if (!id) {
70
+ id = sha256Hex(domain);
71
+ cache.set(domain, id);
72
+ }
73
+ return id;
74
+ }
@@ -0,0 +1,298 @@
1
+ import { signMessage, verifyMessage } from 'unsea';
2
+ import { canonicalJson, isNodeId, relayNodeId } from './kademlia.js';
3
+
4
+ export const RELAY_NODE_RECORD_KIND = 'relay-node';
5
+ export const SCOPE_PROVIDER_RECORD_KIND = 'scope-provider';
6
+ export const PEER_PROVIDER_RECORD_KIND = 'peer-provider';
7
+ export const PROVIDER_RECORD_KINDS = new Set([SCOPE_PROVIDER_RECORD_KIND, PEER_PROVIDER_RECORD_KIND]);
8
+
9
+ const RECORD_VERSION = 1;
10
+ const MAX_CLOCK_SKEW_MS = 60_000;
11
+ const MAX_NODE_RECORD_TTL_MS = 10 * 60_000;
12
+ // A room record is republished only when its relay starts serving the room, or as it nears
13
+ // expiry; it is never withdrawn, so a relay that goes away lapses within this window.
14
+ const MAX_PROVIDER_RECORD_TTL_MS = 30 * 60_000;
15
+ const IDENTITY_SECRET_VERSION = 1;
16
+
17
+ export function encodeRelayIdentitySecret(publicKey, privateKey) {
18
+ if (typeof publicKey !== 'string' || !publicKey || typeof privateKey !== 'string' || !privateKey) {
19
+ throw new TypeError('Both relay signing keys are required');
20
+ }
21
+ return JSON.stringify({ v: IDENTITY_SECRET_VERSION, pub: publicKey, priv: privateKey });
22
+ }
23
+
24
+ export function decodeRelayIdentitySecret(value) {
25
+ if (typeof value !== 'string' || !value) throw new TypeError('Relay identity secret is required');
26
+ let parsed;
27
+ try {
28
+ parsed = JSON.parse(value);
29
+ } catch {
30
+ throw new TypeError('Relay identity secret must be valid JSON');
31
+ }
32
+ if (parsed?.v !== IDENTITY_SECRET_VERSION || typeof parsed.pub !== 'string' || typeof parsed.priv !== 'string') {
33
+ throw new TypeError('Relay identity secret has an unsupported format');
34
+ }
35
+ return { publicKey: parsed.pub, privateKey: parsed.priv };
36
+ }
37
+
38
+ // A relay address only a local network can reach: loopback, a private or
39
+ // link-local range, carrier-grade NAT, or a .local / .localhost name. A record
40
+ // carrying one is meaningless to relays elsewhere, and accepting it sends them
41
+ // calls to an address that answers nobody (or the wrong machine).
42
+ export function isPrivateRelayUrl(value) {
43
+ let host;
44
+ try { host = new URL(String(value)).hostname.toLowerCase().replace(/^\[|\]$/g, ''); } catch { return true; }
45
+ if (!host || host === 'localhost' || host.endsWith('.localhost') || host.endsWith('.local')) return true;
46
+ if (host === '::1' || host === '::' || /^f[cd][0-9a-f]{2}:/.test(host) || /^fe[89ab][0-9a-f]:/.test(host)) return true;
47
+ const v4 = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(host);
48
+ if (!v4) return false;
49
+ const [a, b] = [Number(v4[1]), Number(v4[2])];
50
+ return a === 0 || a === 10 || a === 127
51
+ || (a === 169 && b === 254)
52
+ || (a === 172 && b >= 16 && b <= 31)
53
+ || (a === 192 && b === 168)
54
+ || (a === 100 && b >= 64 && b <= 127);
55
+ }
56
+
57
+ function unsignedRecord(record) {
58
+ const { signature: _signature, ...payload } = record;
59
+ return payload;
60
+ }
61
+
62
+ function normalizeRelayUrl(value) {
63
+ if (typeof value !== 'string' || !value.trim()) throw new TypeError('Relay URL is required');
64
+ const url = new URL(value.trim());
65
+ if (url.protocol === 'https:') url.protocol = 'wss:';
66
+ if (url.protocol === 'http:') url.protocol = 'ws:';
67
+ if (url.protocol !== 'wss:' && url.protocol !== 'ws:') throw new TypeError('Relay URL must use ws:// or wss://');
68
+ url.hash = '';
69
+ url.search = '';
70
+ // A relay behind NAT is reached through a tunnel on a public relay, at
71
+ // /t/<its node id>/ws there (src/tunnel). Every other path is /ws.
72
+ url.pathname = TUNNEL_PATH_RE.test(url.pathname) ? url.pathname : '/ws';
73
+ return url.toString();
74
+ }
75
+
76
+ const TUNNEL_PATH_RE = /^\/t\/[0-9a-f]{64}\/ws$/;
77
+
78
+ /** The node id a tunnel relay URL names, or null for a direct one. */
79
+ export function tunnelNodeIdOf(value) {
80
+ try {
81
+ const match = /^\/t\/([0-9a-f]{64})\/ws$/.exec(new URL(value).pathname);
82
+ return match ? match[1] : null;
83
+ } catch {
84
+ return null;
85
+ }
86
+ }
87
+
88
+ async function signRecord(payload, privateKey) {
89
+ return { ...payload, signature: await signMessage(canonicalJson(payload), privateKey) };
90
+ }
91
+
92
+ export async function createRelayIdentity(publicKey, privateKey) {
93
+ if (typeof publicKey !== 'string' || !publicKey || typeof privateKey !== 'string' || !privateKey) {
94
+ throw new TypeError('Both relay signing keys are required');
95
+ }
96
+ const challenge = canonicalJson(['freertc-kad', 1, 'key-check', publicKey]);
97
+ const signature = await signMessage(challenge, privateKey);
98
+ if (!await verifyMessage(challenge, signature, publicKey)) {
99
+ throw new Error('Relay signing public and private keys do not match');
100
+ }
101
+ return { publicKey, privateKey, nodeId: await relayNodeId(publicKey) };
102
+ }
103
+
104
+ export const RELAY_KINDS = new Set(['cloud', 'local']);
105
+ const REACH_VIAS = new Set(['punch', 'tunnel', 'direct']);
106
+ const MAX_REACH_ENTRIES = 4;
107
+
108
+ /**
109
+ * How a relay can be reached, most preferred first, as it signs it in its node
110
+ * record (a pointer: whoever holds the record can reach the relay without the
111
+ * holder carrying its traffic):
112
+ * { via: 'punch', url: https://<home>/t/<node id>/api/v1/punch/offer } a direct data channel
113
+ * { via: 'tunnel', url: wss://<home>/t/<node id>/ws } through the tunnel home
114
+ * { via: 'direct', url: wss://host/ws } a public address
115
+ * A relay can only point at its own tunnel.
116
+ */
117
+ export function normalizeReach(reach, nodeId) {
118
+ if (!Array.isArray(reach)) return [];
119
+ const out = [];
120
+ for (const entry of reach) {
121
+ if (out.length >= MAX_REACH_ENTRIES) break;
122
+ const via = String(entry?.via ?? '');
123
+ if (!REACH_VIAS.has(via) || typeof entry?.url !== 'string' || entry.url.length > 512) continue;
124
+ let url;
125
+ try { url = new URL(entry.url); } catch { continue; }
126
+ if (!['https:', 'http:', 'wss:', 'ws:'].includes(url.protocol)) continue;
127
+ const tunnel = /^\/t\/([0-9a-f]{64})\//.exec(url.pathname);
128
+ if (tunnel && tunnel[1] !== nodeId) continue;
129
+ if (via !== 'direct' && !tunnel) continue;
130
+ url.hash = '';
131
+ out.push({ via, url: url.toString() });
132
+ }
133
+ return out;
134
+ }
135
+
136
+ export async function createSignedNodeRecord(identity, options) {
137
+ const now = Number(options.now ?? Date.now());
138
+ const ttlMs = Math.min(MAX_NODE_RECORD_TTL_MS, Math.max(30_000, Number(options.ttlMs ?? 5 * 60_000)));
139
+ return signRecord({
140
+ version: RECORD_VERSION,
141
+ kind: RELAY_NODE_RECORD_KIND,
142
+ node_id: identity.nodeId,
143
+ public_key: identity.publicKey,
144
+ url: normalizeRelayUrl(options.url),
145
+ name: typeof options.name === 'string' && options.name ? options.name.slice(0, 128) : null,
146
+ connections: Math.max(0, Number(options.connections || 0)),
147
+ capacity: Math.max(1, Number(options.capacity || 10_000)),
148
+ ...(RELAY_KINDS.has(options.relayKind) ? { relay_kind: options.relayKind } : {}),
149
+ ...(Array.isArray(options.reach) && options.reach.length ? { reach: normalizeReach(options.reach, identity.nodeId) } : {}),
150
+ issued_at_ms: now,
151
+ expires_at_ms: now + ttlMs,
152
+ }, identity.privateKey);
153
+ }
154
+
155
+ export async function createSignedProviderRecord(identity, options) {
156
+ if (!PROVIDER_RECORD_KINDS.has(options.kind)) throw new TypeError('Unsupported provider record kind');
157
+ if (!isNodeId(options.key)) throw new TypeError('Provider routing key must be a Kademlia ID');
158
+ const now = Number(options.now ?? Date.now());
159
+ const ttlMs = Math.min(MAX_PROVIDER_RECORD_TTL_MS, Math.max(15_000, Number(options.ttlMs ?? 45_000)));
160
+ return signRecord({
161
+ version: RECORD_VERSION,
162
+ kind: options.kind,
163
+ key: options.key,
164
+ node_id: identity.nodeId,
165
+ public_key: identity.publicKey,
166
+ url: normalizeRelayUrl(options.url),
167
+ connections: Math.max(0, Number(options.connections || 0)),
168
+ capacity: Math.max(1, Number(options.capacity || 10_000)),
169
+ sequence: Math.max(now, Number(options.sequence || 0)),
170
+ issued_at_ms: now,
171
+ expires_at_ms: now + ttlMs,
172
+ }, identity.privateKey);
173
+ }
174
+
175
+ export async function verifySignedRelayRecord(record, options = {}) {
176
+ try {
177
+ if (!record || typeof record !== 'object' || Array.isArray(record)) return false;
178
+ if (record.version !== RECORD_VERSION || !isNodeId(record.node_id)) return false;
179
+ if (typeof record.public_key !== 'string' || typeof record.signature !== 'string') return false;
180
+ if (await relayNodeId(record.public_key) !== record.node_id) return false;
181
+
182
+ const allowedKinds = options.allowedKinds || new Set([
183
+ RELAY_NODE_RECORD_KIND,
184
+ SCOPE_PROVIDER_RECORD_KIND,
185
+ PEER_PROVIDER_RECORD_KIND,
186
+ ]);
187
+ if (!allowedKinds.has(record.kind)) return false;
188
+
189
+ const now = Number(options.now ?? Date.now());
190
+ const issuedAt = Number(record.issued_at_ms);
191
+ const expiresAt = Number(record.expires_at_ms);
192
+ const maxTtl = record.kind === RELAY_NODE_RECORD_KIND ? MAX_NODE_RECORD_TTL_MS : MAX_PROVIDER_RECORD_TTL_MS;
193
+ if (!Number.isFinite(issuedAt) || !Number.isFinite(expiresAt)) return false;
194
+ if (issuedAt > now + MAX_CLOCK_SKEW_MS || expiresAt <= now || expiresAt - issuedAt > maxTtl) return false;
195
+ if (normalizeRelayUrl(record.url) !== record.url) return false;
196
+ // A relay can only claim its own tunnel.
197
+ const tunnelId = tunnelNodeIdOf(record.url);
198
+ if (tunnelId && tunnelId !== record.node_id) return false;
199
+ if (record.kind !== RELAY_NODE_RECORD_KIND && !isNodeId(record.key)) return false;
200
+ // Pointers: a relay kind from the known set, and reach entries that are
201
+ // already in normal form (so a signed record means exactly one thing).
202
+ if (record.relay_kind !== undefined && !RELAY_KINDS.has(record.relay_kind)) return false;
203
+ if (record.reach !== undefined
204
+ && canonicalJson(normalizeReach(record.reach, record.node_id)) !== canonicalJson(record.reach)) return false;
205
+
206
+ return await verifyMessage(canonicalJson(unsignedRecord(record)), record.signature, record.public_key);
207
+ } catch {
208
+ return false;
209
+ }
210
+ }
211
+
212
+ // A tunnel home proves the relay on the other end of a tunnel holds the key
213
+ // its node id comes from: it sends a fresh nonce, and the relay signs it
214
+ // together with the home's host, so a signature is good for one home and one
215
+ // connection only.
216
+ function tunnelChallengeMessage(nonce, host) {
217
+ return canonicalJson(['freertc-tunnel', 1, String(nonce), String(host).toLowerCase()]);
218
+ }
219
+
220
+ export async function signTunnelChallenge(identity, nonce, host) {
221
+ return signMessage(tunnelChallengeMessage(nonce, host), identity.privateKey);
222
+ }
223
+
224
+ export async function verifyTunnelChallenge(publicKey, nonce, host, signature) {
225
+ try {
226
+ return await verifyMessage(tunnelChallengeMessage(nonce, host), signature, publicKey);
227
+ } catch {
228
+ return false;
229
+ }
230
+ }
231
+
232
+ // A link between two relays (src/node/relay-links.js) is authenticated the same
233
+ // way: each side sends a fresh nonce, and the other answers with its signed
234
+ // node record and a signature over that nonce, so a link is bound to the key
235
+ // its node ID comes from and a recorded answer is good for one link only.
236
+ function linkChallengeMessage(nonce) {
237
+ return canonicalJson(['freertc-link', 1, String(nonce)]);
238
+ }
239
+
240
+ export async function signLinkChallenge(identity, nonce) {
241
+ return signMessage(linkChallengeMessage(nonce), identity.privateKey);
242
+ }
243
+
244
+ export async function verifyLinkChallenge(publicKey, nonce, signature) {
245
+ try {
246
+ return await verifyMessage(linkChallengeMessage(nonce), signature, publicKey);
247
+ } catch {
248
+ return false;
249
+ }
250
+ }
251
+
252
+ // Post-quantum relay keys (local relays: src/node/relay-pq.js). A local relay
253
+ // also holds an ML-DSA-65 key next to its P-256 one, and proves both together
254
+ // (an unsea 3 hybrid signature) where only local relays check: on links
255
+ // between local relays, and to the directory when it lists the relay. Cloud
256
+ // relays do not: on the Workers free plan an ML-DSA signature costs more CPU
257
+ // than a request may use.
258
+ //
259
+ // pqIdentity: { pub, priv, qpub, qpriv } with pub/priv the relay's P-256 keys.
260
+
261
+ // It covers the other side's nonce, this relay's node id, and a digest of the
262
+ // fresh keys this relay made for the link (src/node/link-crypto.js), so the
263
+ // link's encryption is bound to the relay that signed.
264
+ function pqLinkChallengeMessage(nonce, nodeId, ephemeralDigest) {
265
+ return canonicalJson(['freertc-link-pq', 2, String(nonce), String(nodeId), String(ephemeralDigest)]);
266
+ }
267
+
268
+ /** A hybrid signature over a link challenge and the link's fresh keys, bound to this relay's node id. */
269
+ export async function signLinkChallengePq(pqIdentity, nodeId, nonce, ephemeralDigest) {
270
+ return signMessage(pqLinkChallengeMessage(nonce, nodeId, ephemeralDigest), pqIdentity);
271
+ }
272
+
273
+ export async function verifyLinkChallengePq(publicKey, pqPublicKey, nodeId, nonce, signature, ephemeralDigest) {
274
+ try {
275
+ if (typeof pqPublicKey !== 'string' || typeof signature !== 'string' || typeof ephemeralDigest !== 'string') return false;
276
+ return await verifyMessage(pqLinkChallengeMessage(nonce, nodeId, ephemeralDigest), signature, { pub: publicKey, qpub: pqPublicKey });
277
+ } catch {
278
+ return false;
279
+ }
280
+ }
281
+
282
+ /** What a relay signs to show the directory its post-quantum key: the whole signed record (or withdrawal). */
283
+ function pqDirectoryMessage(signed) {
284
+ return canonicalJson(['freertc-directory-pq', 1, signed]);
285
+ }
286
+
287
+ export async function signDirectoryPq(pqIdentity, signed) {
288
+ return signMessage(pqDirectoryMessage(signed), pqIdentity);
289
+ }
290
+
291
+ export async function verifyDirectoryPq(signed, pqPublicKey, signature) {
292
+ try {
293
+ if (typeof pqPublicKey !== 'string' || typeof signature !== 'string') return false;
294
+ return await verifyMessage(pqDirectoryMessage(signed), signature, { pub: signed.public_key, qpub: pqPublicKey });
295
+ } catch {
296
+ return false;
297
+ }
298
+ }