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,201 @@
|
|
|
1
|
+
// Accept direct browser connections (see common.js) on one UDP port and hand
|
|
2
|
+
// each opened data channel to the relay as a socket with the WebSocket surface
|
|
3
|
+
// node-relay's acceptSocket expects (send, close, readyState, on message/close/error).
|
|
4
|
+
//
|
|
5
|
+
// Needs node-datachannel 0.33 or later (an optional dependency): its ICE UDP
|
|
6
|
+
// mux reports the first check of an unknown connection together with the ICE
|
|
7
|
+
// username it was sent to, which is where the browser put its credentials.
|
|
8
|
+
|
|
9
|
+
import { DIRECT_CHANNEL_LABEL, directBrowserOfferSdp, parseRelayIceCredential } from './common.js';
|
|
10
|
+
|
|
11
|
+
const OPEN_TIMEOUT_MS = 20_000;
|
|
12
|
+
const DEFAULT_MAX_PENDING = 64;
|
|
13
|
+
const DEFAULT_MAX_OPEN = 2_000;
|
|
14
|
+
|
|
15
|
+
export async function loadNodeDataChannel() {
|
|
16
|
+
try {
|
|
17
|
+
const mod = await import('node-datachannel');
|
|
18
|
+
const ndc = mod.default ?? mod;
|
|
19
|
+
if (typeof ndc.IceUdpMuxListener !== 'function') return null;
|
|
20
|
+
return ndc;
|
|
21
|
+
} catch {
|
|
22
|
+
return null;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** True when this machine can accept direct connections. */
|
|
27
|
+
export async function directListenerAvailable() {
|
|
28
|
+
return Boolean(await loadNodeDataChannel());
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
class DirectChannelSocket {
|
|
32
|
+
constructor(channel, pc) {
|
|
33
|
+
this.channel = channel;
|
|
34
|
+
this.peerConnection = pc;
|
|
35
|
+
this.OPEN = 1;
|
|
36
|
+
this.CLOSED = 3;
|
|
37
|
+
this.closed = false;
|
|
38
|
+
this.listeners = { message: [], close: [], error: [] };
|
|
39
|
+
this.meta = { direct: true };
|
|
40
|
+
const emit = (event, value) => { for (const listener of this.listeners[event]) listener(value); };
|
|
41
|
+
channel.onMessage((message) => emit('message', typeof message === 'string' ? message : Buffer.from(message)));
|
|
42
|
+
channel.onClosed(() => this.finish(emit));
|
|
43
|
+
channel.onError((error) => emit('error', new Error(String(error))));
|
|
44
|
+
this.emit = emit;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
finish(emit = this.emit) {
|
|
48
|
+
if (this.closed) return;
|
|
49
|
+
this.closed = true;
|
|
50
|
+
try { this.peerConnection.close(); } catch {}
|
|
51
|
+
emit('close');
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
get readyState() {
|
|
55
|
+
return !this.closed && this.channel.isOpen() ? this.OPEN : this.CLOSED;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
send(data) {
|
|
59
|
+
if (this.readyState !== this.OPEN) throw new Error('Direct channel is not open');
|
|
60
|
+
this.channel.sendMessage(typeof data === 'string' ? data : String(data));
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
on(event, listener) {
|
|
64
|
+
this.listeners[event]?.push(listener);
|
|
65
|
+
return this;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
close() {
|
|
69
|
+
try { this.channel.close(); } catch {}
|
|
70
|
+
this.finish();
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/**
|
|
75
|
+
* Listen for direct connections on UDP `port`. Returns { close, stats } or null
|
|
76
|
+
* when node-datachannel (0.33+) is not installed.
|
|
77
|
+
*
|
|
78
|
+
* onSocket(socket, { host, port }) a direct data channel opened
|
|
79
|
+
*/
|
|
80
|
+
export async function startDirectListener({
|
|
81
|
+
port,
|
|
82
|
+
bindAddress = '0.0.0.0',
|
|
83
|
+
certFile,
|
|
84
|
+
keyFile,
|
|
85
|
+
onSocket,
|
|
86
|
+
log = () => {},
|
|
87
|
+
maxPending = DEFAULT_MAX_PENDING,
|
|
88
|
+
maxOpen = DEFAULT_MAX_OPEN,
|
|
89
|
+
}) {
|
|
90
|
+
const ndc = await loadNodeDataChannel();
|
|
91
|
+
if (!ndc) return null;
|
|
92
|
+
|
|
93
|
+
let listener;
|
|
94
|
+
try {
|
|
95
|
+
listener = new ndc.IceUdpMuxListener(port, bindAddress);
|
|
96
|
+
} catch (error) {
|
|
97
|
+
// Most often the port is taken (another relay on this machine). The relay
|
|
98
|
+
// keeps running; only direct connections are off.
|
|
99
|
+
log(`direct connections: off (cannot listen on udp ${bindAddress}:${port}: ${error?.message || error}; set FREERTC_DIRECT_PORT to a free port)`);
|
|
100
|
+
return null;
|
|
101
|
+
}
|
|
102
|
+
// The native listener is released (and stops listening) when nothing on the
|
|
103
|
+
// JavaScript side references it; keep it reachable for as long as we listen.
|
|
104
|
+
const keepAlive = { listener };
|
|
105
|
+
globalThis.__freertcDirectListeners ??= new Set();
|
|
106
|
+
globalThis.__freertcDirectListeners.add(keepAlive);
|
|
107
|
+
|
|
108
|
+
const pending = new Map(); // relay ICE username -> PeerConnection
|
|
109
|
+
let open = 0;
|
|
110
|
+
let accepted = 0;
|
|
111
|
+
let refused = 0;
|
|
112
|
+
let sequence = 0;
|
|
113
|
+
|
|
114
|
+
listener.onUnhandledStunRequest((request) => {
|
|
115
|
+
const credential = request.localUfrag;
|
|
116
|
+
if (!credential || pending.has(credential)) return;
|
|
117
|
+
const browser = parseRelayIceCredential(credential);
|
|
118
|
+
if (!browser || browser.ufrag !== request.ufrag) return;
|
|
119
|
+
if (pending.size >= maxPending || open >= maxOpen) {
|
|
120
|
+
refused += 1;
|
|
121
|
+
return;
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
let pc;
|
|
125
|
+
try {
|
|
126
|
+
pc = new ndc.PeerConnection(`direct-${(sequence += 1)}`, {
|
|
127
|
+
iceServers: [],
|
|
128
|
+
enableIceUdpMux: true,
|
|
129
|
+
bindAddress,
|
|
130
|
+
portRangeBegin: port,
|
|
131
|
+
portRangeEnd: port,
|
|
132
|
+
certificatePemFile: certFile,
|
|
133
|
+
keyPemFile: keyFile,
|
|
134
|
+
disableFingerprintVerification: true,
|
|
135
|
+
disableAutoNegotiation: true,
|
|
136
|
+
});
|
|
137
|
+
} catch (error) {
|
|
138
|
+
log(`direct connection from ${request.host}:${request.port} failed to start: ${error?.message || error}`);
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
pending.set(credential, pc);
|
|
142
|
+
const forget = () => { if (pending.get(credential) === pc) pending.delete(credential); };
|
|
143
|
+
const timer = setTimeout(() => {
|
|
144
|
+
if (!pending.has(credential)) return;
|
|
145
|
+
forget();
|
|
146
|
+
try { pc.close(); } catch {}
|
|
147
|
+
}, OPEN_TIMEOUT_MS);
|
|
148
|
+
|
|
149
|
+
let socket = null;
|
|
150
|
+
pc.onStateChange((state) => {
|
|
151
|
+
// 'disconnected' too: a browser that vanished (tab killed, laptop asleep)
|
|
152
|
+
// closes nothing, and its socket would otherwise stay counted.
|
|
153
|
+
if (state === 'failed' || state === 'closed' || state === 'disconnected') {
|
|
154
|
+
clearTimeout(timer);
|
|
155
|
+
forget();
|
|
156
|
+
socket?.finish();
|
|
157
|
+
}
|
|
158
|
+
});
|
|
159
|
+
pc.onDataChannel((channel) => {
|
|
160
|
+
clearTimeout(timer);
|
|
161
|
+
forget();
|
|
162
|
+
if (channel.getLabel() !== DIRECT_CHANNEL_LABEL) {
|
|
163
|
+
try { channel.close(); } catch {}
|
|
164
|
+
try { pc.close(); } catch {}
|
|
165
|
+
return;
|
|
166
|
+
}
|
|
167
|
+
socket = new DirectChannelSocket(channel, pc);
|
|
168
|
+
open += 1;
|
|
169
|
+
accepted += 1;
|
|
170
|
+
socket.on('close', () => { open -= 1; });
|
|
171
|
+
try {
|
|
172
|
+
onSocket(socket, { host: request.host, port: request.port });
|
|
173
|
+
} catch (error) {
|
|
174
|
+
log(`direct socket handler failed: ${error?.message || error}`);
|
|
175
|
+
socket.close();
|
|
176
|
+
}
|
|
177
|
+
});
|
|
178
|
+
|
|
179
|
+
try {
|
|
180
|
+
pc.setRemoteDescription(directBrowserOfferSdp(browser), 'offer');
|
|
181
|
+
pc.setLocalDescription('answer', { iceUfrag: credential, icePwd: credential });
|
|
182
|
+
pc.addRemoteCandidate(`candidate:1 1 UDP 2130706431 ${request.host} ${request.port} typ host`, '0');
|
|
183
|
+
} catch (error) {
|
|
184
|
+
clearTimeout(timer);
|
|
185
|
+
forget();
|
|
186
|
+
try { pc.close(); } catch {}
|
|
187
|
+
log(`direct connection from ${request.host}:${request.port} refused: ${error?.message || error}`);
|
|
188
|
+
}
|
|
189
|
+
});
|
|
190
|
+
|
|
191
|
+
log(`accepting direct connections on udp ${bindAddress}:${port}`);
|
|
192
|
+
return {
|
|
193
|
+
stats: () => ({ pending: pending.size, open, accepted, refused }),
|
|
194
|
+
close() {
|
|
195
|
+
for (const pc of pending.values()) { try { pc.close(); } catch {} }
|
|
196
|
+
pending.clear();
|
|
197
|
+
try { listener.stop?.(); } catch {}
|
|
198
|
+
globalThis.__freertcDirectListeners?.delete(keepAlive);
|
|
199
|
+
},
|
|
200
|
+
};
|
|
201
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
// Find direct relays with one DNS-over-HTTPS lookup. The answer comes from a
|
|
2
|
+
// public resolver (Cloudflare's by default), not from any relay, so looking up
|
|
3
|
+
// relays costs the relays nothing, and resolvers cache it.
|
|
4
|
+
|
|
5
|
+
import { decodeDirectoryTxt, rankDirectoryRecords, verifyDirectoryRecord } from './record.js';
|
|
6
|
+
|
|
7
|
+
export const DEFAULT_DIRECTORY_NAME = '_relays.peer.ooo';
|
|
8
|
+
export const DEFAULT_DOH_URLS = ['https://cloudflare-dns.com/dns-query', 'https://dns.google/resolve'];
|
|
9
|
+
const LOOKUP_TIMEOUT_MS = 3_000;
|
|
10
|
+
const CACHE_MS = 60_000;
|
|
11
|
+
|
|
12
|
+
const cache = new Map(); // name -> { at, records }
|
|
13
|
+
|
|
14
|
+
async function queryTxt(dohUrl, name, fetchImpl) {
|
|
15
|
+
const url = `${dohUrl}?name=${encodeURIComponent(name)}&type=TXT`;
|
|
16
|
+
const response = await fetchImpl(url, {
|
|
17
|
+
headers: { accept: 'application/dns-json' },
|
|
18
|
+
signal: AbortSignal.timeout(LOOKUP_TIMEOUT_MS),
|
|
19
|
+
});
|
|
20
|
+
if (!response.ok) throw new Error(`DNS-over-HTTPS answered ${response.status}`);
|
|
21
|
+
const body = await response.json();
|
|
22
|
+
return (body?.Answer || []).filter((answer) => answer?.type === 16).map((answer) => String(answer.data));
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* The verified, unexpired directory records published under `name`, closest
|
|
27
|
+
* to the room first (when network and room are given). Asks every resolver at
|
|
28
|
+
* once and merges what they return; an empty list when none answers.
|
|
29
|
+
*/
|
|
30
|
+
export async function lookupDirectRelays({
|
|
31
|
+
name = DEFAULT_DIRECTORY_NAME,
|
|
32
|
+
network,
|
|
33
|
+
room,
|
|
34
|
+
dohUrls = DEFAULT_DOH_URLS,
|
|
35
|
+
fetchImpl = globalThis.fetch,
|
|
36
|
+
now = Date.now(),
|
|
37
|
+
useCache = true,
|
|
38
|
+
} = {}) {
|
|
39
|
+
let records = null;
|
|
40
|
+
const cached = useCache ? cache.get(name) : null;
|
|
41
|
+
if (cached && now - cached.at < CACHE_MS) {
|
|
42
|
+
records = cached.records;
|
|
43
|
+
} else {
|
|
44
|
+
// Every resolver at once, and their answers merged: one resolver can hold
|
|
45
|
+
// an old answer (an empty one cached while no relay was listed, for as
|
|
46
|
+
// long as the zone's negative-cache time) and would hide a relay that
|
|
47
|
+
// another already returns.
|
|
48
|
+
const answers = await Promise.allSettled(dohUrls.map((dohUrl) => queryTxt(dohUrl, name, fetchImpl)));
|
|
49
|
+
const byNode = new Map();
|
|
50
|
+
let answered = false;
|
|
51
|
+
for (const answer of answers) {
|
|
52
|
+
if (answer.status !== 'fulfilled') continue;
|
|
53
|
+
answered = true;
|
|
54
|
+
for (const value of answer.value) {
|
|
55
|
+
const record = decodeDirectoryTxt(value);
|
|
56
|
+
if (!record || !await verifyDirectoryRecord(record, { now })) continue;
|
|
57
|
+
const known = byNode.get(record.node_id);
|
|
58
|
+
if (!known || Number(record.issued_at_ms) > Number(known.issued_at_ms)) byNode.set(record.node_id, record);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
if (answered) {
|
|
62
|
+
records = [...byNode.values()];
|
|
63
|
+
cache.set(name, { at: now, records });
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
if (!records) return [];
|
|
67
|
+
// Newest first: an older entry is likelier to be a relay that went away.
|
|
68
|
+
const live = records.filter((record) => Number(record.expires_at_ms) > now)
|
|
69
|
+
.sort((a, b) => Number(b.issued_at_ms) - Number(a.issued_at_ms));
|
|
70
|
+
return network !== undefined && room !== undefined ? rankDirectoryRecords(live, network, room) : live;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
export function clearDirectRelayCache() {
|
|
74
|
+
cache.clear();
|
|
75
|
+
}
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
// Relay names: a DNS name and a Let's Encrypt certificate for a local relay,
|
|
2
|
+
// kept by its owner's own Worker on the owner's own domain.
|
|
3
|
+
//
|
|
4
|
+
// POST /api/v1/name body: a request signed with the relay's identity
|
|
5
|
+
// action 'claim' point <label>.<NAMES_DOMAIN> at the address this request came from
|
|
6
|
+
// action 'acme-set' put `value` in the TXT record _acme-challenge.<name> (DNS-01)
|
|
7
|
+
// action 'acme-clear' remove that TXT record
|
|
8
|
+
//
|
|
9
|
+
// <label> is the relay's node id, cut to its first LABEL_CHARS hex digits (a
|
|
10
|
+
// DNS label holds 63 characters, a node id 64).
|
|
11
|
+
//
|
|
12
|
+
// Only the Worker holds the DNS token (env.NAMES_DNS_TOKEN, limited to
|
|
13
|
+
// editing DNS on one zone, env.NAMES_ZONE_ID, whose domain is
|
|
14
|
+
// env.NAMES_DOMAIN). It answers only relays its owner registered: their node
|
|
15
|
+
// ids are in the D1 table freertc_name_owners, put there by `freertc name` on
|
|
16
|
+
// the relay's machine (with the owner's Cloudflare login). With
|
|
17
|
+
// env.NAMES_OPEN = '1' it answers any relay (a public naming service, such as
|
|
18
|
+
// relays.peer.ooo).
|
|
19
|
+
//
|
|
20
|
+
// The address is always the one the request came from, so a relay can name
|
|
21
|
+
// only its own machine. Off unless the token, zone and domain are set.
|
|
22
|
+
|
|
23
|
+
import { signMessage, verifyMessage } from 'unsea';
|
|
24
|
+
import { canonicalJson, isNodeId, relayNodeId } from '../kademlia.js';
|
|
25
|
+
|
|
26
|
+
export const NAMES_PATH = '/api/v1/name';
|
|
27
|
+
export const NAME_REQUEST_KIND = 'relay-name';
|
|
28
|
+
export const OWNERS_TABLE = 'freertc_name_owners';
|
|
29
|
+
export const LABEL_CHARS = 16;
|
|
30
|
+
const CLOUDFLARE_API = 'https://api.cloudflare.com/client/v4';
|
|
31
|
+
const MAX_SKEW_MS = 5 * 60_000;
|
|
32
|
+
const NAME_TTL_SECONDS = 120;
|
|
33
|
+
const ACME_TTL_SECONDS = 60;
|
|
34
|
+
const ACTIONS = new Set(['claim', 'acme-set', 'acme-clear']);
|
|
35
|
+
|
|
36
|
+
export function namesEnabled(env) {
|
|
37
|
+
return Boolean(env?.NAMES_DNS_TOKEN && env?.NAMES_ZONE_ID && env?.NAMES_DOMAIN);
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
/** The DNS name a relay gets on `domain`. */
|
|
41
|
+
export function relayHostname(nodeId, domain) {
|
|
42
|
+
return `${String(nodeId).slice(0, LABEL_CHARS).toLowerCase()}.${String(domain).toLowerCase().replace(/\.$/, '')}`;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** A relay's signed naming request. */
|
|
46
|
+
export async function createNameRequest(identity, { action, value = null, now = Date.now() }) {
|
|
47
|
+
const payload = {
|
|
48
|
+
kind: NAME_REQUEST_KIND,
|
|
49
|
+
version: 1,
|
|
50
|
+
action,
|
|
51
|
+
node_id: identity.nodeId,
|
|
52
|
+
public_key: identity.publicKey,
|
|
53
|
+
issued_at_ms: now,
|
|
54
|
+
...(value === null ? {} : { value: String(value) }),
|
|
55
|
+
};
|
|
56
|
+
return { ...payload, signature: await signMessage(canonicalJson(payload), identity.privateKey) };
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export async function verifyNameRequest(request, { now = Date.now() } = {}) {
|
|
60
|
+
try {
|
|
61
|
+
if (!request || request.kind !== NAME_REQUEST_KIND || request.version !== 1 || !ACTIONS.has(request.action)) return false;
|
|
62
|
+
if (!isNodeId(request.node_id) || typeof request.public_key !== 'string' || typeof request.signature !== 'string') return false;
|
|
63
|
+
if (Math.abs(now - Number(request.issued_at_ms)) > MAX_SKEW_MS) return false;
|
|
64
|
+
if (request.action === 'acme-set' && (typeof request.value !== 'string' || !/^[A-Za-z0-9_-]{20,100}$/.test(request.value))) return false;
|
|
65
|
+
if (await relayNodeId(request.public_key) !== request.node_id) return false;
|
|
66
|
+
const { signature, ...payload } = request;
|
|
67
|
+
return await verifyMessage(canonicalJson(payload), signature, request.public_key);
|
|
68
|
+
} catch {
|
|
69
|
+
return false;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function json(body, status = 200) {
|
|
74
|
+
return new Response(JSON.stringify(body), { status, headers: { 'Content-Type': 'application/json' } });
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
async function cloudflare(env, method, path, body, fetchImpl) {
|
|
78
|
+
const response = await fetchImpl(`${CLOUDFLARE_API}/zones/${env.NAMES_ZONE_ID}${path}`, {
|
|
79
|
+
method,
|
|
80
|
+
headers: { Authorization: `Bearer ${env.NAMES_DNS_TOKEN}`, 'Content-Type': 'application/json' },
|
|
81
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
82
|
+
});
|
|
83
|
+
const data = await response.json().catch(() => null);
|
|
84
|
+
if (!response.ok || data?.success === false) {
|
|
85
|
+
const why = data?.errors?.map((error) => error.message).join('; ') || `status ${response.status}`;
|
|
86
|
+
throw new Error(`DNS API: ${why}`);
|
|
87
|
+
}
|
|
88
|
+
return data?.result;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async function records(env, fetchImpl, type, name) {
|
|
92
|
+
return (await cloudflare(env, 'GET', `/dns_records?type=${type}&name=${encodeURIComponent(name)}&per_page=100`, undefined, fetchImpl)) || [];
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** Is this relay one its owner registered (or is this an open naming service)? */
|
|
96
|
+
export async function isRegistered(env, nodeId) {
|
|
97
|
+
if (env.NAMES_OPEN === '1' || env.NAMES_OPEN === true) return true;
|
|
98
|
+
const db = env.DB;
|
|
99
|
+
if (!db) return false;
|
|
100
|
+
await db.prepare(`CREATE TABLE IF NOT EXISTS ${OWNERS_TABLE} (node_id TEXT PRIMARY KEY, added_at_ms INTEGER NOT NULL)`).run();
|
|
101
|
+
return Boolean(await db.prepare(`SELECT node_id FROM ${OWNERS_TABLE} WHERE node_id = ?1`).bind(nodeId).first());
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export async function handleNameRequest(request, env, { fetchImpl = globalThis.fetch, now = Date.now() } = {}) {
|
|
105
|
+
// `names` tells `freertc name` this Worker can give names (and on which domain, not secret).
|
|
106
|
+
if (!namesEnabled(env)) return json({ ok: false, names: false, error: 'this Worker gives no names yet' }, 404);
|
|
107
|
+
if (request.method === 'GET') return json({ ok: true, names: true, domain: String(env.NAMES_DOMAIN).toLowerCase(), open: env.NAMES_OPEN === '1' });
|
|
108
|
+
if (request.method !== 'POST') return json({ ok: false, error: 'method not allowed' }, 405);
|
|
109
|
+
const text = await request.text();
|
|
110
|
+
if (text.length > 4 * 1024) return json({ ok: false, error: 'too large' }, 413);
|
|
111
|
+
let body;
|
|
112
|
+
try { body = JSON.parse(text); } catch { return json({ ok: false, error: 'bad JSON' }, 400); }
|
|
113
|
+
if (!await verifyNameRequest(body, { now })) return json({ ok: false, error: 'bad request signature' }, 400);
|
|
114
|
+
if (!await isRegistered(env, body.node_id)) {
|
|
115
|
+
return json({ ok: false, error: 'this relay is not registered with this Worker; run `npx freertc name` on its machine' }, 403);
|
|
116
|
+
}
|
|
117
|
+
const name = relayHostname(body.node_id, env.NAMES_DOMAIN);
|
|
118
|
+
const comment = `freertc-name:${body.node_id}`;
|
|
119
|
+
try {
|
|
120
|
+
if (body.action === 'claim') {
|
|
121
|
+
const ip = String(request.headers.get('CF-Connecting-IP') || '').replace(/^::ffff:/, '');
|
|
122
|
+
if (!ip) return json({ ok: false, error: 'no address seen' }, 400);
|
|
123
|
+
const type = ip.includes(':') ? 'AAAA' : 'A';
|
|
124
|
+
const other = type === 'A' ? 'AAAA' : 'A';
|
|
125
|
+
const mine = (await records(env, fetchImpl, type, name));
|
|
126
|
+
const entry = { type, name, content: ip, ttl: NAME_TTL_SECONDS, proxied: false, comment };
|
|
127
|
+
let changed = true;
|
|
128
|
+
if (mine[0] && mine[0].content === ip) changed = false;
|
|
129
|
+
else if (mine[0]) await cloudflare(env, 'PUT', `/dns_records/${mine[0].id}`, entry, fetchImpl);
|
|
130
|
+
else await cloudflare(env, 'POST', '/dns_records', entry, fetchImpl);
|
|
131
|
+
for (const extra of mine.slice(1)) await cloudflare(env, 'DELETE', `/dns_records/${extra.id}`, undefined, fetchImpl).catch(() => {});
|
|
132
|
+
// An address of the other family left from before would send clients elsewhere.
|
|
133
|
+
for (const stale of await records(env, fetchImpl, other, name)) await cloudflare(env, 'DELETE', `/dns_records/${stale.id}`, undefined, fetchImpl).catch(() => {});
|
|
134
|
+
return json({ ok: true, name, ip, changed });
|
|
135
|
+
}
|
|
136
|
+
const acmeName = `_acme-challenge.${name}`;
|
|
137
|
+
const existing = await records(env, fetchImpl, 'TXT', acmeName);
|
|
138
|
+
if (body.action === 'acme-set') {
|
|
139
|
+
const content = `"${body.value}"`;
|
|
140
|
+
if (!existing.some((entry) => String(entry.content).replace(/"/g, '') === body.value)) {
|
|
141
|
+
await cloudflare(env, 'POST', '/dns_records', { type: 'TXT', name: acmeName, content, ttl: ACME_TTL_SECONDS, comment: `freertc-acme:${body.node_id}` }, fetchImpl);
|
|
142
|
+
}
|
|
143
|
+
return json({ ok: true, name: acmeName });
|
|
144
|
+
}
|
|
145
|
+
for (const entry of existing) await cloudflare(env, 'DELETE', `/dns_records/${entry.id}`, undefined, fetchImpl).catch(() => {});
|
|
146
|
+
return json({ ok: true, removed: existing.length });
|
|
147
|
+
} catch (error) {
|
|
148
|
+
return json({ ok: false, error: String(error?.message || error).slice(0, 200) }, 502);
|
|
149
|
+
}
|
|
150
|
+
}
|
|
@@ -0,0 +1,170 @@
|
|
|
1
|
+
// node-relay's direct mode: accept direct browser connections on a UDP port,
|
|
2
|
+
// ask the router to forward that port, and list this relay in the DNS relay
|
|
3
|
+
// directory (a cloud relay writes it; see directory.js), so browsers find it
|
|
4
|
+
// with one DNS-over-HTTPS lookup and connect without any cloud relay.
|
|
5
|
+
//
|
|
6
|
+
// Nothing is published unless the router gives a public address that is also
|
|
7
|
+
// the address the directory sees this relay's requests come from (behind
|
|
8
|
+
// carrier-grade NAT or a second router they differ, and browsers could not
|
|
9
|
+
// reach the port). In that case the relay keeps using its tunnel as before.
|
|
10
|
+
|
|
11
|
+
import { loadOrCreateDirectCertificate } from './cert.js';
|
|
12
|
+
import { startDirectListener, directListenerAvailable } from './listener.js';
|
|
13
|
+
import { mapUdpPort, isNonPublicIPv4 } from './portmap.js';
|
|
14
|
+
import { directRelayUrl } from './common.js';
|
|
15
|
+
import { createSignedDirectoryRecord, createSignedWithdrawal } from './record.js';
|
|
16
|
+
import { DIRECTORY_PATH, PQ_KEY_HEADER, PQ_SIGNATURE_HEADER } from './directory.js';
|
|
17
|
+
import { signDirectoryPq } from '../relay-identity.js';
|
|
18
|
+
import { networkInterfaces } from 'node:os';
|
|
19
|
+
import { isLanEndpoint } from './record.js';
|
|
20
|
+
|
|
21
|
+
/** This machine's private IPv4 addresses with the relay's own UDP port, "ip:port". */
|
|
22
|
+
function lanEndpoints(port) {
|
|
23
|
+
const out = [];
|
|
24
|
+
for (const entry of Object.values(networkInterfaces()).flat()) {
|
|
25
|
+
if (!entry || entry.internal || entry.family !== 'IPv4') continue;
|
|
26
|
+
const endpoint = `${entry.address}:${port}`;
|
|
27
|
+
if (isLanEndpoint(endpoint) && !out.includes(endpoint)) out.push(endpoint);
|
|
28
|
+
}
|
|
29
|
+
return out.slice(0, 4);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
const REPUBLISH_MS = 20 * 60_000;
|
|
33
|
+
|
|
34
|
+
export async function startDirectRelay({
|
|
35
|
+
identity,
|
|
36
|
+
dataDir,
|
|
37
|
+
port = 9443,
|
|
38
|
+
directoryUrl,
|
|
39
|
+
publicIp = null, // set when this machine has a public address and no router to ask
|
|
40
|
+
tunnelUrl = () => null, // this relay's tunnel URL, when it has one
|
|
41
|
+
wsUrl = () => null, // ws://<public ip>:<port>/ws when the router forwards its TCP port
|
|
42
|
+
name = null, // a label, or a function giving it (a wss:// name once the relay has one)
|
|
43
|
+
acceptSocket,
|
|
44
|
+
fetchImpl = globalThis.fetch,
|
|
45
|
+
log = () => {},
|
|
46
|
+
pqIdentity = null, // { pub, priv, qpub, qpriv }: prove the relay's post-quantum key too
|
|
47
|
+
}) {
|
|
48
|
+
// JSON headers, and the post-quantum proof when this relay has a key.
|
|
49
|
+
const headersFor = async (signed) => ({
|
|
50
|
+
'Content-Type': 'application/json',
|
|
51
|
+
...(pqIdentity ? { [PQ_KEY_HEADER]: pqIdentity.qpub, [PQ_SIGNATURE_HEADER]: await signDirectoryPq(pqIdentity, signed) } : {}),
|
|
52
|
+
});
|
|
53
|
+
if (!await directListenerAvailable()) {
|
|
54
|
+
log('direct connections: off (needs node-datachannel 0.33 or later: npm install node-datachannel)');
|
|
55
|
+
return null;
|
|
56
|
+
}
|
|
57
|
+
const cert = loadOrCreateDirectCertificate(dataDir);
|
|
58
|
+
const listener = await startDirectListener({
|
|
59
|
+
port,
|
|
60
|
+
certFile: cert.certFile,
|
|
61
|
+
keyFile: cert.keyFile,
|
|
62
|
+
onSocket: (socket) => acceptSocket(socket),
|
|
63
|
+
log,
|
|
64
|
+
});
|
|
65
|
+
if (!listener) return null;
|
|
66
|
+
|
|
67
|
+
let mapping = null;
|
|
68
|
+
let externalIp = publicIp;
|
|
69
|
+
let externalPort = port;
|
|
70
|
+
if (!publicIp) {
|
|
71
|
+
mapping = await mapUdpPort({ internalPort: port, externalPort: port, description: `freertc relay ${identity.nodeId.slice(0, 8)}`, log });
|
|
72
|
+
if (!mapping) {
|
|
73
|
+
log('direct connections: no router answered UPnP or NAT-PMP; browsers reach this relay through its tunnel');
|
|
74
|
+
} else if (isNonPublicIPv4(mapping.externalIp)) {
|
|
75
|
+
log(`direct connections: the router's own address ${mapping.externalIp} is not public (carrier-grade NAT or a second router); using the tunnel`);
|
|
76
|
+
await mapping.close();
|
|
77
|
+
mapping = null;
|
|
78
|
+
} else {
|
|
79
|
+
externalIp = mapping.externalIp;
|
|
80
|
+
externalPort = mapping.externalPort;
|
|
81
|
+
log(`direct connections: router forwards udp ${externalIp}:${externalPort} here (${mapping.method})`);
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
let published = null;
|
|
86
|
+
let retryTimer = null;
|
|
87
|
+
let stopped = false;
|
|
88
|
+
const endpoint = directoryUrl ? new URL(DIRECTORY_PATH, directoryUrl).toString() : null;
|
|
89
|
+
|
|
90
|
+
// A relay that cannot be listed here (no public address on this network,
|
|
91
|
+
// or the directory sees a different one) takes down the entry it may have
|
|
92
|
+
// left from its last network: otherwise browsers keep dialing an address
|
|
93
|
+
// where nothing answers until that entry expires.
|
|
94
|
+
let withdrawnStale = false;
|
|
95
|
+
async function withdrawStale(why) {
|
|
96
|
+
if (withdrawnStale || !endpoint) return;
|
|
97
|
+
withdrawnStale = true;
|
|
98
|
+
try {
|
|
99
|
+
const withdrawal = await createSignedWithdrawal(identity);
|
|
100
|
+
const response = await fetchImpl(endpoint, { method: 'DELETE', headers: await headersFor(withdrawal), body: JSON.stringify(withdrawal), signal: AbortSignal.timeout(5_000) });
|
|
101
|
+
const body = await response.json().catch(() => null);
|
|
102
|
+
if (body?.removed) log(`directory: removed this relay's old entry (${why})`);
|
|
103
|
+
} catch (error) {
|
|
104
|
+
withdrawnStale = false;
|
|
105
|
+
log(`directory: could not remove this relay's old entry: ${error?.message || error}`);
|
|
106
|
+
}
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
async function publish() {
|
|
110
|
+
if (stopped || !endpoint) return;
|
|
111
|
+
if (!externalIp) {
|
|
112
|
+
await withdrawStale('not reachable directly on this network');
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
const record = await createSignedDirectoryRecord(identity, {
|
|
116
|
+
direct: directRelayUrl({ host: externalIp, port: externalPort, fingerprint: cert.fingerprint }),
|
|
117
|
+
tunnel: tunnelUrl() || null,
|
|
118
|
+
name: typeof name === 'function' ? name() : name,
|
|
119
|
+
// The port the relay listens on (the router may forward a different
|
|
120
|
+
// public one): machines on this network use these, not the public address.
|
|
121
|
+
lan: lanEndpoints(port),
|
|
122
|
+
ws: wsUrl() || null,
|
|
123
|
+
});
|
|
124
|
+
try {
|
|
125
|
+
const response = await fetchImpl(endpoint, { method: 'POST', headers: await headersFor(record), body: JSON.stringify(record) });
|
|
126
|
+
const body = await response.json().catch(() => null);
|
|
127
|
+
if (!response.ok || !body?.ok) {
|
|
128
|
+
const why = body?.error || `status ${response.status}`;
|
|
129
|
+
log(`directory: not listed (${why}${body?.seen ? `; it sees ${body.seen}, the router says ${externalIp}` : ''})`);
|
|
130
|
+
if (body?.seen && body.seen !== externalIp) {
|
|
131
|
+
externalIp = null; // a second NAT: stop trying
|
|
132
|
+
await withdrawStale('behind a second NAT');
|
|
133
|
+
}
|
|
134
|
+
// Changed too soon after the last write: try again once that has passed.
|
|
135
|
+
if (response.status === 429 && !retryTimer) {
|
|
136
|
+
retryTimer = setTimeout(() => { retryTimer = null; publish().catch(() => {}); }, 75_000);
|
|
137
|
+
retryTimer.unref?.();
|
|
138
|
+
}
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
if (body.published) log(`directory: listed as ${record.direct}${record.lan ? ` (on this network: ${record.lan.join(', ')})` : ''}`);
|
|
142
|
+
published = record;
|
|
143
|
+
} catch (error) {
|
|
144
|
+
log(`directory: ${error?.message || error}`);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
await publish();
|
|
149
|
+
const timer = setInterval(() => publish().catch(() => {}), REPUBLISH_MS);
|
|
150
|
+
timer.unref?.();
|
|
151
|
+
|
|
152
|
+
return {
|
|
153
|
+
fingerprint: cert.fingerprint,
|
|
154
|
+
url: () => (externalIp ? directRelayUrl({ host: externalIp, port: externalPort, fingerprint: cert.fingerprint }) : null),
|
|
155
|
+
stats: () => listener.stats(),
|
|
156
|
+
republish: publish,
|
|
157
|
+
async stop() {
|
|
158
|
+
stopped = true;
|
|
159
|
+
clearInterval(timer);
|
|
160
|
+
if (published && endpoint) {
|
|
161
|
+
try {
|
|
162
|
+
const withdrawal = await createSignedWithdrawal(identity);
|
|
163
|
+
await fetchImpl(endpoint, { method: 'DELETE', headers: await headersFor(withdrawal), body: JSON.stringify(withdrawal), signal: AbortSignal.timeout(3_000) });
|
|
164
|
+
} catch {}
|
|
165
|
+
}
|
|
166
|
+
await mapping?.close().catch(() => {});
|
|
167
|
+
listener.close();
|
|
168
|
+
},
|
|
169
|
+
};
|
|
170
|
+
}
|