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.
Files changed (60) hide show
  1. package/README.md +204 -12
  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 -169
  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,276 @@
1
+ // The relay end of a tunnel (see home.js): a relay behind NAT keeps one
2
+ // WebSocket open outward to a public relay and answers, through it, what is
3
+ // sent to its public tunnel address. If that home goes away it moves to the
4
+ // next one, and its address moves with it.
5
+ import { createSignedNodeRecord, signTunnelChallenge } from '../relay-identity.js';
6
+ import { TUNNEL_PING, TUNNEL_PONG, MAX_TUNNEL_BODY_BYTES, decodeBody, encodeBody, forwardHeaders, tunnelUrlFor } from './frames.js';
7
+
8
+ const PING_EVERY_MS = 25_000;
9
+ const DEAD_AFTER_MS = 70_000;
10
+ const CONNECT_TIMEOUT_MS = 15_000;
11
+ const MAX_BACKOFF_MS = 30_000;
12
+ // A home that refuses with 429 or 5xx (a cloud relay out of its daily
13
+ // requests answers 503) is left alone, longer each time (1, 2, 4 ... 60
14
+ // min), but tried again just after midnight UTC, when Cloudflare's daily
15
+ // limits reset. Retrying it every second only spends what it has run out of.
16
+ const REFUSED_BACKOFF_MIN_MS = 60_000;
17
+ const REFUSED_BACKOFF_MAX_MS = 60 * 60_000;
18
+
19
+ /** Just after the next midnight UTC. */
20
+ function nextUtcReset(now) {
21
+ const next = new Date(now);
22
+ next.setUTCHours(24, 0, 5, 0);
23
+ return next.getTime();
24
+ }
25
+
26
+ function connectUrl(homeUrl, nodeId) {
27
+ return tunnelUrlFor(homeUrl, nodeId).replace(/\/ws$/, '/connect');
28
+ }
29
+
30
+ /** "41m", "3h12m", "18s": how long a tunnel stayed open. */
31
+ function formatUptime(ms) {
32
+ const seconds = Math.round(ms / 1000);
33
+ if (seconds < 60) return `${seconds}s`;
34
+ const minutes = Math.floor(seconds / 60);
35
+ if (minutes < 60) return `${minutes}m`;
36
+ return `${Math.floor(minutes / 60)}h${String(minutes % 60).padStart(2, '0')}m`;
37
+ }
38
+
39
+ function httpOrigin(tunnelUrl) {
40
+ return tunnelUrl.replace(/^wss:/, 'https:').replace(/^ws:/, 'http:').replace(/\/t\/[0-9a-f]{64}\/ws$/, '');
41
+ }
42
+
43
+ /**
44
+ * A WebSocket opened to the relay's public address, seen from the relay: the
45
+ * same shape as a `ws` socket (send, close, on('message' | 'close' | 'error')).
46
+ */
47
+ class TunnelStream {
48
+ constructor(sid, sendFrame) {
49
+ this.sid = sid;
50
+ this.sendFrame = sendFrame;
51
+ this.OPEN = 1;
52
+ this.readyState = 1;
53
+ this.handlers = { message: [], close: [], error: [] };
54
+ }
55
+
56
+ on(type, handler) {
57
+ this.handlers[type]?.push(handler);
58
+ return this;
59
+ }
60
+
61
+ emit(type, ...args) {
62
+ for (const handler of this.handlers[type] || []) {
63
+ try {
64
+ handler(...args);
65
+ } catch {}
66
+ }
67
+ }
68
+
69
+ send(data) {
70
+ if (this.readyState !== 1) throw new Error('WebSocket is not open');
71
+ this.sendFrame({ t: 'data', sid: this.sid, data: String(data) });
72
+ }
73
+
74
+ close(code = 1000, reason = '') {
75
+ if (this.readyState !== 1) return;
76
+ this.sendFrame({ t: 'end', sid: this.sid, code, reason });
77
+ this.ended(code, reason);
78
+ }
79
+
80
+ ended(code = 1000, reason = '') {
81
+ if (this.readyState !== 1) return;
82
+ this.readyState = 3;
83
+ this.emit('close', code, Buffer.from(String(reason)));
84
+ }
85
+ }
86
+
87
+ /**
88
+ * Keep a tunnel open through the first home that takes it.
89
+ *
90
+ * homes public relay URLs to try, in order
91
+ * identity the relay identity (createRelayIdentity)
92
+ * handleRequest (Request) => Response, for HTTP sent to the tunnel address
93
+ * handleStream (socket, { path, headers }) => void, for WebSockets
94
+ * onUrl (url | null) => void, when the public address changes or is lost
95
+ */
96
+ export function startTunnel({ homes, identity, name, handleRequest, handleStream, onUrl = () => {}, log = () => {}, WebSocketImpl }) {
97
+ if (!homes?.length) throw new Error('A tunnel needs at least one home relay');
98
+ let stopped = false;
99
+ let current = null;
100
+ let currentUrl = null;
101
+ let homeIndex = 0;
102
+ let failures = 0;
103
+ const refusedUntil = new Map(); // home URL -> ms
104
+ const refusedBackoff = new Map(); // home URL -> its next backoff, ms
105
+ let saidAllRefused = false;
106
+ let readyResolve;
107
+ const ready = new Promise((resolve) => { readyResolve = resolve; });
108
+
109
+ const setUrl = (url) => {
110
+ if (url === currentUrl) return;
111
+ currentUrl = url;
112
+ onUrl(url);
113
+ };
114
+
115
+ async function connect() {
116
+ if (stopped) return;
117
+ const WS = WebSocketImpl ?? (await import('ws')).default;
118
+ // Skip homes that refused us recently; if all did, wait for the first
119
+ // to come off its backoff.
120
+ const now = Date.now();
121
+ let tries = 0;
122
+ while (tries < homes.length && (refusedUntil.get(homes[homeIndex % homes.length]) ?? 0) > now) { homeIndex += 1; tries += 1; }
123
+ if (tries >= homes.length) {
124
+ const wait = Math.max(1_000, Math.min(...homes.map((h) => refusedUntil.get(h) ?? now)) - now);
125
+ if (!saidAllRefused) log(`every home relay refused (429/5xx: out of requests?); waiting ${wait < 120_000 ? `${Math.round(wait / 1000)} s` : `${Math.round(wait / 60_000)} min`}`);
126
+ saidAllRefused = true;
127
+ setTimeout(connect, wait).unref?.();
128
+ return;
129
+ }
130
+ saidAllRefused = false;
131
+ const homeUrl = homes[homeIndex % homes.length];
132
+ const tunnelUrl = tunnelUrlFor(homeUrl, identity.nodeId);
133
+ const socket = new WS(connectUrl(homeUrl, identity.nodeId));
134
+ current = socket;
135
+ const streams = new Map();
136
+ let isReady = false;
137
+ let openedAt = 0;
138
+ let lastPong = Date.now();
139
+ let pinger = null;
140
+ const kill = () => (socket.terminate ? socket.terminate() : socket.close());
141
+ const connectTimer = setTimeout(() => { if (!isReady) kill(); }, CONNECT_TIMEOUT_MS);
142
+ const sendFrame = (frame) => {
143
+ if (socket.readyState === 1) socket.send(JSON.stringify(frame));
144
+ };
145
+
146
+ socket.on('message', async (raw) => {
147
+ const text = String(raw);
148
+ if (text === TUNNEL_PONG) {
149
+ lastPong = Date.now();
150
+ return;
151
+ }
152
+ let frame;
153
+ try {
154
+ frame = JSON.parse(text);
155
+ } catch {
156
+ return;
157
+ }
158
+ if (frame.t === 'challenge') {
159
+ const record = await createSignedNodeRecord(identity, { url: tunnelUrl, name });
160
+ const signature = await signTunnelChallenge(identity, frame.nonce, frame.host);
161
+ sendFrame({ t: 'hello', record, signature });
162
+ return;
163
+ }
164
+ if (frame.t === 'ready') {
165
+ isReady = true;
166
+ refusedBackoff.delete(homeUrl);
167
+ refusedUntil.delete(homeUrl);
168
+ openedAt = Date.now();
169
+ failures = 0;
170
+ clearTimeout(connectTimer);
171
+ lastPong = Date.now();
172
+ pinger = setInterval(() => {
173
+ if (Date.now() - lastPong > DEAD_AFTER_MS) {
174
+ log(`tunnel to ${homeUrl} stopped answering`);
175
+ kill();
176
+ return;
177
+ }
178
+ if (socket.readyState === 1) socket.send(TUNNEL_PING);
179
+ }, PING_EVERY_MS);
180
+ log(`tunnel open: reachable at ${frame.url}`);
181
+ setUrl(frame.url);
182
+ readyResolve(frame.url);
183
+ return;
184
+ }
185
+ if (frame.t === 'req') {
186
+ let reply;
187
+ try {
188
+ const response = await handleRequest(new Request(new URL(frame.path, httpOrigin(tunnelUrl)), {
189
+ method: frame.method,
190
+ headers: frame.headers,
191
+ body: frame.body && frame.method !== 'GET' && frame.method !== 'HEAD' ? decodeBody(frame.body) : undefined,
192
+ }));
193
+ const bytes = new Uint8Array(await response.arrayBuffer());
194
+ reply = bytes.byteLength > MAX_TUNNEL_BODY_BYTES
195
+ ? { status: 502, headers: [], body: null }
196
+ : { status: response.status, headers: forwardHeaders(response.headers), body: bytes.byteLength ? encodeBody(bytes) : null };
197
+ } catch (error) {
198
+ log(`tunneled request ${frame.method} ${frame.path} failed: ${error?.message || error}`);
199
+ reply = { status: 500, headers: [['content-type', 'application/json']], body: encodeBody(new TextEncoder().encode('{"ok":false,"error":"Relay error"}')) };
200
+ }
201
+ sendFrame({ t: 'res', id: frame.id, ...reply });
202
+ return;
203
+ }
204
+ if (frame.t === 'open') {
205
+ const stream = new TunnelStream(frame.sid, sendFrame);
206
+ streams.set(frame.sid, stream);
207
+ stream.on('close', () => streams.delete(frame.sid));
208
+ try {
209
+ await handleStream(stream, { path: frame.path, headers: frame.headers });
210
+ } catch (error) {
211
+ log(`tunneled WebSocket failed: ${error?.message || error}`);
212
+ stream.close(1011, 'Relay error');
213
+ }
214
+ return;
215
+ }
216
+ if (frame.t === 'data') {
217
+ streams.get(frame.sid)?.emit('message', String(frame.data));
218
+ return;
219
+ }
220
+ if (frame.t === 'end') {
221
+ streams.get(frame.sid)?.ended(frame.code, frame.reason);
222
+ }
223
+ });
224
+
225
+ let refusedStatus = 0;
226
+ socket.on('error', (error) => {
227
+ const status = Number(/Unexpected server response: (\d{3})/.exec(String(error?.message || ''))?.[1] || 0);
228
+ if (status === 429 || status >= 500) refusedStatus = status;
229
+ log(`tunnel to ${homeUrl}: ${error?.message || error}`);
230
+ });
231
+ socket.on('close', (code, reason) => {
232
+ clearTimeout(connectTimer);
233
+ clearInterval(pinger);
234
+ for (const stream of streams.values()) stream.ended(1011, 'Relay tunnel closed');
235
+ streams.clear();
236
+ if (current === socket) current = null;
237
+ if (stopped) return;
238
+ if (isReady) {
239
+ const why = String(reason || '').trim();
240
+ log(`tunnel to ${homeUrl} closed (${code}${why ? ` ${why}` : ''}) after ${formatUptime(Date.now() - openedAt)}; reconnecting`);
241
+ failures = 1;
242
+ } else if (refusedStatus) {
243
+ const now = Date.now();
244
+ const backoff = refusedBackoff.get(homeUrl) ?? REFUSED_BACKOFF_MIN_MS;
245
+ refusedBackoff.set(homeUrl, Math.min(REFUSED_BACKOFF_MAX_MS, backoff * 2));
246
+ const until = Math.min(now + backoff, nextUtcReset(now));
247
+ refusedUntil.set(homeUrl, until);
248
+ log(`${homeUrl} refused (${refusedStatus}); trying it again ${until - now < 120_000 ? `in ${Math.round((until - now) / 1000)} s` : `in ${Math.round((until - now) / 60_000)} min`}${until === nextUtcReset(now) ? ' (midnight UTC, when daily limits reset)' : ''}`);
249
+ homeIndex += 1;
250
+ failures = 0;
251
+ setUrl(null);
252
+ } else {
253
+ failures += 1;
254
+ // Two failed tries at one home: move to the next.
255
+ if (failures >= 2) {
256
+ homeIndex += 1;
257
+ failures = 0;
258
+ setUrl(null);
259
+ }
260
+ }
261
+ const rounds = Math.floor(homeIndex / homes.length);
262
+ const delay = isReady ? 1000 : Math.min(MAX_BACKOFF_MS, 1000 * 2 ** Math.min(rounds, 5));
263
+ setTimeout(connect, delay);
264
+ });
265
+ }
266
+
267
+ connect();
268
+ return {
269
+ ready,
270
+ get url() { return currentUrl; },
271
+ close() {
272
+ stopped = true;
273
+ try { current?.close(1000, 'Relay shutting down'); } catch {}
274
+ },
275
+ };
276
+ }
@@ -0,0 +1,64 @@
1
+ // What a tunnel carries between a relay behind NAT and its tunnel home: JSON
2
+ // text frames over one WebSocket the relay opened outward.
3
+ //
4
+ // home → relay { t: 'challenge', nonce, host }
5
+ // relay → home { t: 'hello', record, signature } signed node record + signed nonce
6
+ // home → relay { t: 'ready', url }
7
+ // home → relay { t: 'req', id, method, path, headers, body } an HTTP request for the relay
8
+ // relay → home { t: 'res', id, status, headers, body } its answer
9
+ // home → relay { t: 'open', sid, path, headers } a WebSocket opened to the relay's /ws
10
+ // both ways { t: 'data', sid, data } one message on that WebSocket
11
+ // both ways { t: 'end', sid, code, reason } it closed
12
+ // relay → home 'ping' answered 'pong' without waking a hibernating home
13
+ //
14
+ // Bodies are base64 so any response, not just JSON, makes it through.
15
+
16
+ export const TUNNEL_PING = 'ping';
17
+ export const TUNNEL_PONG = 'pong';
18
+ export const MAX_TUNNEL_BODY_BYTES = 1_000_000;
19
+
20
+ const HOP_BY_HOP = new Set([
21
+ 'connection', 'upgrade', 'keep-alive', 'transfer-encoding', 'te', 'trailer', 'host', 'content-length',
22
+ 'proxy-authorization', 'proxy-authenticate', 'sec-websocket-key', 'sec-websocket-version',
23
+ 'sec-websocket-extensions', 'sec-websocket-accept', 'sec-websocket-protocol',
24
+ ]);
25
+
26
+ export function forwardHeaders(headers) {
27
+ const out = [];
28
+ headers.forEach((value, name) => {
29
+ if (!HOP_BY_HOP.has(name.toLowerCase())) out.push([name, value]);
30
+ });
31
+ return out;
32
+ }
33
+
34
+ export function encodeBody(bytes) {
35
+ let binary = '';
36
+ for (let i = 0; i < bytes.length; i += 0x8000) binary += String.fromCharCode.apply(null, bytes.subarray(i, i + 0x8000));
37
+ return btoa(binary);
38
+ }
39
+
40
+ export function decodeBody(base64) {
41
+ const binary = atob(base64);
42
+ const bytes = new Uint8Array(binary.length);
43
+ for (let i = 0; i < binary.length; i += 1) bytes[i] = binary.charCodeAt(i);
44
+ return bytes;
45
+ }
46
+
47
+ const TUNNEL_ROUTE_RE = /^\/t\/([0-9a-f]{64})(\/.*)?$/;
48
+
49
+ /** For a path under /t/<node id>, the node id and the path the relay itself sees. */
50
+ export function tunnelRoute(pathname) {
51
+ const match = TUNNEL_ROUTE_RE.exec(pathname);
52
+ return match ? { nodeId: match[1], rest: match[2] || '/' } : null;
53
+ }
54
+
55
+ /** ws(s)://home/ws → ws(s)://home/t/<nodeId>/ws */
56
+ export function tunnelUrlFor(homeUrl, nodeId) {
57
+ const url = new URL(homeUrl);
58
+ if (url.protocol === 'https:') url.protocol = 'wss:';
59
+ if (url.protocol === 'http:') url.protocol = 'ws:';
60
+ url.pathname = `/t/${nodeId}/ws`;
61
+ url.search = '';
62
+ url.hash = '';
63
+ return url.toString();
64
+ }
@@ -0,0 +1,271 @@
1
+ // A tunnel home: a public relay that gives a relay behind NAT a public address.
2
+ //
3
+ // The relay behind NAT opens one WebSocket outward to /t/<its node id>/connect
4
+ // here and proves it holds that node's key. From then on its federation
5
+ // address is wss://<this host>/t/<node id>/ws, and anything sent there (HTTP
6
+ // federation calls, and WebSockets from peers) is carried down the tunnel and
7
+ // answered by the relay itself.
8
+ //
9
+ // One instance (one Durable Object on Cloudflare) per node id. Sockets are
10
+ // accepted through the hibernation API, so an idle tunnel costs no duration:
11
+ // keepalive pings are answered by the runtime without waking the object, and
12
+ // only a request or a message wakes it.
13
+ import { RELAY_NODE_RECORD_KIND, tunnelNodeIdOf, verifySignedRelayRecord, verifyTunnelChallenge } from '../relay-identity.js';
14
+ import {
15
+ MAX_TUNNEL_BODY_BYTES, TUNNEL_PING, TUNNEL_PONG, decodeBody, encodeBody, forwardHeaders, tunnelRoute,
16
+ } from './frames.js';
17
+
18
+ // A tunneled request with no reply by then is answered 504, and the tunnel it
19
+ // went down is treated as dead: it is closed so the relay reconnects at once.
20
+ const REQUEST_TIMEOUT_MS = 10_000;
21
+ const NODE_RECORD_KINDS = new Set([RELAY_NODE_RECORD_KIND]);
22
+
23
+ function json(body, status) {
24
+ return new Response(JSON.stringify(body), {
25
+ status,
26
+ headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' },
27
+ });
28
+ }
29
+
30
+ function closeQuietly(socket, code = 1000, reason = '') {
31
+ try {
32
+ socket.close(code >= 1000 && code < 5000 && code !== 1005 && code !== 1006 ? code : 1000, reason);
33
+ } catch {}
34
+ }
35
+
36
+ /** Open, as far as the runtime says (the Node test shim has no readyState). */
37
+ function isOpen(socket) {
38
+ return socket.readyState === undefined || socket.readyState === 1;
39
+ }
40
+
41
+ function attachmentOf(socket) {
42
+ try {
43
+ return socket.deserializeAttachment() ?? null;
44
+ } catch {
45
+ return null;
46
+ }
47
+ }
48
+
49
+ export class RelayTunnel {
50
+ constructor(state, env) {
51
+ this.state = state;
52
+ this.env = env;
53
+ this.pending = new Map();
54
+ try {
55
+ state.setWebSocketAutoResponse?.(new WebSocketRequestResponsePair(TUNNEL_PING, TUNNEL_PONG));
56
+ } catch {}
57
+ }
58
+
59
+ /**
60
+ * The relay's tunnel: the newest signed-in tunnel socket that is still open.
61
+ * A replaced or closed socket can stay listed by the runtime for a while (its
62
+ * close is never acknowledged when the old connection is dead), so the first
63
+ * signed-in socket in the list may be one that goes nowhere.
64
+ */
65
+ tunnelSocket() {
66
+ let best = null;
67
+ let bestSince = -1;
68
+ for (const socket of this.state.getWebSockets('tunnel')) {
69
+ const meta = attachmentOf(socket);
70
+ if (!meta?.authed || !isOpen(socket)) continue;
71
+ const since = meta.since ?? 0;
72
+ if (since > bestSince) {
73
+ best = socket;
74
+ bestSince = since;
75
+ }
76
+ }
77
+ return best;
78
+ }
79
+
80
+ /** A tunnel that cannot carry a request is dead: sign it out and close it, so the relay reconnects. */
81
+ dropTunnel(socket, reason) {
82
+ const meta = attachmentOf(socket);
83
+ try {
84
+ if (meta) socket.serializeAttachment({ ...meta, authed: false });
85
+ } catch {}
86
+ closeQuietly(socket, 1011, reason);
87
+ this.closePeersOf(meta?.gen);
88
+ }
89
+
90
+ /** Peers that came in through a tunnel have nothing on the other end once it is gone. */
91
+ closePeersOf(gen) {
92
+ if (!gen) return;
93
+ for (const peer of this.state.getWebSockets('peer')) {
94
+ if (attachmentOf(peer)?.gen === gen) closeQuietly(peer, 1011, 'Relay tunnel closed');
95
+ }
96
+ }
97
+
98
+ /** Sends one frame down the tunnel; false (and the tunnel dropped) when it cannot. */
99
+ sendToTunnel(tunnel, frame) {
100
+ try {
101
+ tunnel.send(JSON.stringify(frame));
102
+ return true;
103
+ } catch {
104
+ this.dropTunnel(tunnel, 'Tunnel send failed');
105
+ return false;
106
+ }
107
+ }
108
+
109
+ async fetch(request) {
110
+ const url = new URL(request.url);
111
+ const route = tunnelRoute(url.pathname);
112
+ if (!route) return json({ ok: false, error: 'Not a tunnel path' }, 404);
113
+ const upgrade = request.headers.get('Upgrade')?.toLowerCase() === 'websocket';
114
+
115
+ if (route.rest === '/connect') {
116
+ if (!upgrade) return json({ ok: false, error: 'Expected WebSocket upgrade' }, 426);
117
+ const [client, server] = Object.values(new WebSocketPair());
118
+ const nonce = crypto.randomUUID();
119
+ this.state.acceptWebSocket(server, ['tunnel']);
120
+ server.serializeAttachment({ role: 'tunnel', nodeId: route.nodeId, host: url.host, nonce, authed: false, gen: null });
121
+ server.send(JSON.stringify({ t: 'challenge', nonce, host: url.host }));
122
+ return new Response(null, { status: 101, webSocket: client });
123
+ }
124
+
125
+ const tunnel = this.tunnelSocket();
126
+ if (!tunnel) return json({ ok: false, error: 'That relay is not connected through this tunnel' }, 502);
127
+ const { gen } = attachmentOf(tunnel);
128
+ const path = `${route.rest}${url.search}`;
129
+
130
+ if (upgrade) {
131
+ const [client, server] = Object.values(new WebSocketPair());
132
+ const sid = crypto.randomUUID();
133
+ this.state.acceptWebSocket(server, ['peer', `sid:${sid}`]);
134
+ server.serializeAttachment({ role: 'peer', sid, gen });
135
+ if (!this.sendToTunnel(tunnel, { t: 'open', sid, path, headers: forwardHeaders(request.headers) })) {
136
+ closeQuietly(server, 1011, 'Relay tunnel closed');
137
+ return json({ ok: false, error: 'That relay is not connected through this tunnel' }, 502);
138
+ }
139
+ return new Response(null, { status: 101, webSocket: client });
140
+ }
141
+
142
+ let body = null;
143
+ if (request.method !== 'GET' && request.method !== 'HEAD') {
144
+ const bytes = new Uint8Array(await request.arrayBuffer());
145
+ if (bytes.byteLength > MAX_TUNNEL_BODY_BYTES) return json({ ok: false, error: 'Request too large' }, 413);
146
+ body = encodeBody(bytes);
147
+ }
148
+ const id = crypto.randomUUID();
149
+ const reply = new Promise((resolve) => {
150
+ const timer = setTimeout(() => {
151
+ this.pending.delete(id);
152
+ // Nothing came back: the connection to the relay is dead, though neither end was told.
153
+ if (this.tunnelSocket() === tunnel) this.dropTunnel(tunnel, 'Tunnel stopped answering');
154
+ resolve(null);
155
+ }, REQUEST_TIMEOUT_MS);
156
+ this.pending.set(id, (frame) => {
157
+ clearTimeout(timer);
158
+ this.pending.delete(id);
159
+ resolve(frame);
160
+ });
161
+ });
162
+ if (!this.sendToTunnel(tunnel, { t: 'req', id, method: request.method, path, headers: forwardHeaders(request.headers), body })) {
163
+ this.pending.get(id)?.(null);
164
+ return json({ ok: false, error: 'That relay is not connected through this tunnel' }, 502);
165
+ }
166
+ const frame = await reply;
167
+ if (!frame) return json({ ok: false, error: 'The tunneled relay did not answer' }, 504);
168
+ const status = Number(frame.status) || 502;
169
+ const nullBody = request.method === 'HEAD' || status === 204 || status === 304 || !frame.body;
170
+ return new Response(nullBody ? null : decodeBody(frame.body), { status, headers: frame.headers || [] });
171
+ }
172
+
173
+ async webSocketMessage(socket, message) {
174
+ const meta = attachmentOf(socket);
175
+ if (!meta) return;
176
+ const text = typeof message === 'string' ? message : new TextDecoder().decode(message);
177
+
178
+ if (meta.role === 'peer') {
179
+ const tunnel = this.tunnelSocket();
180
+ if (!tunnel || attachmentOf(tunnel).gen !== meta.gen) {
181
+ closeQuietly(socket, 1011, 'Relay tunnel closed');
182
+ return;
183
+ }
184
+ if (!this.sendToTunnel(tunnel, { t: 'data', sid: meta.sid, data: text })) closeQuietly(socket, 1011, 'Relay tunnel closed');
185
+ return;
186
+ }
187
+
188
+ if (text === TUNNEL_PING) {
189
+ // Where the runtime has no auto-response.
190
+ socket.send(TUNNEL_PONG);
191
+ return;
192
+ }
193
+ let frame;
194
+ try {
195
+ frame = JSON.parse(text);
196
+ } catch {
197
+ return;
198
+ }
199
+
200
+ if (!meta.authed) {
201
+ if (frame?.t !== 'hello' || !meta.nonce) {
202
+ closeQuietly(socket, 1008, 'hello expected');
203
+ return;
204
+ }
205
+ const record = frame.record;
206
+ let recordHost = null;
207
+ try {
208
+ recordHost = new URL(record?.url).host;
209
+ } catch {}
210
+ const ok = record?.node_id === meta.nodeId
211
+ && tunnelNodeIdOf(record.url) === meta.nodeId
212
+ && recordHost === meta.host
213
+ && await verifySignedRelayRecord(record, { allowedKinds: NODE_RECORD_KINDS })
214
+ && await verifyTunnelChallenge(record.public_key, meta.nonce, meta.host, frame.signature);
215
+ if (!ok) {
216
+ closeQuietly(socket, 1008, 'Tunnel authentication failed');
217
+ return;
218
+ }
219
+ // The newest tunnel for a node wins: a relay that reconnects replaces its old one.
220
+ // The old one is signed out first: it may stay listed until its close is acknowledged.
221
+ for (const other of this.state.getWebSockets('tunnel')) {
222
+ if (other === socket) continue;
223
+ const old = attachmentOf(other);
224
+ try {
225
+ if (old) other.serializeAttachment({ ...old, authed: false });
226
+ } catch {}
227
+ closeQuietly(other, 1012, 'Replaced by a newer tunnel');
228
+ this.closePeersOf(old?.gen);
229
+ }
230
+ socket.serializeAttachment({ ...meta, nonce: null, authed: true, gen: crypto.randomUUID(), since: Date.now() });
231
+ socket.send(JSON.stringify({ t: 'ready', url: record.url }));
232
+ return;
233
+ }
234
+
235
+ if (frame?.t === 'res') {
236
+ this.pending.get(frame.id)?.(frame);
237
+ return;
238
+ }
239
+ if (frame?.t === 'data') {
240
+ for (const peer of this.state.getWebSockets(`sid:${frame.sid}`)) {
241
+ try {
242
+ peer.send(String(frame.data));
243
+ } catch {}
244
+ }
245
+ return;
246
+ }
247
+ if (frame?.t === 'end') {
248
+ for (const peer of this.state.getWebSockets(`sid:${frame.sid}`)) closeQuietly(peer, frame.code, frame.reason || '');
249
+ }
250
+ }
251
+
252
+ async webSocketClose(socket, code, reason) {
253
+ const meta = attachmentOf(socket);
254
+ closeQuietly(socket, code, reason);
255
+ if (!meta) return;
256
+ if (meta.role === 'peer') {
257
+ const tunnel = this.tunnelSocket();
258
+ if (tunnel && attachmentOf(tunnel).gen === meta.gen) {
259
+ try {
260
+ tunnel.send(JSON.stringify({ t: 'end', sid: meta.sid, code, reason }));
261
+ } catch {}
262
+ }
263
+ return;
264
+ }
265
+ this.closePeersOf(meta.gen);
266
+ }
267
+
268
+ async webSocketError(socket) {
269
+ await this.webSocketClose(socket, 1011, 'error');
270
+ }
271
+ }