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
package/src/kademlia.js
ADDED
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { sha256 } from 'unsea';
|
|
2
|
+
|
|
3
|
+
export const KADEMLIA_ID_BITS = 256;
|
|
4
|
+
export const KADEMLIA_ID_HEX_LENGTH = KADEMLIA_ID_BITS / 4;
|
|
5
|
+
export const DEFAULT_K_BUCKET_SIZE = 20;
|
|
6
|
+
export const DEFAULT_LOOKUP_ALPHA = 3;
|
|
7
|
+
export const DEFAULT_REPLICATION_FACTOR = 5;
|
|
8
|
+
|
|
9
|
+
const NODE_ID_RE = /^[0-9a-f]{64}$/;
|
|
10
|
+
|
|
11
|
+
export function isNodeId(value) {
|
|
12
|
+
return typeof value === 'string' && NODE_ID_RE.test(value);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
function encodeCanonical(value, seen) {
|
|
16
|
+
if (value === null) return 'null';
|
|
17
|
+
|
|
18
|
+
const type = typeof value;
|
|
19
|
+
if (type === 'string' || type === 'boolean') return JSON.stringify(value);
|
|
20
|
+
if (type === 'number') {
|
|
21
|
+
if (!Number.isFinite(value)) throw new TypeError('Canonical JSON only supports finite numbers');
|
|
22
|
+
return JSON.stringify(value);
|
|
23
|
+
}
|
|
24
|
+
if (type !== 'object') throw new TypeError(`Canonical JSON does not support ${type}`);
|
|
25
|
+
if (seen.has(value)) throw new TypeError('Canonical JSON does not support circular values');
|
|
26
|
+
|
|
27
|
+
seen.add(value);
|
|
28
|
+
let result;
|
|
29
|
+
if (Array.isArray(value)) {
|
|
30
|
+
result = `[${value.map((item) => encodeCanonical(item, seen)).join(',')}]`;
|
|
31
|
+
} else {
|
|
32
|
+
const entries = Object.keys(value)
|
|
33
|
+
.sort()
|
|
34
|
+
.map((key) => `${JSON.stringify(key)}:${encodeCanonical(value[key], seen)}`);
|
|
35
|
+
result = `{${entries.join(',')}}`;
|
|
36
|
+
}
|
|
37
|
+
seen.delete(value);
|
|
38
|
+
return result;
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** Stable JSON encoding used for signatures and routing-key derivation. */
|
|
42
|
+
export function canonicalJson(value) {
|
|
43
|
+
return encodeCanonical(value, new Set());
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export async function relayNodeId(publicKey) {
|
|
47
|
+
if (typeof publicKey !== 'string' || !publicKey) {
|
|
48
|
+
throw new TypeError('Relay public key is required');
|
|
49
|
+
}
|
|
50
|
+
return sha256(canonicalJson(['freertc-kad', 1, 'relay', publicKey]));
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export async function scopeRoutingKey(network, room) {
|
|
54
|
+
return sha256(canonicalJson(['freertc-kad', 1, 'scope', network, room]));
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export async function peerRoutingKey(network, room, peerId) {
|
|
58
|
+
return sha256(canonicalJson(['freertc-kad', 1, 'peer', network, room, peerId]));
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Return the Kademlia bucket number for another node. Bucket zero contains
|
|
63
|
+
* XOR distances [1, 2); bucket 255 contains distances [2^255, 2^256).
|
|
64
|
+
*/
|
|
65
|
+
export function bucketIndex(selfId, otherId) {
|
|
66
|
+
if (!isNodeId(selfId) || !isNodeId(otherId)) throw new TypeError('Kademlia IDs must be 64 lowercase hex characters');
|
|
67
|
+
for (let index = 0; index < KADEMLIA_ID_HEX_LENGTH; index += 1) {
|
|
68
|
+
const xorNibble = Number.parseInt(selfId[index], 16) ^ Number.parseInt(otherId[index], 16);
|
|
69
|
+
if (xorNibble !== 0) {
|
|
70
|
+
return ((KADEMLIA_ID_HEX_LENGTH - index - 1) * 4) + Math.floor(Math.log2(xorNibble));
|
|
71
|
+
}
|
|
72
|
+
}
|
|
73
|
+
return -1;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export function xorDistanceHex(leftId, rightId) {
|
|
77
|
+
if (!isNodeId(leftId) || !isNodeId(rightId)) throw new TypeError('Kademlia IDs must be 64 lowercase hex characters');
|
|
78
|
+
let result = '';
|
|
79
|
+
for (let index = 0; index < KADEMLIA_ID_HEX_LENGTH; index += 1) {
|
|
80
|
+
result += (Number.parseInt(leftId[index], 16) ^ Number.parseInt(rightId[index], 16)).toString(16);
|
|
81
|
+
}
|
|
82
|
+
return result;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** Sort signed node records by XOR distance without relying on BigInt. */
|
|
86
|
+
export function selectClosestNodes(nodes, targetId, limit = DEFAULT_K_BUCKET_SIZE) {
|
|
87
|
+
if (!isNodeId(targetId)) throw new TypeError('Kademlia target must be a 64-character lowercase hex ID');
|
|
88
|
+
const unique = new Map();
|
|
89
|
+
for (const node of nodes || []) {
|
|
90
|
+
if (!node || !isNodeId(node.node_id)) continue;
|
|
91
|
+
unique.set(node.node_id, node);
|
|
92
|
+
}
|
|
93
|
+
return Array.from(unique.values())
|
|
94
|
+
.map((node) => ({ node, distance: xorDistanceHex(node.node_id, targetId) }))
|
|
95
|
+
.sort((left, right) => {
|
|
96
|
+
if (left.distance !== right.distance) return left.distance < right.distance ? -1 : 1;
|
|
97
|
+
return left.node.node_id < right.node.node_id ? -1 : left.node.node_id > right.node.node_id ? 1 : 0;
|
|
98
|
+
})
|
|
99
|
+
.slice(0, Math.max(0, limit))
|
|
100
|
+
.map(({ node }) => node);
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Keep at most k most-recently-seen contacts in each XOR-distance bucket. */
|
|
104
|
+
export function compactRoutingTable(selfId, nodes, k = DEFAULT_K_BUCKET_SIZE) {
|
|
105
|
+
const buckets = Array.from({ length: KADEMLIA_ID_BITS }, () => []);
|
|
106
|
+
for (const node of nodes || []) {
|
|
107
|
+
if (!node || node.node_id === selfId || !isNodeId(node.node_id)) continue;
|
|
108
|
+
const index = bucketIndex(selfId, node.node_id);
|
|
109
|
+
if (index >= 0) buckets[index].push(node);
|
|
110
|
+
}
|
|
111
|
+
return buckets.flatMap((bucket) => bucket
|
|
112
|
+
.sort((left, right) => Number(right.last_seen_ms || 0) - Number(left.last_seen_ms || 0))
|
|
113
|
+
.slice(0, Math.max(1, k)));
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/** Prefer healthy providers while keeping the result deterministic. */
|
|
117
|
+
export function rankProviderRecords(records, limit = DEFAULT_REPLICATION_FACTOR) {
|
|
118
|
+
const unique = new Map();
|
|
119
|
+
for (const record of records || []) {
|
|
120
|
+
if (!record?.node_id || !record?.url) continue;
|
|
121
|
+
const key = `${record.kind}:${record.node_id}`;
|
|
122
|
+
const previous = unique.get(key);
|
|
123
|
+
if (!previous || Number(record.sequence || 0) > Number(previous.sequence || 0)) unique.set(key, record);
|
|
124
|
+
}
|
|
125
|
+
return Array.from(unique.values())
|
|
126
|
+
.sort((left, right) => {
|
|
127
|
+
const leftCapacity = Math.max(1, Number(left.capacity || 1));
|
|
128
|
+
const rightCapacity = Math.max(1, Number(right.capacity || 1));
|
|
129
|
+
const loadDifference = (Number(left.connections || 0) / leftCapacity) - (Number(right.connections || 0) / rightCapacity);
|
|
130
|
+
return loadDifference || left.node_id.localeCompare(right.node_id);
|
|
131
|
+
})
|
|
132
|
+
.slice(0, Math.max(0, limit));
|
|
133
|
+
}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
// Accounts between linked local relays (src/node/relay-links.js). When a link
|
|
2
|
+
// opens, and every 10 minutes after, each side takes the other's whole
|
|
3
|
+
// PigeonIdP store over it (pigeonidp/relay exportRecords / importRecords), so
|
|
4
|
+
// a relay has every account before anyone asks for it, also after a network
|
|
5
|
+
// change. Only a linked relay can ask: a link proves both ends, and with
|
|
6
|
+
// post-quantum keys it is encrypted end to end.
|
|
7
|
+
|
|
8
|
+
import { signMessage, verifyMessage } from 'unsea';
|
|
9
|
+
import { canonicalJson, relayNodeId } from '../kademlia.js';
|
|
10
|
+
|
|
11
|
+
export const ACCOUNT_SYNC_PATH = '/api/v1/idp/sync';
|
|
12
|
+
export const ACCOUNT_SYNC_EVERY_MS = 10 * 60_000;
|
|
13
|
+
|
|
14
|
+
export function createAccountSync({ store, event = () => {}, log = () => {} }) {
|
|
15
|
+
/** The answer to a linked relay asking for the store, or null for any other request. */
|
|
16
|
+
function handleLinkRequest(request) {
|
|
17
|
+
if (new URL(request.url).pathname !== ACCOUNT_SYNC_PATH) return null;
|
|
18
|
+
const current = store();
|
|
19
|
+
if (!current) return new Response(JSON.stringify({ ok: false, error: 'no accounts here' }), { status: 404 });
|
|
20
|
+
return new Response(JSON.stringify({ ok: true, records: current.exportRecords() }), {
|
|
21
|
+
headers: { 'Content-Type': 'application/json' },
|
|
22
|
+
});
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** Take what the relay at the other end of a link holds. */
|
|
26
|
+
async function syncOver(nodeId, link) {
|
|
27
|
+
const current = store();
|
|
28
|
+
if (!current || !link?.open) return null;
|
|
29
|
+
const who = `relay ${String(nodeId).slice(0, 8)}`;
|
|
30
|
+
try {
|
|
31
|
+
const response = await link.request('POST', ACCOUNT_SYNC_PATH, [['content-type', 'application/json']], new TextEncoder().encode('{}'));
|
|
32
|
+
const answer = await response.json().catch(() => null);
|
|
33
|
+
if (!response.ok || !answer?.ok) {
|
|
34
|
+
event(`accounts: ${who}: no sync (${answer?.error || `answered ${response.status}`})`);
|
|
35
|
+
return null;
|
|
36
|
+
}
|
|
37
|
+
const result = await current.importRecords(answer.records, { from: who });
|
|
38
|
+
if (result.stored) log(`accounts: ${result.stored} from ${who}`);
|
|
39
|
+
return result;
|
|
40
|
+
} catch (error) {
|
|
41
|
+
event(`accounts: ${who}: sync failed (${error?.message || error})`);
|
|
42
|
+
return null;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
return { handleLinkRequest, syncOver };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// ---------------------------------------------------------------------------
|
|
50
|
+
// The same exchange without a link: over the relays' ordinary federation path
|
|
51
|
+
// (POST /api/v1/idp), which works wherever one relay can reach another. That
|
|
52
|
+
// path is open to anyone, so the request is signed by the asking relay's own
|
|
53
|
+
// key (with its post-quantum key, when it has one), and a relay hands over its
|
|
54
|
+
// store only to a relay it already knows as a local relay of the federation,
|
|
55
|
+
// showing the post-quantum key pinned for it, if one is.
|
|
56
|
+
|
|
57
|
+
export const ACCOUNT_SYNC_ACTION = 'idp-sync';
|
|
58
|
+
const SYNC_REQUEST_MAX_AGE_MS = 5 * 60_000;
|
|
59
|
+
|
|
60
|
+
const syncRequestText = (nodeId, target, at) => canonicalJson(['freertc-idp-sync', 1, String(nodeId), String(target), Number(at)]);
|
|
61
|
+
|
|
62
|
+
/** A signed request for another relay's store. target is that relay's federation URL. */
|
|
63
|
+
export async function createSyncRequest({ identity, pqIdentity = null, target, now = Date.now() }) {
|
|
64
|
+
const text = syncRequestText(identity.nodeId, target, now);
|
|
65
|
+
return {
|
|
66
|
+
action: ACCOUNT_SYNC_ACTION,
|
|
67
|
+
node_id: identity.nodeId,
|
|
68
|
+
public_key: identity.publicKey,
|
|
69
|
+
...(pqIdentity ? { pq_public_key: pqIdentity.qpub } : {}),
|
|
70
|
+
target,
|
|
71
|
+
at: now,
|
|
72
|
+
sig: await signMessage(text, pqIdentity || identity.privateKey),
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Whether a sync request comes from a local relay this one knows: signed by
|
|
78
|
+
* the key its node id comes from (and its pinned post-quantum key), recent,
|
|
79
|
+
* and meant for this relay.
|
|
80
|
+
*/
|
|
81
|
+
export async function verifySyncRequest(body, { selfUrl, knownLocalNodeIds, pinnedPqKey = () => null, now = Date.now() }) {
|
|
82
|
+
try {
|
|
83
|
+
if (body?.action !== ACCOUNT_SYNC_ACTION || typeof body.sig !== 'string') return { ok: false, error: 'malformed' };
|
|
84
|
+
if (Math.abs(now - Number(body.at)) > SYNC_REQUEST_MAX_AGE_MS) return { ok: false, error: 'stale request' };
|
|
85
|
+
const same = (a, b) => { try { return new URL(String(a)).toString() === new URL(String(b)).toString(); } catch { return false; } };
|
|
86
|
+
if (!same(body.target, selfUrl)) return { ok: false, error: 'meant for another relay' };
|
|
87
|
+
if (await relayNodeId(body.public_key) !== body.node_id) return { ok: false, error: 'key does not match node id' };
|
|
88
|
+
const known = await knownLocalNodeIds();
|
|
89
|
+
if (!known.has(body.node_id)) return { ok: false, error: 'not a local relay this one knows' };
|
|
90
|
+
const pinned = pinnedPqKey(body.node_id);
|
|
91
|
+
if (pinned && body.pq_public_key !== pinned) return { ok: false, error: 'not the post-quantum key this relay showed before' };
|
|
92
|
+
const keys = typeof body.pq_public_key === 'string' ? { pub: body.public_key, qpub: body.pq_public_key } : body.public_key;
|
|
93
|
+
if (!await verifyMessage(syncRequestText(body.node_id, body.target, body.at), body.sig, keys)) return { ok: false, error: 'bad signature' };
|
|
94
|
+
return { ok: true };
|
|
95
|
+
} catch (error) {
|
|
96
|
+
return { ok: false, error: String(error?.message || error) };
|
|
97
|
+
}
|
|
98
|
+
}
|
|
@@ -0,0 +1,92 @@
|
|
|
1
|
+
// What this relay would cost on Cloudflare's free plan, counted while it runs
|
|
2
|
+
// under Node. The Node relay runs the worker's own code, so every request,
|
|
3
|
+
// WebSocket message and D1 query here is one the worker would see too. Each
|
|
4
|
+
// event is classified the way the worker deployment bills it:
|
|
5
|
+
//
|
|
6
|
+
// Worker request every HTTP request and WebSocket upgrade that reaches the relay
|
|
7
|
+
// DO request a request the worker hands to a Durable Object: the relay
|
|
8
|
+
// coordinator (/ws upgrades, /health, /debug/state, POST
|
|
9
|
+
// /api/v1/relay) or a relay tunnel (/t/<node id>/...)
|
|
10
|
+
// DO WS message a message arriving on a socket a Durable Object holds (peer
|
|
11
|
+
// sockets, tunnel sockets). Cloudflare bills these at 20:1 as
|
|
12
|
+
// DO requests. Tunnel keepalive pings are auto-answered by the
|
|
13
|
+
// runtime and not billed, so they are not counted.
|
|
14
|
+
// D1 read / write one statement each; rows written from the statement's changes
|
|
15
|
+
//
|
|
16
|
+
// GET /debug/cost on a Node relay returns the counters.
|
|
17
|
+
|
|
18
|
+
import { TUNNEL_PING } from '../tunnel/frames.js';
|
|
19
|
+
|
|
20
|
+
const DO_PATHS = new Set(['/health', '/debug/state']);
|
|
21
|
+
const WRITE_SQL = /^\s*(insert|update|delete|replace|create|drop|alter)\b/i;
|
|
22
|
+
|
|
23
|
+
export function createCostMeter() {
|
|
24
|
+
const counts = {
|
|
25
|
+
workerRequests: 0,
|
|
26
|
+
doRequests: 0,
|
|
27
|
+
doWsMessages: 0,
|
|
28
|
+
d1Reads: 0,
|
|
29
|
+
d1Writes: 0,
|
|
30
|
+
d1RowsWritten: 0,
|
|
31
|
+
byPath: {},
|
|
32
|
+
};
|
|
33
|
+
const bump = (key) => { counts.byPath[key] = (counts.byPath[key] ?? 0) + 1; };
|
|
34
|
+
const pathKey = (method, pathname, upgrade) => {
|
|
35
|
+
const base = pathname.startsWith('/t/') ? `/t/*/${pathname.split('/').slice(3).join('/')}` : pathname;
|
|
36
|
+
return `${upgrade ? 'WS' : method} ${base}`;
|
|
37
|
+
};
|
|
38
|
+
|
|
39
|
+
return {
|
|
40
|
+
counts,
|
|
41
|
+
/** One HTTP request or upgrade reaching the relay. */
|
|
42
|
+
request(method, pathname, upgrade = false) {
|
|
43
|
+
counts.workerRequests += 1;
|
|
44
|
+
bump(pathKey(method, pathname, upgrade));
|
|
45
|
+
const isDo = pathname.startsWith('/t/')
|
|
46
|
+
|| (upgrade && pathname === '/ws')
|
|
47
|
+
|| DO_PATHS.has(pathname)
|
|
48
|
+
|| (method === 'POST' && pathname === '/api/v1/relay');
|
|
49
|
+
if (isDo) counts.doRequests += 1;
|
|
50
|
+
},
|
|
51
|
+
/** One message arriving on a socket a Durable Object would hold. */
|
|
52
|
+
wsMessage(data) {
|
|
53
|
+
if (String(data) === TUNNEL_PING) return;
|
|
54
|
+
counts.doWsMessages += 1;
|
|
55
|
+
},
|
|
56
|
+
/** Wrap a D1 binding so every statement it runs is counted. */
|
|
57
|
+
wrapD1(db) {
|
|
58
|
+
const meter = counts;
|
|
59
|
+
const wrapStatement = (sql, statement) => ({
|
|
60
|
+
bind: (...values) => wrapStatement(sql, statement.bind(...values)),
|
|
61
|
+
async all() { meter.d1Reads += 1; return statement.all(); },
|
|
62
|
+
async first(column) { meter.d1Reads += 1; return statement.first(column); },
|
|
63
|
+
async run() {
|
|
64
|
+
const result = await statement.run();
|
|
65
|
+
if (WRITE_SQL.test(sql)) {
|
|
66
|
+
meter.d1Writes += 1;
|
|
67
|
+
meter.d1RowsWritten += Number(result?.meta?.changes ?? 0);
|
|
68
|
+
} else {
|
|
69
|
+
meter.d1Reads += 1;
|
|
70
|
+
}
|
|
71
|
+
return result;
|
|
72
|
+
},
|
|
73
|
+
});
|
|
74
|
+
return {
|
|
75
|
+
...db,
|
|
76
|
+
prepare: (sql) => wrapStatement(sql, db.prepare(sql)),
|
|
77
|
+
async batch(statements) {
|
|
78
|
+
const results = [];
|
|
79
|
+
for (const statement of statements) results.push(await statement.run());
|
|
80
|
+
return results;
|
|
81
|
+
},
|
|
82
|
+
};
|
|
83
|
+
},
|
|
84
|
+
snapshot() {
|
|
85
|
+
return {
|
|
86
|
+
...counts,
|
|
87
|
+
doWsMessagesBilled: counts.doWsMessages / 20,
|
|
88
|
+
byPath: { ...counts.byPath },
|
|
89
|
+
};
|
|
90
|
+
},
|
|
91
|
+
};
|
|
92
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
// D1 on a local SQLite file, so a relay running under Node executes the same
|
|
2
|
+
// SQL the Cloudflare worker does. D1 is SQLite; this is the subset of its
|
|
3
|
+
// binding the relay uses: prepare(sql).bind(...).all() / .run() / .first().
|
|
4
|
+
import { mkdirSync, readdirSync, readFileSync } from 'node:fs';
|
|
5
|
+
import path from 'node:path';
|
|
6
|
+
|
|
7
|
+
const MIGRATIONS_TABLE = 'freertc_node_migrations';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* D1 SQL numbers its parameters (?1, ?2) and binds them by position. Node's
|
|
11
|
+
* SQLite before 22.13 refuses that ("column index out of range"), so each
|
|
12
|
+
* statement is rewritten to plain ? placeholders with the values reordered to
|
|
13
|
+
* match. Quoted text and identifiers are left alone.
|
|
14
|
+
*/
|
|
15
|
+
export function positionalSql(sql) {
|
|
16
|
+
const order = [];
|
|
17
|
+
let out = '';
|
|
18
|
+
let highest = 0;
|
|
19
|
+
for (let i = 0; i < sql.length; i += 1) {
|
|
20
|
+
const ch = sql[i];
|
|
21
|
+
if (ch === "'" || ch === '"' || ch === '`') {
|
|
22
|
+
const end = sql.indexOf(ch, i + 1);
|
|
23
|
+
const stop = end === -1 ? sql.length : end + 1;
|
|
24
|
+
out += sql.slice(i, stop);
|
|
25
|
+
i = stop - 1;
|
|
26
|
+
continue;
|
|
27
|
+
}
|
|
28
|
+
if (ch === '?') {
|
|
29
|
+
let j = i + 1;
|
|
30
|
+
while (j < sql.length && sql[j] >= '0' && sql[j] <= '9') j += 1;
|
|
31
|
+
const index = j > i + 1 ? Number(sql.slice(i + 1, j)) : highest + 1;
|
|
32
|
+
highest = Math.max(highest, index);
|
|
33
|
+
order.push(index - 1);
|
|
34
|
+
out += '?';
|
|
35
|
+
i = j - 1;
|
|
36
|
+
continue;
|
|
37
|
+
}
|
|
38
|
+
out += ch;
|
|
39
|
+
}
|
|
40
|
+
return { sql: out, order };
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
function statementApi(prepared, given = []) {
|
|
44
|
+
const { statement, order } = prepared;
|
|
45
|
+
const values = order.map((index) => given[index] ?? null);
|
|
46
|
+
return {
|
|
47
|
+
bind: (...next) => statementApi(prepared, next),
|
|
48
|
+
async all() {
|
|
49
|
+
return { success: true, results: statement.all(...values) };
|
|
50
|
+
},
|
|
51
|
+
async run() {
|
|
52
|
+
const result = statement.run(...values);
|
|
53
|
+
return { success: true, meta: { changes: Number(result.changes), last_row_id: Number(result.lastInsertRowid) } };
|
|
54
|
+
},
|
|
55
|
+
async first(column) {
|
|
56
|
+
const row = statement.get(...values);
|
|
57
|
+
if (!row) return null;
|
|
58
|
+
return column ? row[column] : row;
|
|
59
|
+
},
|
|
60
|
+
};
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Open (creating if needed) a SQLite database at `filename` and apply every
|
|
65
|
+
* migration in `migrationsDir` that has not been applied to it yet.
|
|
66
|
+
*/
|
|
67
|
+
export async function openSqliteD1({ filename, migrationsDir }) {
|
|
68
|
+
const { DatabaseSync } = await import('node:sqlite');
|
|
69
|
+
if (filename !== ':memory:') mkdirSync(path.dirname(filename), { recursive: true });
|
|
70
|
+
const db = new DatabaseSync(filename);
|
|
71
|
+
db.exec('PRAGMA journal_mode = WAL');
|
|
72
|
+
db.exec(`CREATE TABLE IF NOT EXISTS ${MIGRATIONS_TABLE} (name TEXT PRIMARY KEY, applied_at TEXT NOT NULL)`);
|
|
73
|
+
const applied = new Set(db.prepare(`SELECT name FROM ${MIGRATIONS_TABLE}`).all().map((row) => row.name));
|
|
74
|
+
const files = readdirSync(migrationsDir).filter((name) => name.endsWith('.sql')).sort();
|
|
75
|
+
for (const name of files) {
|
|
76
|
+
if (applied.has(name)) continue;
|
|
77
|
+
db.exec('BEGIN');
|
|
78
|
+
try {
|
|
79
|
+
db.exec(readFileSync(path.join(migrationsDir, name), 'utf8'));
|
|
80
|
+
db.prepare(`INSERT INTO ${MIGRATIONS_TABLE} (name, applied_at) VALUES (?, ?)`).run(name, new Date().toISOString());
|
|
81
|
+
db.exec('COMMIT');
|
|
82
|
+
} catch (error) {
|
|
83
|
+
db.exec('ROLLBACK');
|
|
84
|
+
throw new Error(`Migration ${name} failed: ${error.message}`);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
const statements = new Map();
|
|
88
|
+
return {
|
|
89
|
+
raw: db,
|
|
90
|
+
prepare(sql) {
|
|
91
|
+
let prepared = statements.get(sql);
|
|
92
|
+
if (!prepared) {
|
|
93
|
+
const rewritten = positionalSql(sql);
|
|
94
|
+
prepared = { statement: db.prepare(rewritten.sql), order: rewritten.order };
|
|
95
|
+
statements.set(sql, prepared);
|
|
96
|
+
}
|
|
97
|
+
return statementApi(prepared);
|
|
98
|
+
},
|
|
99
|
+
async batch(prepared) {
|
|
100
|
+
const results = [];
|
|
101
|
+
for (const item of prepared) results.push(await item.run());
|
|
102
|
+
return results;
|
|
103
|
+
},
|
|
104
|
+
close() {
|
|
105
|
+
db.close();
|
|
106
|
+
},
|
|
107
|
+
};
|
|
108
|
+
}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
// Where a Node relay keeps its identity, name, certificate and database: one
|
|
2
|
+
// folder per user (~/.freertc-relay), wherever the relay is started from, so a
|
|
3
|
+
// relay keeps its id and its https name across clones, folders and drives.
|
|
4
|
+
//
|
|
5
|
+
// FREERTC_DATA_DIR still chooses another folder. The first time the home
|
|
6
|
+
// folder has no identity, the relay looks for one it had before (a
|
|
7
|
+
// .freertc-relay folder next to a freertc clone, in the home folder or on an
|
|
8
|
+
// attached drive), prefers one with a name (names.json), and copies it home.
|
|
9
|
+
import { cpSync, existsSync, readdirSync, statSync } from 'node:fs';
|
|
10
|
+
import os from 'node:os';
|
|
11
|
+
import path from 'node:path';
|
|
12
|
+
|
|
13
|
+
const FOLDER = '.freertc-relay';
|
|
14
|
+
const SKIP = new Set(['node_modules', 'Library', '.Trash', '.git', '.npm', '.cache', '.nvm', '.cargo', '.rustup', 'Applications']);
|
|
15
|
+
|
|
16
|
+
function relayFolders(root, depth, out) {
|
|
17
|
+
if (depth < 0) return;
|
|
18
|
+
let entries;
|
|
19
|
+
try { entries = readdirSync(root, { withFileTypes: true }); } catch { return; }
|
|
20
|
+
for (const entry of entries) {
|
|
21
|
+
if (!entry.isDirectory()) continue;
|
|
22
|
+
const full = path.join(root, entry.name);
|
|
23
|
+
if (entry.name === FOLDER) {
|
|
24
|
+
if (existsSync(path.join(full, 'relay-identity.json'))) out.push(full);
|
|
25
|
+
continue;
|
|
26
|
+
}
|
|
27
|
+
if (SKIP.has(entry.name) || (entry.name.startsWith('.') && entry.name !== FOLDER)) continue;
|
|
28
|
+
relayFolders(full, depth - 1, out);
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function mtime(file) {
|
|
33
|
+
try { return statSync(file).mtimeMs; } catch { return 0; }
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/**
|
|
37
|
+
* The relay's data folder. `log` hears where an earlier identity was found.
|
|
38
|
+
*/
|
|
39
|
+
export function resolveDataDir({ env = process.env, cwd = process.cwd(), home = os.homedir(), volumes = '/Volumes', log = () => {} } = {}) {
|
|
40
|
+
if (env.FREERTC_DATA_DIR) return path.resolve(env.FREERTC_DATA_DIR);
|
|
41
|
+
const dir = path.join(home, FOLDER);
|
|
42
|
+
if (existsSync(path.join(dir, 'relay-identity.json'))) return dir;
|
|
43
|
+
|
|
44
|
+
// None at home yet: the one this relay had before, if any.
|
|
45
|
+
const found = [];
|
|
46
|
+
if (existsSync(path.join(cwd, FOLDER, 'relay-identity.json'))) found.push(path.join(cwd, FOLDER));
|
|
47
|
+
relayFolders(home, 4, found);
|
|
48
|
+
let drives = [];
|
|
49
|
+
try { drives = readdirSync(volumes).map((name) => path.join(volumes, name)); } catch { /* not a Mac */ }
|
|
50
|
+
for (const drive of drives) relayFolders(drive, 4, found);
|
|
51
|
+
const unique = [...new Set(found)].filter((f) => f !== dir);
|
|
52
|
+
unique.sort((a, b) => {
|
|
53
|
+
const named = Number(existsSync(path.join(b, 'names.json'))) - Number(existsSync(path.join(a, 'names.json')));
|
|
54
|
+
return named || mtime(path.join(b, 'relay-identity.json')) - mtime(path.join(a, 'relay-identity.json'));
|
|
55
|
+
});
|
|
56
|
+
if (unique[0]) {
|
|
57
|
+
try {
|
|
58
|
+
cpSync(unique[0], dir, { recursive: true, errorOnExist: false, force: false });
|
|
59
|
+
log(`kept this relay's identity${existsSync(path.join(dir, 'names.json')) ? ' and name' : ''} from ${unique[0]} in ${dir}`);
|
|
60
|
+
} catch (error) {
|
|
61
|
+
log(`could not copy ${unique[0]} (${error?.message || error}); using it where it is`);
|
|
62
|
+
return unique[0];
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return dir;
|
|
66
|
+
}
|
|
@@ -0,0 +1,58 @@
|
|
|
1
|
+
// A Durable Object namespace for a relay running under Node: one instance per
|
|
2
|
+
// name, in this process. It covers what the relay's objects use: fetch(), and
|
|
3
|
+
// the WebSocket hibernation API (acceptWebSocket with tags, getWebSockets,
|
|
4
|
+
// serialize/deserializeAttachment, setWebSocketAutoResponse, and the
|
|
5
|
+
// webSocketMessage / webSocketClose / webSocketError handlers). Nothing
|
|
6
|
+
// hibernates here; the process simply keeps the object.
|
|
7
|
+
|
|
8
|
+
function createState(instanceOf) {
|
|
9
|
+
const sockets = new Map(); // socket → tags
|
|
10
|
+
let autoResponse = null;
|
|
11
|
+
return {
|
|
12
|
+
acceptWebSocket(socket, tags = []) {
|
|
13
|
+
sockets.set(socket, [...tags]);
|
|
14
|
+
socket.accept?.();
|
|
15
|
+
socket.addEventListener('message', (event) => {
|
|
16
|
+
if (autoResponse && event.data === autoResponse.request) {
|
|
17
|
+
try { socket.send(autoResponse.response); } catch {}
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
return instanceOf().webSocketMessage?.(socket, event.data);
|
|
21
|
+
});
|
|
22
|
+
socket.addEventListener('close', (event) => {
|
|
23
|
+
if (!sockets.delete(socket)) return;
|
|
24
|
+
return instanceOf().webSocketClose?.(socket, event.code, event.reason, true);
|
|
25
|
+
});
|
|
26
|
+
socket.addEventListener('error', (event) => {
|
|
27
|
+
if (!sockets.has(socket)) return;
|
|
28
|
+
return instanceOf().webSocketError?.(socket, event.error);
|
|
29
|
+
});
|
|
30
|
+
},
|
|
31
|
+
getWebSockets(tag) {
|
|
32
|
+
return [...sockets].filter(([, tags]) => tag === undefined || tags.includes(tag)).map(([socket]) => socket);
|
|
33
|
+
},
|
|
34
|
+
setWebSocketAutoResponse(pair) {
|
|
35
|
+
autoResponse = pair ?? null;
|
|
36
|
+
},
|
|
37
|
+
};
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function nodeDurableNamespace(ObjectClass, env) {
|
|
41
|
+
const instances = new Map();
|
|
42
|
+
const instance = (name) => {
|
|
43
|
+
let object = instances.get(name);
|
|
44
|
+
if (!object) {
|
|
45
|
+
object = new ObjectClass(createState(() => instances.get(name)), env);
|
|
46
|
+
instances.set(name, object);
|
|
47
|
+
}
|
|
48
|
+
return object;
|
|
49
|
+
};
|
|
50
|
+
return {
|
|
51
|
+
/** The live objects by name (Node only; a Worker namespace has no such list). */
|
|
52
|
+
instances,
|
|
53
|
+
idFromName: (name) => String(name),
|
|
54
|
+
get: (id) => ({
|
|
55
|
+
fetch: (input, init) => instance(String(id)).fetch(input instanceof Request && !init ? input : new Request(input, init)),
|
|
56
|
+
}),
|
|
57
|
+
};
|
|
58
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// LAN discovery for local relays: relays on one network find each other with
|
|
2
|
+
// a UDP broadcast and link over the LAN (relay-links.js), so federation
|
|
3
|
+
// between them never leaves the building.
|
|
4
|
+
//
|
|
5
|
+
// Every BEACON_EVERY_MS a relay broadcasts { freertc: 'lan', v: 1, node_id, port }
|
|
6
|
+
// to 255.255.255.255:FREERTC_LAN_PORT. A beacon is only a hint: the link it
|
|
7
|
+
// leads to is authenticated (each side signs the other's nonce with the key its
|
|
8
|
+
// node ID comes from), so a false beacon costs a failed handshake and nothing
|
|
9
|
+
// else. Loopback addresses are never linked, and nothing learned here is stored
|
|
10
|
+
// in the overlay: a relay is still federated under its public (tunnel) address,
|
|
11
|
+
// and a public relay still never publishes a private one.
|
|
12
|
+
|
|
13
|
+
import dgram from 'node:dgram';
|
|
14
|
+
import { networkInterfaces } from 'node:os';
|
|
15
|
+
|
|
16
|
+
export const DEFAULT_LAN_PORT = 41235;
|
|
17
|
+
const BEACON_EVERY_MS = 30_000;
|
|
18
|
+
|
|
19
|
+
/** Whether an IPv4 address is on a LAN this relay could link over (not loopback). */
|
|
20
|
+
export function isLanAddress(address) {
|
|
21
|
+
const v4 = /^(\d{1,3})\.(\d{1,3})\.\d{1,3}\.\d{1,3}$/.exec(String(address));
|
|
22
|
+
if (!v4) return false;
|
|
23
|
+
const [a, b] = [Number(v4[1]), Number(v4[2])];
|
|
24
|
+
return a === 10 || (a === 172 && b >= 16 && b <= 31) || (a === 192 && b === 168) || (a === 169 && b === 254);
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** Whether this host has any LAN address at all. */
|
|
28
|
+
export function hasLanAddress() {
|
|
29
|
+
return Object.values(networkInterfaces()).flat().some((entry) => entry && !entry.internal && entry.family === 'IPv4' && isLanAddress(entry.address));
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function startLanBeacon({ nodeId, port, lanPort = DEFAULT_LAN_PORT, onRelay, log = () => {} }) {
|
|
33
|
+
const socket = dgram.createSocket({ type: 'udp4', reuseAddr: true });
|
|
34
|
+
let timer = null;
|
|
35
|
+
socket.on('error', (error) => log(`LAN beacon: ${error.message}`));
|
|
36
|
+
socket.on('message', (raw, remote) => {
|
|
37
|
+
let beacon;
|
|
38
|
+
try { beacon = JSON.parse(String(raw)); } catch { return; }
|
|
39
|
+
if (beacon?.freertc !== 'lan' || beacon.v !== 1 || beacon.node_id === nodeId) return;
|
|
40
|
+
if (!/^[0-9a-f]{64}$/.test(String(beacon.node_id)) || !Number.isInteger(beacon.port)) return;
|
|
41
|
+
if (!isLanAddress(remote.address)) return;
|
|
42
|
+
onRelay(beacon.node_id, `ws://${remote.address}:${beacon.port}/api/v1/link`);
|
|
43
|
+
});
|
|
44
|
+
socket.bind(lanPort, () => {
|
|
45
|
+
try { socket.setBroadcast(true); } catch {}
|
|
46
|
+
const beacon = Buffer.from(JSON.stringify({ freertc: 'lan', v: 1, node_id: nodeId, port }));
|
|
47
|
+
const send = () => socket.send(beacon, lanPort, '255.255.255.255', () => {});
|
|
48
|
+
send();
|
|
49
|
+
timer = setInterval(send, BEACON_EVERY_MS);
|
|
50
|
+
timer.unref?.();
|
|
51
|
+
log(`LAN beacon on udp ${lanPort}`);
|
|
52
|
+
});
|
|
53
|
+
socket.unref?.();
|
|
54
|
+
return { stop() { clearInterval(timer); try { socket.close(); } catch {} } };
|
|
55
|
+
}
|