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,214 @@
|
|
|
1
|
+
// Ask the home router to forward a port to this machine: UDP for browsers'
|
|
2
|
+
// direct connections, TCP for other relays' calls. No configuration: UPnP
|
|
3
|
+
// IGD first (most home routers), then NAT-PMP (Apple and some others). No
|
|
4
|
+
// dependencies.
|
|
5
|
+
//
|
|
6
|
+
// Returns { externalIp, externalPort, protocol, method, close() } or null when
|
|
7
|
+
// no router answers or it refuses. The mapping is renewed while it is held and
|
|
8
|
+
// removed by close().
|
|
9
|
+
|
|
10
|
+
import { createSocket } from 'node:dgram';
|
|
11
|
+
import { execFile } from 'node:child_process';
|
|
12
|
+
import { networkInterfaces } from 'node:os';
|
|
13
|
+
import { readFile } from 'node:fs/promises';
|
|
14
|
+
|
|
15
|
+
const SSDP_ADDRESS = '239.255.255.250';
|
|
16
|
+
const SSDP_PORT = 1900;
|
|
17
|
+
const SEARCH_MS = 3_000;
|
|
18
|
+
const LEASE_SECONDS = 3_600;
|
|
19
|
+
const RENEW_MS = 45 * 60_000;
|
|
20
|
+
const WAN_SERVICES = [
|
|
21
|
+
'urn:schemas-upnp-org:service:WANIPConnection:2',
|
|
22
|
+
'urn:schemas-upnp-org:service:WANIPConnection:1',
|
|
23
|
+
'urn:schemas-upnp-org:service:WANPPPConnection:1',
|
|
24
|
+
];
|
|
25
|
+
|
|
26
|
+
function lanAddressFor(gatewayHost) {
|
|
27
|
+
const prefix = String(gatewayHost).split('.').slice(0, 3).join('.');
|
|
28
|
+
let fallback = null;
|
|
29
|
+
for (const addresses of Object.values(networkInterfaces())) {
|
|
30
|
+
for (const address of addresses || []) {
|
|
31
|
+
if (address.family !== 'IPv4' || address.internal) continue;
|
|
32
|
+
if (address.address.startsWith(`${prefix}.`)) return address.address;
|
|
33
|
+
fallback ??= address.address;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
return fallback;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** SSDP search: the LOCATION URLs of internet gateway devices on this network. */
|
|
40
|
+
function ssdpSearch(timeoutMs = SEARCH_MS) {
|
|
41
|
+
return new Promise((resolve) => {
|
|
42
|
+
const socket = createSocket({ type: 'udp4', reuseAddr: true });
|
|
43
|
+
const found = new Set();
|
|
44
|
+
const done = () => { try { socket.close(); } catch {} resolve([...found]); };
|
|
45
|
+
socket.on('message', (message) => {
|
|
46
|
+
const location = /^location:\s*(\S+)/im.exec(message.toString())?.[1];
|
|
47
|
+
if (location) found.add(location);
|
|
48
|
+
});
|
|
49
|
+
socket.on('error', done);
|
|
50
|
+
socket.bind(0, () => {
|
|
51
|
+
for (const target of ['urn:schemas-upnp-org:device:InternetGatewayDevice:1', 'urn:schemas-upnp-org:device:InternetGatewayDevice:2', ...WAN_SERVICES]) {
|
|
52
|
+
const search = Buffer.from([
|
|
53
|
+
'M-SEARCH * HTTP/1.1', `HOST: ${SSDP_ADDRESS}:${SSDP_PORT}`, 'MAN: "ssdp:discover"', 'MX: 2', `ST: ${target}`, '', '',
|
|
54
|
+
].join('\r\n'));
|
|
55
|
+
socket.send(search, SSDP_PORT, SSDP_ADDRESS);
|
|
56
|
+
}
|
|
57
|
+
setTimeout(done, timeoutMs).unref?.();
|
|
58
|
+
});
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
async function fetchText(url, options = {}) {
|
|
63
|
+
const response = await fetch(url, { ...options, signal: AbortSignal.timeout(5_000) });
|
|
64
|
+
const text = await response.text();
|
|
65
|
+
if (!response.ok) throw new Error(`${response.status}: ${(/<errorDescription>([^<]*)/.exec(text) || [])[1] || text.slice(0, 120)}`);
|
|
66
|
+
return text;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** The WAN connection service of the gateway described at `location`: { controlUrl, serviceType }. */
|
|
70
|
+
async function wanService(location) {
|
|
71
|
+
const xml = await fetchText(location);
|
|
72
|
+
for (const block of xml.split(/<service>/i).slice(1)) {
|
|
73
|
+
const serviceType = /<serviceType>\s*([^<\s]+)\s*<\/serviceType>/i.exec(block)?.[1];
|
|
74
|
+
const control = /<controlURL>\s*([^<\s]+)\s*<\/controlURL>/i.exec(block)?.[1];
|
|
75
|
+
if (serviceType && control && WAN_SERVICES.includes(serviceType)) {
|
|
76
|
+
return { controlUrl: new URL(control, location).toString(), serviceType };
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
return null;
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
function soapCall({ controlUrl, serviceType }, action, args = {}) {
|
|
83
|
+
const body = `<?xml version="1.0"?><s:Envelope xmlns:s="http://schemas.xmlsoap.org/soap/envelope/" s:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"><s:Body><u:${action} xmlns:u="${serviceType}">${
|
|
84
|
+
Object.entries(args).map(([key, value]) => `<${key}>${String(value).replace(/[<&>]/g, '')}</${key}>`).join('')
|
|
85
|
+
}</u:${action}></s:Body></s:Envelope>`;
|
|
86
|
+
return fetchText(controlUrl, {
|
|
87
|
+
method: 'POST',
|
|
88
|
+
headers: { 'Content-Type': 'text/xml; charset="utf-8"', SOAPAction: `"${serviceType}#${action}"` },
|
|
89
|
+
body,
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
async function mapWithUpnp({ internalPort, externalPort, description, protocol, log }) {
|
|
94
|
+
for (const location of await ssdpSearch()) {
|
|
95
|
+
let service;
|
|
96
|
+
try { service = await wanService(location); } catch { continue; }
|
|
97
|
+
if (!service) continue;
|
|
98
|
+
const gatewayHost = new URL(location).hostname;
|
|
99
|
+
const internalClient = lanAddressFor(gatewayHost);
|
|
100
|
+
if (!internalClient) continue;
|
|
101
|
+
try {
|
|
102
|
+
const ipXml = await soapCall(service, 'GetExternalIPAddress');
|
|
103
|
+
const externalIp = /<NewExternalIPAddress>\s*([^<\s]*)\s*</i.exec(ipXml)?.[1];
|
|
104
|
+
const add = () => soapCall(service, 'AddPortMapping', {
|
|
105
|
+
NewRemoteHost: '',
|
|
106
|
+
NewExternalPort: externalPort,
|
|
107
|
+
NewProtocol: protocol,
|
|
108
|
+
NewInternalPort: internalPort,
|
|
109
|
+
NewInternalClient: internalClient,
|
|
110
|
+
NewEnabled: 1,
|
|
111
|
+
NewPortMappingDescription: description,
|
|
112
|
+
NewLeaseDuration: LEASE_SECONDS,
|
|
113
|
+
});
|
|
114
|
+
await add();
|
|
115
|
+
const renew = setInterval(() => add().catch((error) => log(`UPnP renewal failed: ${error.message}`)), RENEW_MS);
|
|
116
|
+
renew.unref?.();
|
|
117
|
+
return {
|
|
118
|
+
method: 'upnp',
|
|
119
|
+
externalIp,
|
|
120
|
+
externalPort,
|
|
121
|
+
internalClient,
|
|
122
|
+
protocol,
|
|
123
|
+
async close() {
|
|
124
|
+
clearInterval(renew);
|
|
125
|
+
await soapCall(service, 'DeletePortMapping', { NewRemoteHost: '', NewExternalPort: externalPort, NewProtocol: protocol }).catch(() => {});
|
|
126
|
+
},
|
|
127
|
+
};
|
|
128
|
+
} catch (error) {
|
|
129
|
+
log(`UPnP gateway ${gatewayHost} refused the mapping: ${error.message}`);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
return null;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
async function defaultGateway() {
|
|
136
|
+
if (process.platform === 'linux') {
|
|
137
|
+
try {
|
|
138
|
+
for (const line of (await readFile('/proc/net/route', 'utf8')).split('\n').slice(1)) {
|
|
139
|
+
const [, destination, gateway] = line.trim().split(/\s+/);
|
|
140
|
+
if (destination === '00000000' && gateway && gateway !== '00000000') {
|
|
141
|
+
return gateway.match(/../g).reverse().map((h) => parseInt(h, 16)).join('.');
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
} catch {}
|
|
145
|
+
return null;
|
|
146
|
+
}
|
|
147
|
+
if (process.platform === 'darwin' || process.platform.endsWith('bsd')) {
|
|
148
|
+
return new Promise((resolve) => execFile('route', ['-n', 'get', 'default'], { timeout: 3_000 }, (error, stdout) => {
|
|
149
|
+
resolve(error ? null : (/gateway:\s*(\d+\.\d+\.\d+\.\d+)/.exec(stdout)?.[1] ?? null));
|
|
150
|
+
}));
|
|
151
|
+
}
|
|
152
|
+
return null;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function pmpRequest(gateway, request, timeoutMs = 2_000) {
|
|
156
|
+
return new Promise((resolve, reject) => {
|
|
157
|
+
const socket = createSocket('udp4');
|
|
158
|
+
const timer = setTimeout(() => { try { socket.close(); } catch {} reject(new Error('NAT-PMP: no answer')); }, timeoutMs);
|
|
159
|
+
socket.on('message', (message) => { clearTimeout(timer); try { socket.close(); } catch {} resolve(message); });
|
|
160
|
+
socket.on('error', (error) => { clearTimeout(timer); try { socket.close(); } catch {} reject(error); });
|
|
161
|
+
socket.send(request, 5351, gateway);
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
async function mapWithPmp({ internalPort, externalPort, protocol, log }) {
|
|
166
|
+
const gateway = await defaultGateway();
|
|
167
|
+
if (!gateway) return null;
|
|
168
|
+
try {
|
|
169
|
+
const ipAnswer = await pmpRequest(gateway, Buffer.from([0, 0]));
|
|
170
|
+
if (ipAnswer.length < 12 || ipAnswer.readUInt16BE(2) !== 0) return null;
|
|
171
|
+
const externalIp = [...ipAnswer.subarray(8, 12)].join('.');
|
|
172
|
+
const map = async (lifetime) => {
|
|
173
|
+
const request = Buffer.alloc(12);
|
|
174
|
+
request[0] = 0; request[1] = protocol === 'TCP' ? 2 : 1; // version 0, map UDP (1) or TCP (2)
|
|
175
|
+
request.writeUInt16BE(internalPort, 4);
|
|
176
|
+
request.writeUInt16BE(externalPort, 6);
|
|
177
|
+
request.writeUInt32BE(lifetime, 8);
|
|
178
|
+
const answer = await pmpRequest(gateway, request);
|
|
179
|
+
if (answer.length < 16 || answer.readUInt16BE(2) !== 0) throw new Error(`NAT-PMP refused (result ${answer.readUInt16BE(2)})`);
|
|
180
|
+
return answer.readUInt16BE(10);
|
|
181
|
+
};
|
|
182
|
+
const mappedPort = await map(LEASE_SECONDS);
|
|
183
|
+
const renew = setInterval(() => map(LEASE_SECONDS).catch((error) => log(`NAT-PMP renewal failed: ${error.message}`)), RENEW_MS);
|
|
184
|
+
renew.unref?.();
|
|
185
|
+
return {
|
|
186
|
+
method: 'nat-pmp',
|
|
187
|
+
externalIp,
|
|
188
|
+
externalPort: mappedPort,
|
|
189
|
+
protocol,
|
|
190
|
+
async close() { clearInterval(renew); await map(0).catch(() => {}); },
|
|
191
|
+
};
|
|
192
|
+
} catch (error) {
|
|
193
|
+
log(`NAT-PMP gateway ${gateway}: ${error.message}`);
|
|
194
|
+
return null;
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/** Forward externalPort (protocol 'UDP' or 'TCP') on the router to internalPort here. */
|
|
199
|
+
export async function mapPort({ internalPort, externalPort = internalPort, protocol = 'UDP', description = 'freertc relay', log = () => {} }) {
|
|
200
|
+
return (await mapWithUpnp({ internalPort, externalPort, description, protocol, log }))
|
|
201
|
+
?? (await mapWithPmp({ internalPort, externalPort, protocol, log }));
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
export const mapUdpPort = (options) => mapPort({ ...options, protocol: 'UDP' });
|
|
205
|
+
export const mapTcpPort = (options) => mapPort({ ...options, protocol: 'TCP' });
|
|
206
|
+
|
|
207
|
+
/** True for an address that is not reachable from the internet (private, CGNAT, loopback, link-local). */
|
|
208
|
+
export function isNonPublicIPv4(ip) {
|
|
209
|
+
const m = /^(\d+)\.(\d+)\.(\d+)\.(\d+)$/.exec(String(ip));
|
|
210
|
+
if (!m) return true;
|
|
211
|
+
const [a, b] = [Number(m[1]), Number(m[2])];
|
|
212
|
+
return a === 0 || a === 10 || a === 127 || (a === 169 && b === 254) || (a === 172 && b >= 16 && b <= 31)
|
|
213
|
+
|| (a === 192 && b === 168) || (a === 100 && b >= 64 && b <= 127) || a >= 224;
|
|
214
|
+
}
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
// Can relays reach this address? A local relay whose router forwards its TCP
|
|
2
|
+
// port asks a cloud relay to call it back before it federates under its
|
|
3
|
+
// public address instead of a tunnel:
|
|
4
|
+
//
|
|
5
|
+
// POST /api/v1/reachable body: { port, node_id }
|
|
6
|
+
//
|
|
7
|
+
// The cloud relay calls http://<the address the request came from>:<port>/health
|
|
8
|
+
// (from a Worker, over a TCP socket: see relay-fetch.js) and says whether a
|
|
9
|
+
// relay with that node ID answered. It only ever calls the caller's own
|
|
10
|
+
// address, so it cannot be used to probe anyone else.
|
|
11
|
+
|
|
12
|
+
import { relayFetch } from '../relay-fetch.js';
|
|
13
|
+
|
|
14
|
+
export const REACHABLE_PATH = '/api/v1/reachable';
|
|
15
|
+
const PROBE_TIMEOUT_MS = 5_000;
|
|
16
|
+
|
|
17
|
+
function json(body, status = 200) {
|
|
18
|
+
return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export async function handleReachableRequest(request, { fetchImpl = relayFetch } = {}) {
|
|
22
|
+
if (request.method !== 'POST') return json({ ok: false, error: 'method not allowed' }, 405);
|
|
23
|
+
let body;
|
|
24
|
+
try { body = JSON.parse((await request.text()).slice(0, 2048)); } catch { return json({ ok: false, error: 'bad JSON' }, 400); }
|
|
25
|
+
const port = Number(body?.port);
|
|
26
|
+
const nodeId = String(body?.node_id || '');
|
|
27
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535 || port === 25) return json({ ok: false, error: 'bad port' }, 400);
|
|
28
|
+
if (!/^[0-9a-f]{64}$/.test(nodeId)) return json({ ok: false, error: 'bad node_id' }, 400);
|
|
29
|
+
const ip = request.headers.get('CF-Connecting-IP');
|
|
30
|
+
if (!ip) return json({ ok: false, error: 'no caller address' }, 400);
|
|
31
|
+
const host = ip.includes(':') ? `[${ip}]` : ip;
|
|
32
|
+
try {
|
|
33
|
+
const response = await fetchImpl(`http://${host}:${port}/health`, { signal: AbortSignal.timeout(PROBE_TIMEOUT_MS) });
|
|
34
|
+
const health = await response.json().catch(() => null);
|
|
35
|
+
const reachable = response.ok && health?.node_id === nodeId;
|
|
36
|
+
return json({ ok: true, reachable, ip, ...(reachable ? {} : { why: response.ok ? 'another relay answered' : `status ${response.status}` }) });
|
|
37
|
+
} catch (error) {
|
|
38
|
+
return json({ ok: true, reachable: false, ip, why: String(error?.message || error).slice(0, 120) });
|
|
39
|
+
}
|
|
40
|
+
}
|
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
// A relay's entry in the DNS relay directory (see directory.js and lookup.js):
|
|
2
|
+
// a signed record saying where browsers can reach it directly. It is its own
|
|
3
|
+
// record kind, separate from the Kademlia node record, so relays on older code
|
|
4
|
+
// that federate node records never see it.
|
|
5
|
+
//
|
|
6
|
+
// {
|
|
7
|
+
// version: 1, kind: 'relay-directory',
|
|
8
|
+
// node_id, public_key, name,
|
|
9
|
+
// direct: 'webrtc-direct://<ip>:<port>/sha256/<fingerprint>',
|
|
10
|
+
// tunnel: 'wss://<home>/t/<node id>/ws' | null, the way in when direct fails
|
|
11
|
+
// capacity, issued_at_ms, expires_at_ms, signature,
|
|
12
|
+
// ws: 'ws://<ip>:<port>/ws' optional: the relay's open TCP port, at
|
|
13
|
+
// the same address as direct; relays
|
|
14
|
+
// behind NAT use it as their home
|
|
15
|
+
// lan: ['<private ip>:<port>', …] optional: where machines on the
|
|
16
|
+
// relay's own network reach it (a
|
|
17
|
+
// router seldom loops its public
|
|
18
|
+
// address back inside)
|
|
19
|
+
// }
|
|
20
|
+
//
|
|
21
|
+
// In DNS it is one TXT record, the record's canonical JSON in base64url, in
|
|
22
|
+
// strings of at most 255 characters, prefixed "frtc1:".
|
|
23
|
+
|
|
24
|
+
import { signMessage, verifyMessage } from 'unsea';
|
|
25
|
+
import { canonicalJson, isNodeId, relayNodeId, scopeRoutingKey, xorDistanceHex } from '../kademlia.js';
|
|
26
|
+
import { parseDirectRelayUrl } from './common.js';
|
|
27
|
+
|
|
28
|
+
export const DIRECTORY_RECORD_KIND = 'relay-directory';
|
|
29
|
+
export const DIRECTORY_WITHDRAW_KIND = 'relay-directory-withdraw';
|
|
30
|
+
const RECORD_VERSION = 1;
|
|
31
|
+
const MAX_CLOCK_SKEW_MS = 60_000;
|
|
32
|
+
export const MAX_DIRECTORY_TTL_MS = 26 * 60 * 60_000;
|
|
33
|
+
const TXT_PREFIX = 'frtc1:';
|
|
34
|
+
|
|
35
|
+
function unsigned(record) {
|
|
36
|
+
const { signature: _signature, ...payload } = record;
|
|
37
|
+
return payload;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const MAX_LAN_ADDRESSES = 4;
|
|
41
|
+
|
|
42
|
+
/** A private IPv4 address and port, as "a.b.c.d:port". */
|
|
43
|
+
export function isLanEndpoint(value) {
|
|
44
|
+
const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3}):(\d{1,5})$/.exec(String(value || ''));
|
|
45
|
+
if (!m || m.slice(1, 5).some((part) => Number(part) > 255)) return false;
|
|
46
|
+
const [a, b] = [Number(m[1]), Number(m[2])];
|
|
47
|
+
const port = Number(m[5]);
|
|
48
|
+
const lan = a === 10 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168);
|
|
49
|
+
return lan && port >= 1 && port <= 65535;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
function lanOk(value) {
|
|
53
|
+
return Array.isArray(value) && value.length >= 1 && value.length <= MAX_LAN_ADDRESSES && value.every(isLanEndpoint);
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function wsUrlOk(value, direct) {
|
|
57
|
+
try {
|
|
58
|
+
const url = new URL(value);
|
|
59
|
+
const host = parseDirectRelayUrl(direct)?.host;
|
|
60
|
+
return url.protocol === 'ws:' && url.hostname === host && url.port !== '' && url.pathname === '/ws' && !url.search && !url.hash;
|
|
61
|
+
} catch {
|
|
62
|
+
return false;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
function tunnelUrlOk(value, nodeId) {
|
|
67
|
+
if (value === null) return true;
|
|
68
|
+
try {
|
|
69
|
+
const url = new URL(value);
|
|
70
|
+
return url.protocol === 'wss:' && url.pathname === `/t/${nodeId}/ws` && !url.search && !url.hash;
|
|
71
|
+
} catch {
|
|
72
|
+
return false;
|
|
73
|
+
}
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export async function createSignedDirectoryRecord(identity, { direct, tunnel = null, name = null, capacity = 10_000, ttlMs = 2 * 60 * 60_000, now = Date.now(), lan = [], ws = null }) {
|
|
77
|
+
if (!parseDirectRelayUrl(direct)) throw new TypeError('direct must be a webrtc-direct URL');
|
|
78
|
+
if (!tunnelUrlOk(tunnel, identity.nodeId)) throw new TypeError('tunnel must be this relay\'s own tunnel URL');
|
|
79
|
+
const payload = {
|
|
80
|
+
version: RECORD_VERSION,
|
|
81
|
+
kind: DIRECTORY_RECORD_KIND,
|
|
82
|
+
node_id: identity.nodeId,
|
|
83
|
+
public_key: identity.publicKey,
|
|
84
|
+
name: typeof name === 'string' && name ? name.slice(0, 64) : null,
|
|
85
|
+
direct,
|
|
86
|
+
tunnel,
|
|
87
|
+
capacity: Math.max(1, Math.floor(Number(capacity) || 1)),
|
|
88
|
+
issued_at_ms: now,
|
|
89
|
+
expires_at_ms: now + Math.min(MAX_DIRECTORY_TTL_MS, Math.max(60_000, ttlMs)),
|
|
90
|
+
};
|
|
91
|
+
// Left out when there is none, so such a record reads the same as before.
|
|
92
|
+
const lanEndpoints = [...new Set((lan || []).filter(isLanEndpoint))].slice(0, MAX_LAN_ADDRESSES);
|
|
93
|
+
if (lanEndpoints.length) payload.lan = lanEndpoints;
|
|
94
|
+
if (ws && wsUrlOk(ws, direct)) payload.ws = ws;
|
|
95
|
+
return { ...payload, signature: await signMessage(canonicalJson(payload), identity.privateKey) };
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export async function verifyDirectoryRecord(record, { now = Date.now() } = {}) {
|
|
99
|
+
try {
|
|
100
|
+
if (!record || typeof record !== 'object' || Array.isArray(record)) return false;
|
|
101
|
+
if (record.version !== RECORD_VERSION || record.kind !== DIRECTORY_RECORD_KIND) return false;
|
|
102
|
+
if (!isNodeId(record.node_id) || typeof record.public_key !== 'string' || typeof record.signature !== 'string') return false;
|
|
103
|
+
if (await relayNodeId(record.public_key) !== record.node_id) return false;
|
|
104
|
+
if (!parseDirectRelayUrl(record.direct) || !tunnelUrlOk(record.tunnel, record.node_id)) return false;
|
|
105
|
+
if (record.name !== null && (typeof record.name !== 'string' || record.name.length > 64)) return false;
|
|
106
|
+
if (!Number.isInteger(record.capacity) || record.capacity < 1) return false;
|
|
107
|
+
const issued = Number(record.issued_at_ms);
|
|
108
|
+
const expires = Number(record.expires_at_ms);
|
|
109
|
+
if (!Number.isFinite(issued) || !Number.isFinite(expires)) return false;
|
|
110
|
+
if (issued > now + MAX_CLOCK_SKEW_MS || expires <= now || expires - issued > MAX_DIRECTORY_TTL_MS) return false;
|
|
111
|
+
const keys = Object.keys(record).filter((key) => key !== 'lan' && key !== 'ws').sort().join(',');
|
|
112
|
+
if (keys !== 'capacity,direct,expires_at_ms,issued_at_ms,kind,name,node_id,public_key,signature,tunnel,version') return false;
|
|
113
|
+
if ('lan' in record && !lanOk(record.lan)) return false;
|
|
114
|
+
if ('ws' in record && !wsUrlOk(record.ws, record.direct)) return false;
|
|
115
|
+
return await verifyMessage(canonicalJson(unsigned(record)), record.signature, record.public_key);
|
|
116
|
+
} catch {
|
|
117
|
+
return false;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/** A signed request to remove this relay's directory entry. */
|
|
122
|
+
export async function createSignedWithdrawal(identity, { now = Date.now() } = {}) {
|
|
123
|
+
const payload = {
|
|
124
|
+
version: RECORD_VERSION,
|
|
125
|
+
kind: DIRECTORY_WITHDRAW_KIND,
|
|
126
|
+
node_id: identity.nodeId,
|
|
127
|
+
public_key: identity.publicKey,
|
|
128
|
+
issued_at_ms: now,
|
|
129
|
+
};
|
|
130
|
+
return { ...payload, signature: await signMessage(canonicalJson(payload), identity.privateKey) };
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
export async function verifyWithdrawal(withdrawal, { now = Date.now() } = {}) {
|
|
134
|
+
try {
|
|
135
|
+
if (!withdrawal || withdrawal.version !== RECORD_VERSION || withdrawal.kind !== DIRECTORY_WITHDRAW_KIND) return false;
|
|
136
|
+
if (!isNodeId(withdrawal.node_id) || await relayNodeId(withdrawal.public_key) !== withdrawal.node_id) return false;
|
|
137
|
+
if (Math.abs(now - Number(withdrawal.issued_at_ms)) > 5 * 60_000) return false;
|
|
138
|
+
return await verifyMessage(canonicalJson(unsigned(withdrawal)), withdrawal.signature, withdrawal.public_key);
|
|
139
|
+
} catch {
|
|
140
|
+
return false;
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function base64urlEncode(text) {
|
|
145
|
+
const bytes = new TextEncoder().encode(text);
|
|
146
|
+
let bin = '';
|
|
147
|
+
for (const b of bytes) bin += String.fromCharCode(b);
|
|
148
|
+
return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function base64urlDecode(text) {
|
|
152
|
+
const b64 = text.replace(/-/g, '+').replace(/_/g, '/') + '==='.slice((text.length + 3) % 4);
|
|
153
|
+
const bin = atob(b64);
|
|
154
|
+
return new TextDecoder().decode(Uint8Array.from(bin, (c) => c.charCodeAt(0)));
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** TXT record content for a record: quoted strings of at most 255 characters. */
|
|
158
|
+
export function encodeDirectoryTxt(record) {
|
|
159
|
+
const text = TXT_PREFIX + base64urlEncode(canonicalJson(record));
|
|
160
|
+
return text.match(/.{1,255}/g).map((chunk) => `"${chunk}"`).join(' ');
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** The record in a TXT value (quoted strings, as DNS-over-HTTPS returns it), or null. */
|
|
164
|
+
export function decodeDirectoryTxt(value) {
|
|
165
|
+
try {
|
|
166
|
+
const parts = String(value).match(/"([^"]*)"/g);
|
|
167
|
+
const text = parts ? parts.map((part) => part.slice(1, -1)).join('') : String(value);
|
|
168
|
+
if (!text.startsWith(TXT_PREFIX)) return null;
|
|
169
|
+
const record = JSON.parse(base64urlDecode(text.slice(TXT_PREFIX.length)));
|
|
170
|
+
return record && typeof record === 'object' ? record : null;
|
|
171
|
+
} catch {
|
|
172
|
+
return null;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/**
|
|
177
|
+
* Order verified records for a room: closest relay (by XOR distance from the
|
|
178
|
+
* room's routing key to the relay's node ID) first, so every peer of a room
|
|
179
|
+
* reaches for the same relays.
|
|
180
|
+
*/
|
|
181
|
+
export async function rankDirectoryRecords(records, network, room) {
|
|
182
|
+
const key = await scopeRoutingKey(network, room);
|
|
183
|
+
return [...records].sort((a, b) => {
|
|
184
|
+
const da = xorDistanceHex(key, a.node_id);
|
|
185
|
+
const db = xorDistanceHex(key, b.node_id);
|
|
186
|
+
return da < db ? -1 : da > db ? 1 : 0;
|
|
187
|
+
});
|
|
188
|
+
}
|