freertc 0.1.32 → 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.
- package/README.md +204 -12
- package/bin/freertc.mjs +38 -633
- package/migrations/0001_initial.sql +43 -0
- package/migrations/0002_kademlia_overlay.sql +32 -0
- package/migrations/0003_announcement_role.sql +4 -0
- package/package.json +44 -17
- package/public/app.js +746 -169
- package/public/icon-180.png +0 -0
- package/public/icon-192.png +0 -0
- package/public/index.html +200 -799
- package/public/pigeonlogo.svg +51 -0
- package/scripts/d1-schema.sql +36 -0
- package/scripts/deploy-cloudflare.mjs +190 -0
- package/scripts/dev-server.mjs +54 -7
- package/scripts/generate-relay-identity.mjs +14 -0
- package/scripts/name-setup.mjs +332 -0
- package/scripts/node-relay.mjs +1128 -0
- package/scripts/project-bootstrap.mjs +13 -6
- package/scripts/wrangler-install-wizard.mjs +21 -11
- package/src/client.js +3468 -0
- package/src/direct/cert.js +95 -0
- package/src/direct/common.js +187 -0
- package/src/direct/dial.js +47 -0
- package/src/direct/directory.js +230 -0
- package/src/direct/listener.js +201 -0
- package/src/direct/lookup.js +75 -0
- package/src/direct/names.js +150 -0
- package/src/direct/node-relay-direct.js +170 -0
- package/src/direct/portmap.js +214 -0
- package/src/direct/reachable.js +40 -0
- package/src/direct/record.js +188 -0
- package/src/index.js +1401 -199
- package/src/kademlia.js +133 -0
- package/src/node/account-sync.js +98 -0
- package/src/node/cost-meter.js +92 -0
- package/src/node/d1-sqlite.js +108 -0
- package/src/node/data-dir.js +66 -0
- package/src/node/durable-object.js +58 -0
- package/src/node/lan-beacon.js +55 -0
- package/src/node/link-crypto.js +99 -0
- package/src/node/relay-links.js +385 -0
- package/src/node/relay-name.js +193 -0
- package/src/node/relay-pq.js +68 -0
- package/src/node/relay-stats.js +276 -0
- package/src/node/stats-page.js +281 -0
- package/src/node/websocket-pair.js +117 -0
- package/src/punch/offer.js +143 -0
- package/src/punch/rendezvous.js +124 -0
- package/src/punch/transport.js +257 -0
- package/src/relay-fetch.js +131 -0
- package/src/relay-id.js +74 -0
- package/src/relay-identity.js +298 -0
- package/src/relay-overlay.js +857 -0
- package/src/tunnel/client.js +276 -0
- package/src/tunnel/frames.js +64 -0
- package/src/tunnel/home.js +271 -0
- package/wrangler.template.jsonc +34 -9
- package/wrangler.workers-dev.jsonc +20 -3
- package/scripts/non-cloudflare-server.mjs +0 -433
- package/scripts/postinstall-message.mjs +0 -133
|
@@ -0,0 +1,857 @@
|
|
|
1
|
+
import { relayFetch } from './relay-fetch.js';
|
|
2
|
+
import {
|
|
3
|
+
DEFAULT_K_BUCKET_SIZE,
|
|
4
|
+
DEFAULT_LOOKUP_ALPHA,
|
|
5
|
+
DEFAULT_REPLICATION_FACTOR,
|
|
6
|
+
bucketIndex,
|
|
7
|
+
isNodeId,
|
|
8
|
+
rankProviderRecords,
|
|
9
|
+
scopeRoutingKey,
|
|
10
|
+
selectClosestNodes,
|
|
11
|
+
} from './kademlia.js';
|
|
12
|
+
import {
|
|
13
|
+
PROVIDER_RECORD_KINDS,
|
|
14
|
+
RELAY_NODE_RECORD_KIND,
|
|
15
|
+
SCOPE_PROVIDER_RECORD_KIND,
|
|
16
|
+
createRelayIdentity,
|
|
17
|
+
createSignedNodeRecord,
|
|
18
|
+
createSignedProviderRecord,
|
|
19
|
+
decodeRelayIdentitySecret,
|
|
20
|
+
isPrivateRelayUrl,
|
|
21
|
+
tunnelNodeIdOf,
|
|
22
|
+
verifySignedRelayRecord,
|
|
23
|
+
} from './relay-identity.js';
|
|
24
|
+
|
|
25
|
+
const MAX_ROUTING_CONTACTS = 256 * DEFAULT_K_BUCKET_SIZE;
|
|
26
|
+
const MAX_LOOKUP_QUERIES = 24;
|
|
27
|
+
const MAX_LOOKUP_RECORDS = 64;
|
|
28
|
+
const MAX_PROVIDER_RELAYS = 8;
|
|
29
|
+
const MAX_RPC_BODY_BYTES = 128 * 1024;
|
|
30
|
+
const RPC_TIMEOUT_MS = 3_000;
|
|
31
|
+
// How long a completed bootstrap join is trusted. Every join is a fan-out of
|
|
32
|
+
// find RPCs and a database write per contact heard, and the cache is per
|
|
33
|
+
// isolate, so a short interval multiplies across every isolate the platform
|
|
34
|
+
// starts. Node records live five minutes by default; rejoining at under half
|
|
35
|
+
// that keeps this relay announced to its bootstraps without churning them.
|
|
36
|
+
const BOOTSTRAP_REFRESH_INTERVAL_MS = 120_000;
|
|
37
|
+
// A relay announces that it serves a room when it starts serving it, and again only as the
|
|
38
|
+
// record nears expiry, never on a peer's heartbeat: a record that has not changed is not
|
|
39
|
+
// published again. Nothing withdraws a record, so a room a relay stops serving, or a relay
|
|
40
|
+
// that goes away, lapses when the record expires. Both are per relay and room, never per peer.
|
|
41
|
+
const PROVIDER_RECORD_TTL_MS = 30 * 60_000;
|
|
42
|
+
const PROVIDER_PUBLISH_INTERVAL_MS = 20 * 60_000;
|
|
43
|
+
const MAX_RECENT_PROVIDER_PUBLISHES = 20_000;
|
|
44
|
+
// Which relays serve a room changes only when a relay starts serving it or its record lapses,
|
|
45
|
+
// so a lookup is trusted for minutes. A forward that the cached relays cannot deliver asks
|
|
46
|
+
// again (refreshRoomProviders), at most once per room per PEER_PROVIDER_REFRESH_MIN_AGE_MS.
|
|
47
|
+
const PEER_PROVIDER_LOOKUP_CACHE_MS = 10 * 60_000;
|
|
48
|
+
const PEER_PROVIDER_REFRESH_MIN_AGE_MS = 30_000;
|
|
49
|
+
const MAX_RECENT_PEER_PROVIDER_LOOKUPS = 2_000;
|
|
50
|
+
// A shared pending promise must never park every caller forever. A join or a
|
|
51
|
+
// lookup started on behalf of one socket can be abandoned by the platform when
|
|
52
|
+
// that socket's request ends; whoever awaits it next would otherwise hang,
|
|
53
|
+
// and every relay operation funnels through these two waits.
|
|
54
|
+
const SHARED_WAIT_TIMEOUT_MS = 6_000;
|
|
55
|
+
|
|
56
|
+
function withTimeout(promise, ms, label) {
|
|
57
|
+
let timer;
|
|
58
|
+
const deadline = new Promise((_, reject) => {
|
|
59
|
+
timer = setTimeout(() => reject(new Error(`${label} timed out after ${ms}ms`)), ms);
|
|
60
|
+
});
|
|
61
|
+
return Promise.race([promise, deadline]).finally(() => clearTimeout(timer));
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const identityPromises = new WeakMap();
|
|
65
|
+
const joinPromises = new WeakMap();
|
|
66
|
+
const recentBootstrapJoins = new WeakMap();
|
|
67
|
+
const recentProviderPublishes = new Map();
|
|
68
|
+
const recentPeerProviderLookups = new Map();
|
|
69
|
+
|
|
70
|
+
function rememberPeerProviderLookup(key, entry) {
|
|
71
|
+
recentPeerProviderLookups.delete(key);
|
|
72
|
+
recentPeerProviderLookups.set(key, entry);
|
|
73
|
+
while (recentPeerProviderLookups.size > MAX_RECENT_PEER_PROVIDER_LOOKUPS) {
|
|
74
|
+
recentPeerProviderLookups.delete(recentPeerProviderLookups.keys().next().value);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function markProviderPublish(key, now) {
|
|
79
|
+
const previous = Number(recentProviderPublishes.get(key) || 0);
|
|
80
|
+
if (now - previous < PROVIDER_PUBLISH_INTERVAL_MS) return false;
|
|
81
|
+
|
|
82
|
+
recentProviderPublishes.delete(key);
|
|
83
|
+
recentProviderPublishes.set(key, now);
|
|
84
|
+
while (recentProviderPublishes.size > MAX_RECENT_PROVIDER_PUBLISHES) {
|
|
85
|
+
recentProviderPublishes.delete(recentProviderPublishes.keys().next().value);
|
|
86
|
+
}
|
|
87
|
+
return true;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function jsonResponse(body, status = 200) {
|
|
91
|
+
return new Response(JSON.stringify(body), {
|
|
92
|
+
status,
|
|
93
|
+
headers: {
|
|
94
|
+
'Content-Type': 'application/json; charset=utf-8',
|
|
95
|
+
'Access-Control-Allow-Origin': '*',
|
|
96
|
+
},
|
|
97
|
+
});
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
function relayHttpBase(relayUrl) {
|
|
101
|
+
return relayUrl
|
|
102
|
+
.replace(/^wss:\/\//, 'https://')
|
|
103
|
+
.replace(/^ws:\/\//, 'http://')
|
|
104
|
+
.replace(/\/ws$/, '');
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
export function configuredBootstrapUrls(env) {
|
|
108
|
+
const values = [
|
|
109
|
+
...(typeof env.KADEMLIA_BOOTSTRAP_URLS === 'string' ? env.KADEMLIA_BOOTSTRAP_URLS.split(',') : []),
|
|
110
|
+
env.GLOBAL_RELAY_URL,
|
|
111
|
+
];
|
|
112
|
+
const urls = new Set();
|
|
113
|
+
for (const value of values) {
|
|
114
|
+
if (typeof value !== 'string' || !value.trim()) continue;
|
|
115
|
+
let normalized = value.trim().replace(/^https:\/\//, 'wss://').replace(/^http:\/\//, 'ws://');
|
|
116
|
+
if (!normalized.endsWith('/ws')) normalized = `${normalized.replace(/\/$/, '')}/ws`;
|
|
117
|
+
urls.add(normalized);
|
|
118
|
+
}
|
|
119
|
+
return Array.from(urls);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export function isKademliaEnabled(env) {
|
|
123
|
+
return Boolean(env?.DB && (
|
|
124
|
+
env?.RELAY_IDENTITY_SECRET ||
|
|
125
|
+
(env?.RELAY_SIGNING_PUBLIC_KEY && env?.RELAY_SIGNING_PRIVATE_KEY)
|
|
126
|
+
));
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
async function configuredIdentity(env) {
|
|
130
|
+
if (env?.RELAY_IDENTITY_SECRET) {
|
|
131
|
+
const identity = decodeRelayIdentitySecret(env.RELAY_IDENTITY_SECRET);
|
|
132
|
+
if (!identityPromises.has(env)) {
|
|
133
|
+
identityPromises.set(env, createRelayIdentity(identity.publicKey, identity.privateKey));
|
|
134
|
+
}
|
|
135
|
+
return identityPromises.get(env);
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
const publicKey = env?.RELAY_SIGNING_PUBLIC_KEY;
|
|
139
|
+
const privateKey = env?.RELAY_SIGNING_PRIVATE_KEY;
|
|
140
|
+
if (!publicKey && !privateKey) return null;
|
|
141
|
+
if (!publicKey || !privateKey) throw new Error('Both RELAY_SIGNING_PUBLIC_KEY and RELAY_SIGNING_PRIVATE_KEY are required');
|
|
142
|
+
|
|
143
|
+
if (!identityPromises.has(env)) {
|
|
144
|
+
identityPromises.set(env, createRelayIdentity(publicKey, privateKey));
|
|
145
|
+
}
|
|
146
|
+
return identityPromises.get(env);
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* This relay's Kademlia node ID (sha256 of its signing key), or null when it
|
|
151
|
+
* has no federation identity. One relay ID everywhere: the overlay, tunnel
|
|
152
|
+
* paths, the relay list clients rank, and the relay's own PSP peer ID.
|
|
153
|
+
*/
|
|
154
|
+
export async function relayNodeIdOf(env) {
|
|
155
|
+
if (!isKademliaEnabled(env)) return null;
|
|
156
|
+
try {
|
|
157
|
+
const identity = await configuredIdentity(env);
|
|
158
|
+
return identity?.nodeId ?? null;
|
|
159
|
+
} catch {
|
|
160
|
+
return null;
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
/** 'cloud' unless the relay says otherwise (a Node relay says 'local'). */
|
|
165
|
+
export function relayKindOf(env) {
|
|
166
|
+
const kind = String(env?.RELAY_KIND ?? 'cloud').trim().toLowerCase();
|
|
167
|
+
return kind === 'local' ? 'local' : 'cloud';
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
/**
|
|
171
|
+
* The pointers this relay signs into its node record. A relay behind NAT is
|
|
172
|
+
* reached through its tunnel, and, when it accepts punched connections
|
|
173
|
+
* (PUNCH_OFFER=on, a Node relay with WebRTC), directly over a data channel
|
|
174
|
+
* introduced through that tunnel. A relay with a public address is reached there.
|
|
175
|
+
*/
|
|
176
|
+
export function relayReachOf(env, selfUrl) {
|
|
177
|
+
if (!selfUrl) return [];
|
|
178
|
+
const tunnelId = tunnelNodeIdOf(selfUrl);
|
|
179
|
+
if (!tunnelId) return [{ via: 'direct', url: selfUrl }];
|
|
180
|
+
const reach = [];
|
|
181
|
+
if (String(env?.PUNCH_OFFER ?? '').toLowerCase() === 'on') {
|
|
182
|
+
reach.push({ via: 'punch', url: punchOfferUrlFor(selfUrl) });
|
|
183
|
+
}
|
|
184
|
+
reach.push({ via: 'tunnel', url: selfUrl });
|
|
185
|
+
return reach;
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/** wss://<home>/t/<id>/ws → https://<home>/t/<id>/api/v1/punch/offer */
|
|
189
|
+
export function punchOfferUrlFor(relayUrl) {
|
|
190
|
+
const url = new URL(relayUrl);
|
|
191
|
+
url.protocol = url.protocol === 'wss:' ? 'https:' : 'http:';
|
|
192
|
+
url.pathname = url.pathname.replace(/\/ws$/, '/api/v1/punch/offer');
|
|
193
|
+
url.search = '';
|
|
194
|
+
url.hash = '';
|
|
195
|
+
return url.toString();
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
async function overlayContext(env, selfUrl, options = {}) {
|
|
199
|
+
if (!env?.DB || !selfUrl || !isKademliaEnabled(env)) return null;
|
|
200
|
+
// A public relay whose own address is loopback or private has nothing it
|
|
201
|
+
// could announce that another relay could reach: it stays out.
|
|
202
|
+
if (isPublicRelay(env) && isPrivateRelayUrl(selfUrl)) return null;
|
|
203
|
+
const identity = await configuredIdentity(env);
|
|
204
|
+
if (!identity) return null;
|
|
205
|
+
const nodeRecord = await createSignedNodeRecord(identity, {
|
|
206
|
+
url: selfUrl,
|
|
207
|
+
name: env.RELAY_NAME || null,
|
|
208
|
+
connections: options.connections || 0,
|
|
209
|
+
capacity: Number(env.RELAY_CAPACITY || 10_000),
|
|
210
|
+
relayKind: relayKindOf(env),
|
|
211
|
+
reach: relayReachOf(env, selfUrl),
|
|
212
|
+
});
|
|
213
|
+
return { env, db: env.DB, identity, nodeRecord, selfUrl: nodeRecord.url };
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
async function cleanupExpiredOverlay(context) {
|
|
217
|
+
const now = Date.now();
|
|
218
|
+
await Promise.all([
|
|
219
|
+
context.db.prepare('DELETE FROM psp_kad_nodes WHERE expires_at_ms <= ?1').bind(now).run(),
|
|
220
|
+
context.db.prepare('DELETE FROM psp_kad_records WHERE expires_at_ms <= ?1').bind(now).run(),
|
|
221
|
+
]);
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
async function upsertNodeRecord(context, record) {
|
|
225
|
+
if (record.node_id === context.identity.nodeId) return;
|
|
226
|
+
const index = bucketIndex(context.identity.nodeId, record.node_id);
|
|
227
|
+
const now = Date.now();
|
|
228
|
+
// Every RPC carries a freshly signed requester record, so an unconditional
|
|
229
|
+
// upsert rewrites a row (and both of its indexes) on every message from a
|
|
230
|
+
// contact already known. Rewrite only when the contact is new, has moved, or
|
|
231
|
+
// its stored record has less than half of its lifetime left: rows are still
|
|
232
|
+
// renewed well before they expire, but a busy contact costs one write per
|
|
233
|
+
// half-life instead of one per message. A skipped write changes no rows.
|
|
234
|
+
const written = await context.db.prepare(`
|
|
235
|
+
INSERT INTO psp_kad_nodes
|
|
236
|
+
(node_id, bucket_index, url, record_json, expires_at_ms, last_seen_ms)
|
|
237
|
+
VALUES (?1, ?2, ?3, ?4, ?5, ?6)
|
|
238
|
+
ON CONFLICT(node_id) DO UPDATE SET
|
|
239
|
+
bucket_index = excluded.bucket_index,
|
|
240
|
+
url = excluded.url,
|
|
241
|
+
record_json = excluded.record_json,
|
|
242
|
+
expires_at_ms = excluded.expires_at_ms,
|
|
243
|
+
last_seen_ms = excluded.last_seen_ms
|
|
244
|
+
WHERE psp_kad_nodes.url != excluded.url
|
|
245
|
+
OR (psp_kad_nodes.expires_at_ms - excluded.last_seen_ms) * 2
|
|
246
|
+
<= (excluded.expires_at_ms - excluded.last_seen_ms)
|
|
247
|
+
`).bind(
|
|
248
|
+
record.node_id,
|
|
249
|
+
index,
|
|
250
|
+
record.url,
|
|
251
|
+
JSON.stringify(record),
|
|
252
|
+
record.expires_at_ms,
|
|
253
|
+
now,
|
|
254
|
+
).run();
|
|
255
|
+
// Nothing was inserted or renewed, so no bucket can have grown past k.
|
|
256
|
+
if (written?.meta?.changes === 0) return;
|
|
257
|
+
|
|
258
|
+
await context.db.prepare(`
|
|
259
|
+
DELETE FROM psp_kad_nodes
|
|
260
|
+
WHERE node_id IN (
|
|
261
|
+
SELECT node_id FROM psp_kad_nodes
|
|
262
|
+
WHERE bucket_index = ?1
|
|
263
|
+
ORDER BY last_seen_ms DESC, node_id ASC
|
|
264
|
+
LIMIT -1 OFFSET ?2
|
|
265
|
+
)
|
|
266
|
+
`).bind(index, DEFAULT_K_BUCKET_SIZE).run();
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
// A record read back from the table carries the row's last_seen_ms beside
|
|
270
|
+
// the signed fields. That column is bookkeeping, not part of what the relay
|
|
271
|
+
// signed, so it is dropped before the signature is checked. Relays already
|
|
272
|
+
// deployed still serve their contacts with it attached; without this a new
|
|
273
|
+
// relay rejected every second-hand contact those relays offered and only
|
|
274
|
+
// ever knew the relays it had spoken to itself.
|
|
275
|
+
function signedNodeRecord(record) {
|
|
276
|
+
if (!record || typeof record !== 'object') return record;
|
|
277
|
+
const { last_seen_ms: _lastSeen, ...signed } = record;
|
|
278
|
+
return signed;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/**
|
|
282
|
+
* A public relay (the default) never federates a loopback or private address:
|
|
283
|
+
* it neither stores nor passes on a record naming one. Only a relay configured
|
|
284
|
+
* as part of a private mesh (FREERTC_PUBLIC=false) accepts them.
|
|
285
|
+
*/
|
|
286
|
+
export function isPublicRelay(env) {
|
|
287
|
+
const value = String(env?.FREERTC_PUBLIC ?? 'true').trim().toLowerCase();
|
|
288
|
+
return !['false', '0', 'off', 'no'].includes(value);
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
function allowsPrivateRelays(context) {
|
|
292
|
+
return !isPublicRelay(context?.env);
|
|
293
|
+
}
|
|
294
|
+
|
|
295
|
+
async function acceptNodeRecord(context, record) {
|
|
296
|
+
const signed = signedNodeRecord(record);
|
|
297
|
+
const valid = await verifySignedRelayRecord(signed, { allowedKinds: new Set([RELAY_NODE_RECORD_KIND]) });
|
|
298
|
+
if (!valid) return false;
|
|
299
|
+
if (isPrivateRelayUrl(signed.url) && !allowsPrivateRelays(context)) return false;
|
|
300
|
+
await upsertNodeRecord(context, signed);
|
|
301
|
+
return true;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
async function listActiveNodeRecords(context) {
|
|
305
|
+
const result = await context.db.prepare(`
|
|
306
|
+
SELECT record_json, last_seen_ms
|
|
307
|
+
FROM psp_kad_nodes
|
|
308
|
+
WHERE expires_at_ms > ?1
|
|
309
|
+
ORDER BY last_seen_ms DESC
|
|
310
|
+
LIMIT ?2
|
|
311
|
+
`).bind(Date.now(), MAX_ROUTING_CONTACTS).all();
|
|
312
|
+
|
|
313
|
+
const nodes = [];
|
|
314
|
+
for (const row of result.results || []) {
|
|
315
|
+
try {
|
|
316
|
+
const record = JSON.parse(row.record_json);
|
|
317
|
+
if (isNodeId(record.node_id)) nodes.push({ ...record, last_seen_ms: row.last_seen_ms });
|
|
318
|
+
} catch {}
|
|
319
|
+
}
|
|
320
|
+
return nodes;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
async function storeProviderRecord(context, record) {
|
|
324
|
+
const valid = await verifySignedRelayRecord(record, { allowedKinds: PROVIDER_RECORD_KINDS });
|
|
325
|
+
if (!valid) return false;
|
|
326
|
+
if (isPrivateRelayUrl(record.url) && !allowsPrivateRelays(context)) return false;
|
|
327
|
+
await context.db.prepare(`
|
|
328
|
+
INSERT INTO psp_kad_records
|
|
329
|
+
(routing_key, owner_node_id, kind, sequence, record_json, expires_at_ms)
|
|
330
|
+
VALUES (?1, ?2, ?3, ?4, ?5, ?6)
|
|
331
|
+
ON CONFLICT(routing_key, owner_node_id, kind) DO UPDATE SET
|
|
332
|
+
sequence = excluded.sequence,
|
|
333
|
+
record_json = excluded.record_json,
|
|
334
|
+
expires_at_ms = excluded.expires_at_ms
|
|
335
|
+
WHERE excluded.sequence > psp_kad_records.sequence
|
|
336
|
+
`).bind(
|
|
337
|
+
record.key,
|
|
338
|
+
record.node_id,
|
|
339
|
+
record.kind,
|
|
340
|
+
record.sequence,
|
|
341
|
+
JSON.stringify(record),
|
|
342
|
+
record.expires_at_ms,
|
|
343
|
+
).run();
|
|
344
|
+
return true;
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
async function findLocalProviderRecords(context, routingKey) {
|
|
348
|
+
const result = await context.db.prepare(`
|
|
349
|
+
SELECT record_json
|
|
350
|
+
FROM psp_kad_records
|
|
351
|
+
WHERE routing_key = ?1 AND expires_at_ms > ?2
|
|
352
|
+
ORDER BY sequence DESC
|
|
353
|
+
LIMIT ?3
|
|
354
|
+
`).bind(routingKey, Date.now(), MAX_LOOKUP_RECORDS).all();
|
|
355
|
+
const records = [];
|
|
356
|
+
for (const row of result.results || []) {
|
|
357
|
+
try {
|
|
358
|
+
const record = JSON.parse(row.record_json);
|
|
359
|
+
if (record.key === routingKey) records.push(record);
|
|
360
|
+
} catch {}
|
|
361
|
+
}
|
|
362
|
+
return records;
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
async function postRpc(relayUrl, path, body) {
|
|
366
|
+
const controller = new AbortController();
|
|
367
|
+
const timer = setTimeout(() => controller.abort(), RPC_TIMEOUT_MS);
|
|
368
|
+
try {
|
|
369
|
+
const response = await relayFetch(`${relayHttpBase(relayUrl)}${path}`, {
|
|
370
|
+
method: 'POST',
|
|
371
|
+
headers: { 'Content-Type': 'application/json' },
|
|
372
|
+
body: JSON.stringify(body),
|
|
373
|
+
signal: controller.signal,
|
|
374
|
+
});
|
|
375
|
+
if (!response.ok) return null;
|
|
376
|
+
const responseBody = await response.text();
|
|
377
|
+
if (responseBody.length > MAX_RPC_BODY_BYTES) return null;
|
|
378
|
+
return JSON.parse(responseBody);
|
|
379
|
+
} catch {
|
|
380
|
+
return null;
|
|
381
|
+
} finally {
|
|
382
|
+
clearTimeout(timer);
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
async function acceptLookupResponse(context, response, targetId, records, knownNodeIds = null) {
|
|
387
|
+
if (!response?.ok) return [];
|
|
388
|
+
const responseNodes = Array.isArray(response.nodes) ? response.nodes : [];
|
|
389
|
+
const uniqueNodes = Array.from(new Map(
|
|
390
|
+
[response.node, ...responseNodes]
|
|
391
|
+
.filter((node) => typeof node?.node_id === 'string')
|
|
392
|
+
// Another relay's table holds this relay too; a lookup never adds
|
|
393
|
+
// itself to its own shortlist.
|
|
394
|
+
.filter((node) => node.node_id !== context.identity.nodeId)
|
|
395
|
+
.filter((node) => !knownNodeIds?.has(node.node_id))
|
|
396
|
+
.map((node) => [node.node_id, node]),
|
|
397
|
+
).values());
|
|
398
|
+
const acceptedNodes = await Promise.all(uniqueNodes.map(async (node) => (
|
|
399
|
+
await acceptNodeRecord(context, node) ? node : null
|
|
400
|
+
)));
|
|
401
|
+
|
|
402
|
+
const responseRecords = Array.isArray(response.records) ? response.records : [];
|
|
403
|
+
const acceptedRecords = await Promise.all(responseRecords.map(async (record) => {
|
|
404
|
+
if (record?.key !== targetId || !await storeProviderRecord(context, record)) return null;
|
|
405
|
+
return record;
|
|
406
|
+
}));
|
|
407
|
+
for (const record of acceptedRecords) {
|
|
408
|
+
if (record) records.set(`${record.kind}:${record.node_id}`, record);
|
|
409
|
+
}
|
|
410
|
+
return acceptedNodes.filter(Boolean);
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
async function iterativeLookup(context, targetId, wantRecords = false) {
|
|
414
|
+
const known = new Map();
|
|
415
|
+
const queried = new Set();
|
|
416
|
+
const records = new Map();
|
|
417
|
+
for (const node of await listActiveNodeRecords(context)) known.set(node.node_id, node);
|
|
418
|
+
|
|
419
|
+
let queryCount = 0;
|
|
420
|
+
while (queryCount < MAX_LOOKUP_QUERIES) {
|
|
421
|
+
const shortlist = selectClosestNodes(Array.from(known.values()), targetId, DEFAULT_K_BUCKET_SIZE * 2);
|
|
422
|
+
const remainingQueries = MAX_LOOKUP_QUERIES - queryCount;
|
|
423
|
+
const batch = shortlist
|
|
424
|
+
.filter((node) => !queried.has(node.node_id))
|
|
425
|
+
.slice(0, Math.min(DEFAULT_LOOKUP_ALPHA, remainingQueries));
|
|
426
|
+
if (batch.length === 0) break;
|
|
427
|
+
for (const node of batch) queried.add(node.node_id);
|
|
428
|
+
queryCount += batch.length;
|
|
429
|
+
|
|
430
|
+
const responses = await Promise.all(batch.map((node) => postRpc(node.url, '/api/v1/kad/find', {
|
|
431
|
+
target: targetId,
|
|
432
|
+
want_records: wantRecords,
|
|
433
|
+
requester: context.nodeRecord,
|
|
434
|
+
})));
|
|
435
|
+
const knownNodeIds = new Set(known.keys());
|
|
436
|
+
const receivedGroups = await Promise.all(
|
|
437
|
+
responses.map((response) => acceptLookupResponse(
|
|
438
|
+
context,
|
|
439
|
+
response,
|
|
440
|
+
targetId,
|
|
441
|
+
records,
|
|
442
|
+
knownNodeIds,
|
|
443
|
+
)),
|
|
444
|
+
);
|
|
445
|
+
for (const received of receivedGroups) {
|
|
446
|
+
for (const node of received) known.set(node.node_id, node);
|
|
447
|
+
}
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
if (wantRecords) {
|
|
451
|
+
for (const record of await findLocalProviderRecords(context, targetId)) {
|
|
452
|
+
if (await verifySignedRelayRecord(record, { allowedKinds: PROVIDER_RECORD_KINDS })) {
|
|
453
|
+
records.set(`${record.kind}:${record.node_id}`, record);
|
|
454
|
+
}
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
return {
|
|
459
|
+
nodes: selectClosestNodes(Array.from(known.values()), targetId, DEFAULT_K_BUCKET_SIZE),
|
|
460
|
+
records: Array.from(records.values()),
|
|
461
|
+
queries: queryCount,
|
|
462
|
+
};
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
/** The urls in a random order, so no one seed is every relay's first stop. */
|
|
466
|
+
function shuffled(urls) {
|
|
467
|
+
const out = [...urls];
|
|
468
|
+
for (let i = out.length - 1; i > 0; i -= 1) {
|
|
469
|
+
const j = Math.floor(Math.random() * (i + 1));
|
|
470
|
+
[out[i], out[j]] = [out[j], out[i]];
|
|
471
|
+
}
|
|
472
|
+
return out;
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
/** The relays closest to this one among those it has heard of: where to join when no seed answers. */
|
|
476
|
+
async function learnedBootstrapUrls(context, exclude) {
|
|
477
|
+
const known = await listActiveNodeRecords(context);
|
|
478
|
+
return selectClosestNodes(known, context.identity.nodeId, DEFAULT_K_BUCKET_SIZE)
|
|
479
|
+
.map((node) => node.url)
|
|
480
|
+
.filter((url) => typeof url === 'string' && url && !exclude.has(url) && url !== context.selfUrl);
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
/**
|
|
484
|
+
* Every relay this one can join or rejoin through: the configured seeds and
|
|
485
|
+
* every live federated relay it knows. Any federated relay is a bootstrap;
|
|
486
|
+
* the configured ones are only where a relay that knows nobody yet starts.
|
|
487
|
+
*/
|
|
488
|
+
export async function listBootstrapUrls(env, selfUrl, options = {}) {
|
|
489
|
+
const urls = new Set(configuredBootstrapUrls(env));
|
|
490
|
+
const context = await overlayContext(env, selfUrl, options).catch(() => null);
|
|
491
|
+
if (context) {
|
|
492
|
+
for (const node of await listActiveNodeRecords(context)) {
|
|
493
|
+
if (typeof node?.url === 'string' && node.url) urls.add(node.url);
|
|
494
|
+
}
|
|
495
|
+
}
|
|
496
|
+
urls.delete(selfUrl);
|
|
497
|
+
if (context) urls.delete(context.selfUrl);
|
|
498
|
+
return [...urls];
|
|
499
|
+
}
|
|
500
|
+
|
|
501
|
+
// The standard Kademlia join. No relay is the hub: any relay can be a seed, and a seed answers
|
|
502
|
+
// with the relays closest to the joiner's own id, which is how a new relay is directed to the
|
|
503
|
+
// ones near it. So one seed is asked, in random order, and the first to answer is enough;
|
|
504
|
+
// asking every seed and every relay ever heard of at once was a fan-out that grew with the
|
|
505
|
+
// network and that every receiver wrote down. Relays learned from earlier answers are only
|
|
506
|
+
// tried when every configured seed is unreachable, so a relay still rejoins through its
|
|
507
|
+
// neighbours when the seeds are down.
|
|
508
|
+
async function joinBootstrap(context) {
|
|
509
|
+
const seeds = shuffled(configuredBootstrapUrls(context.env).filter((url) => url !== context.selfUrl));
|
|
510
|
+
const tried = [];
|
|
511
|
+
const records = new Map();
|
|
512
|
+
const askOneOf = async (urls) => {
|
|
513
|
+
for (const url of urls) {
|
|
514
|
+
tried.push(url);
|
|
515
|
+
const response = await postRpc(url, '/api/v1/kad/find', {
|
|
516
|
+
target: context.identity.nodeId,
|
|
517
|
+
want_records: false,
|
|
518
|
+
requester: context.nodeRecord,
|
|
519
|
+
});
|
|
520
|
+
if (response?.ok) {
|
|
521
|
+
await acceptLookupResponse(context, response, context.identity.nodeId, records);
|
|
522
|
+
return true;
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
return false;
|
|
526
|
+
};
|
|
527
|
+
// Every federated relay is a bootstrap: a relay rejoins through any one it knows, configured or not.
|
|
528
|
+
const joined = await askOneOf(seeds) || await askOneOf(shuffled(await learnedBootstrapUrls(context, new Set(seeds))));
|
|
529
|
+
return { bootstrapUrls: tried, joined: joined ? 1 : 0 };
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
async function ensureRoutingContacts(context) {
|
|
533
|
+
const bootstrapKey = configuredBootstrapUrls(context.env)
|
|
534
|
+
.filter((url) => url !== context.selfUrl)
|
|
535
|
+
.sort()
|
|
536
|
+
.join("\n");
|
|
537
|
+
const recentJoin = recentBootstrapJoins.get(context.env);
|
|
538
|
+
if (recentJoin?.bootstrapKey === bootstrapKey &&
|
|
539
|
+
Date.now() - recentJoin.completedAt < BOOTSTRAP_REFRESH_INTERVAL_MS) {
|
|
540
|
+
return;
|
|
541
|
+
}
|
|
542
|
+
|
|
543
|
+
if (!joinPromises.has(context.env)) {
|
|
544
|
+
const join = joinBootstrap(context)
|
|
545
|
+
.then(({ bootstrapUrls, joined }) => {
|
|
546
|
+
// Do not cache a failed bootstrap attempt. An isolated relay retries on
|
|
547
|
+
// the very next operation instead of inheriting a recovery backoff.
|
|
548
|
+
if (bootstrapUrls.length === 0 || joined > 0) {
|
|
549
|
+
recentBootstrapJoins.set(context.env, {
|
|
550
|
+
bootstrapKey,
|
|
551
|
+
completedAt: Date.now(),
|
|
552
|
+
});
|
|
553
|
+
}
|
|
554
|
+
})
|
|
555
|
+
.finally(() => joinPromises.delete(context.env));
|
|
556
|
+
joinPromises.set(context.env, join);
|
|
557
|
+
}
|
|
558
|
+
const pending = joinPromises.get(context.env);
|
|
559
|
+
try {
|
|
560
|
+
await withTimeout(pending, SHARED_WAIT_TIMEOUT_MS, 'Kademlia bootstrap');
|
|
561
|
+
} catch (error) {
|
|
562
|
+
// Forget the stuck join so the next operation starts a fresh one; this
|
|
563
|
+
// caller carries on with whatever contacts are already in the table.
|
|
564
|
+
if (joinPromises.get(context.env) === pending) joinPromises.delete(context.env);
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
async function replicateProviderRecord(context, record, wantRecords = false) {
|
|
569
|
+
await storeProviderRecord(context, record);
|
|
570
|
+
const lookup = await iterativeLookup(context, record.key, wantRecords);
|
|
571
|
+
const closest = selectClosestNodes([...lookup.nodes, context.nodeRecord], record.key, DEFAULT_REPLICATION_FACTOR);
|
|
572
|
+
await Promise.all(closest
|
|
573
|
+
.filter((node) => node.node_id !== context.identity.nodeId)
|
|
574
|
+
.map((node) => postRpc(node.url, '/api/v1/kad/store', {
|
|
575
|
+
requester: context.nodeRecord,
|
|
576
|
+
record,
|
|
577
|
+
})));
|
|
578
|
+
return lookup;
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
/**
|
|
582
|
+
* Every relay in the routing table, as a client-facing bootstrap list. A
|
|
583
|
+
* client that reaches any one relay can learn every relay that one has
|
|
584
|
+
* verified, so no relay is a private detour and the hub is not the only
|
|
585
|
+
* place a peer can start from.
|
|
586
|
+
*/
|
|
587
|
+
export async function listKnownRelays(env, selfUrl, options = {}) {
|
|
588
|
+
const context = await overlayContext(env, selfUrl, options);
|
|
589
|
+
if (!context) return [];
|
|
590
|
+
const known = await listActiveNodeRecords(context);
|
|
591
|
+
const relays = [];
|
|
592
|
+
for (const node of [context.nodeRecord, ...known]) {
|
|
593
|
+
if (typeof node?.url !== 'string' || !node.url) continue;
|
|
594
|
+
relays.push({
|
|
595
|
+
url: node.url,
|
|
596
|
+
name: node.name ?? null,
|
|
597
|
+
node_id: node.node_id,
|
|
598
|
+
connections: Number(node.connections || 0),
|
|
599
|
+
capacity: Number(node.capacity || 0),
|
|
600
|
+
relay_kind: node.relay_kind ?? 'cloud',
|
|
601
|
+
reach: Array.isArray(node.reach) ? node.reach : [],
|
|
602
|
+
});
|
|
603
|
+
}
|
|
604
|
+
return relays;
|
|
605
|
+
}
|
|
606
|
+
|
|
607
|
+
async function hasLiveContacts(context) {
|
|
608
|
+
const result = await context.db.prepare(
|
|
609
|
+
'SELECT node_id FROM psp_kad_nodes WHERE expires_at_ms > ?1 LIMIT ?2',
|
|
610
|
+
).bind(Date.now(), 1).all();
|
|
611
|
+
return (result.results || []).length > 0;
|
|
612
|
+
}
|
|
613
|
+
|
|
614
|
+
/**
|
|
615
|
+
* Join the overlay when this relay knows nobody. A relay that already holds a live contact
|
|
616
|
+
* has nothing to refresh on a clock: it learns contacts from the traffic that passes through
|
|
617
|
+
* it, and an operation that needs more joins on demand (ensureRoutingContacts). Without this
|
|
618
|
+
* every isolate the platform starts repeated the join and a walk toward its own id every
|
|
619
|
+
* two minutes, and each repeat was a fan-out of RPCs that the receivers wrote down.
|
|
620
|
+
*/
|
|
621
|
+
/** How many relays one heartbeat announces itself to. */
|
|
622
|
+
const MAX_HEARTBEAT_ANNOUNCE = 16;
|
|
623
|
+
|
|
624
|
+
/**
|
|
625
|
+
* Stay federated. Other relays drop a node record that isn't refreshed before it
|
|
626
|
+
* expires (MAX_NODE_RECORD_TTL_MS), so every heartbeat announces this relay: it
|
|
627
|
+
* pings each relay it knows and its bootstrap relays, and every ping carries
|
|
628
|
+
* this relay's signed record. A relay that knows nobody joins first. The
|
|
629
|
+
* answers say who confirmed it: `confirmed_by` lists the relays that answered.
|
|
630
|
+
*/
|
|
631
|
+
export async function heartbeatKademlia(env, selfUrl, options = {}) {
|
|
632
|
+
const context = await overlayContext(env, selfUrl, options);
|
|
633
|
+
if (!context) return { enabled: false };
|
|
634
|
+
await cleanupExpiredOverlay(context);
|
|
635
|
+
let joined = false;
|
|
636
|
+
if (!await hasLiveContacts(context)) {
|
|
637
|
+
await ensureRoutingContacts(context);
|
|
638
|
+
await iterativeLookup(context, context.identity.nodeId, false);
|
|
639
|
+
joined = true;
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
const targets = new Set();
|
|
643
|
+
for (const node of await listActiveNodeRecords(context)) {
|
|
644
|
+
if (typeof node.url === 'string' && node.url !== context.selfUrl) targets.add(node.url);
|
|
645
|
+
}
|
|
646
|
+
for (const url of configuredBootstrapUrls(context.env)) {
|
|
647
|
+
if (url !== context.selfUrl) targets.add(url);
|
|
648
|
+
}
|
|
649
|
+
const asked = [...targets].slice(0, MAX_HEARTBEAT_ANNOUNCE);
|
|
650
|
+
const answers = await Promise.all(asked.map(async (url) => {
|
|
651
|
+
const response = await postRpc(url, '/api/v1/kad/ping', { requester: context.nodeRecord });
|
|
652
|
+
if (!response?.ok) return null;
|
|
653
|
+
if (response.node) await acceptNodeRecord(context, response.node).catch(() => false);
|
|
654
|
+
return url;
|
|
655
|
+
}));
|
|
656
|
+
return {
|
|
657
|
+
enabled: true,
|
|
658
|
+
node_id: context.identity.nodeId,
|
|
659
|
+
joined,
|
|
660
|
+
asked,
|
|
661
|
+
confirmed_by: answers.filter(Boolean),
|
|
662
|
+
};
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
/**
|
|
666
|
+
* Announce that this relay serves a room. Called on every peer's announce and heartbeat, it
|
|
667
|
+
* publishes at most once a minute per relay and room, whichever peer asks. Which relay holds
|
|
668
|
+
* one particular peer is not published: a sender asks the relays that serve the room, and
|
|
669
|
+
* only the one that holds the peer delivers (see handleRelayForward). `_peerId` stays in the
|
|
670
|
+
* signature for the callers that pass it.
|
|
671
|
+
*/
|
|
672
|
+
export async function publishPeerProviderRecords(env, selfUrl, network, room, _peerId, options = {}) {
|
|
673
|
+
const context = await overlayContext(env, selfUrl, options);
|
|
674
|
+
if (!context) return false;
|
|
675
|
+
// Keyed by address too: a relay whose address changes (a NAT'd relay moving to
|
|
676
|
+
// another tunnel home) republishes at once instead of leaving the old one up.
|
|
677
|
+
const throttleKey = `${context.identity.nodeId}:${context.selfUrl}:${network}:${room}`;
|
|
678
|
+
const now = Date.now();
|
|
679
|
+
if (!markProviderPublish(throttleKey, now)) return true;
|
|
680
|
+
await ensureRoutingContacts(context);
|
|
681
|
+
|
|
682
|
+
const scopeRecord = await createSignedProviderRecord(context.identity, {
|
|
683
|
+
url: context.selfUrl,
|
|
684
|
+
connections: options.connections || 0,
|
|
685
|
+
capacity: Number(env.RELAY_CAPACITY || 10_000),
|
|
686
|
+
ttlMs: PROVIDER_RECORD_TTL_MS,
|
|
687
|
+
now,
|
|
688
|
+
kind: SCOPE_PROVIDER_RECORD_KIND,
|
|
689
|
+
key: await scopeRoutingKey(network, room),
|
|
690
|
+
});
|
|
691
|
+
const scopeLookup = await replicateProviderRecord(context, scopeRecord, Boolean(options.returnScopeProviders));
|
|
692
|
+
if (options.returnScopeProviders) {
|
|
693
|
+
const records = [scopeRecord, ...scopeLookup.records]
|
|
694
|
+
.filter((record) => record.kind === SCOPE_PROVIDER_RECORD_KIND && record.key === scopeRecord.key);
|
|
695
|
+
return rankProviderRecords(records, MAX_PROVIDER_RELAYS);
|
|
696
|
+
}
|
|
697
|
+
return true;
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
async function lookupProviders(env, selfUrl, routingKey, kind, options = {}) {
|
|
701
|
+
const context = await overlayContext(env, selfUrl, options);
|
|
702
|
+
if (!context) return [];
|
|
703
|
+
await ensureRoutingContacts(context);
|
|
704
|
+
const lookup = await iterativeLookup(context, routingKey, true);
|
|
705
|
+
const records = [];
|
|
706
|
+
for (const record of lookup.records) {
|
|
707
|
+
if (record.kind !== kind || record.key !== routingKey) continue;
|
|
708
|
+
if (await verifySignedRelayRecord(record, { allowedKinds: new Set([kind]) })) records.push(record);
|
|
709
|
+
}
|
|
710
|
+
return rankProviderRecords(records, MAX_PROVIDER_RELAYS);
|
|
711
|
+
}
|
|
712
|
+
|
|
713
|
+
// Discovery always asks the overlay. A relay that looked a room up before any other relay served
|
|
714
|
+
// it would otherwise keep "only me" for minutes and never find the peers that joined elsewhere.
|
|
715
|
+
// Asking means asking recently, not once per peer: discovers for one room within
|
|
716
|
+
// SCOPE_LOOKUP_SHARE_MS share one lookup (a room filling up was one overlay walk per joining
|
|
717
|
+
// peer, two find RPCs at every relay each time), and a relay that starts serving the room is
|
|
718
|
+
// still found within that window.
|
|
719
|
+
const SCOPE_LOOKUP_SHARE_MS = 5_000;
|
|
720
|
+
const MAX_SHARED_SCOPE_LOOKUPS = 2_000;
|
|
721
|
+
const sharedScopeLookups = new Map();
|
|
722
|
+
|
|
723
|
+
export async function lookupScopeProviders(env, selfUrl, network, room, options = {}) {
|
|
724
|
+
const cacheKey = JSON.stringify([selfUrl, network, room]);
|
|
725
|
+
const now = Date.now();
|
|
726
|
+
const shared = sharedScopeLookups.get(cacheKey);
|
|
727
|
+
if (shared && now - shared.startedAt < SCOPE_LOOKUP_SHARE_MS) {
|
|
728
|
+
try {
|
|
729
|
+
return await withTimeout(shared.promise, SHARED_WAIT_TIMEOUT_MS * 2, 'Scope provider lookup');
|
|
730
|
+
} catch {
|
|
731
|
+
// A failed or stuck shared lookup: fall through to one of our own.
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
const promise = (async () => lookupProviders(env, selfUrl, await scopeRoutingKey(network, room), SCOPE_PROVIDER_RECORD_KIND, options))();
|
|
735
|
+
sharedScopeLookups.set(cacheKey, { promise, startedAt: now });
|
|
736
|
+
if (sharedScopeLookups.size > MAX_SHARED_SCOPE_LOOKUPS) {
|
|
737
|
+
const oldest = sharedScopeLookups.keys().next().value;
|
|
738
|
+
if (oldest !== undefined) sharedScopeLookups.delete(oldest);
|
|
739
|
+
}
|
|
740
|
+
promise.catch(() => { if (sharedScopeLookups.get(cacheKey)?.promise === promise) sharedScopeLookups.delete(cacheKey); });
|
|
741
|
+
return promise;
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
/**
|
|
745
|
+
* Forget a room's cached providers so the next lookup asks the overlay, unless they were
|
|
746
|
+
* fetched within PEER_PROVIDER_REFRESH_MIN_AGE_MS. Returns whether they were forgotten: a
|
|
747
|
+
* forward the cached relays could not deliver calls this, and a peer that is simply gone
|
|
748
|
+
* cannot make every message for it a fresh lookup.
|
|
749
|
+
*/
|
|
750
|
+
export function refreshRoomProviders(selfUrl, network, room, now = Date.now()) {
|
|
751
|
+
const cacheKey = JSON.stringify([selfUrl, network, room]);
|
|
752
|
+
const cached = recentPeerProviderLookups.get(cacheKey);
|
|
753
|
+
if (!cached?.records) return false;
|
|
754
|
+
if (now - cached.fetchedAt < PEER_PROVIDER_REFRESH_MIN_AGE_MS) return false;
|
|
755
|
+
recentPeerProviderLookups.delete(cacheKey);
|
|
756
|
+
return true;
|
|
757
|
+
}
|
|
758
|
+
|
|
759
|
+
/**
|
|
760
|
+
* The relays that serve a room, which is where a message for any peer in it may be waiting.
|
|
761
|
+
* No relay publishes where one peer lives, so a sender asks these, and the one that does not
|
|
762
|
+
* hold the peer says so (handleRelayForward). Concurrent callers share one lookup: an offer
|
|
763
|
+
* and its burst of ICE packets all target the same room.
|
|
764
|
+
*/
|
|
765
|
+
export async function lookupRoomProviders(env, selfUrl, network, room, options = {}) {
|
|
766
|
+
const routingKey = await scopeRoutingKey(network, room);
|
|
767
|
+
const cacheKey = JSON.stringify([selfUrl, network, room]);
|
|
768
|
+
const now = Date.now();
|
|
769
|
+
const cached = recentPeerProviderLookups.get(cacheKey);
|
|
770
|
+
if (cached?.promise) {
|
|
771
|
+
if (now - cached.startedAt < SHARED_WAIT_TIMEOUT_MS) {
|
|
772
|
+
try {
|
|
773
|
+
return await withTimeout(cached.promise, SHARED_WAIT_TIMEOUT_MS, 'Peer provider lookup');
|
|
774
|
+
} catch {
|
|
775
|
+
// Fall through to a fresh lookup of our own.
|
|
776
|
+
}
|
|
777
|
+
}
|
|
778
|
+
if (recentPeerProviderLookups.get(cacheKey) === cached) recentPeerProviderLookups.delete(cacheKey);
|
|
779
|
+
} else if (cached?.records && cached.expiresAt > now) {
|
|
780
|
+
return cached.records;
|
|
781
|
+
} else if (cached) {
|
|
782
|
+
recentPeerProviderLookups.delete(cacheKey);
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
// One WebRTC offer commonly produces an offer plus a burst of ICE packets.
|
|
786
|
+
// They all target the same peer and must share one Kademlia lookup instead of
|
|
787
|
+
// launching an expensive overlay walk per packet. Empty results are not
|
|
788
|
+
// cached so a just-published provider can be found by the next packet.
|
|
789
|
+
const promise = lookupProviders(env, selfUrl, routingKey, SCOPE_PROVIDER_RECORD_KIND, options)
|
|
790
|
+
.then((records) => {
|
|
791
|
+
if (records.length > 0) {
|
|
792
|
+
rememberPeerProviderLookup(cacheKey, {
|
|
793
|
+
records,
|
|
794
|
+
fetchedAt: Date.now(),
|
|
795
|
+
// Never trusted past the first of its records to lapse.
|
|
796
|
+
expiresAt: Math.min(
|
|
797
|
+
Date.now() + PEER_PROVIDER_LOOKUP_CACHE_MS,
|
|
798
|
+
...records.map((record) => Number(record.expires_at_ms) || Infinity),
|
|
799
|
+
),
|
|
800
|
+
});
|
|
801
|
+
} else {
|
|
802
|
+
recentPeerProviderLookups.delete(cacheKey);
|
|
803
|
+
}
|
|
804
|
+
return records;
|
|
805
|
+
})
|
|
806
|
+
.catch((error) => {
|
|
807
|
+
recentPeerProviderLookups.delete(cacheKey);
|
|
808
|
+
throw error;
|
|
809
|
+
});
|
|
810
|
+
rememberPeerProviderLookup(cacheKey, { promise, expiresAt: now, startedAt: now });
|
|
811
|
+
return withTimeout(promise, SHARED_WAIT_TIMEOUT_MS * 2, 'Peer provider lookup');
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
export async function handleKademliaRequest(request, env, options = {}) {
|
|
815
|
+
if (request.method !== 'POST') return jsonResponse({ ok: false, error: 'Method not allowed' }, 405);
|
|
816
|
+
const contentLength = Number(request.headers.get('Content-Length') || 0);
|
|
817
|
+
if (contentLength > MAX_RPC_BODY_BYTES) return jsonResponse({ ok: false, error: 'Request too large' }, 413);
|
|
818
|
+
|
|
819
|
+
const context = await overlayContext(env, options.selfUrl, options);
|
|
820
|
+
if (!context) return jsonResponse({ ok: false, error: 'Kademlia relay identity is not configured' }, 503);
|
|
821
|
+
|
|
822
|
+
let body;
|
|
823
|
+
try {
|
|
824
|
+
body = await request.json();
|
|
825
|
+
} catch {
|
|
826
|
+
return jsonResponse({ ok: false, error: 'Invalid JSON' }, 400);
|
|
827
|
+
}
|
|
828
|
+
if (!await acceptNodeRecord(context, body?.requester)) {
|
|
829
|
+
return jsonResponse({ ok: false, error: 'Invalid signed requester record' }, 401);
|
|
830
|
+
}
|
|
831
|
+
|
|
832
|
+
const path = new URL(request.url).pathname;
|
|
833
|
+
if (path === '/api/v1/kad/ping') {
|
|
834
|
+
return jsonResponse({ ok: true, node: context.nodeRecord });
|
|
835
|
+
}
|
|
836
|
+
|
|
837
|
+
if (path === '/api/v1/kad/find') {
|
|
838
|
+
if (!isNodeId(body.target)) return jsonResponse({ ok: false, error: 'Invalid target' }, 400);
|
|
839
|
+
const localNodes = await listActiveNodeRecords(context);
|
|
840
|
+
const nodes = selectClosestNodes([...localNodes, context.nodeRecord], body.target, DEFAULT_K_BUCKET_SIZE)
|
|
841
|
+
.map(signedNodeRecord);
|
|
842
|
+
const records = body.want_records ? await findLocalProviderRecords(context, body.target) : [];
|
|
843
|
+
return jsonResponse({ ok: true, node: context.nodeRecord, nodes, records });
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
if (path === '/api/v1/kad/store') {
|
|
847
|
+
if (body.record?.node_id !== body.requester.node_id) {
|
|
848
|
+
return jsonResponse({ ok: false, error: 'A relay may only publish its own provider record' }, 403);
|
|
849
|
+
}
|
|
850
|
+
if (!await storeProviderRecord(context, body.record)) {
|
|
851
|
+
return jsonResponse({ ok: false, error: 'Invalid signed provider record' }, 400);
|
|
852
|
+
}
|
|
853
|
+
return jsonResponse({ ok: true, stored: true });
|
|
854
|
+
}
|
|
855
|
+
|
|
856
|
+
return jsonResponse({ ok: false, error: 'Unknown Kademlia endpoint' }, 404);
|
|
857
|
+
}
|