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.
- package/README.md +205 -13
- 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 -172
- 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,99 @@
|
|
|
1
|
+
// The secure channel inside a link between two local relays (relay-links.js).
|
|
2
|
+
//
|
|
3
|
+
// Proving keys at the start of a link is not enough on its own: someone in
|
|
4
|
+
// the middle could pass both relays' challenges and answers along unchanged
|
|
5
|
+
// and then read and inject frames. So with post-quantum keys a link is also
|
|
6
|
+
// encrypted, end to end between the two relays:
|
|
7
|
+
// - each side makes a fresh key pair for the link (P-256 + ML-KEM-768) and
|
|
8
|
+
// sends its public half in its hello, covered by its hybrid signature;
|
|
9
|
+
// - each side then sends a random secret encrypted to the other's fresh
|
|
10
|
+
// keys (unsea 3 hybrid encryption);
|
|
11
|
+
// - both secrets, both nonces and both node ids go into HKDF-SHA256, which
|
|
12
|
+
// gives one AES-256-GCM key for each direction;
|
|
13
|
+
// - every frame after that is sealed, numbered, and refused if it is out of
|
|
14
|
+
// order or replayed.
|
|
15
|
+
// Someone in the middle sees only ciphertext, cannot change it, and cannot
|
|
16
|
+
// make the keys: each needs a secret only the two relays can decrypt.
|
|
17
|
+
|
|
18
|
+
const encoder = new TextEncoder();
|
|
19
|
+
const decoder = new TextDecoder();
|
|
20
|
+
|
|
21
|
+
const b64 = (bytes) => Buffer.from(bytes).toString('base64url');
|
|
22
|
+
const unb64 = (text) => new Uint8Array(Buffer.from(String(text), 'base64url'));
|
|
23
|
+
|
|
24
|
+
export function randomLinkSecret() {
|
|
25
|
+
return b64(crypto.getRandomValues(new Uint8Array(32)));
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** A digest of a link's fresh public keys, as the hello signature covers it. */
|
|
29
|
+
export async function ephemeralDigest(ephemeral) {
|
|
30
|
+
const text = `${ephemeral?.epub}|${ephemeral?.kpub}`;
|
|
31
|
+
return b64(new Uint8Array(await crypto.subtle.digest('SHA-256', encoder.encode(text))));
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
async function directionKey(secret, salt, info) {
|
|
35
|
+
const base = await crypto.subtle.importKey('raw', secret, 'HKDF', false, ['deriveKey']);
|
|
36
|
+
return crypto.subtle.deriveKey(
|
|
37
|
+
{ name: 'HKDF', hash: 'SHA-256', salt, info: encoder.encode(info) },
|
|
38
|
+
base,
|
|
39
|
+
{ name: 'AES-GCM', length: 256 },
|
|
40
|
+
false,
|
|
41
|
+
['encrypt', 'decrypt'],
|
|
42
|
+
);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* The two directions' keys for a link, from both sides' secrets. Both sides
|
|
47
|
+
* get the same pair (ordered by node id), each sending with one and
|
|
48
|
+
* receiving with the other.
|
|
49
|
+
*/
|
|
50
|
+
export async function createLinkChannel({ selfId, peerId, selfNonce, peerNonce, selfSecret, peerSecret }) {
|
|
51
|
+
const selfFirst = selfId < peerId;
|
|
52
|
+
const [lowId, highId] = selfFirst ? [selfId, peerId] : [peerId, selfId];
|
|
53
|
+
const [lowNonce, highNonce] = selfFirst ? [selfNonce, peerNonce] : [peerNonce, selfNonce];
|
|
54
|
+
const [lowSecret, highSecret] = selfFirst ? [selfSecret, peerSecret] : [peerSecret, selfSecret];
|
|
55
|
+
const secret = new Uint8Array([...unb64(lowSecret), ...unb64(highSecret)]);
|
|
56
|
+
if (secret.length !== 64) throw new Error('bad link secret');
|
|
57
|
+
const transcript = `freertc-link/v2|${lowId}|${highId}|${lowNonce}|${highNonce}`;
|
|
58
|
+
const salt = encoder.encode('freertc-link/v2');
|
|
59
|
+
const sendKey = await directionKey(secret, salt, `${transcript}|${selfId}>${peerId}`);
|
|
60
|
+
const receiveKey = await directionKey(secret, salt, `${transcript}|${peerId}>${selfId}`);
|
|
61
|
+
|
|
62
|
+
let sent = 0;
|
|
63
|
+
let received = 0;
|
|
64
|
+
let sending = Promise.resolve();
|
|
65
|
+
let receiving = Promise.resolve();
|
|
66
|
+
const ivFor = (n) => {
|
|
67
|
+
const iv = new Uint8Array(12);
|
|
68
|
+
new DataView(iv.buffer).setBigUint64(4, BigInt(n));
|
|
69
|
+
return iv;
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
return {
|
|
73
|
+
/** Seal a frame and pass it to transmit, in the order seal was called. */
|
|
74
|
+
seal(frame, transmit) {
|
|
75
|
+
const n = ++sent;
|
|
76
|
+
sending = sending.then(async () => {
|
|
77
|
+
const data = await crypto.subtle.encrypt({ name: 'AES-GCM', iv: ivFor(n) }, sendKey, encoder.encode(JSON.stringify(frame)));
|
|
78
|
+
transmit({ t: 'enc', n, c: b64(new Uint8Array(data)) });
|
|
79
|
+
}).catch(() => {});
|
|
80
|
+
return sending;
|
|
81
|
+
},
|
|
82
|
+
/** Open a sealed frame, in arrival order; null when it is forged, replayed or out of order. */
|
|
83
|
+
open(sealed) {
|
|
84
|
+
const result = receiving.then(async () => {
|
|
85
|
+
const n = Number(sealed?.n);
|
|
86
|
+
if (!Number.isSafeInteger(n) || n !== received + 1 || typeof sealed.c !== 'string') return null;
|
|
87
|
+
try {
|
|
88
|
+
const plain = await crypto.subtle.decrypt({ name: 'AES-GCM', iv: ivFor(n) }, receiveKey, unb64(sealed.c));
|
|
89
|
+
received = n;
|
|
90
|
+
return JSON.parse(decoder.decode(plain));
|
|
91
|
+
} catch {
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
});
|
|
95
|
+
receiving = result.catch(() => null);
|
|
96
|
+
return result;
|
|
97
|
+
},
|
|
98
|
+
};
|
|
99
|
+
}
|
|
@@ -0,0 +1,385 @@
|
|
|
1
|
+
// Local-to-local federation: links between relays that carry their federation
|
|
2
|
+
// calls directly, instead of out through a cloud tunnel home and back.
|
|
3
|
+
//
|
|
4
|
+
// Two local relays behind NAT reach each other at wss://<home>/t/<node id>/...,
|
|
5
|
+
// so every DHT lookup, peer query and forwarded signal between them crossed a
|
|
6
|
+
// cloud relay twice. A link is a socket between the two relays themselves:
|
|
7
|
+
// - a punched data channel (label freertc-federation), introduced once
|
|
8
|
+
// through the other relay's tunnel exactly as a client's would be; or
|
|
9
|
+
// - a WebSocket to the other relay's LAN address (/api/v1/link), when the two
|
|
10
|
+
// share a network (see lan-beacon.js).
|
|
11
|
+
// Either way both ends prove who they are before anything else crosses:
|
|
12
|
+
// each side → { t: 'challenge', nonce }
|
|
13
|
+
// each side → { t: 'hello', record, signature, its signed node record, and
|
|
14
|
+
// pq_public_key, pq_signature } a signature over the other's nonce;
|
|
15
|
+
// with its post-quantum key (relay-pq.js),
|
|
16
|
+
// also a hybrid one. A relay with pq set
|
|
17
|
+
// links only to relays that prove one,
|
|
18
|
+
// the same one as the first time, and the
|
|
19
|
+
// link is then encrypted end to end
|
|
20
|
+
// (link-crypto.js): hello carries fresh
|
|
21
|
+
// keys, then each side sends
|
|
22
|
+
// { t: 'key', c } and every frame after is
|
|
23
|
+
// { t: 'enc', n, c }.
|
|
24
|
+
// then requests flow both ways in the tunnel's own frame format:
|
|
25
|
+
// { t: 'req', id, method, path, headers, body } → { t: 'res', id, status, headers, body }
|
|
26
|
+
// The relay's fetch is wrapped (wrapFetch) so a federation call to a linked
|
|
27
|
+
// relay's tunnel URL goes over the link; everything else is unchanged.
|
|
28
|
+
//
|
|
29
|
+
// Which relays to link to: other local relays this relay has verified through
|
|
30
|
+
// the overlay, at most MAX_LINKS, one per XOR bucket first (the relays most
|
|
31
|
+
// unlike this one in ID, as Kademlia keeps its contacts), and only the one with
|
|
32
|
+
// the lower node ID dials, so two relays make one link between them.
|
|
33
|
+
|
|
34
|
+
import { decodeBody, encodeBody, forwardHeaders } from '../tunnel/frames.js';
|
|
35
|
+
import { decryptMessageWithMeta, encryptMessageWithMeta, generateRandomPair } from 'unsea';
|
|
36
|
+
import { signLinkChallenge, signLinkChallengePq, verifyLinkChallenge, verifyLinkChallengePq, verifySignedRelayRecord } from '../relay-identity.js';
|
|
37
|
+
import { createLinkChannel, ephemeralDigest, randomLinkSecret } from './link-crypto.js';
|
|
38
|
+
|
|
39
|
+
export const LINK_CHANNEL_LABEL = 'freertc-federation';
|
|
40
|
+
export const LINK_PATH = '/api/v1/link';
|
|
41
|
+
const MAX_LINKS = 8;
|
|
42
|
+
const HELLO_TIMEOUT_MS = 10_000;
|
|
43
|
+
const REQUEST_TIMEOUT_MS = 10_000;
|
|
44
|
+
const MAINTAIN_EVERY_MS = 60_000;
|
|
45
|
+
const REDIAL_AFTER_MS = 5 * 60_000;
|
|
46
|
+
const TUNNEL_PATH_RE = /^\/t\/([0-9a-f]{64})(\/.*)$/;
|
|
47
|
+
|
|
48
|
+
const randomNonce = () => Array.from(globalThis.crypto.getRandomValues(new Uint8Array(16)), (b) => b.toString(16).padStart(2, '0')).join('');
|
|
49
|
+
|
|
50
|
+
/** Highest differing bit between two node IDs: the Kademlia bucket. */
|
|
51
|
+
export function bucketOf(a, b) {
|
|
52
|
+
for (let i = 0; i < 64; i += 1) {
|
|
53
|
+
const x = Number.parseInt(a[i], 16) ^ Number.parseInt(b[i], 16);
|
|
54
|
+
if (x) return 255 - (i * 4 + (3 - Math.floor(Math.log2(x))));
|
|
55
|
+
}
|
|
56
|
+
return -1;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Choose which relays to link to: distinct buckets first, then the closest rest. */
|
|
60
|
+
export function chooseLinkTargets(selfNodeId, records, max = MAX_LINKS) {
|
|
61
|
+
const others = records.filter((r) => r?.node_id && r.node_id !== selfNodeId);
|
|
62
|
+
const byBucket = new Map();
|
|
63
|
+
for (const record of others) {
|
|
64
|
+
const bucket = bucketOf(selfNodeId, record.node_id);
|
|
65
|
+
if (!byBucket.has(bucket)) byBucket.set(bucket, []);
|
|
66
|
+
byBucket.get(bucket).push(record);
|
|
67
|
+
}
|
|
68
|
+
const chosen = [];
|
|
69
|
+
for (const bucket of [...byBucket.keys()].sort((a, b) => b - a)) {
|
|
70
|
+
if (chosen.length >= max) break;
|
|
71
|
+
chosen.push(byBucket.get(bucket).sort((a, b) => a.node_id.localeCompare(b.node_id))[0]);
|
|
72
|
+
}
|
|
73
|
+
for (const record of others.sort((a, b) => a.node_id.localeCompare(b.node_id))) {
|
|
74
|
+
if (chosen.length >= max) break;
|
|
75
|
+
if (!chosen.includes(record)) chosen.push(record);
|
|
76
|
+
}
|
|
77
|
+
return chosen;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function createRelayLinks({
|
|
81
|
+
identity,
|
|
82
|
+
nodeRecord,
|
|
83
|
+
handleRequest,
|
|
84
|
+
dialPunch = null,
|
|
85
|
+
dialLan = null,
|
|
86
|
+
listRelays = async () => [],
|
|
87
|
+
maxLinks = MAX_LINKS,
|
|
88
|
+
log = () => {},
|
|
89
|
+
verifyRecord = verifySignedRelayRecord,
|
|
90
|
+
// { identity: { pub, priv, qpub, qpriv }, pins: { get, set }, required = true }
|
|
91
|
+
pq = null,
|
|
92
|
+
// Called once a link has proved both ends (and, with pq, is encrypted):
|
|
93
|
+
// the place to exchange what only proved relays may have.
|
|
94
|
+
onLinked = () => {},
|
|
95
|
+
}) {
|
|
96
|
+
const links = new Map(); // node id -> link
|
|
97
|
+
const lastDial = new Map(); // node id -> when we last tried
|
|
98
|
+
let stopped = false;
|
|
99
|
+
|
|
100
|
+
// A post-quantum answer: valid, and the key pinned for that node id (or the
|
|
101
|
+
// first one seen, which is pinned now).
|
|
102
|
+
async function pqOk(record, frame, nonce, peerEphemeralDigest) {
|
|
103
|
+
const pinned = pq.pins?.get(record.node_id) ?? null;
|
|
104
|
+
const short = record.node_id.slice(0, 8);
|
|
105
|
+
if (typeof frame.pq_public_key !== 'string') {
|
|
106
|
+
if (pinned || pq.required !== false) {
|
|
107
|
+
log(`refused a link from ${short}: it did not prove a post-quantum key${pinned ? ' (it had one before)' : ''}`);
|
|
108
|
+
return false;
|
|
109
|
+
}
|
|
110
|
+
return true;
|
|
111
|
+
}
|
|
112
|
+
if (pinned && pinned !== frame.pq_public_key) {
|
|
113
|
+
log(`refused a link from ${short}: its post-quantum key is not the one it had before`);
|
|
114
|
+
return false;
|
|
115
|
+
}
|
|
116
|
+
if (!await verifyLinkChallengePq(record.public_key, frame.pq_public_key, record.node_id, nonce, frame.pq_signature, peerEphemeralDigest)) {
|
|
117
|
+
log(`refused a link from ${short}: its post-quantum signature did not check out`);
|
|
118
|
+
return false;
|
|
119
|
+
}
|
|
120
|
+
if (!pinned) pq.pins?.set(record.node_id, frame.pq_public_key);
|
|
121
|
+
return true;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
function attach(socket, { via = 'punch', expectNodeId = null } = {}) {
|
|
125
|
+
const myNonce = randomNonce();
|
|
126
|
+
const pending = new Map();
|
|
127
|
+
const answered = new Set();
|
|
128
|
+
let peerNodeId = null;
|
|
129
|
+
let closed = false;
|
|
130
|
+
// Encrypted links (with post-quantum keys): this link's fresh keys, the
|
|
131
|
+
// secret this side contributes, and the channel once both are in.
|
|
132
|
+
const secure = Boolean(pq?.identity);
|
|
133
|
+
const ephemeral = secure ? generateRandomPair() : null;
|
|
134
|
+
const mySecret = secure ? randomLinkSecret() : null;
|
|
135
|
+
let peerNonce = null;
|
|
136
|
+
let verified = null; // { record, ephemeral } once the peer's hello checks out
|
|
137
|
+
let peerKeyFrame = null;
|
|
138
|
+
let channel = null;
|
|
139
|
+
// Sealed frames that arrive while this side is still opening the other's
|
|
140
|
+
// link key (the other side may finish first and send at once): held, and
|
|
141
|
+
// opened in order once the channel exists.
|
|
142
|
+
const earlySealed = [];
|
|
143
|
+
const link = {
|
|
144
|
+
via,
|
|
145
|
+
get nodeId() { return peerNodeId; },
|
|
146
|
+
get open() { return Boolean(peerNodeId) && !closed; },
|
|
147
|
+
request,
|
|
148
|
+
close: () => { try { socket.close(); } catch {} },
|
|
149
|
+
};
|
|
150
|
+
const sendRaw = (frame) => { try { socket.send(JSON.stringify(frame)); } catch {} };
|
|
151
|
+
// Requests and responses go sealed on an encrypted link.
|
|
152
|
+
const send = (frame) => (channel && (frame.t === 'req' || frame.t === 'res') ? channel.seal(frame, sendRaw) : sendRaw(frame));
|
|
153
|
+
const helloTimer = setTimeout(() => { if (!peerNodeId) { log(`link over ${via} did not identify itself`); link.close(); } }, HELLO_TIMEOUT_MS);
|
|
154
|
+
helloTimer.unref?.();
|
|
155
|
+
|
|
156
|
+
async function request(method, path, headers, bodyBytes) {
|
|
157
|
+
if (!link.open) throw new Error('link is not open');
|
|
158
|
+
const id = randomNonce();
|
|
159
|
+
const reply = new Promise((resolve, reject) => {
|
|
160
|
+
const timer = setTimeout(() => { pending.delete(id); reject(new Error('link request timed out')); }, REQUEST_TIMEOUT_MS);
|
|
161
|
+
timer.unref?.();
|
|
162
|
+
pending.set(id, (frame) => { clearTimeout(timer); pending.delete(id); resolve(frame); });
|
|
163
|
+
});
|
|
164
|
+
send({ t: 'req', id, method, path, headers, body: bodyBytes ? encodeBody(bodyBytes) : null });
|
|
165
|
+
const frame = await reply;
|
|
166
|
+
const status = Number(frame.status) || 502;
|
|
167
|
+
const nullBody = method === 'HEAD' || status === 204 || status === 304 || !frame.body;
|
|
168
|
+
return new Response(nullBody ? null : decodeBody(frame.body), { status, headers: frame.headers || [] });
|
|
169
|
+
}
|
|
170
|
+
|
|
171
|
+
socket.on('message', async (raw) => {
|
|
172
|
+
let frame;
|
|
173
|
+
try { frame = JSON.parse(String(raw)); } catch { return; }
|
|
174
|
+
if (frame?.t === 'challenge' && typeof frame.nonce === 'string') {
|
|
175
|
+
if (answered.has(frame.nonce)) return;
|
|
176
|
+
if (secure && peerNonce && peerNonce !== frame.nonce) return; // one handshake per link
|
|
177
|
+
answered.add(frame.nonce);
|
|
178
|
+
peerNonce = frame.nonce;
|
|
179
|
+
const fresh = secure ? await ephemeral : null;
|
|
180
|
+
const freshPublic = fresh ? { epub: fresh.epub, kpub: fresh.kpub } : null;
|
|
181
|
+
sendRaw({
|
|
182
|
+
t: 'hello',
|
|
183
|
+
record: await nodeRecord(),
|
|
184
|
+
signature: await signLinkChallenge(identity, frame.nonce),
|
|
185
|
+
...(pq?.identity ? {
|
|
186
|
+
pq_public_key: pq.identity.qpub,
|
|
187
|
+
pq_signature: await signLinkChallengePq(pq.identity, identity.nodeId, frame.nonce, await ephemeralDigest(freshPublic)),
|
|
188
|
+
ephemeral: freshPublic,
|
|
189
|
+
} : {}),
|
|
190
|
+
});
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
if (frame?.t === 'key' && secure) {
|
|
194
|
+
if (channel || peerKeyFrame) return;
|
|
195
|
+
peerKeyFrame = frame;
|
|
196
|
+
await finishSecure();
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
if (frame?.t === 'enc' && secure) {
|
|
200
|
+
if (!channel) {
|
|
201
|
+
if (earlySealed.length < 64) earlySealed.push(frame);
|
|
202
|
+
return;
|
|
203
|
+
}
|
|
204
|
+
await openSealed(frame);
|
|
205
|
+
return;
|
|
206
|
+
}
|
|
207
|
+
if (frame?.t === 'hello') {
|
|
208
|
+
if (peerNodeId) return;
|
|
209
|
+
const record = frame.record;
|
|
210
|
+
const ok = record && record.node_id !== identity.nodeId
|
|
211
|
+
&& (!expectNodeId || record.node_id === expectNodeId)
|
|
212
|
+
&& await verifyRecord(record)
|
|
213
|
+
&& await verifyLinkChallenge(record.public_key, myNonce, frame.signature);
|
|
214
|
+
if (!ok) { log(`link over ${via} failed to identify itself`); link.close(); return; }
|
|
215
|
+
const peerEphemeral = frame.ephemeral && typeof frame.ephemeral.epub === 'string' && typeof frame.ephemeral.kpub === 'string'
|
|
216
|
+
? { epub: frame.ephemeral.epub, kpub: frame.ephemeral.kpub } : null;
|
|
217
|
+
if (secure && !peerEphemeral && frame.pq_public_key) { log(`refused a link from ${record.node_id.slice(0, 8)}: no keys for an encrypted link`); link.close(); return; }
|
|
218
|
+
if (pq && !await pqOk(record, frame, myNonce, peerEphemeral ? await ephemeralDigest(peerEphemeral) : '')) { link.close(); return; }
|
|
219
|
+
if (verified || peerNodeId) return;
|
|
220
|
+
if (!secure || !frame.pq_public_key) {
|
|
221
|
+
// Without post-quantum keys on both ends (FREERTC_PQ=off and pq not
|
|
222
|
+
// required): the link as before, unencrypted.
|
|
223
|
+
open(record);
|
|
224
|
+
return;
|
|
225
|
+
}
|
|
226
|
+
verified = { record, ephemeral: peerEphemeral };
|
|
227
|
+
// This side's secret, encrypted to the other side's fresh keys.
|
|
228
|
+
sendRaw({ t: 'key', c: await encryptMessageWithMeta(mySecret, peerEphemeral) });
|
|
229
|
+
await finishSecure();
|
|
230
|
+
return;
|
|
231
|
+
}
|
|
232
|
+
if (!peerNodeId || channel) return; // nothing but the handshake before it completes; sealed frames only on an encrypted link
|
|
233
|
+
await handleFrame(frame);
|
|
234
|
+
});
|
|
235
|
+
|
|
236
|
+
function open(record) {
|
|
237
|
+
if (peerNodeId || closed) return;
|
|
238
|
+
clearTimeout(helloTimer);
|
|
239
|
+
const existing = links.get(record.node_id);
|
|
240
|
+
if (existing?.open) { log(`already linked to ${record.node_id.slice(0, 8)}; closing the second link`); link.close(); return; }
|
|
241
|
+
peerNodeId = record.node_id;
|
|
242
|
+
link.url = typeof record.url === 'string' ? record.url : null;
|
|
243
|
+
links.set(peerNodeId, link);
|
|
244
|
+
log(`linked to ${peerNodeId.slice(0, 8)} over ${via}${channel ? ' (encrypted, post-quantum)' : ''}`);
|
|
245
|
+
try { Promise.resolve(onLinked(peerNodeId, link)).catch(() => {}); } catch { /* the link stands either way */ }
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
// Both secrets in (ours sent, theirs received): make the channel and open the link.
|
|
249
|
+
// Runs once: the hello and the key frame can each be the one that
|
|
250
|
+
// completes the handshake, and both may arrive while the other's
|
|
251
|
+
// decryption is still under way; a second channel would restart the
|
|
252
|
+
// frame numbering and every later frame would fail to open.
|
|
253
|
+
let finishing = null;
|
|
254
|
+
function finishSecure() {
|
|
255
|
+
if (channel || !verified || !peerKeyFrame) return finishing ?? Promise.resolve();
|
|
256
|
+
finishing ??= finishSecureOnce();
|
|
257
|
+
return finishing;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
async function finishSecureOnce() {
|
|
261
|
+
const keyFrame = peerKeyFrame;
|
|
262
|
+
let peerSecret;
|
|
263
|
+
try {
|
|
264
|
+
peerSecret = await decryptMessageWithMeta(keyFrame.c, await ephemeral);
|
|
265
|
+
} catch {
|
|
266
|
+
log(`link from ${verified.record.node_id.slice(0, 8)}: its link key did not open; closing`);
|
|
267
|
+
link.close();
|
|
268
|
+
return;
|
|
269
|
+
}
|
|
270
|
+
if (channel) return;
|
|
271
|
+
channel = await createLinkChannel({
|
|
272
|
+
selfId: identity.nodeId,
|
|
273
|
+
peerId: verified.record.node_id,
|
|
274
|
+
selfNonce: myNonce,
|
|
275
|
+
peerNonce,
|
|
276
|
+
selfSecret: mySecret,
|
|
277
|
+
peerSecret,
|
|
278
|
+
}).catch(() => null);
|
|
279
|
+
if (!channel) { link.close(); return; }
|
|
280
|
+
open(verified.record);
|
|
281
|
+
for (const frame of earlySealed.splice(0)) openSealed(frame);
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
async function openSealed(frame) {
|
|
285
|
+
const inner = await channel.open(frame);
|
|
286
|
+
if (!inner) { log(`link to ${peerNodeId?.slice(0, 8) ?? '?'}: a frame did not open; closing`); link.close(); return; }
|
|
287
|
+
if (inner.t === 'req' || inner.t === 'res') await handleFrame(inner);
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
async function handleFrame(frame) {
|
|
291
|
+
if (frame?.t === 'req' && typeof frame.id === 'string' && typeof frame.path === 'string') {
|
|
292
|
+
try {
|
|
293
|
+
const request = new Request(new URL(frame.path, 'http://relay-link'), {
|
|
294
|
+
method: frame.method || 'GET',
|
|
295
|
+
headers: frame.headers || [],
|
|
296
|
+
body: frame.body && frame.method !== 'GET' && frame.method !== 'HEAD' ? decodeBody(frame.body) : undefined,
|
|
297
|
+
});
|
|
298
|
+
const response = await handleRequest(request);
|
|
299
|
+
const bytes = new Uint8Array(await response.arrayBuffer());
|
|
300
|
+
send({ t: 'res', id: frame.id, status: response.status, headers: forwardHeaders(response.headers), body: bytes.byteLength ? encodeBody(bytes) : null });
|
|
301
|
+
} catch (error) {
|
|
302
|
+
send({ t: 'res', id: frame.id, status: 502, headers: [], body: null });
|
|
303
|
+
log(`link request ${frame.path} failed: ${error?.message ?? error}`);
|
|
304
|
+
}
|
|
305
|
+
return;
|
|
306
|
+
}
|
|
307
|
+
if (frame?.t === 'res' && pending.has(frame.id)) pending.get(frame.id)(frame);
|
|
308
|
+
}
|
|
309
|
+
socket.on('close', () => {
|
|
310
|
+
closed = true;
|
|
311
|
+
clearTimeout(helloTimer);
|
|
312
|
+
if (peerNodeId && links.get(peerNodeId) === link) links.delete(peerNodeId);
|
|
313
|
+
for (const resolve of pending.values()) resolve({ status: 502 });
|
|
314
|
+
pending.clear();
|
|
315
|
+
if (peerNodeId) log(`link to ${peerNodeId.slice(0, 8)} closed`);
|
|
316
|
+
});
|
|
317
|
+
// The other end may attach its handler a moment after the channel opens
|
|
318
|
+
// (the dialer only gets the socket once its open resolves), so a challenge
|
|
319
|
+
// sent into that gap is lost. Repeat it until the other end has answered.
|
|
320
|
+
send({ t: 'challenge', nonce: myNonce });
|
|
321
|
+
const resend = setInterval(() => {
|
|
322
|
+
if (peerNodeId || closed) { clearInterval(resend); return; }
|
|
323
|
+
send({ t: 'challenge', nonce: myNonce });
|
|
324
|
+
}, 1_000);
|
|
325
|
+
resend.unref?.();
|
|
326
|
+
return link;
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
async function maintain() {
|
|
330
|
+
if (stopped) return;
|
|
331
|
+
const records = (await listRelays().catch(() => [])).filter((r) => r?.relay_kind === 'local');
|
|
332
|
+
const targets = chooseLinkTargets(identity.nodeId, records, maxLinks);
|
|
333
|
+
for (const record of targets) {
|
|
334
|
+
if (links.get(record.node_id)?.open) continue;
|
|
335
|
+
// One link per pair: the lower node ID dials.
|
|
336
|
+
if (identity.nodeId > record.node_id) continue;
|
|
337
|
+
if (Date.now() - (lastDial.get(record.node_id) ?? 0) < REDIAL_AFTER_MS) continue;
|
|
338
|
+
const punch = Array.isArray(record.reach) ? record.reach.find((entry) => entry?.via === 'punch') : null;
|
|
339
|
+
if (!punch || !dialPunch) continue;
|
|
340
|
+
lastDial.set(record.node_id, Date.now());
|
|
341
|
+
dialPunch(punch.url)
|
|
342
|
+
.then((socket) => attach(socket, { via: 'punch', expectNodeId: record.node_id }))
|
|
343
|
+
.catch((error) => log(`no link to ${record.node_id.slice(0, 8)}: ${error?.message ?? error}`));
|
|
344
|
+
}
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
const timer = setInterval(() => { maintain().catch(() => {}); }, MAINTAIN_EVERY_MS);
|
|
348
|
+
timer.unref?.();
|
|
349
|
+
|
|
350
|
+
return {
|
|
351
|
+
links,
|
|
352
|
+
/** The federation URLs of the relays this one is linked to right now. */
|
|
353
|
+
linkedRelayUrls: () => [...links.values()].filter((link) => link.open && link.url).map((link) => link.url),
|
|
354
|
+
accept: (socket, options) => attach(socket, options),
|
|
355
|
+
maintain,
|
|
356
|
+
/** A relay on the LAN announced itself: link to it there (lower node ID dials). */
|
|
357
|
+
lanSeen(nodeId, url) {
|
|
358
|
+
if (stopped || !dialLan || !/^[0-9a-f]{64}$/.test(nodeId) || nodeId === identity.nodeId) return;
|
|
359
|
+
if (links.get(nodeId)?.open || identity.nodeId > nodeId) return;
|
|
360
|
+
if (Date.now() - (lastDial.get(nodeId) ?? 0) < REDIAL_AFTER_MS / 5) return;
|
|
361
|
+
lastDial.set(nodeId, Date.now());
|
|
362
|
+
dialLan(url)
|
|
363
|
+
.then((socket) => attach(socket, { via: 'lan', expectNodeId: nodeId }))
|
|
364
|
+
.catch((error) => log(`no LAN link to ${nodeId.slice(0, 8)}: ${error?.message ?? error}`));
|
|
365
|
+
},
|
|
366
|
+
/** Send federation calls to a linked relay's tunnel URL over the link. */
|
|
367
|
+
wrapFetch(fetchImpl) {
|
|
368
|
+
return async (input, init = undefined) => {
|
|
369
|
+
let url;
|
|
370
|
+
try { url = new URL(typeof input === 'string' || input instanceof URL ? String(input) : input.url); } catch { return fetchImpl(input, init); }
|
|
371
|
+
const match = TUNNEL_PATH_RE.exec(url.pathname);
|
|
372
|
+
const link = match ? links.get(match[1]) : null;
|
|
373
|
+
if (!link?.open) return fetchImpl(input, init);
|
|
374
|
+
const request = new Request(input, init);
|
|
375
|
+
const body = request.method === 'GET' || request.method === 'HEAD' ? null : new Uint8Array(await request.arrayBuffer());
|
|
376
|
+
return link.request(request.method, `${match[2]}${url.search}`, forwardHeaders(request.headers), body && body.byteLength ? body : null);
|
|
377
|
+
};
|
|
378
|
+
},
|
|
379
|
+
stop() {
|
|
380
|
+
stopped = true;
|
|
381
|
+
clearInterval(timer);
|
|
382
|
+
for (const link of links.values()) link.close();
|
|
383
|
+
},
|
|
384
|
+
};
|
|
385
|
+
}
|
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
// A local relay's own DNS name and TLS certificate, so browsers anywhere can
|
|
2
|
+
// reach it as wss://<name>:<port>/ws.
|
|
3
|
+
//
|
|
4
|
+
// 1. It asks its owner's Worker (POST /api/v1/name, src/direct/names.js) to
|
|
5
|
+
// point <label>.<owner's domain> at the address its request comes from,
|
|
6
|
+
// and asks again every CLAIM_EVERY_MS (the home address can change).
|
|
7
|
+
// 2. It gets a Let's Encrypt certificate for that name by DNS-01: the
|
|
8
|
+
// Worker writes the challenge TXT record (it holds the DNS token; this
|
|
9
|
+
// relay never does), the relay waits until public DNS shows it, then
|
|
10
|
+
// Let's Encrypt checks it. No inbound port is needed for this, and the
|
|
11
|
+
// private key never leaves this machine. It renews when RENEW_DAYS are
|
|
12
|
+
// left.
|
|
13
|
+
// 3. It asks the router to forward its TLS port (UPnP or NAT-PMP), so the
|
|
14
|
+
// name works from outside the home network.
|
|
15
|
+
//
|
|
16
|
+
// The relay must be registered with the Worker first (`npx freertc name` on
|
|
17
|
+
// this machine, with the owner's Cloudflare login).
|
|
18
|
+
|
|
19
|
+
import { readFileSync, writeFileSync, mkdirSync, existsSync } from 'node:fs';
|
|
20
|
+
import { X509Certificate } from 'node:crypto';
|
|
21
|
+
import path from 'node:path';
|
|
22
|
+
import { createNameRequest, NAMES_PATH } from '../direct/names.js';
|
|
23
|
+
|
|
24
|
+
const CLAIM_EVERY_MS = 10 * 60_000;
|
|
25
|
+
const CHECK_CERT_EVERY_MS = 12 * 60 * 60_000;
|
|
26
|
+
const RENEW_DAYS = 30;
|
|
27
|
+
const RETRY_MS = 5 * 60_000;
|
|
28
|
+
const TXT_WAIT_MS = 3 * 60_000;
|
|
29
|
+
const DOH_URLS = ['https://cloudflare-dns.com/dns-query', 'https://dns.google/resolve'];
|
|
30
|
+
const LETS_ENCRYPT = 'https://acme-v02.api.letsencrypt.org/directory';
|
|
31
|
+
const LETS_ENCRYPT_STAGING = 'https://acme-staging-v02.api.letsencrypt.org/directory';
|
|
32
|
+
/** Directory records hold names of at most this many characters (src/direct/record.js). */
|
|
33
|
+
const MAX_DIRECTORY_NAME = 64;
|
|
34
|
+
|
|
35
|
+
/** The naming settings `freertc name` leaves in the data directory, or null. */
|
|
36
|
+
export function loadNameSettings(dataDir, env = process.env) {
|
|
37
|
+
if (env.FREERTC_NAMES_URL) return { worker: env.FREERTC_NAMES_URL };
|
|
38
|
+
const file = path.join(dataDir, 'names.json');
|
|
39
|
+
if (!existsSync(file)) return null;
|
|
40
|
+
try {
|
|
41
|
+
const settings = JSON.parse(readFileSync(file, 'utf8'));
|
|
42
|
+
return settings?.worker ? settings : null;
|
|
43
|
+
} catch {
|
|
44
|
+
return null;
|
|
45
|
+
}
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
/** Days until a PEM certificate expires (negative: expired), and whether it is for `name`. */
|
|
49
|
+
export function certificateState(pem, name) {
|
|
50
|
+
try {
|
|
51
|
+
const cert = new X509Certificate(pem);
|
|
52
|
+
const days = (Date.parse(cert.validTo) - Date.now()) / 86_400_000;
|
|
53
|
+
return { days, forName: cert.checkHost(name) === name };
|
|
54
|
+
} catch {
|
|
55
|
+
return { days: -1, forName: false };
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Wait until public DNS shows TXT `value` at `name` (Let's Encrypt asks public DNS too). */
|
|
60
|
+
export async function waitForTxt(name, value, { fetchImpl = globalThis.fetch, timeoutMs = TXT_WAIT_MS, everyMs = 5_000 } = {}) {
|
|
61
|
+
const until = Date.now() + timeoutMs;
|
|
62
|
+
while (Date.now() < until) {
|
|
63
|
+
for (const doh of DOH_URLS) {
|
|
64
|
+
try {
|
|
65
|
+
const response = await fetchImpl(`${doh}?name=${encodeURIComponent(name)}&type=TXT`, { headers: { accept: 'application/dns-json' } });
|
|
66
|
+
const answer = await response.json();
|
|
67
|
+
if ((answer?.Answer || []).some((a) => String(a.data).replace(/"/g, '') === value)) return true;
|
|
68
|
+
} catch { /* try the next */ }
|
|
69
|
+
}
|
|
70
|
+
await new Promise((resolve) => setTimeout(resolve, everyMs));
|
|
71
|
+
}
|
|
72
|
+
return false;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
export async function startRelayName({
|
|
76
|
+
identity,
|
|
77
|
+
dataDir,
|
|
78
|
+
worker,
|
|
79
|
+
tlsPort,
|
|
80
|
+
/** async (port) => { externalIp, externalPort, close } | null: the router's forward for the TLS port. */
|
|
81
|
+
mapPort = async () => null,
|
|
82
|
+
/** Called with { name, key, cert } when a certificate is ready (first time and on renewal). */
|
|
83
|
+
onCertificate,
|
|
84
|
+
/** Called when the wss address (for the directory) changes: wss://<name>:<port>/ws, or null. */
|
|
85
|
+
onAddress = () => {},
|
|
86
|
+
log = () => {},
|
|
87
|
+
fetchImpl = globalThis.fetch,
|
|
88
|
+
staging = false,
|
|
89
|
+
}) {
|
|
90
|
+
const dir = path.join(dataDir, 'tls');
|
|
91
|
+
mkdirSync(dir, { recursive: true, mode: 0o700 });
|
|
92
|
+
const endpoint = new URL(NAMES_PATH, worker).toString();
|
|
93
|
+
let name = null, ip = null, mapping = null, wssUrl = null, stopped = false;
|
|
94
|
+
const timers = [];
|
|
95
|
+
|
|
96
|
+
async function ask(action, value = null) {
|
|
97
|
+
const body = await createNameRequest(identity, { action, value });
|
|
98
|
+
const response = await fetchImpl(endpoint, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(body) });
|
|
99
|
+
const result = await response.json().catch(() => null);
|
|
100
|
+
if (!response.ok || !result?.ok) throw new Error(result?.error || `status ${response.status}`);
|
|
101
|
+
return result;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
async function claim() {
|
|
105
|
+
const result = await ask('claim');
|
|
106
|
+
if (result.name !== name || result.ip !== ip) log(`name: ${result.name} -> ${result.ip}`);
|
|
107
|
+
name = result.name;
|
|
108
|
+
ip = result.ip;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
async function obtain() {
|
|
112
|
+
const acme = (await import('acme-client')).default;
|
|
113
|
+
const accountFile = path.join(dir, 'acme-account.key');
|
|
114
|
+
const accountKey = existsSync(accountFile) ? readFileSync(accountFile) : await acme.crypto.createPrivateEcdsaKey();
|
|
115
|
+
if (!existsSync(accountFile)) writeFileSync(accountFile, accountKey, { mode: 0o600 });
|
|
116
|
+
const client = new acme.Client({ directoryUrl: staging ? LETS_ENCRYPT_STAGING : LETS_ENCRYPT, accountKey });
|
|
117
|
+
const [key, csr] = await acme.crypto.createCsr({ commonName: name, altNames: [name] }, await acme.crypto.createPrivateEcdsaKey());
|
|
118
|
+
log(`certificate: asking Let's Encrypt for ${name}${staging ? ' (staging)' : ''}`);
|
|
119
|
+
const cert = await client.auto({
|
|
120
|
+
csr,
|
|
121
|
+
termsOfServiceAgreed: true,
|
|
122
|
+
challengePriority: ['dns-01'],
|
|
123
|
+
// Checked here against public DNS instead (the local resolver may cache).
|
|
124
|
+
skipChallengeVerification: true,
|
|
125
|
+
challengeCreateFn: async (_authz, _challenge, keyAuthorization) => {
|
|
126
|
+
await ask('acme-set', keyAuthorization);
|
|
127
|
+
if (!await waitForTxt(`_acme-challenge.${name}`, keyAuthorization, { fetchImpl })) throw new Error('the challenge record did not show up in public DNS');
|
|
128
|
+
},
|
|
129
|
+
challengeRemoveFn: async () => { await ask('acme-clear').catch(() => {}); },
|
|
130
|
+
});
|
|
131
|
+
writeFileSync(path.join(dir, `${name}.key`), key, { mode: 0o600 });
|
|
132
|
+
writeFileSync(path.join(dir, `${name}.crt`), cert);
|
|
133
|
+
log(`certificate: issued for ${name}, valid ${Math.round(certificateState(cert, name).days)} days`);
|
|
134
|
+
return { key: key.toString(), cert: cert.toString() };
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** The certificate on disk if it is good for a while yet, else a new one. */
|
|
138
|
+
async function certificate(force = false) {
|
|
139
|
+
const keyFile = path.join(dir, `${name}.key`), certFile = path.join(dir, `${name}.crt`);
|
|
140
|
+
if (!force && existsSync(keyFile) && existsSync(certFile)) {
|
|
141
|
+
const cert = readFileSync(certFile, 'utf8');
|
|
142
|
+
const state = certificateState(cert, name);
|
|
143
|
+
if (state.forName && state.days > RENEW_DAYS) return { key: readFileSync(keyFile, 'utf8'), cert, fresh: false };
|
|
144
|
+
}
|
|
145
|
+
return { ...(await obtain()), fresh: true };
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
function setAddress() {
|
|
149
|
+
const port = mapping?.externalPort ?? null;
|
|
150
|
+
const next = name && port ? `wss://${name}:${port}/ws` : null;
|
|
151
|
+
const fits = next && next.length <= MAX_DIRECTORY_NAME ? next : null;
|
|
152
|
+
if (next && !fits) log(`directory: ${next} is longer than ${MAX_DIRECTORY_NAME} characters; listed without it`);
|
|
153
|
+
if (fits !== wssUrl) { wssUrl = fits; onAddress(wssUrl); }
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
async function run() {
|
|
157
|
+
try {
|
|
158
|
+
await claim();
|
|
159
|
+
const { key, cert } = await certificate();
|
|
160
|
+
onCertificate({ name, key, cert });
|
|
161
|
+
if (!mapping) {
|
|
162
|
+
mapping = await mapPort(tlsPort).catch(() => null);
|
|
163
|
+
if (mapping) log(`router forwards tcp ${mapping.externalIp}:${mapping.externalPort} to ${tlsPort}`);
|
|
164
|
+
else log(`no router forward for tcp ${tlsPort}: wss://${name}:${tlsPort}/ws works on this network only`);
|
|
165
|
+
}
|
|
166
|
+
setAddress();
|
|
167
|
+
} catch (error) {
|
|
168
|
+
log(`name: ${error?.message || error}; trying again in ${RETRY_MS / 60_000} min`);
|
|
169
|
+
if (!stopped) timers.push(setTimeout(() => run().catch(() => {}), RETRY_MS));
|
|
170
|
+
return;
|
|
171
|
+
}
|
|
172
|
+
timers.push(setInterval(() => claim().catch((error) => log(`name: ${error?.message || error}`)), CLAIM_EVERY_MS));
|
|
173
|
+
timers.push(setInterval(async () => {
|
|
174
|
+
try {
|
|
175
|
+
const { key, cert, fresh } = await certificate();
|
|
176
|
+
if (fresh) onCertificate({ name, key, cert });
|
|
177
|
+
} catch (error) {
|
|
178
|
+
log(`certificate: renewal failed (${error?.message || error}); trying again later`);
|
|
179
|
+
}
|
|
180
|
+
}, CHECK_CERT_EVERY_MS));
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
await run();
|
|
184
|
+
return {
|
|
185
|
+
get name() { return name; },
|
|
186
|
+
get wssUrl() { return wssUrl; },
|
|
187
|
+
stop() {
|
|
188
|
+
stopped = true;
|
|
189
|
+
for (const t of timers) { clearTimeout(t); clearInterval(t); }
|
|
190
|
+
mapping?.close?.().catch?.(() => {});
|
|
191
|
+
},
|
|
192
|
+
};
|
|
193
|
+
}
|