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,117 @@
|
|
|
1
|
+
// Cloudflare's WebSocketPair for a relay running under Node. The worker
|
|
2
|
+
// creates a pair, keeps the "server" end (addEventListener, accept, send,
|
|
3
|
+
// close) and returns the "client" end in a 101 Response. Here the server end
|
|
4
|
+
// is a deferred wrapper: listeners and accept() are recorded while the worker
|
|
5
|
+
// runs, and attach() binds them to a real socket once the HTTP upgrade (or a
|
|
6
|
+
// hole-punched channel) delivers one. Anything that looks like a `ws` socket
|
|
7
|
+
// works: send(), close(), on('message' | 'close' | 'error').
|
|
8
|
+
|
|
9
|
+
export class NodeServerSocket {
|
|
10
|
+
constructor() {
|
|
11
|
+
this.listeners = { message: [], close: [], error: [] };
|
|
12
|
+
this.socket = null;
|
|
13
|
+
this.accepted = false;
|
|
14
|
+
this.closed = false;
|
|
15
|
+
this.queued = [];
|
|
16
|
+
this.attachment = undefined;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// The Durable Object hibernation API keeps a small value with each socket.
|
|
20
|
+
serializeAttachment(value) {
|
|
21
|
+
this.attachment = value === undefined ? undefined : structuredClone(value);
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
deserializeAttachment() {
|
|
25
|
+
return this.attachment === undefined ? null : structuredClone(this.attachment);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
addEventListener(type, listener) {
|
|
29
|
+
this.listeners[type]?.push(listener);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
accept() {
|
|
33
|
+
this.accepted = true;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
attach(socket) {
|
|
37
|
+
this.socket = socket;
|
|
38
|
+
const emit = (type, event) => {
|
|
39
|
+
for (const listener of this.listeners[type]) {
|
|
40
|
+
try {
|
|
41
|
+
const result = listener(event);
|
|
42
|
+
if (result && typeof result.catch === 'function') result.catch(() => {});
|
|
43
|
+
} catch {}
|
|
44
|
+
}
|
|
45
|
+
};
|
|
46
|
+
socket.on('message', (data) => emit('message', { data: typeof data === 'string' ? data : data.toString() }));
|
|
47
|
+
socket.on('close', (code, reason) => {
|
|
48
|
+
if (this.closed) return;
|
|
49
|
+
this.closed = true;
|
|
50
|
+
emit('close', { code, reason: reason?.toString?.() ?? '' });
|
|
51
|
+
});
|
|
52
|
+
socket.on('error', (error) => emit('error', { error }));
|
|
53
|
+
// Sent before the upgrade completed, as a worker may do right after accepting.
|
|
54
|
+
for (const data of this.queued.splice(0)) socket.send(data);
|
|
55
|
+
if (this.pendingClose) socket.close(...this.pendingClose);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
send(data) {
|
|
59
|
+
if (this.closed) throw new Error('WebSocket is not open');
|
|
60
|
+
const text = typeof data === 'string' ? data : String(data);
|
|
61
|
+
if (!this.socket) this.queued.push(text);
|
|
62
|
+
else this.socket.send(text);
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
close(code, reason) {
|
|
66
|
+
if (!this.socket) {
|
|
67
|
+
this.pendingClose = [code, reason];
|
|
68
|
+
return;
|
|
69
|
+
}
|
|
70
|
+
try { this.socket.close(code, reason); } catch {}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export class NodeWebSocketPair {
|
|
75
|
+
constructor() {
|
|
76
|
+
const server = new NodeServerSocket();
|
|
77
|
+
const client = { server };
|
|
78
|
+
this[0] = client;
|
|
79
|
+
this[1] = server;
|
|
80
|
+
}
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/**
|
|
84
|
+
* Install the pair on globalThis so the worker's `new WebSocketPair()` resolves
|
|
85
|
+
* to it, and let `new Response(null, { status: 101, webSocket })` through:
|
|
86
|
+
* Node's Response only accepts 200–599 and drops the webSocket field.
|
|
87
|
+
*/
|
|
88
|
+
export function installWebSocketPair() {
|
|
89
|
+
if (typeof globalThis.WebSocketPair !== 'function') globalThis.WebSocketPair = NodeWebSocketPair;
|
|
90
|
+
if (typeof globalThis.WebSocketRequestResponsePair !== 'function') {
|
|
91
|
+
globalThis.WebSocketRequestResponsePair = class WebSocketRequestResponsePair {
|
|
92
|
+
constructor(request, response) {
|
|
93
|
+
this.request = request;
|
|
94
|
+
this.response = response;
|
|
95
|
+
}
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
if (globalThis.Response.__freertcUpgradeAware) return;
|
|
99
|
+
const BaseResponse = globalThis.Response;
|
|
100
|
+
class UpgradeAwareResponse extends BaseResponse {
|
|
101
|
+
constructor(body, init = {}) {
|
|
102
|
+
const upgrade = init?.status === 101;
|
|
103
|
+
super(upgrade ? null : body, upgrade ? { ...init, status: 200 } : init);
|
|
104
|
+
if (upgrade) {
|
|
105
|
+
Object.defineProperty(this, 'status', { value: 101 });
|
|
106
|
+
Object.defineProperty(this, 'webSocket', { value: init.webSocket ?? null });
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
UpgradeAwareResponse.__freertcUpgradeAware = true;
|
|
111
|
+
globalThis.Response = UpgradeAwareResponse;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/** The server socket a worker Response carries for a 101 upgrade, if any. */
|
|
115
|
+
export function serverSocketOf(response) {
|
|
116
|
+
return response?.status === 101 ? response.webSocket?.server ?? null : null;
|
|
117
|
+
}
|
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
// A punched connection in one HTTP round trip: POST /api/v1/punch/offer.
|
|
2
|
+
//
|
|
3
|
+
// A relay behind NAT keeps a tunnel open to its home, so the home can carry an
|
|
4
|
+
// introduction to it without a rendezvous store or any polling: a client posts
|
|
5
|
+
// its complete offer (every ICE candidate gathered first) to
|
|
6
|
+
// https://<home>/t/<node id>/api/v1/punch/offer
|
|
7
|
+
// the tunnel delivers it here, and the answer, complete too, comes back in the
|
|
8
|
+
// response. Both sides' own packets then open the path between them, and the
|
|
9
|
+
// data channel that opens carries the relay protocol, the same JSON frames a
|
|
10
|
+
// WebSocket would. The home sees one request per introduction and nothing
|
|
11
|
+
// after it.
|
|
12
|
+
//
|
|
13
|
+
// request { sdp } an offer with its candidates in it
|
|
14
|
+
// response { ok: true, sdp } the answer, with this side's candidates
|
|
15
|
+
// { ok: false, error } no WebRTC here, too many at once, a bad offer
|
|
16
|
+
|
|
17
|
+
import { DataChannelSocket } from './transport.js';
|
|
18
|
+
|
|
19
|
+
const DEFAULT_ICE_SERVERS = [
|
|
20
|
+
{ urls: 'stun:stun.l.google.com:19302' },
|
|
21
|
+
{ urls: 'stun:stun.cloudflare.com:3478' },
|
|
22
|
+
];
|
|
23
|
+
const MAX_OFFER_BYTES = 64 * 1024;
|
|
24
|
+
const GATHER_TIMEOUT_MS = 4_000;
|
|
25
|
+
const OPEN_TIMEOUT_MS = 20_000;
|
|
26
|
+
const MAX_PENDING = 64;
|
|
27
|
+
|
|
28
|
+
export const PUNCH_OFFER_PATH = '/api/v1/punch/offer';
|
|
29
|
+
|
|
30
|
+
function json(body, status = 200) {
|
|
31
|
+
return new Response(JSON.stringify(body), {
|
|
32
|
+
status,
|
|
33
|
+
headers: { 'Content-Type': 'application/json', 'Access-Control-Allow-Origin': '*' },
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Resolve once ICE gathering is complete, or after timeoutMs with what there is. */
|
|
38
|
+
export function iceGatheringComplete(pc, timeoutMs = GATHER_TIMEOUT_MS) {
|
|
39
|
+
if (pc.iceGatheringState === 'complete') return Promise.resolve();
|
|
40
|
+
return new Promise((resolve) => {
|
|
41
|
+
const timer = setTimeout(resolve, timeoutMs);
|
|
42
|
+
const done = () => { clearTimeout(timer); resolve(); };
|
|
43
|
+
const previousCandidate = pc.onicecandidate;
|
|
44
|
+
pc.onicecandidate = (event) => {
|
|
45
|
+
previousCandidate?.(event);
|
|
46
|
+
if (!event?.candidate) done();
|
|
47
|
+
};
|
|
48
|
+
const previousState = pc.onicegatheringstatechange;
|
|
49
|
+
pc.onicegatheringstatechange = (event) => {
|
|
50
|
+
previousState?.(event);
|
|
51
|
+
if (pc.iceGatheringState === 'complete') done();
|
|
52
|
+
};
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
async function loadPeerConnection(provided) {
|
|
57
|
+
if (provided) return provided;
|
|
58
|
+
if (typeof globalThis.RTCPeerConnection === 'function') return globalThis.RTCPeerConnection;
|
|
59
|
+
try {
|
|
60
|
+
const { RTCPeerConnection } = await import('werift');
|
|
61
|
+
return RTCPeerConnection;
|
|
62
|
+
} catch {
|
|
63
|
+
return null;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Whether this process can accept punched connections (it has WebRTC). */
|
|
68
|
+
export async function punchOfferAvailable(RTCPeerConnection = null) {
|
|
69
|
+
return Boolean(await loadPeerConnection(RTCPeerConnection));
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
/**
|
|
73
|
+
* Handler for POST /api/v1/punch/offer. Each opened channel is handed to
|
|
74
|
+
* onSocket as a socket the relay treats exactly like a WebSocket client.
|
|
75
|
+
*/
|
|
76
|
+
export function createPunchOfferHandler({
|
|
77
|
+
onSocket,
|
|
78
|
+
iceServers = DEFAULT_ICE_SERVERS,
|
|
79
|
+
RTCPeerConnection = null,
|
|
80
|
+
log = () => {},
|
|
81
|
+
openTimeoutMs = OPEN_TIMEOUT_MS,
|
|
82
|
+
gatherTimeoutMs = GATHER_TIMEOUT_MS,
|
|
83
|
+
} = {}) {
|
|
84
|
+
let pending = 0;
|
|
85
|
+
return async function handlePunchOffer(request) {
|
|
86
|
+
if (request.method === 'OPTIONS') {
|
|
87
|
+
return new Response(null, {
|
|
88
|
+
status: 204,
|
|
89
|
+
headers: {
|
|
90
|
+
'Access-Control-Allow-Origin': '*',
|
|
91
|
+
'Access-Control-Allow-Methods': 'POST, OPTIONS',
|
|
92
|
+
'Access-Control-Allow-Headers': 'Content-Type',
|
|
93
|
+
},
|
|
94
|
+
});
|
|
95
|
+
}
|
|
96
|
+
if (request.method !== 'POST') return json({ ok: false, error: 'POST an offer' }, 405);
|
|
97
|
+
const PeerConnection = await loadPeerConnection(RTCPeerConnection);
|
|
98
|
+
if (!PeerConnection) return json({ ok: false, error: 'This relay has no WebRTC (npm install werift)' }, 501);
|
|
99
|
+
if (pending >= MAX_PENDING) return json({ ok: false, error: 'Too many introductions at once' }, 503);
|
|
100
|
+
|
|
101
|
+
const text = await request.text();
|
|
102
|
+
if (text.length > MAX_OFFER_BYTES) return json({ ok: false, error: 'Offer too large' }, 413);
|
|
103
|
+
let sdp;
|
|
104
|
+
try { sdp = JSON.parse(text)?.sdp; } catch {}
|
|
105
|
+
if (typeof sdp !== 'string' || !sdp.startsWith('v=')) return json({ ok: false, error: 'Missing offer sdp' }, 400);
|
|
106
|
+
|
|
107
|
+
pending += 1;
|
|
108
|
+
const pc = new PeerConnection({ iceServers });
|
|
109
|
+
let settled = false;
|
|
110
|
+
const release = () => { if (!settled) { settled = true; pending -= 1; } };
|
|
111
|
+
const giveUp = setTimeout(() => {
|
|
112
|
+
if (settled) return;
|
|
113
|
+
release();
|
|
114
|
+
log('punched channel did not open in time');
|
|
115
|
+
try { pc.close(); } catch {}
|
|
116
|
+
}, openTimeoutMs);
|
|
117
|
+
giveUp.unref?.();
|
|
118
|
+
|
|
119
|
+
pc.ondatachannel = (event) => {
|
|
120
|
+
const channel = event.channel;
|
|
121
|
+
const ready = () => {
|
|
122
|
+
clearTimeout(giveUp);
|
|
123
|
+
release();
|
|
124
|
+
log('punched channel open');
|
|
125
|
+
onSocket(new DataChannelSocket(channel, pc, { punched: true }));
|
|
126
|
+
};
|
|
127
|
+
if (channel.readyState === 'open') ready(); else channel.onopen = ready;
|
|
128
|
+
};
|
|
129
|
+
|
|
130
|
+
try {
|
|
131
|
+
await pc.setRemoteDescription({ type: 'offer', sdp });
|
|
132
|
+
const gathered = iceGatheringComplete(pc, gatherTimeoutMs);
|
|
133
|
+
await pc.setLocalDescription(await pc.createAnswer());
|
|
134
|
+
await gathered;
|
|
135
|
+
return json({ ok: true, sdp: pc.localDescription.sdp });
|
|
136
|
+
} catch (error) {
|
|
137
|
+
clearTimeout(giveUp);
|
|
138
|
+
release();
|
|
139
|
+
try { pc.close(); } catch {}
|
|
140
|
+
return json({ ok: false, error: `Bad offer: ${error?.message ?? error}` }, 400);
|
|
141
|
+
}
|
|
142
|
+
};
|
|
143
|
+
}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
// Rendezvous for hole punching: the only thing a public service does for a
|
|
2
|
+
// local freertc server is introduce it. A local server registers a listener
|
|
3
|
+
// id; a node that wants to reach it posts an offer to that id; the two swap a
|
|
4
|
+
// few signaling messages (offer, answer, ICE candidates) through here; then
|
|
5
|
+
// they talk directly over the hole their own packets punched, and this
|
|
6
|
+
// service is out of the loop until the next introduction.
|
|
7
|
+
//
|
|
8
|
+
// Written against the fetch Request/Response API so the same handler runs in
|
|
9
|
+
// the Cloudflare worker and in a plain Node server. State lives in a store
|
|
10
|
+
// with get/put/delete, so the worker can back it with D1 or KV and a Node
|
|
11
|
+
// stand-in with a Map.
|
|
12
|
+
|
|
13
|
+
const LISTENER_TTL_MS = 90_000;
|
|
14
|
+
const MESSAGE_TTL_MS = 60_000;
|
|
15
|
+
const MAX_MESSAGES_PER_MAILBOX = 64;
|
|
16
|
+
const MAX_BODY_BYTES = 64 * 1024;
|
|
17
|
+
const ID = /^[A-Za-z0-9._:-]{1,128}$/;
|
|
18
|
+
const POLL_STEP_MS = 250;
|
|
19
|
+
|
|
20
|
+
export class MemoryRendezvousStore {
|
|
21
|
+
constructor() {
|
|
22
|
+
this.listeners = new Map(); // listenerId -> { info, expiresAt }
|
|
23
|
+
this.mailboxes = new Map(); // id -> [{ message, expiresAt }]
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
registerListener(listenerId, info, now = Date.now()) {
|
|
27
|
+
this.listeners.set(listenerId, { info, expiresAt: now + LISTENER_TTL_MS });
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
listListeners(now = Date.now()) {
|
|
31
|
+
const out = [];
|
|
32
|
+
for (const [listenerId, entry] of this.listeners) {
|
|
33
|
+
if (entry.expiresAt <= now) { this.listeners.delete(listenerId); continue; }
|
|
34
|
+
out.push({ listenerId, ...entry.info });
|
|
35
|
+
}
|
|
36
|
+
return out;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
hasListener(listenerId, now = Date.now()) {
|
|
40
|
+
const entry = this.listeners.get(listenerId);
|
|
41
|
+
return Boolean(entry && entry.expiresAt > now);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
push(to, message, now = Date.now()) {
|
|
45
|
+
const box = (this.mailboxes.get(to) ?? []).filter((item) => item.expiresAt > now);
|
|
46
|
+
box.push({ message, expiresAt: now + MESSAGE_TTL_MS });
|
|
47
|
+
while (box.length > MAX_MESSAGES_PER_MAILBOX) box.shift();
|
|
48
|
+
this.mailboxes.set(to, box);
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
take(id, now = Date.now()) {
|
|
52
|
+
const box = (this.mailboxes.get(id) ?? []).filter((item) => item.expiresAt > now);
|
|
53
|
+
this.mailboxes.delete(id);
|
|
54
|
+
return box.map((item) => item.message);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function json(body, status = 200) {
|
|
59
|
+
return new Response(JSON.stringify(body), {
|
|
60
|
+
status,
|
|
61
|
+
headers: { 'Content-Type': 'application/json; charset=utf-8', 'Access-Control-Allow-Origin': '*' },
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
async function readJson(request) {
|
|
66
|
+
const length = Number(request.headers.get('Content-Length') || 0);
|
|
67
|
+
if (length > MAX_BODY_BYTES) return null;
|
|
68
|
+
const text = await request.text();
|
|
69
|
+
if (text.length > MAX_BODY_BYTES) return null;
|
|
70
|
+
try { return JSON.parse(text); } catch { return null; }
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Handle /api/v1/punch/*. Returns null for any other path so a caller can
|
|
75
|
+
* mount it in front of its own routes.
|
|
76
|
+
*
|
|
77
|
+
* POST /api/v1/punch/register { listenerId, info? } a local server is here
|
|
78
|
+
* GET /api/v1/punch/listeners who can be dialed
|
|
79
|
+
* POST /api/v1/punch/send { to, from, session, signal } one signaling message
|
|
80
|
+
* GET /api/v1/punch/poll?id=&waitMs= messages for id (long-poll)
|
|
81
|
+
*/
|
|
82
|
+
export async function handleRendezvousRequest(request, store, { wait = (ms) => new Promise((r) => setTimeout(r, ms)) } = {}) {
|
|
83
|
+
const url = new URL(request.url);
|
|
84
|
+
if (!url.pathname.startsWith('/api/v1/punch/')) return null;
|
|
85
|
+
const route = url.pathname.slice('/api/v1/punch/'.length);
|
|
86
|
+
|
|
87
|
+
if (route === 'register' && request.method === 'POST') {
|
|
88
|
+
const body = await readJson(request);
|
|
89
|
+
if (!ID.test(String(body?.listenerId ?? ''))) return json({ ok: false, error: 'Invalid listenerId' }, 400);
|
|
90
|
+
const info = body.info && typeof body.info === 'object' ? { name: String(body.info.name ?? '').slice(0, 120) } : {};
|
|
91
|
+
await store.registerListener(body.listenerId, info);
|
|
92
|
+
return json({ ok: true, ttlMs: LISTENER_TTL_MS });
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
if (route === 'listeners' && request.method === 'GET') {
|
|
96
|
+
return json({ ok: true, listeners: await store.listListeners() });
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
if (route === 'send' && request.method === 'POST') {
|
|
100
|
+
const body = await readJson(request);
|
|
101
|
+
const { to, from, session, signal } = body ?? {};
|
|
102
|
+
if (![to, from, session].every((value) => ID.test(String(value ?? '')))) {
|
|
103
|
+
return json({ ok: false, error: 'Invalid to, from or session' }, 400);
|
|
104
|
+
}
|
|
105
|
+
if (!signal || typeof signal !== 'object') return json({ ok: false, error: 'Missing signal' }, 400);
|
|
106
|
+
await store.push(to, { from, session, signal });
|
|
107
|
+
return json({ ok: true });
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
if (route === 'poll' && request.method === 'GET') {
|
|
111
|
+
const id = String(url.searchParams.get('id') ?? '');
|
|
112
|
+
if (!ID.test(id)) return json({ ok: false, error: 'Invalid id' }, 400);
|
|
113
|
+
const waitMs = Math.max(0, Math.min(25_000, Number(url.searchParams.get('waitMs') || 0)));
|
|
114
|
+
const deadline = Date.now() + waitMs;
|
|
115
|
+
let messages = await store.take(id);
|
|
116
|
+
while (messages.length === 0 && Date.now() < deadline) {
|
|
117
|
+
await wait(Math.min(POLL_STEP_MS, deadline - Date.now()));
|
|
118
|
+
messages = await store.take(id);
|
|
119
|
+
}
|
|
120
|
+
return json({ ok: true, messages });
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
return json({ ok: false, error: 'Unknown punch endpoint' }, 404);
|
|
124
|
+
}
|
|
@@ -0,0 +1,257 @@
|
|
|
1
|
+
// A hole-punched transport for a freertc server behind NAT.
|
|
2
|
+
//
|
|
3
|
+
// The local server cannot be dialed over TCP from the public internet, but it
|
|
4
|
+
// can open UDP flows outward, and so can whoever wants to reach it. Each side
|
|
5
|
+
// learns its public address from STUN and both send at once, so each one's
|
|
6
|
+
// own packets open the hole the other's arrive through. ICE does exactly that,
|
|
7
|
+
// with candidate pairing and keepalives, so the punch is a WebRTC data channel
|
|
8
|
+
// negotiated through the rendezvous (rendezvous.js) and then used for the
|
|
9
|
+
// relay protocol itself: the same JSON envelopes a WebSocket carries.
|
|
10
|
+
|
|
11
|
+
const DEFAULT_ICE_SERVERS = [
|
|
12
|
+
{ urls: 'stun:stun.l.google.com:19302' },
|
|
13
|
+
{ urls: 'stun:stun.cloudflare.com:3478' },
|
|
14
|
+
];
|
|
15
|
+
const POLL_WAIT_MS = 20_000;
|
|
16
|
+
const REGISTER_EVERY_MS = 60_000;
|
|
17
|
+
const DIAL_TIMEOUT_MS = 20_000;
|
|
18
|
+
const CHANNEL_LABEL = 'freertc-relay';
|
|
19
|
+
|
|
20
|
+
async function loadRTCPeerConnection(provided) {
|
|
21
|
+
if (provided) return provided;
|
|
22
|
+
if (typeof globalThis.RTCPeerConnection === 'function') return globalThis.RTCPeerConnection;
|
|
23
|
+
const { RTCPeerConnection } = await import('werift');
|
|
24
|
+
return RTCPeerConnection;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function randomId(prefix) {
|
|
28
|
+
return `${prefix}-${globalThis.crypto.randomUUID()}`;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
async function post(base, path, body, fetchImpl) {
|
|
32
|
+
const response = await fetchImpl(new URL(path, base), {
|
|
33
|
+
method: 'POST',
|
|
34
|
+
headers: { 'Content-Type': 'application/json' },
|
|
35
|
+
body: JSON.stringify(body),
|
|
36
|
+
});
|
|
37
|
+
if (!response.ok) throw new Error(`${path} answered ${response.status}`);
|
|
38
|
+
return response.json();
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
async function poll(base, id, waitMs, fetchImpl, signal) {
|
|
42
|
+
const url = new URL('/api/v1/punch/poll', base);
|
|
43
|
+
url.searchParams.set('id', id);
|
|
44
|
+
url.searchParams.set('waitMs', String(waitMs));
|
|
45
|
+
const response = await fetchImpl(url, { signal });
|
|
46
|
+
if (!response.ok) throw new Error(`poll answered ${response.status}`);
|
|
47
|
+
const body = await response.json();
|
|
48
|
+
return Array.isArray(body?.messages) ? body.messages : [];
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Make a data channel look like the `ws` socket the relay already handles:
|
|
53
|
+
* send(), readyState/OPEN, and on('message' | 'close' | 'error').
|
|
54
|
+
*/
|
|
55
|
+
export class DataChannelSocket {
|
|
56
|
+
constructor(channel, peerConnection, meta = {}) {
|
|
57
|
+
this.channel = channel;
|
|
58
|
+
this.peerConnection = peerConnection;
|
|
59
|
+
this.meta = meta;
|
|
60
|
+
this.OPEN = 1;
|
|
61
|
+
this.CLOSED = 3;
|
|
62
|
+
this.listeners = { message: [], close: [], error: [] };
|
|
63
|
+
this.closed = false;
|
|
64
|
+
const emit = (event, value) => { for (const listener of this.listeners[event]) listener(value); };
|
|
65
|
+
channel.onmessage = (event) => emit('message', typeof event.data === 'string' ? event.data : Buffer.from(event.data));
|
|
66
|
+
channel.onclose = () => this.finish(emit);
|
|
67
|
+
channel.onerror = (error) => emit('error', error);
|
|
68
|
+
peerConnection.onconnectionstatechange = () => {
|
|
69
|
+
if (['failed', 'closed'].includes(peerConnection.connectionState)) this.finish(emit);
|
|
70
|
+
};
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
finish(emit) {
|
|
74
|
+
if (this.closed) return;
|
|
75
|
+
this.closed = true;
|
|
76
|
+
emit('close');
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
get readyState() {
|
|
80
|
+
return !this.closed && this.channel.readyState === 'open' ? this.OPEN : this.CLOSED;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
send(data) {
|
|
84
|
+
if (this.readyState !== this.OPEN) throw new Error('Punched channel is not open');
|
|
85
|
+
this.channel.send(typeof data === 'string' ? data : String(data));
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
on(event, listener) {
|
|
89
|
+
this.listeners[event]?.push(listener);
|
|
90
|
+
return this;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
close() {
|
|
94
|
+
try { this.channel.close(); } catch {}
|
|
95
|
+
try { this.peerConnection.close(); } catch {}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
/** Wire one side's ICE candidates to the rendezvous and apply the other side's. */
|
|
100
|
+
function bridgeIce(pc, send) {
|
|
101
|
+
pc.onicecandidate = (event) => {
|
|
102
|
+
const candidate = event?.candidate;
|
|
103
|
+
send(candidate ? { kind: 'candidate', candidate: candidate.toJSON?.() ?? candidate } : { kind: 'end' }).catch(() => {});
|
|
104
|
+
};
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
// A candidate can reach the rendezvous before the description it belongs to:
|
|
108
|
+
// gathering starts the moment the other side sets its local description. One
|
|
109
|
+
// applied too early is refused, so it waits here until the description lands.
|
|
110
|
+
async function applySignal(pc, signal) {
|
|
111
|
+
pc.__pendingCandidates ??= [];
|
|
112
|
+
if (signal.kind === 'offer' || signal.kind === 'answer') {
|
|
113
|
+
await pc.setRemoteDescription({ type: signal.kind, sdp: signal.sdp });
|
|
114
|
+
pc.__remoteSet = true;
|
|
115
|
+
for (const candidate of pc.__pendingCandidates.splice(0)) {
|
|
116
|
+
await pc.addIceCandidate(candidate).catch(() => {});
|
|
117
|
+
}
|
|
118
|
+
} else if (signal.kind === 'candidate' && signal.candidate) {
|
|
119
|
+
if (!pc.__remoteSet) pc.__pendingCandidates.push(signal.candidate);
|
|
120
|
+
else await pc.addIceCandidate(signal.candidate).catch(() => {});
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/**
|
|
125
|
+
* Run inside a local freertc server: register with the rendezvous and accept
|
|
126
|
+
* punched connections, handing each one to `onSocket` as a socket the relay
|
|
127
|
+
* treats exactly like a WebSocket client.
|
|
128
|
+
*/
|
|
129
|
+
export function listenForPunches({
|
|
130
|
+
rendezvousUrl,
|
|
131
|
+
listenerId,
|
|
132
|
+
name = '',
|
|
133
|
+
onSocket,
|
|
134
|
+
iceServers = DEFAULT_ICE_SERVERS,
|
|
135
|
+
RTCPeerConnection = null,
|
|
136
|
+
fetchImpl = globalThis.fetch,
|
|
137
|
+
log = () => {},
|
|
138
|
+
}) {
|
|
139
|
+
let stopped = false;
|
|
140
|
+
const controller = new AbortController();
|
|
141
|
+
const sessions = new Map(); // session -> { pc, remote }
|
|
142
|
+
|
|
143
|
+
const register = () => post(rendezvousUrl, '/api/v1/punch/register', { listenerId, info: { name } }, fetchImpl)
|
|
144
|
+
.then(() => log(`registered as ${listenerId}`))
|
|
145
|
+
.catch((error) => log(`register failed: ${error.message}`));
|
|
146
|
+
register();
|
|
147
|
+
const timer = setInterval(register, REGISTER_EVERY_MS);
|
|
148
|
+
timer.unref?.();
|
|
149
|
+
|
|
150
|
+
const accept = async (from, session, signal) => {
|
|
151
|
+
const PeerConnection = await loadRTCPeerConnection(RTCPeerConnection);
|
|
152
|
+
const pc = new PeerConnection({ iceServers });
|
|
153
|
+
sessions.set(session, { pc, remote: from });
|
|
154
|
+
const send = (out) => post(rendezvousUrl, '/api/v1/punch/send', { to: from, from: listenerId, session, signal: out }, fetchImpl);
|
|
155
|
+
bridgeIce(pc, send);
|
|
156
|
+
pc.ondatachannel = (event) => {
|
|
157
|
+
const channel = event.channel;
|
|
158
|
+
const ready = () => {
|
|
159
|
+
log(`punched channel open with ${from}`);
|
|
160
|
+
onSocket(new DataChannelSocket(channel, pc, { remote: from, session }));
|
|
161
|
+
};
|
|
162
|
+
if (channel.readyState === 'open') ready(); else channel.onopen = ready;
|
|
163
|
+
};
|
|
164
|
+
await applySignal(pc, signal);
|
|
165
|
+
const answer = await pc.createAnswer();
|
|
166
|
+
await pc.setLocalDescription(answer);
|
|
167
|
+
await send({ kind: 'answer', sdp: pc.localDescription.sdp });
|
|
168
|
+
};
|
|
169
|
+
|
|
170
|
+
(async () => {
|
|
171
|
+
while (!stopped) {
|
|
172
|
+
let messages = [];
|
|
173
|
+
try {
|
|
174
|
+
messages = await poll(rendezvousUrl, listenerId, POLL_WAIT_MS, fetchImpl, controller.signal);
|
|
175
|
+
} catch (error) {
|
|
176
|
+
if (stopped) break;
|
|
177
|
+
log(`poll failed: ${error.message}`);
|
|
178
|
+
await new Promise((resolve) => setTimeout(resolve, 2_000));
|
|
179
|
+
continue;
|
|
180
|
+
}
|
|
181
|
+
for (const { from, session, signal } of messages) {
|
|
182
|
+
try {
|
|
183
|
+
if (signal?.kind === 'offer' && !sessions.has(session)) await accept(from, session, signal);
|
|
184
|
+
else if (sessions.has(session)) await applySignal(sessions.get(session).pc, signal);
|
|
185
|
+
} catch (error) {
|
|
186
|
+
log(`session ${session} failed: ${error.message}`);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
})();
|
|
191
|
+
|
|
192
|
+
return {
|
|
193
|
+
stop() {
|
|
194
|
+
stopped = true;
|
|
195
|
+
clearInterval(timer);
|
|
196
|
+
controller.abort();
|
|
197
|
+
for (const { pc } of sessions.values()) { try { pc.close(); } catch {} }
|
|
198
|
+
},
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/**
|
|
203
|
+
* Reach a local freertc server that is listening for punches. Resolves with a
|
|
204
|
+
* socket that speaks the relay protocol, as a WebSocket to it would.
|
|
205
|
+
*/
|
|
206
|
+
export async function dialPunched({
|
|
207
|
+
rendezvousUrl,
|
|
208
|
+
listenerId,
|
|
209
|
+
iceServers = DEFAULT_ICE_SERVERS,
|
|
210
|
+
RTCPeerConnection = null,
|
|
211
|
+
fetchImpl = globalThis.fetch,
|
|
212
|
+
timeoutMs = DIAL_TIMEOUT_MS,
|
|
213
|
+
log = () => {},
|
|
214
|
+
}) {
|
|
215
|
+
const PeerConnection = await loadRTCPeerConnection(RTCPeerConnection);
|
|
216
|
+
const selfId = randomId('dialer');
|
|
217
|
+
const session = randomId('punch');
|
|
218
|
+
const pc = new PeerConnection({ iceServers });
|
|
219
|
+
const channel = pc.createDataChannel(CHANNEL_LABEL);
|
|
220
|
+
const send = (signal) => post(rendezvousUrl, '/api/v1/punch/send', { to: listenerId, from: selfId, session, signal }, fetchImpl);
|
|
221
|
+
bridgeIce(pc, send);
|
|
222
|
+
const controller = new AbortController();
|
|
223
|
+
|
|
224
|
+
const opened = new Promise((resolve, reject) => {
|
|
225
|
+
const timer = setTimeout(() => reject(new Error(`No punched channel to ${listenerId} within ${timeoutMs}ms`)), timeoutMs);
|
|
226
|
+
channel.onopen = () => { clearTimeout(timer); resolve(); };
|
|
227
|
+
});
|
|
228
|
+
|
|
229
|
+
const offer = await pc.createOffer();
|
|
230
|
+
await pc.setLocalDescription(offer);
|
|
231
|
+
await send({ kind: 'offer', sdp: pc.localDescription.sdp });
|
|
232
|
+
log(`offer sent to ${listenerId}`);
|
|
233
|
+
|
|
234
|
+
(async () => {
|
|
235
|
+
while (!controller.signal.aborted) {
|
|
236
|
+
let messages = [];
|
|
237
|
+
try {
|
|
238
|
+
messages = await poll(rendezvousUrl, selfId, 5_000, fetchImpl, controller.signal);
|
|
239
|
+
} catch {
|
|
240
|
+
if (controller.signal.aborted) break;
|
|
241
|
+
continue;
|
|
242
|
+
}
|
|
243
|
+
for (const { session: incoming, signal } of messages) {
|
|
244
|
+
if (incoming === session) await applySignal(pc, signal).catch(() => {});
|
|
245
|
+
}
|
|
246
|
+
}
|
|
247
|
+
})();
|
|
248
|
+
|
|
249
|
+
try {
|
|
250
|
+
await opened;
|
|
251
|
+
} finally {
|
|
252
|
+
// The introduction is over either way: stop asking the rendezvous.
|
|
253
|
+
controller.abort();
|
|
254
|
+
}
|
|
255
|
+
log(`punched channel open to ${listenerId}`);
|
|
256
|
+
return new DataChannelSocket(channel, pc, { remote: listenerId, session });
|
|
257
|
+
}
|