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,95 @@
|
|
|
1
|
+
// The direct listener's DTLS certificate: self-signed ECDSA P-256, made once
|
|
2
|
+
// with Node's own crypto and kept beside the relay's data, so its fingerprint
|
|
3
|
+
// (which the relay publishes in its signed directory record) stays the same
|
|
4
|
+
// across restarts. WebRTC checks the certificate only against that
|
|
5
|
+
// fingerprint, never against a certificate authority, so self-signed is all it
|
|
6
|
+
// needs.
|
|
7
|
+
|
|
8
|
+
import { createHash, createPrivateKey, createPublicKey, generateKeyPairSync, randomBytes, sign, X509Certificate } from 'node:crypto';
|
|
9
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync, chmodSync } from 'node:fs';
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
|
|
12
|
+
function derLength(n) {
|
|
13
|
+
if (n < 0x80) return [n];
|
|
14
|
+
if (n < 0x100) return [0x81, n];
|
|
15
|
+
return [0x82, n >> 8, n & 0xff];
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
function tlv(tag, ...parts) {
|
|
19
|
+
const body = Buffer.concat(parts.map((part) => Buffer.from(part)));
|
|
20
|
+
return Buffer.concat([Buffer.from([tag, ...derLength(body.length)]), body]);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const seq = (...parts) => tlv(0x30, ...parts);
|
|
24
|
+
const OID_ECDSA_SHA256 = Buffer.from([0x06, 0x08, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x04, 0x03, 0x02]);
|
|
25
|
+
const OID_COMMON_NAME = Buffer.from([0x06, 0x03, 0x55, 0x04, 0x03]);
|
|
26
|
+
|
|
27
|
+
function derTime(date) {
|
|
28
|
+
const year = date.getUTCFullYear();
|
|
29
|
+
const pad = (n) => String(n).padStart(2, '0');
|
|
30
|
+
const rest = `${pad(date.getUTCMonth() + 1)}${pad(date.getUTCDate())}${pad(date.getUTCHours())}${pad(date.getUTCMinutes())}${pad(date.getUTCSeconds())}Z`;
|
|
31
|
+
return year < 2050
|
|
32
|
+
? tlv(0x17, Buffer.from(`${String(year).slice(2)}${rest}`, 'ascii'))
|
|
33
|
+
: tlv(0x18, Buffer.from(`${year}${rest}`, 'ascii'));
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function name(commonName) {
|
|
37
|
+
return seq(tlv(0x31, seq(OID_COMMON_NAME, tlv(0x0c, Buffer.from(commonName, 'utf8')))));
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** A new self-signed P-256 certificate: { certPem, keyPem, fingerprint (hex) }. */
|
|
41
|
+
export function createDirectCertificate({ commonName = 'freertc-relay', days = 3650, now = new Date() } = {}) {
|
|
42
|
+
const { privateKey, publicKey } = generateKeyPairSync('ec', { namedCurve: 'P-256' });
|
|
43
|
+
const serial = randomBytes(16);
|
|
44
|
+
serial[0] &= 0x7f; // a positive INTEGER
|
|
45
|
+
const notBefore = new Date(now.getTime() - 24 * 60 * 60_000);
|
|
46
|
+
const notAfter = new Date(now.getTime() + days * 24 * 60 * 60_000);
|
|
47
|
+
const tbs = seq(
|
|
48
|
+
tlv(0xa0, tlv(0x02, Buffer.from([0x02]))), // version 3
|
|
49
|
+
tlv(0x02, serial),
|
|
50
|
+
seq(OID_ECDSA_SHA256),
|
|
51
|
+
name(commonName),
|
|
52
|
+
seq(derTime(notBefore), derTime(notAfter)),
|
|
53
|
+
name(commonName),
|
|
54
|
+
publicKey.export({ type: 'spki', format: 'der' }),
|
|
55
|
+
);
|
|
56
|
+
const signature = sign('sha256', tbs, privateKey);
|
|
57
|
+
const der = seq(tbs, seq(OID_ECDSA_SHA256), tlv(0x03, Buffer.from([0x00]), signature));
|
|
58
|
+
const certPem = `-----BEGIN CERTIFICATE-----\n${der.toString('base64').match(/.{1,64}/g).join('\n')}\n-----END CERTIFICATE-----\n`;
|
|
59
|
+
const keyPem = privateKey.export({ type: 'pkcs8', format: 'pem' });
|
|
60
|
+
return { certPem, keyPem, fingerprint: createHash('sha256').update(der).digest('hex') };
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** SHA-256 fingerprint (hex) of a PEM certificate. */
|
|
64
|
+
export function certificateFingerprint(certPem) {
|
|
65
|
+
return new X509Certificate(certPem).fingerprint256.replace(/:/g, '').toLowerCase();
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Load the certificate kept in `dir`, or make and keep one. Returns
|
|
70
|
+
* { certFile, keyFile, fingerprint }. A certificate within 30 days of expiry,
|
|
71
|
+
* or one that does not match its key, is replaced.
|
|
72
|
+
*/
|
|
73
|
+
export function loadOrCreateDirectCertificate(dir, { now = new Date() } = {}) {
|
|
74
|
+
mkdirSync(dir, { recursive: true });
|
|
75
|
+
const certFile = path.join(dir, 'direct-cert.pem');
|
|
76
|
+
const keyFile = path.join(dir, 'direct-key.pem');
|
|
77
|
+
if (existsSync(certFile) && existsSync(keyFile)) {
|
|
78
|
+
try {
|
|
79
|
+
const certPem = readFileSync(certFile, 'utf8');
|
|
80
|
+
const cert = new X509Certificate(certPem);
|
|
81
|
+
const key = createPrivateKey(readFileSync(keyFile, 'utf8'));
|
|
82
|
+
const fresh = new Date(cert.validTo).getTime() - now.getTime() > 30 * 24 * 60 * 60_000;
|
|
83
|
+
if (fresh && cert.checkPrivateKey(key) && createPublicKey(key).asymmetricKeyDetails?.namedCurve === 'prime256v1') {
|
|
84
|
+
return { certFile, keyFile, fingerprint: certificateFingerprint(certPem) };
|
|
85
|
+
}
|
|
86
|
+
} catch {
|
|
87
|
+
// unreadable or mismatched: make a new one below
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
const { certPem, keyPem, fingerprint } = createDirectCertificate({ now });
|
|
91
|
+
writeFileSync(keyFile, keyPem, { mode: 0o600 });
|
|
92
|
+
try { chmodSync(keyFile, 0o600); } catch {}
|
|
93
|
+
writeFileSync(certFile, certPem);
|
|
94
|
+
return { certFile, keyFile, fingerprint };
|
|
95
|
+
}
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
// Direct relays: a browser opens a WebRTC data channel straight to a relay's
|
|
2
|
+
// public address, with no signaling server, no DNS name for the relay and no
|
|
3
|
+
// certificate authority. The relay publishes (in its signed directory record,
|
|
4
|
+
// see record.js) its address, a UDP port and the SHA-256 fingerprint of its
|
|
5
|
+
// self-signed DTLS certificate; that is everything the browser needs.
|
|
6
|
+
//
|
|
7
|
+
// The handshake needs no round trip because each side can write the other's
|
|
8
|
+
// half itself:
|
|
9
|
+
// - The browser makes an ordinary offer and leaves it alone (Chrome refuses
|
|
10
|
+
// rewritten ICE credentials). It then writes the relay's answer: the relay's
|
|
11
|
+
// address, its fingerprint, and ICE credentials of its own choosing that
|
|
12
|
+
// carry the browser's own ICE username and password inside them:
|
|
13
|
+
// freertc+direct+v1/<browser ufrag>/<browser pwd>
|
|
14
|
+
// - The browser's first ICE check reaches the relay's shared UDP port with
|
|
15
|
+
// that username. The relay reads the browser's credentials out of it,
|
|
16
|
+
// writes the browser's offer to match, answers with the same credentials,
|
|
17
|
+
// and the connection completes.
|
|
18
|
+
// DTLS checks the relay's certificate against the fingerprint the browser put
|
|
19
|
+
// in the answer, so only the relay that signed the record can answer. The relay
|
|
20
|
+
// cannot tell who the browser is; peers prove who they are with signed frames.
|
|
21
|
+
|
|
22
|
+
export const DIRECT_SCHEME = 'webrtc-direct:';
|
|
23
|
+
export const DIRECT_UFRAG_PREFIX = 'freertc+direct+v1/';
|
|
24
|
+
export const DIRECT_CHANNEL_LABEL = 'freertc-relay';
|
|
25
|
+
|
|
26
|
+
const ICE_CHARS = /^[A-Za-z0-9+/]+$/;
|
|
27
|
+
|
|
28
|
+
function normalizeFingerprintHex(value) {
|
|
29
|
+
const hex = String(value || '').replace(/:/g, '').toLowerCase();
|
|
30
|
+
return /^[0-9a-f]{64}$/.test(hex) ? hex : null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** "AB:CD:…" (SDP form) for a 64-digit hex fingerprint. */
|
|
34
|
+
export function fingerprintToSdp(hex) {
|
|
35
|
+
return normalizeFingerprintHex(hex).toUpperCase().match(/.{2}/g).join(':');
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function isIPv4(host) {
|
|
39
|
+
const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(host);
|
|
40
|
+
return Boolean(m) && m.slice(1).every((part) => Number(part) <= 255);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function isIPv6(host) {
|
|
44
|
+
return /^[0-9a-f:]+$/i.test(host) && host.includes(':') && host.length <= 39;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** webrtc-direct://<ip>:<port>/sha256/<hex>, with the IPv6 address in brackets. */
|
|
48
|
+
export function directRelayUrl({ host, port, fingerprint }) {
|
|
49
|
+
const hex = normalizeFingerprintHex(fingerprint);
|
|
50
|
+
const p = Number(port);
|
|
51
|
+
if (!hex) throw new TypeError('Direct relay fingerprint must be a SHA-256 fingerprint');
|
|
52
|
+
if (!Number.isInteger(p) || p < 1 || p > 65535) throw new TypeError('Direct relay port must be 1-65535');
|
|
53
|
+
if (isIPv4(host)) return `${DIRECT_SCHEME}//${host}:${p}/sha256/${hex}`;
|
|
54
|
+
if (isIPv6(host)) return `${DIRECT_SCHEME}//[${host.toLowerCase()}]:${p}/sha256/${hex}`;
|
|
55
|
+
throw new TypeError('Direct relay host must be an IP address');
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** { host, port, fingerprint (hex), family } for a direct relay URL, or null. */
|
|
59
|
+
export function parseDirectRelayUrl(value) {
|
|
60
|
+
const m = /^webrtc-direct:\/\/(?:\[([0-9a-f:]+)\]|(\d{1,3}(?:\.\d{1,3}){3})):(\d{1,5})\/sha256\/([0-9a-f]{64})$/i.exec(String(value || ''));
|
|
61
|
+
if (!m) return null;
|
|
62
|
+
const host = (m[1] || m[2]).toLowerCase();
|
|
63
|
+
const port = Number(m[3]);
|
|
64
|
+
if (port < 1 || port > 65535) return null;
|
|
65
|
+
if (m[2] && !isIPv4(host)) return null;
|
|
66
|
+
return { host, port, fingerprint: m[4].toLowerCase(), family: m[1] ? 6 : 4 };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** The relay's LAN addresses ("ip:port") in a direct relay URL's ?lan= (comma-separated). */
|
|
70
|
+
export function directRelayLan(url) {
|
|
71
|
+
const query = String(url || '').split('?')[1] || '';
|
|
72
|
+
const value = new URLSearchParams(query).get('lan') || '';
|
|
73
|
+
return value.split(',').map((part) => part.trim()).filter((part) => /^\d{1,3}(\.\d{1,3}){3}:\d{1,5}$/.test(part)).slice(0, 4);
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* The URL a client uses for a directory record:
|
|
78
|
+
* webrtc-direct://…[?lan=<ip:port,…>][&tunnel=<tunnel URL>].
|
|
79
|
+
*/
|
|
80
|
+
export function directoryRecordUrl(record) {
|
|
81
|
+
const params = new URLSearchParams();
|
|
82
|
+
if (Array.isArray(record?.lan) && record.lan.length) params.set('lan', record.lan.join(','));
|
|
83
|
+
if (record?.tunnel) params.set('tunnel', record.tunnel);
|
|
84
|
+
const query = params.toString();
|
|
85
|
+
return query ? `${record.direct}?${query}` : record.direct;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
export function isDirectRelayUrl(value) {
|
|
89
|
+
return parseDirectRelayUrl(value) !== null;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** The ICE username (and password) the relay answers with, carrying the browser's own. */
|
|
93
|
+
export function relayIceCredentialFor(browserUfrag, browserPwd) {
|
|
94
|
+
if (!ICE_CHARS.test(browserUfrag) || !ICE_CHARS.test(browserPwd)) {
|
|
95
|
+
throw new TypeError('ICE credentials must be ice-chars');
|
|
96
|
+
}
|
|
97
|
+
const value = `${DIRECT_UFRAG_PREFIX}${browserUfrag}/${browserPwd}`;
|
|
98
|
+
if (value.length > 256) throw new TypeError('ICE credentials are too long');
|
|
99
|
+
return value;
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
/** The browser's { ufrag, pwd } inside a relay ICE username, or null. */
|
|
103
|
+
export function parseRelayIceCredential(value) {
|
|
104
|
+
const text = String(value || '');
|
|
105
|
+
if (!text.startsWith(DIRECT_UFRAG_PREFIX) || text.length > 256) return null;
|
|
106
|
+
const parts = text.slice(DIRECT_UFRAG_PREFIX.length).split('/');
|
|
107
|
+
// The password may itself contain '/', so everything after the first part is the password.
|
|
108
|
+
const ufrag = parts.shift();
|
|
109
|
+
const pwd = parts.join('/');
|
|
110
|
+
if (!ufrag || !pwd || !ICE_CHARS.test(ufrag) || !ICE_CHARS.test(pwd)) return null;
|
|
111
|
+
if (ufrag.length < 4 || pwd.length < 22) return null;
|
|
112
|
+
return { ufrag, pwd };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** The relay's answer, written by the browser. lan: more "ip:port" addresses of the relay to try. */
|
|
116
|
+
export function directAnswerSdp({ host, port, fingerprint, family }, credential, lan = []) {
|
|
117
|
+
// A machine on the relay's own network seldom reaches the relay at its
|
|
118
|
+
// public address (few routers loop it back), so its LAN addresses are
|
|
119
|
+
// candidates too; ICE uses whichever answers.
|
|
120
|
+
const extra = (lan || []).map((endpoint, index) => {
|
|
121
|
+
const m = /^(\d{1,3}(?:\.\d{1,3}){3}):(\d{1,5})$/.exec(String(endpoint));
|
|
122
|
+
return m && family !== 6 ? `a=candidate:${index + 2} 1 UDP 2130706430 ${m[1]} ${m[2]} typ host` : null;
|
|
123
|
+
}).filter(Boolean);
|
|
124
|
+
const ipVersion = family === 6 ? 'IP6' : 'IP4';
|
|
125
|
+
return [
|
|
126
|
+
'v=0',
|
|
127
|
+
`o=- 0 0 IN ${ipVersion} ${host}`,
|
|
128
|
+
's=-',
|
|
129
|
+
't=0 0',
|
|
130
|
+
'a=ice-lite',
|
|
131
|
+
'a=group:BUNDLE 0',
|
|
132
|
+
`m=application ${port} UDP/DTLS/SCTP webrtc-datachannel`,
|
|
133
|
+
`c=IN ${ipVersion} ${host}`,
|
|
134
|
+
'a=mid:0',
|
|
135
|
+
`a=ice-ufrag:${credential}`,
|
|
136
|
+
`a=ice-pwd:${credential}`,
|
|
137
|
+
`a=fingerprint:sha-256 ${fingerprintToSdp(fingerprint)}`,
|
|
138
|
+
'a=setup:passive',
|
|
139
|
+
'a=sctp-port:5000',
|
|
140
|
+
'a=max-message-size:262144',
|
|
141
|
+
`a=candidate:1 1 UDP 2130706431 ${host} ${port} typ host`,
|
|
142
|
+
...extra,
|
|
143
|
+
'a=end-of-candidates',
|
|
144
|
+
'',
|
|
145
|
+
].join('\r\n');
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
/** The browser's offer, written by the relay from the credentials in its ICE username. */
|
|
149
|
+
export function directBrowserOfferSdp({ ufrag, pwd }) {
|
|
150
|
+
return [
|
|
151
|
+
'v=0',
|
|
152
|
+
'o=- 0 0 IN IP4 0.0.0.0',
|
|
153
|
+
's=-',
|
|
154
|
+
't=0 0',
|
|
155
|
+
'a=group:BUNDLE 0',
|
|
156
|
+
'm=application 9 UDP/DTLS/SCTP webrtc-datachannel',
|
|
157
|
+
'c=IN IP4 0.0.0.0',
|
|
158
|
+
'a=mid:0',
|
|
159
|
+
`a=ice-ufrag:${ufrag}`,
|
|
160
|
+
`a=ice-pwd:${pwd}`,
|
|
161
|
+
// The browser's certificate is not known in advance; the relay does not
|
|
162
|
+
// authenticate browsers (it is started with fingerprint checks off), so
|
|
163
|
+
// this placeholder is never compared.
|
|
164
|
+
`a=fingerprint:sha-256 ${Array(32).fill('00').join(':')}`,
|
|
165
|
+
// The browser is the DTLS client: the answer it wrote says passive.
|
|
166
|
+
'a=setup:active',
|
|
167
|
+
'a=sctp-port:5000',
|
|
168
|
+
'a=max-message-size:262144',
|
|
169
|
+
'',
|
|
170
|
+
].join('\r\n');
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* A directory record's TLS name: its `name` when that is a wss:// address of
|
|
175
|
+
* a DNS name (wss://<name>:<port>/ws), else null. Records carry it in `name`,
|
|
176
|
+
* which clients that do not know it simply show as a label.
|
|
177
|
+
*/
|
|
178
|
+
export function recordWssUrl(record) {
|
|
179
|
+
try {
|
|
180
|
+
const url = new URL(String(record?.name ?? ''));
|
|
181
|
+
if (url.protocol !== 'wss:' || url.pathname !== '/ws' || url.search || url.hash) return null;
|
|
182
|
+
if (/^[0-9.]+$/.test(url.hostname) || url.hostname.includes(':') || !url.hostname.includes('.')) return null;
|
|
183
|
+
return url.toString();
|
|
184
|
+
} catch {
|
|
185
|
+
return null;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
// Open a data channel straight to a direct relay (see common.js) with the
|
|
2
|
+
// standard WebRTC API, in a browser or with any W3C-compatible RTCPeerConnection.
|
|
3
|
+
// The browser's own offer is used exactly as created; only the relay's answer
|
|
4
|
+
// is written here.
|
|
5
|
+
|
|
6
|
+
import { DIRECT_CHANNEL_LABEL, directAnswerSdp, directRelayLan, parseDirectRelayUrl, relayIceCredentialFor } from './common.js';
|
|
7
|
+
|
|
8
|
+
export const DIRECT_OPEN_TIMEOUT_MS = 5_000;
|
|
9
|
+
|
|
10
|
+
/** Resolves { pc, channel } once the channel is open; rejects if it does not open in time. */
|
|
11
|
+
export async function directRelayChannel(url, {
|
|
12
|
+
PeerConnection = globalThis.RTCPeerConnection,
|
|
13
|
+
timeoutMs = DIRECT_OPEN_TIMEOUT_MS,
|
|
14
|
+
label = DIRECT_CHANNEL_LABEL,
|
|
15
|
+
lan = directRelayLan(url),
|
|
16
|
+
} = {}) {
|
|
17
|
+
const target = parseDirectRelayUrl(String(url).split('?')[0]);
|
|
18
|
+
if (!target) throw new TypeError(`not a direct relay URL: ${url}`);
|
|
19
|
+
if (typeof PeerConnection !== 'function') throw new Error('WebRTC is not available here');
|
|
20
|
+
|
|
21
|
+
const pc = new PeerConnection({ iceServers: [] });
|
|
22
|
+
const channel = pc.createDataChannel(label);
|
|
23
|
+
let timer = null;
|
|
24
|
+
try {
|
|
25
|
+
const opened = new Promise((resolve, reject) => {
|
|
26
|
+
timer = setTimeout(() => reject(new Error('direct channel did not open')), timeoutMs);
|
|
27
|
+
channel.onopen = () => { clearTimeout(timer); resolve(); };
|
|
28
|
+
pc.onconnectionstatechange = () => {
|
|
29
|
+
if (pc.connectionState === 'failed') { clearTimeout(timer); reject(new Error('direct connection failed')); }
|
|
30
|
+
};
|
|
31
|
+
});
|
|
32
|
+
opened.catch(() => {});
|
|
33
|
+
await pc.setLocalDescription(await pc.createOffer());
|
|
34
|
+
const sdp = pc.localDescription.sdp;
|
|
35
|
+
const ufrag = /a=ice-ufrag:(\S+)/.exec(sdp)?.[1];
|
|
36
|
+
const pwd = /a=ice-pwd:(\S+)/.exec(sdp)?.[1];
|
|
37
|
+
if (!ufrag || !pwd) throw new Error('offer has no ICE credentials');
|
|
38
|
+
await pc.setRemoteDescription({ type: 'answer', sdp: directAnswerSdp(target, relayIceCredentialFor(ufrag, pwd), lan) });
|
|
39
|
+
await opened;
|
|
40
|
+
return { pc, channel };
|
|
41
|
+
} catch (error) {
|
|
42
|
+
clearTimeout(timer);
|
|
43
|
+
try { channel.close(); } catch {}
|
|
44
|
+
try { pc.close(); } catch {}
|
|
45
|
+
throw error;
|
|
46
|
+
}
|
|
47
|
+
}
|
|
@@ -0,0 +1,230 @@
|
|
|
1
|
+
// The relay directory, kept in DNS by a cloud relay that holds a DNS token.
|
|
2
|
+
//
|
|
3
|
+
// POST /api/v1/directory body: a signed directory record (record.js)
|
|
4
|
+
// DELETE /api/v1/directory body: a signed withdrawal
|
|
5
|
+
//
|
|
6
|
+
// Only the Worker holds the token (env.DIRECTORY_DNS_TOKEN, a Cloudflare API
|
|
7
|
+
// token limited to editing DNS on one zone, env.DIRECTORY_ZONE_ID). Each relay
|
|
8
|
+
// has one TXT record at env.DIRECTORY_RECORD_NAME (for example
|
|
9
|
+
// _relays.peer.ooo), found by its comment "freertc:<node id>"; a relay can
|
|
10
|
+
// write and remove only its own. The record's direct address must be the
|
|
11
|
+
// address the request came from, so nobody can list someone else's machine
|
|
12
|
+
// and send browsers' connection attempts to it.
|
|
13
|
+
//
|
|
14
|
+
// Off unless all three are set.
|
|
15
|
+
|
|
16
|
+
import { decodeDirectoryTxt, encodeDirectoryTxt, verifyDirectoryRecord, verifyWithdrawal } from './record.js';
|
|
17
|
+
import { verifyDirectoryPq } from '../relay-identity.js';
|
|
18
|
+
import { parseDirectRelayUrl, recordWssUrl } from './common.js';
|
|
19
|
+
|
|
20
|
+
export const DIRECTORY_PATH = '/api/v1/directory';
|
|
21
|
+
const CLOUDFLARE_API = 'https://api.cloudflare.com/client/v4';
|
|
22
|
+
const MIN_PUBLISH_INTERVAL_MS = 60_000;
|
|
23
|
+
const REFRESH_BEFORE_EXPIRY_MS = 60 * 60_000;
|
|
24
|
+
const PROBE_TIMEOUT_MS = 4_000;
|
|
25
|
+
const DNS_TTL_SECONDS = 300;
|
|
26
|
+
const MAX_CLEANUP_PER_CALL = 5;
|
|
27
|
+
const DOH_URL = 'https://cloudflare-dns.com/dns-query';
|
|
28
|
+
|
|
29
|
+
// A record may carry a TLS name (name = wss://<host>:<port>/ws). It is
|
|
30
|
+
// listed only if DNS for <host> points at the address the request came from,
|
|
31
|
+
// so a relay cannot send browsers to a name that is not its own.
|
|
32
|
+
async function nameIsOurs(record, from, fetchImpl) {
|
|
33
|
+
if (!String(record.name ?? '').startsWith('wss:')) return true;
|
|
34
|
+
const wss = recordWssUrl(record);
|
|
35
|
+
if (!wss) return false;
|
|
36
|
+
const host = new URL(wss).hostname;
|
|
37
|
+
const type = String(from).includes(':') ? 'AAAA' : 'A';
|
|
38
|
+
try {
|
|
39
|
+
const response = await fetchImpl(`${DOH_URL}?name=${encodeURIComponent(host)}&type=${type}`, { headers: { accept: 'application/dns-json' }, signal: AbortSignal.timeout(PROBE_TIMEOUT_MS) });
|
|
40
|
+
const answer = await response.json();
|
|
41
|
+
return (answer?.Answer || []).some((a) => sameIp(a.data, from));
|
|
42
|
+
} catch {
|
|
43
|
+
return false;
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function directoryEnabled(env) {
|
|
48
|
+
return Boolean(env?.DIRECTORY_DNS_TOKEN && env?.DIRECTORY_ZONE_ID && env?.DIRECTORY_RECORD_NAME);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function json(body, status = 200) {
|
|
52
|
+
return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function commentFor(nodeId) {
|
|
56
|
+
return `freertc:${nodeId}`;
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
function sameIp(a, b) {
|
|
60
|
+
const norm = (ip) => String(ip || '').toLowerCase().replace(/^::ffff:/, '');
|
|
61
|
+
return norm(a) !== '' && norm(a) === norm(b);
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
async function cloudflare(env, method, path, body, fetchImpl) {
|
|
65
|
+
const response = await fetchImpl(`${CLOUDFLARE_API}/zones/${env.DIRECTORY_ZONE_ID}${path}`, {
|
|
66
|
+
method,
|
|
67
|
+
headers: { Authorization: `Bearer ${env.DIRECTORY_DNS_TOKEN}`, 'Content-Type': 'application/json' },
|
|
68
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
69
|
+
});
|
|
70
|
+
const data = await response.json().catch(() => null);
|
|
71
|
+
if (!response.ok || data?.success === false) {
|
|
72
|
+
const why = data?.errors?.map((error) => error.message).join('; ') || `status ${response.status}`;
|
|
73
|
+
throw new Error(`DNS API: ${why}`);
|
|
74
|
+
}
|
|
75
|
+
return data?.result;
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
async function listDirectory(env, fetchImpl, extra = '') {
|
|
79
|
+
const name = encodeURIComponent(env.DIRECTORY_RECORD_NAME);
|
|
80
|
+
return (await cloudflare(env, 'GET', `/dns_records?type=TXT&name=${name}&per_page=100${extra}`, undefined, fetchImpl)) || [];
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// Is the relay behind this entry still there? Only entries with an open ws
|
|
84
|
+
// port can be checked from here: its /health must answer, and with this
|
|
85
|
+
// entry's node id when it reports one. A relay that stopped without
|
|
86
|
+
// withdrawing (crash, lost network, the cloud was down when it tried) fails
|
|
87
|
+
// this, and so does an old entry whose forwarded port now reaches a
|
|
88
|
+
// different relay on the same network.
|
|
89
|
+
async function stillThere(record, fetchImpl) {
|
|
90
|
+
if (!record.ws) return true;
|
|
91
|
+
const url = String(record.ws).replace(/^ws:/, 'http:').replace(/\/ws$/, '/health');
|
|
92
|
+
try {
|
|
93
|
+
const response = await fetchImpl(url, { signal: AbortSignal.timeout(PROBE_TIMEOUT_MS) });
|
|
94
|
+
if (!response.ok) return false;
|
|
95
|
+
const health = await response.json().catch(() => null);
|
|
96
|
+
return !health?.node_id || health.node_id === record.node_id;
|
|
97
|
+
} catch {
|
|
98
|
+
return false;
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
// Drop entries whose record has expired, no longer verifies, or whose relay
|
|
103
|
+
// is gone. Bounded per call; the checks run side by side.
|
|
104
|
+
async function cleanup(env, fetchImpl, entries, now) {
|
|
105
|
+
const ours = entries.filter((entry) => String(entry.comment || '').startsWith('freertc:')).slice(0, 4 * MAX_CLEANUP_PER_CALL);
|
|
106
|
+
const verdicts = await Promise.all(ours.map(async (entry) => {
|
|
107
|
+
const record = decodeDirectoryTxt(entry.content);
|
|
108
|
+
if (!record || !await verifyDirectoryRecord(record, { now })) return entry;
|
|
109
|
+
return await stillThere(record, fetchImpl) ? null : entry;
|
|
110
|
+
}));
|
|
111
|
+
let removed = 0;
|
|
112
|
+
for (const entry of verdicts.filter(Boolean).slice(0, MAX_CLEANUP_PER_CALL)) {
|
|
113
|
+
await cloudflare(env, 'DELETE', `/dns_records/${entry.id}`, undefined, fetchImpl).catch(() => {});
|
|
114
|
+
removed += 1;
|
|
115
|
+
}
|
|
116
|
+
return removed;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
// Post-quantum keys (local relays, src/node/relay-pq.js): a relay may send its
|
|
120
|
+
// ML-DSA-65 public key and a hybrid signature over its signed record (or
|
|
121
|
+
// withdrawal) in two headers. The first key a node id shows is pinned in D1;
|
|
122
|
+
// from then on that node id is listed or withdrawn only with that same key, so
|
|
123
|
+
// forging the relay's P-256 signature alone (a quantum computer) is no longer
|
|
124
|
+
// enough. Pinned on first sight: a relay is protected from the first time it
|
|
125
|
+
// lists itself with a key, not before. The TXT record itself is unchanged, so every client reads it as
|
|
126
|
+
// before; only this directory writes it.
|
|
127
|
+
export const PQ_KEY_HEADER = 'X-Freertc-Pq-Key';
|
|
128
|
+
export const PQ_SIGNATURE_HEADER = 'X-Freertc-Pq-Signature';
|
|
129
|
+
const PQ_PIN_TABLE = 'psp_directory_pq';
|
|
130
|
+
let warnedNoPins = false;
|
|
131
|
+
|
|
132
|
+
async function sha256Hex(text) {
|
|
133
|
+
const digest = new Uint8Array(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text)));
|
|
134
|
+
return Array.from(digest, (b) => b.toString(16).padStart(2, '0')).join('');
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
async function pinTable(db) {
|
|
138
|
+
await db.prepare(`CREATE TABLE IF NOT EXISTS ${PQ_PIN_TABLE} (node_id TEXT PRIMARY KEY, key_sha256 TEXT NOT NULL, pinned_at_ms INTEGER NOT NULL)`).run();
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** null when the request may go ahead, or why it may not. */
|
|
142
|
+
async function postQuantumCheck(request, env, signed, now) {
|
|
143
|
+
const key = request.headers.get(PQ_KEY_HEADER);
|
|
144
|
+
const signature = request.headers.get(PQ_SIGNATURE_HEADER);
|
|
145
|
+
const db = env.DB || null;
|
|
146
|
+
if (db) await pinTable(db);
|
|
147
|
+
else if (!warnedNoPins) {
|
|
148
|
+
warnedNoPins = true;
|
|
149
|
+
console.warn('[directory] no database (env.DB): relays\' post-quantum keys are checked but not pinned');
|
|
150
|
+
}
|
|
151
|
+
const pinned = db
|
|
152
|
+
? (await db.prepare(`SELECT key_sha256 FROM ${PQ_PIN_TABLE} WHERE node_id = ?1`).bind(signed.node_id).first())?.key_sha256 ?? null
|
|
153
|
+
: null;
|
|
154
|
+
if (!key && !signature) {
|
|
155
|
+
return pinned ? 'this relay was listed with a post-quantum key: prove it' : null;
|
|
156
|
+
}
|
|
157
|
+
if (!await verifyDirectoryPq(signed, key, signature)) return 'bad post-quantum signature';
|
|
158
|
+
const hash = await sha256Hex(key);
|
|
159
|
+
if (pinned && pinned !== hash) return 'not the post-quantum key this relay was listed with';
|
|
160
|
+
if (!pinned && db) {
|
|
161
|
+
await db.prepare(`INSERT OR IGNORE INTO ${PQ_PIN_TABLE} (node_id, key_sha256, pinned_at_ms) VALUES (?1, ?2, ?3)`).bind(signed.node_id, hash, now).run();
|
|
162
|
+
}
|
|
163
|
+
return null;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
export async function handleDirectoryRequest(request, env, { fetchImpl = globalThis.fetch, now = Date.now() } = {}) {
|
|
167
|
+
if (!directoryEnabled(env)) return json({ ok: false, error: 'no directory on this relay' }, 404);
|
|
168
|
+
if (request.method !== 'POST' && request.method !== 'DELETE') return json({ ok: false, error: 'method not allowed' }, 405);
|
|
169
|
+
const text = await request.text();
|
|
170
|
+
if (text.length > 8 * 1024) return json({ ok: false, error: 'too large' }, 413);
|
|
171
|
+
let body;
|
|
172
|
+
try { body = JSON.parse(text); } catch { return json({ ok: false, error: 'bad JSON' }, 400); }
|
|
173
|
+
|
|
174
|
+
try {
|
|
175
|
+
if (request.method === 'DELETE') {
|
|
176
|
+
if (!await verifyWithdrawal(body, { now })) return json({ ok: false, error: 'bad withdrawal' }, 400);
|
|
177
|
+
const refused = await postQuantumCheck(request, env, body, now);
|
|
178
|
+
if (refused) return json({ ok: false, error: refused }, 403);
|
|
179
|
+
const mine = await listDirectory(env, fetchImpl, `&comment.exact=${encodeURIComponent(commentFor(body.node_id))}`);
|
|
180
|
+
for (const entry of mine) await cloudflare(env, 'DELETE', `/dns_records/${entry.id}`, undefined, fetchImpl);
|
|
181
|
+
return json({ ok: true, removed: mine.length });
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
if (!await verifyDirectoryRecord(body, { now })) return json({ ok: false, error: 'bad record' }, 400);
|
|
185
|
+
const direct = parseDirectRelayUrl(body.direct);
|
|
186
|
+
const from = request.headers.get('CF-Connecting-IP');
|
|
187
|
+
if (!sameIp(direct.host, from)) {
|
|
188
|
+
return json({ ok: false, error: 'the direct address must be the address this request came from', seen: from || null }, 400);
|
|
189
|
+
}
|
|
190
|
+
if (!await nameIsOurs(body, from, fetchImpl)) {
|
|
191
|
+
return json({ ok: false, error: 'the record\'s wss name must point at the address this request came from', seen: from || null }, 400);
|
|
192
|
+
}
|
|
193
|
+
const refused = await postQuantumCheck(request, env, body, now);
|
|
194
|
+
if (refused) return json({ ok: false, error: refused }, 403);
|
|
195
|
+
|
|
196
|
+
const all = await listDirectory(env, fetchImpl);
|
|
197
|
+
const mine = all.filter((entry) => entry.comment === commentFor(body.node_id));
|
|
198
|
+
const current = mine[0] ? decodeDirectoryTxt(mine[0].content) : null;
|
|
199
|
+
const sameList = (a, b) => JSON.stringify(a ?? null) === JSON.stringify(b ?? null);
|
|
200
|
+
const changed = !current || current.direct !== body.direct || current.tunnel !== body.tunnel || current.name !== body.name
|
|
201
|
+
|| !sameList(current.lan, body.lan) || (current.ws ?? null) !== (body.ws ?? null);
|
|
202
|
+
// An unchanged entry is rewritten only as it nears expiry, so a relay that
|
|
203
|
+
// republishes on a timer costs no DNS writes.
|
|
204
|
+
const others = all.filter((entry) => entry.comment !== commentFor(body.node_id));
|
|
205
|
+
if (!changed && Number(current.expires_at_ms) - now > REFRESH_BEFORE_EXPIRY_MS) {
|
|
206
|
+
// Republishes are the directory's heartbeat: each one also clears out
|
|
207
|
+
// relays that went away.
|
|
208
|
+
const removed = await cleanup(env, fetchImpl, others, now);
|
|
209
|
+
return json({ ok: true, published: false, reason: 'unchanged', cleaned: removed });
|
|
210
|
+
}
|
|
211
|
+
if (changed && current && now - Number(current.issued_at_ms) < MIN_PUBLISH_INTERVAL_MS) {
|
|
212
|
+
return json({ ok: false, error: 'changed too recently; try again in a few minutes' }, 429);
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
const entry = {
|
|
216
|
+
type: 'TXT',
|
|
217
|
+
name: env.DIRECTORY_RECORD_NAME,
|
|
218
|
+
content: encodeDirectoryTxt(body),
|
|
219
|
+
ttl: DNS_TTL_SECONDS,
|
|
220
|
+
comment: commentFor(body.node_id),
|
|
221
|
+
};
|
|
222
|
+
if (mine[0]) await cloudflare(env, 'PUT', `/dns_records/${mine[0].id}`, entry, fetchImpl);
|
|
223
|
+
else await cloudflare(env, 'POST', '/dns_records', entry, fetchImpl);
|
|
224
|
+
for (const extra of mine.slice(1)) await cloudflare(env, 'DELETE', `/dns_records/${extra.id}`, undefined, fetchImpl).catch(() => {});
|
|
225
|
+
const removed = await cleanup(env, fetchImpl, others, now);
|
|
226
|
+
return json({ ok: true, published: true, cleaned: removed });
|
|
227
|
+
} catch (error) {
|
|
228
|
+
return json({ ok: false, error: String(error?.message || error).slice(0, 200) }, 502);
|
|
229
|
+
}
|
|
230
|
+
}
|