freertc 0.1.32 → 0.5.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +204 -12
- package/bin/freertc.mjs +38 -633
- package/migrations/0001_initial.sql +43 -0
- package/migrations/0002_kademlia_overlay.sql +32 -0
- package/migrations/0003_announcement_role.sql +4 -0
- package/package.json +44 -17
- package/public/app.js +746 -169
- package/public/icon-180.png +0 -0
- package/public/icon-192.png +0 -0
- package/public/index.html +200 -799
- package/public/pigeonlogo.svg +51 -0
- package/scripts/d1-schema.sql +36 -0
- package/scripts/deploy-cloudflare.mjs +190 -0
- package/scripts/dev-server.mjs +54 -7
- package/scripts/generate-relay-identity.mjs +14 -0
- package/scripts/name-setup.mjs +332 -0
- package/scripts/node-relay.mjs +1128 -0
- package/scripts/project-bootstrap.mjs +13 -6
- package/scripts/wrangler-install-wizard.mjs +21 -11
- package/src/client.js +3468 -0
- package/src/direct/cert.js +95 -0
- package/src/direct/common.js +187 -0
- package/src/direct/dial.js +47 -0
- package/src/direct/directory.js +230 -0
- package/src/direct/listener.js +201 -0
- package/src/direct/lookup.js +75 -0
- package/src/direct/names.js +150 -0
- package/src/direct/node-relay-direct.js +170 -0
- package/src/direct/portmap.js +214 -0
- package/src/direct/reachable.js +40 -0
- package/src/direct/record.js +188 -0
- package/src/index.js +1401 -199
- package/src/kademlia.js +133 -0
- package/src/node/account-sync.js +98 -0
- package/src/node/cost-meter.js +92 -0
- package/src/node/d1-sqlite.js +108 -0
- package/src/node/data-dir.js +66 -0
- package/src/node/durable-object.js +58 -0
- package/src/node/lan-beacon.js +55 -0
- package/src/node/link-crypto.js +99 -0
- package/src/node/relay-links.js +385 -0
- package/src/node/relay-name.js +193 -0
- package/src/node/relay-pq.js +68 -0
- package/src/node/relay-stats.js +276 -0
- package/src/node/stats-page.js +281 -0
- package/src/node/websocket-pair.js +117 -0
- package/src/punch/offer.js +143 -0
- package/src/punch/rendezvous.js +124 -0
- package/src/punch/transport.js +257 -0
- package/src/relay-fetch.js +131 -0
- package/src/relay-id.js +74 -0
- package/src/relay-identity.js +298 -0
- package/src/relay-overlay.js +857 -0
- package/src/tunnel/client.js +276 -0
- package/src/tunnel/frames.js +64 -0
- package/src/tunnel/home.js +271 -0
- package/wrangler.template.jsonc +34 -9
- package/wrangler.workers-dev.jsonc +20 -3
- package/scripts/non-cloudflare-server.mjs +0 -433
- package/scripts/postinstall-message.mjs +0 -133
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
// A local relay's post-quantum key, and the post-quantum keys of the local
|
|
2
|
+
// relays it has linked with (Node only).
|
|
3
|
+
//
|
|
4
|
+
// The key is an ML-DSA-65 seed kept in <data dir>/relay-pq.json, made on first
|
|
5
|
+
// start; with the relay's P-256 keys it signs hybrid (unsea 3), so the relay's
|
|
6
|
+
// node id (from its P-256 key) is unchanged. A link answer and a directory
|
|
7
|
+
// listing carry the relay's post-quantum public key and a hybrid signature.
|
|
8
|
+
//
|
|
9
|
+
// Pins: the first post-quantum key a linked relay shows for its node id is
|
|
10
|
+
// kept in <data dir>/relay-pins.json, and from then on a link from that node
|
|
11
|
+
// id must prove that same key. So someone who could forge the relay's P-256
|
|
12
|
+
// signature (a quantum computer) still cannot pose as it: they would need its
|
|
13
|
+
// ML-DSA key as well. The link itself is encrypted end to end with keys bound
|
|
14
|
+
// to those signatures (link-crypto.js), so passing the handshake along from
|
|
15
|
+
// the middle gains nothing either. A relay is protected from the first link
|
|
16
|
+
// that pins it, not before.
|
|
17
|
+
|
|
18
|
+
import { existsSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
|
19
|
+
import path from 'node:path';
|
|
20
|
+
import { upgradePair } from 'unsea';
|
|
21
|
+
|
|
22
|
+
const KEY_FILE = 'relay-pq.json';
|
|
23
|
+
const PINS_FILE = 'relay-pins.json';
|
|
24
|
+
|
|
25
|
+
function writeAtomic(file, text) {
|
|
26
|
+
const temporary = `${file}.${process.pid}.tmp`;
|
|
27
|
+
writeFileSync(temporary, text, { mode: 0o600 });
|
|
28
|
+
renameSync(temporary, file);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** { pub, priv, qpub, qpriv } for this relay: its P-256 keys and its post-quantum key. */
|
|
32
|
+
export function loadRelayPqIdentity(dataDir, { publicKey, privateKey, nodeId }) {
|
|
33
|
+
const file = path.join(dataDir, KEY_FILE);
|
|
34
|
+
let seeds = null;
|
|
35
|
+
if (existsSync(file)) {
|
|
36
|
+
try {
|
|
37
|
+
const saved = JSON.parse(readFileSync(file, 'utf8'));
|
|
38
|
+
// Kept per node id: a relay given a new P-256 identity gets a new key too.
|
|
39
|
+
if (saved?.v === 1 && saved.node_id === nodeId && typeof saved.qpriv === 'string' && typeof saved.kpriv === 'string') {
|
|
40
|
+
seeds = { qpriv: saved.qpriv, kpriv: saved.kpriv };
|
|
41
|
+
}
|
|
42
|
+
} catch { /* made again below */ }
|
|
43
|
+
}
|
|
44
|
+
const pair = upgradePair({ pub: publicKey, priv: privateKey, ...(seeds || {}) });
|
|
45
|
+
if (!seeds) writeAtomic(file, JSON.stringify({ v: 1, node_id: nodeId, qpriv: pair.qpriv, kpriv: pair.kpriv }));
|
|
46
|
+
return { pub: pair.pub, priv: pair.priv, qpub: pair.qpub, qpriv: pair.qpriv };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** The post-quantum keys seen for other relays' node ids, kept across restarts. */
|
|
50
|
+
export function loadRelayPins(dataDir) {
|
|
51
|
+
const file = path.join(dataDir, PINS_FILE);
|
|
52
|
+
const pins = new Map();
|
|
53
|
+
try {
|
|
54
|
+
const saved = JSON.parse(readFileSync(file, 'utf8'));
|
|
55
|
+
for (const [nodeId, qpub] of Object.entries(saved?.pins || {})) {
|
|
56
|
+
if (typeof qpub === 'string') pins.set(nodeId, qpub);
|
|
57
|
+
}
|
|
58
|
+
} catch { /* none yet */ }
|
|
59
|
+
return {
|
|
60
|
+
get: (nodeId) => pins.get(nodeId) ?? null,
|
|
61
|
+
set: (nodeId, qpub) => {
|
|
62
|
+
if (pins.get(nodeId) === qpub) return;
|
|
63
|
+
pins.set(nodeId, qpub);
|
|
64
|
+
writeAtomic(file, JSON.stringify({ v: 1, pins: Object.fromEntries(pins) }));
|
|
65
|
+
},
|
|
66
|
+
size: () => pins.size,
|
|
67
|
+
};
|
|
68
|
+
}
|
|
@@ -0,0 +1,276 @@
|
|
|
1
|
+
// A Node relay's own numbers, for the people running it: GET /stats (the
|
|
2
|
+
// dashboard, src/node/stats-page.js) and GET /api/v1/stats (JSON).
|
|
3
|
+
//
|
|
4
|
+
// traffic HTTP requests, WebSocket connections (now, peak, total),
|
|
5
|
+
// messages and bytes each way, totals and per second
|
|
6
|
+
// accounts PigeonIdP records kept, looked up, registered, refused, and
|
|
7
|
+
// shared with other local relays (sent on, fetched, received)
|
|
8
|
+
// federation links to other local relays, how the relay is reached
|
|
9
|
+
// performance this process (CPU, memory, event-loop delay) and the machine
|
|
10
|
+
// (load, memory, CPUs)
|
|
11
|
+
// history a sample every 5 s for the last hour, for the charts
|
|
12
|
+
// credit what this relay has served, added up across restarts (kept
|
|
13
|
+
// by the caller, <data dir>/credit.json): connection-minutes and
|
|
14
|
+
// messages delivered, and one number weighing them (CREDIT_PER)
|
|
15
|
+
//
|
|
16
|
+
// Counters only: no peer IDs, addresses or account names are kept.
|
|
17
|
+
|
|
18
|
+
import os from 'node:os';
|
|
19
|
+
import { monitorEventLoopDelay } from 'node:perf_hooks';
|
|
20
|
+
|
|
21
|
+
const SAMPLE_MS = 5_000;
|
|
22
|
+
|
|
23
|
+
// One credit for every 1,000 connection-minutes, or every 400 messages
|
|
24
|
+
// delivered: the same weighing as a hosted realtime service's list price
|
|
25
|
+
// (about $1 per million connection-minutes, $2.50 per million messages), so a
|
|
26
|
+
// credit is about a tenth of a US cent of service. Unnamed for now.
|
|
27
|
+
export const CREDIT_PER = { connectionMinutes: 1 / 1000, messagesDelivered: 1 / 400 };
|
|
28
|
+
|
|
29
|
+
/** The credit for what was served. */
|
|
30
|
+
export function creditOf({ connectionMinutes = 0, messagesDelivered = 0 } = {}) {
|
|
31
|
+
return connectionMinutes * CREDIT_PER.connectionMinutes + messagesDelivered * CREDIT_PER.messagesDelivered;
|
|
32
|
+
}
|
|
33
|
+
const HISTORY_SAMPLES = 720; // an hour
|
|
34
|
+
|
|
35
|
+
const byteLength = (data) => {
|
|
36
|
+
if (data == null) return 0;
|
|
37
|
+
if (typeof data === 'string') return Buffer.byteLength(data);
|
|
38
|
+
if (typeof data.byteLength === 'number') return data.byteLength;
|
|
39
|
+
if (Array.isArray(data)) return data.reduce((n, part) => n + byteLength(part), 0);
|
|
40
|
+
return Buffer.byteLength(String(data));
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
export function createRelayStats({ now = () => Date.now(), credit: earlier = null } = {}) {
|
|
44
|
+
const startedAt = now();
|
|
45
|
+
// Added up across restarts: starts from what the caller kept.
|
|
46
|
+
const served = {
|
|
47
|
+
since: Number(earlier?.since) || startedAt,
|
|
48
|
+
connectionMinutes: Number(earlier?.connectionMinutes) || 0,
|
|
49
|
+
messagesDelivered: Number(earlier?.messagesDelivered) || 0,
|
|
50
|
+
};
|
|
51
|
+
const traffic = {
|
|
52
|
+
httpRequests: 0,
|
|
53
|
+
httpBytesIn: 0,
|
|
54
|
+
httpBytesOut: 0,
|
|
55
|
+
connectionsOpened: 0,
|
|
56
|
+
connectionsOpen: 0,
|
|
57
|
+
connectionsPeak: 0,
|
|
58
|
+
messagesIn: 0,
|
|
59
|
+
messagesOut: 0,
|
|
60
|
+
bytesIn: 0,
|
|
61
|
+
bytesOut: 0,
|
|
62
|
+
};
|
|
63
|
+
const accounts = {
|
|
64
|
+
lookups: 0, // idp-get from browsers on this relay
|
|
65
|
+
found: 0, // ... answered with a record
|
|
66
|
+
registrations: 0, // idp-put from browsers that were stored
|
|
67
|
+
unchanged: 0, // idp-put already up to date
|
|
68
|
+
refused: 0, // idp-put refused (taken, invalid, upgrade, full)
|
|
69
|
+
receivedFromRelays: 0, // idp-put from another relay, stored
|
|
70
|
+
askedByRelays: 0, // idp-get from another relay
|
|
71
|
+
sentToRelays: 0, // records this relay sent on
|
|
72
|
+
askedRelays: 0, // lookups this relay made of other relays
|
|
73
|
+
stored: () => 0,
|
|
74
|
+
};
|
|
75
|
+
let links = () => ({ linked: 0, relays: [] });
|
|
76
|
+
let reach = () => ({});
|
|
77
|
+
let events = () => [];
|
|
78
|
+
|
|
79
|
+
// Node's measurement includes its own sampling interval: subtract it, so an
|
|
80
|
+
// idle relay reads about 0 ms.
|
|
81
|
+
const LOOP_RESOLUTION_MS = 10;
|
|
82
|
+
const loopDelay = monitorEventLoopDelay({ resolution: LOOP_RESOLUTION_MS });
|
|
83
|
+
loopDelay.enable();
|
|
84
|
+
|
|
85
|
+
/** Count a WebSocket (or anything with send and on('message')) both ways. */
|
|
86
|
+
function watchSocket(socket) {
|
|
87
|
+
if (!socket || socket.__freertcStats) return socket;
|
|
88
|
+
socket.__freertcStats = true;
|
|
89
|
+
traffic.connectionsOpened++;
|
|
90
|
+
traffic.connectionsOpen++;
|
|
91
|
+
traffic.connectionsPeak = Math.max(traffic.connectionsPeak, traffic.connectionsOpen);
|
|
92
|
+
socket.on?.('message', (data) => {
|
|
93
|
+
traffic.messagesIn++;
|
|
94
|
+
traffic.bytesIn += byteLength(data);
|
|
95
|
+
});
|
|
96
|
+
let counted = true;
|
|
97
|
+
socket.on?.('close', () => {
|
|
98
|
+
if (!counted) return;
|
|
99
|
+
counted = false;
|
|
100
|
+
traffic.connectionsOpen = Math.max(0, traffic.connectionsOpen - 1);
|
|
101
|
+
});
|
|
102
|
+
if (typeof socket.send === 'function') {
|
|
103
|
+
const send = socket.send.bind(socket);
|
|
104
|
+
socket.send = (data, ...rest) => {
|
|
105
|
+
traffic.messagesOut++;
|
|
106
|
+
traffic.bytesOut += byteLength(data);
|
|
107
|
+
return send(data, ...rest);
|
|
108
|
+
};
|
|
109
|
+
}
|
|
110
|
+
return socket;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
function http(bytesIn, bytesOut) {
|
|
114
|
+
traffic.httpRequests++;
|
|
115
|
+
traffic.httpBytesIn += bytesIn;
|
|
116
|
+
traffic.httpBytesOut += bytesOut;
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/** Count an account request and what the store answered. */
|
|
120
|
+
function account(body, result) {
|
|
121
|
+
const fromRelay = body?.from_relay === true;
|
|
122
|
+
if (body?.action === 'idp-get') {
|
|
123
|
+
if (fromRelay) accounts.askedByRelays++;
|
|
124
|
+
else {
|
|
125
|
+
accounts.lookups++;
|
|
126
|
+
if (result?.record) accounts.found++;
|
|
127
|
+
}
|
|
128
|
+
} else if (body?.action === 'idp-put') {
|
|
129
|
+
if (result?.ok && result.stored) {
|
|
130
|
+
if (fromRelay) accounts.receivedFromRelays++;
|
|
131
|
+
else accounts.registrations++;
|
|
132
|
+
} else if (result?.ok) accounts.unchanged++;
|
|
133
|
+
else accounts.refused++;
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/** Count a request this relay's account store made of another relay. */
|
|
138
|
+
function accountOutbound(body) {
|
|
139
|
+
if (body?.action === 'idp-put') accounts.sentToRelays++;
|
|
140
|
+
else if (body?.action === 'idp-get') accounts.askedRelays++;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// History: one sample every 5 s.
|
|
144
|
+
const history = [];
|
|
145
|
+
let last = { at: startedAt, ...traffic, cpu: process.cpuUsage() };
|
|
146
|
+
let latest = { cpuPercent: 0 };
|
|
147
|
+
const sample = () => {
|
|
148
|
+
const at = now();
|
|
149
|
+
const seconds = Math.max(0.001, (at - last.at) / 1000);
|
|
150
|
+
const cpu = process.cpuUsage();
|
|
151
|
+
const cpuPercent = ((cpu.user - last.cpu.user + cpu.system - last.cpu.system) / 1e6 / seconds) * 100;
|
|
152
|
+
const memory = process.memoryUsage();
|
|
153
|
+
const point = {
|
|
154
|
+
at,
|
|
155
|
+
connections: traffic.connectionsOpen,
|
|
156
|
+
messagesInPerSecond: (traffic.messagesIn - last.messagesIn) / seconds,
|
|
157
|
+
messagesOutPerSecond: (traffic.messagesOut - last.messagesOut) / seconds,
|
|
158
|
+
bytesInPerSecond: (traffic.bytesIn + traffic.httpBytesIn - last.bytesIn - last.httpBytesIn) / seconds,
|
|
159
|
+
bytesOutPerSecond: (traffic.bytesOut + traffic.httpBytesOut - last.bytesOut - last.httpBytesOut) / seconds,
|
|
160
|
+
cpuPercent,
|
|
161
|
+
loopDelayP99Ms: Math.max(0, loopDelay.percentile(99) / 1e6 - LOOP_RESOLUTION_MS),
|
|
162
|
+
rssMb: memory.rss / 1048576,
|
|
163
|
+
};
|
|
164
|
+
loopDelay.reset();
|
|
165
|
+
// Connections held over this sample, and messages delivered in it.
|
|
166
|
+
served.connectionMinutes += (last.connectionsOpen ?? traffic.connectionsOpen) * seconds / 60;
|
|
167
|
+
served.messagesDelivered += traffic.messagesOut - last.messagesOut;
|
|
168
|
+
point.credit = creditOf(served);
|
|
169
|
+
history.push(point);
|
|
170
|
+
if (history.length > HISTORY_SAMPLES) history.shift();
|
|
171
|
+
latest = point;
|
|
172
|
+
last = { at, ...traffic, cpu };
|
|
173
|
+
};
|
|
174
|
+
const timer = setInterval(sample, SAMPLE_MS);
|
|
175
|
+
timer.unref?.();
|
|
176
|
+
|
|
177
|
+
function snapshot() {
|
|
178
|
+
const memory = process.memoryUsage();
|
|
179
|
+
const cpus = os.cpus();
|
|
180
|
+
return {
|
|
181
|
+
ok: true,
|
|
182
|
+
at: now(),
|
|
183
|
+
startedAt,
|
|
184
|
+
uptimeSeconds: Math.round((now() - startedAt) / 1000),
|
|
185
|
+
traffic: { ...traffic },
|
|
186
|
+
rates: {
|
|
187
|
+
messagesInPerSecond: latest.messagesInPerSecond ?? 0,
|
|
188
|
+
messagesOutPerSecond: latest.messagesOutPerSecond ?? 0,
|
|
189
|
+
bytesInPerSecond: latest.bytesInPerSecond ?? 0,
|
|
190
|
+
bytesOutPerSecond: latest.bytesOutPerSecond ?? 0,
|
|
191
|
+
},
|
|
192
|
+
accounts: { ...accounts, stored: accounts.stored() },
|
|
193
|
+
federation: { ...links(), ...reach() },
|
|
194
|
+
process: {
|
|
195
|
+
cpuPercent: latest.cpuPercent ?? 0,
|
|
196
|
+
loopDelayP99Ms: latest.loopDelayP99Ms ?? 0,
|
|
197
|
+
rssMb: memory.rss / 1048576,
|
|
198
|
+
heapUsedMb: memory.heapUsed / 1048576,
|
|
199
|
+
heapTotalMb: memory.heapTotal / 1048576,
|
|
200
|
+
node: process.version,
|
|
201
|
+
pid: process.pid,
|
|
202
|
+
},
|
|
203
|
+
system: {
|
|
204
|
+
platform: `${os.type()} ${os.release()} (${os.arch()})`,
|
|
205
|
+
cpus: cpus.length,
|
|
206
|
+
cpuModel: cpus[0]?.model ?? null,
|
|
207
|
+
loadAverage: os.loadavg(),
|
|
208
|
+
memoryTotalMb: os.totalmem() / 1048576,
|
|
209
|
+
memoryFreeMb: os.freemem() / 1048576,
|
|
210
|
+
uptimeSeconds: Math.round(os.uptime()),
|
|
211
|
+
},
|
|
212
|
+
credit: creditState(),
|
|
213
|
+
events: events(),
|
|
214
|
+
history,
|
|
215
|
+
};
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
/** What was served so far (to keep across restarts) and its credit. */
|
|
219
|
+
function creditState() {
|
|
220
|
+
return { ...served, total: creditOf(served) };
|
|
221
|
+
}
|
|
222
|
+
|
|
223
|
+
return {
|
|
224
|
+
watchSocket,
|
|
225
|
+
creditState,
|
|
226
|
+
http,
|
|
227
|
+
account,
|
|
228
|
+
accountOutbound,
|
|
229
|
+
snapshot,
|
|
230
|
+
/** Where the account count comes from (the store's size). */
|
|
231
|
+
setAccountCount: (fn) => { accounts.stored = fn; },
|
|
232
|
+
/** Where the link list comes from. */
|
|
233
|
+
setLinks: (fn) => { links = fn; },
|
|
234
|
+
/** How the relay is reached, its name and kind, its federation line. */
|
|
235
|
+
setReach: (fn) => { reach = fn; },
|
|
236
|
+
/** Recent account events between relays (newest last). */
|
|
237
|
+
setEvents: (fn) => { events = fn; },
|
|
238
|
+
stop: () => { clearInterval(timer); loopDelay.disable(); },
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
/** Whether an address is this machine itself (loopback). */
|
|
243
|
+
export function isLoopbackAddress(address) {
|
|
244
|
+
const value = String(address || '').replace(/^::ffff:/, '').toLowerCase();
|
|
245
|
+
return value === '::1' || value === 'localhost' || /^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(value);
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
/**
|
|
249
|
+
* Who may see the stats. local (default): this machine, its network, and
|
|
250
|
+
* anyone asking through the relay's own name over https (its TLS listener);
|
|
251
|
+
* private: this machine and its network only; public: anyone.
|
|
252
|
+
*/
|
|
253
|
+
export function statsAllowed({ mode = 'local', address, encrypted = false, host = '', name = null }) {
|
|
254
|
+
if (mode === 'off') return false;
|
|
255
|
+
if (mode === 'public' || isLocalAddress(address)) return true;
|
|
256
|
+
return mode === 'local' && Boolean(encrypted && name)
|
|
257
|
+
&& String(host || '').toLowerCase().replace(/:\d+$/, '') === String(name).toLowerCase();
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
/** The stats as one caller may see them: accounts only on this machine itself. */
|
|
261
|
+
export function statsFor(snapshot, address) {
|
|
262
|
+
if (isLoopbackAddress(address)) return snapshot;
|
|
263
|
+
const { accounts, events, ...rest } = snapshot;
|
|
264
|
+
return rest;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
/** Whether an address is this machine or the local network (loopback, private, link-local). */
|
|
268
|
+
export function isLocalAddress(address) {
|
|
269
|
+
const value = String(address || '').replace(/^::ffff:/, '').toLowerCase();
|
|
270
|
+
if (!value) return false;
|
|
271
|
+
if (value === '::1' || value === 'localhost' || /^f[cd][0-9a-f]{2}:/.test(value) || /^fe[89ab][0-9a-f]:/.test(value)) return true;
|
|
272
|
+
const v4 = /^(\d{1,3})\.(\d{1,3})\.\d{1,3}\.\d{1,3}$/.exec(value);
|
|
273
|
+
if (!v4) return false;
|
|
274
|
+
const [a, b] = [Number(v4[1]), Number(v4[2])];
|
|
275
|
+
return a === 127 || a === 10 || (a === 192 && b === 168) || (a === 172 && b >= 16 && b <= 31) || (a === 169 && b === 254);
|
|
276
|
+
}
|
|
@@ -0,0 +1,281 @@
|
|
|
1
|
+
// The relay's dashboard, served at GET /stats by a Node relay. One
|
|
2
|
+
// self-contained page: it reads GET /api/v1/stats every 2 s and draws the
|
|
3
|
+
// numbers and the last hour as small charts. Night slate and bone, with one
|
|
4
|
+
// green for what is live.
|
|
5
|
+
|
|
6
|
+
export const STATS_PAGE = `<!doctype html>
|
|
7
|
+
<html lang="en">
|
|
8
|
+
<head>
|
|
9
|
+
<meta charset="utf-8" />
|
|
10
|
+
<meta name="viewport" content="width=device-width, initial-scale=1" />
|
|
11
|
+
<meta name="theme-color" content="#1b2430" />
|
|
12
|
+
<title>Relay stats</title>
|
|
13
|
+
<link rel="icon" type="image/svg+xml" href="/pigeonlogo.svg" />
|
|
14
|
+
<link rel="icon" type="image/png" sizes="192x192" href="/icon-192.png" />
|
|
15
|
+
<link rel="apple-touch-icon" sizes="180x180" href="/icon-180.png" />
|
|
16
|
+
<style>
|
|
17
|
+
:root {
|
|
18
|
+
/* Pickled Bluewood (deepened) and Cruise, as PigeonAI, PigeonFS, PigeonChess and the FreeRTC page. */
|
|
19
|
+
--night: #1b2430; --night-2: #151d27; --line: #2c394a; --line-strong: #3d4c5f;
|
|
20
|
+
--bright: #e8f6f9; --bone: #bee6ee; --bone-2: #9dbfc8; --bone-3: #8aa7b3;
|
|
21
|
+
--sheen: #7fd8a6; --info: #9cc3f5; --warn: #f2c879; --stop: #f29b91;
|
|
22
|
+
color-scheme: dark;
|
|
23
|
+
}
|
|
24
|
+
* { box-sizing: border-box; margin: 0; padding: 0; }
|
|
25
|
+
body { background: var(--night); color: var(--bone); font: 14px/1.45 'Archivo', system-ui, -apple-system, 'Segoe UI', sans-serif; -webkit-font-smoothing: antialiased; }
|
|
26
|
+
main { max-width: 1180px; margin: 0 auto; padding: 28px clamp(16px, 4vw, 40px) 56px; }
|
|
27
|
+
header { display: flex; flex-wrap: wrap; align-items: baseline; justify-content: space-between; gap: 8px 24px; padding-bottom: 20px; border-bottom: 1px solid var(--line); }
|
|
28
|
+
h1 { font-size: 1.6rem; font-weight: 800; letter-spacing: -0.02em; color: var(--bright); }
|
|
29
|
+
h1 small { font-size: 0.85rem; font-weight: 500; color: var(--bone-3); margin-left: 8px; letter-spacing: 0; }
|
|
30
|
+
.where { color: var(--bone-2); font-family: ui-monospace, Menlo, monospace; font-size: 0.85rem; word-break: break-all; }
|
|
31
|
+
.live { display: inline-flex; align-items: center; gap: 7px; color: var(--bone-3); font-size: 0.85rem; }
|
|
32
|
+
.live i { width: 8px; height: 8px; border-radius: 50%; background: var(--sheen); }
|
|
33
|
+
.live.stale i { background: var(--stop); }
|
|
34
|
+
.tiles { display: grid; grid-template-columns: repeat(auto-fit, minmax(160px, 1fr)); gap: 12px; margin: 24px 0; }
|
|
35
|
+
.tile { background: var(--night-2); border: 1px solid var(--line); border-radius: 8px; padding: 14px 16px; }
|
|
36
|
+
.tile h2 { font-size: 0.78rem; font-weight: 600; color: var(--bone-3); text-transform: uppercase; letter-spacing: 0.06em; }
|
|
37
|
+
@media (max-width: 420px) { .big { font-size: 1.5rem; } dt { padding-right: 12px; } }
|
|
38
|
+
.big { font-size: 1.9rem; font-weight: 800; letter-spacing: -0.02em; margin-top: 4px; font-variant-numeric: tabular-nums; }
|
|
39
|
+
.big small { font-size: 0.9rem; font-weight: 600; color: var(--bone-2); margin-left: 4px; }
|
|
40
|
+
.sub { color: var(--bone-2); font-size: 0.85rem; font-variant-numeric: tabular-nums; }
|
|
41
|
+
.charts { display: grid; grid-template-columns: repeat(auto-fit, minmax(340px, 1fr)); gap: 12px; }
|
|
42
|
+
.chart { background: var(--night-2); border: 1px solid var(--line); border-radius: 8px; padding: 12px 14px 10px; }
|
|
43
|
+
.chart-head { display: flex; justify-content: space-between; align-items: baseline; gap: 12px; }
|
|
44
|
+
.chart-head h3 { font-size: 0.85rem; font-weight: 600; color: var(--bone-2); }
|
|
45
|
+
.chart-head span { font-size: 0.85rem; font-variant-numeric: tabular-nums; }
|
|
46
|
+
.chart svg { display: block; width: 100%; height: 72px; margin-top: 6px; }
|
|
47
|
+
.key { display: flex; gap: 14px; font-size: 0.75rem; color: var(--bone-3); margin-top: 4px; }
|
|
48
|
+
.key i { display: inline-block; width: 10px; height: 2px; vertical-align: middle; margin-right: 5px; }
|
|
49
|
+
section { margin-top: 28px; }
|
|
50
|
+
[hidden] { display: none !important; }
|
|
51
|
+
section > h2 { font-size: 1rem; font-weight: 700; margin-bottom: 10px; }
|
|
52
|
+
.cols { display: grid; grid-template-columns: repeat(auto-fit, minmax(320px, 1fr)); gap: 12px; align-items: start; }
|
|
53
|
+
.state { color: var(--bone-2); margin: -2px 0 12px; word-break: break-word; }
|
|
54
|
+
dl { display: grid; grid-template-columns: 1fr auto; background: var(--night-2); border: 1px solid var(--line); border-radius: 8px; padding: 6px 16px; }
|
|
55
|
+
dt, dd { padding: 8px 0; border-bottom: 1px solid var(--line); }
|
|
56
|
+
dt { color: var(--bone-2); }
|
|
57
|
+
dd { text-align: right; font-variant-numeric: tabular-nums; font-weight: 600; }
|
|
58
|
+
dl > :nth-last-child(-n+2) { border-bottom: 0; }
|
|
59
|
+
.relays { list-style: none; background: var(--night-2); border: 1px solid var(--line); border-radius: 8px; padding: 6px 16px; }
|
|
60
|
+
.relays li { padding: 8px 0; border-bottom: 1px solid var(--line); font-family: ui-monospace, Menlo, monospace; font-size: 0.82rem; color: var(--bone-2); word-break: break-all; }
|
|
61
|
+
.relays li:last-child { border-bottom: 0; }
|
|
62
|
+
.muted { color: var(--bone-3); }
|
|
63
|
+
footer { margin-top: 32px; color: var(--bone-3); font-size: 0.8rem; }
|
|
64
|
+
</style>
|
|
65
|
+
</head>
|
|
66
|
+
<body>
|
|
67
|
+
<main>
|
|
68
|
+
<header>
|
|
69
|
+
<div>
|
|
70
|
+
<h1 id="name">Relay<small id="kind"></small></h1>
|
|
71
|
+
<p class="where" id="url"></p>
|
|
72
|
+
</div>
|
|
73
|
+
<p class="live" id="live"><i></i><span>Connecting…</span></p>
|
|
74
|
+
</header>
|
|
75
|
+
|
|
76
|
+
<div class="tiles">
|
|
77
|
+
<div class="tile"><h2>Up for</h2><p class="big" id="uptime">–</p><p class="sub" id="started"></p></div>
|
|
78
|
+
<div class="tile"><h2>Connections</h2><p class="big" id="conn">–</p><p class="sub" id="conn-sub"></p></div>
|
|
79
|
+
<div class="tile"><h2>Messages</h2><p class="big" id="msgs">–</p><p class="sub" id="msgs-sub"></p></div>
|
|
80
|
+
<div class="tile"><h2>Bandwidth</h2><p class="big" id="bw">–</p><p class="sub" id="bw-sub"></p></div>
|
|
81
|
+
<div class="tile"><h2>Pigeon Seeds</h2><p class="big" id="credit">–</p><p class="sub" id="credit-sub"></p></div>
|
|
82
|
+
<div class="tile" id="acc-tile"><h2>Accounts kept</h2><p class="big" id="acc">–</p><p class="sub" id="acc-sub"></p></div>
|
|
83
|
+
</div>
|
|
84
|
+
|
|
85
|
+
<div class="charts">
|
|
86
|
+
<div class="chart"><div class="chart-head"><h3>Connections</h3><span id="c-conn"></span></div><svg id="g-conn" preserveAspectRatio="none"></svg></div>
|
|
87
|
+
<div class="chart"><div class="chart-head"><h3>Messages a second</h3><span id="c-msgs"></span></div><svg id="g-msgs" preserveAspectRatio="none"></svg>
|
|
88
|
+
<div class="key"><span><i style="background:var(--sheen)"></i>in</span><span><i style="background:var(--bone-2)"></i>out</span></div></div>
|
|
89
|
+
<div class="chart"><div class="chart-head"><h3>Bandwidth</h3><span id="c-bw"></span></div><svg id="g-bw" preserveAspectRatio="none"></svg>
|
|
90
|
+
<div class="key"><span><i style="background:var(--sheen)"></i>in</span><span><i style="background:var(--bone-2)"></i>out</span></div></div>
|
|
91
|
+
<div class="chart"><div class="chart-head"><h3>CPU (this relay)</h3><span id="c-cpu"></span></div><svg id="g-cpu" preserveAspectRatio="none"></svg></div>
|
|
92
|
+
<div class="chart"><div class="chart-head"><h3>Event-loop delay, p99</h3><span id="c-loop"></span></div><svg id="g-loop" preserveAspectRatio="none"></svg></div>
|
|
93
|
+
<div class="chart"><div class="chart-head"><h3>Memory (this relay)</h3><span id="c-mem"></span></div><svg id="g-mem" preserveAspectRatio="none"></svg></div>
|
|
94
|
+
</div>
|
|
95
|
+
|
|
96
|
+
<section id="acc-section">
|
|
97
|
+
<h2>Accounts</h2>
|
|
98
|
+
<div class="cols">
|
|
99
|
+
<dl id="acc-browsers"></dl>
|
|
100
|
+
<dl id="acc-relays"></dl>
|
|
101
|
+
</div>
|
|
102
|
+
</section>
|
|
103
|
+
|
|
104
|
+
<section id="events-section">
|
|
105
|
+
<h2>Account events between relays</h2>
|
|
106
|
+
<ul class="relays" id="events"></ul>
|
|
107
|
+
</section>
|
|
108
|
+
|
|
109
|
+
<section>
|
|
110
|
+
<h2>Federation</h2>
|
|
111
|
+
<p class="state" id="fed-state"></p>
|
|
112
|
+
<div class="cols">
|
|
113
|
+
<dl id="fed"></dl>
|
|
114
|
+
<ul class="relays" id="links"></ul>
|
|
115
|
+
</div>
|
|
116
|
+
</section>
|
|
117
|
+
|
|
118
|
+
<section>
|
|
119
|
+
<h2>Performance</h2>
|
|
120
|
+
<div class="cols">
|
|
121
|
+
<dl id="proc"></dl>
|
|
122
|
+
<dl id="sys"></dl>
|
|
123
|
+
</div>
|
|
124
|
+
</section>
|
|
125
|
+
|
|
126
|
+
<footer>Counts since this relay started. Nothing here names a peer, an address or an account. <span id="history-span"></span></footer>
|
|
127
|
+
</main>
|
|
128
|
+
<script>
|
|
129
|
+
(() => {
|
|
130
|
+
const $ = (id) => document.getElementById(id);
|
|
131
|
+
const num = (n) => Math.round(n).toLocaleString();
|
|
132
|
+
const rate = (n) => n >= 100 ? num(n) : n >= 10 ? n.toFixed(1) : n.toFixed(2);
|
|
133
|
+
const bytes = (n) => {
|
|
134
|
+
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
|
|
135
|
+
let i = 0;
|
|
136
|
+
while (n >= 1024 && i < units.length - 1) { n /= 1024; i++; }
|
|
137
|
+
return (i === 0 ? Math.round(n) : n >= 100 ? Math.round(n) : n.toFixed(1)) + ' ' + units[i];
|
|
138
|
+
};
|
|
139
|
+
const duration = (s) => {
|
|
140
|
+
const d = Math.floor(s / 86400), h = Math.floor(s % 86400 / 3600), m = Math.floor(s % 3600 / 60);
|
|
141
|
+
if (d) return d + 'd ' + h + 'h';
|
|
142
|
+
if (h) return h + 'h ' + m + 'm';
|
|
143
|
+
if (m) return m + 'm ' + Math.floor(s % 60) + 's';
|
|
144
|
+
return Math.floor(s) + 's';
|
|
145
|
+
};
|
|
146
|
+
const rows = (el, list) => {
|
|
147
|
+
el.innerHTML = list.map(([k, v]) => '<dt>' + k + '</dt><dd>' + v + '</dd>').join('');
|
|
148
|
+
};
|
|
149
|
+
|
|
150
|
+
// A line (or two) over the last hour, scaled to its own range.
|
|
151
|
+
function chart(svg, series, colors) {
|
|
152
|
+
const w = 300, h = 72, pad = 3;
|
|
153
|
+
svg.setAttribute('viewBox', '0 0 ' + w + ' ' + h);
|
|
154
|
+
const all = series.flat();
|
|
155
|
+
if (!all.length) { svg.innerHTML = ''; return; }
|
|
156
|
+
const max = Math.max(...all, 0.0001);
|
|
157
|
+
const lines = series.map((values, i) => {
|
|
158
|
+
if (values.length < 2) return '';
|
|
159
|
+
const step = w / (values.length - 1);
|
|
160
|
+
const points = values.map((v, j) => (j * step).toFixed(1) + ',' + (h - pad - (v / max) * (h - pad * 2)).toFixed(1)).join(' ');
|
|
161
|
+
const area = i === 0 ? '<polygon points="0,' + h + ' ' + points + ' ' + w + ',' + h + '" fill="' + colors[i] + '" fill-opacity="0.08"/>' : '';
|
|
162
|
+
return area + '<polyline points="' + points + '" fill="none" stroke="' + colors[i] + '" stroke-width="1.5" vector-effect="non-scaling-stroke" stroke-linejoin="round"/>';
|
|
163
|
+
}).join('');
|
|
164
|
+
svg.innerHTML = '<line x1="0" x2="' + w + '" y1="' + (h - 0.5) + '" y2="' + (h - 0.5) + '" stroke="#2c394a"/>' + lines;
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const SHEEN = '#7fd8a6', BONE = '#9dbfc8';
|
|
168
|
+
let lastOk = 0;
|
|
169
|
+
|
|
170
|
+
async function refresh() {
|
|
171
|
+
let s;
|
|
172
|
+
try {
|
|
173
|
+
const response = await fetch('/api/v1/stats', { cache: 'no-store' });
|
|
174
|
+
if (!response.ok) throw new Error(response.status);
|
|
175
|
+
s = await response.json();
|
|
176
|
+
} catch {
|
|
177
|
+
$('live').className = 'live stale';
|
|
178
|
+
$('live').lastElementChild.textContent = lastOk ? 'Not answering (last update ' + duration((Date.now() - lastOk) / 1000) + ' ago)' : 'Not answering';
|
|
179
|
+
return;
|
|
180
|
+
}
|
|
181
|
+
lastOk = Date.now();
|
|
182
|
+
$('live').className = 'live';
|
|
183
|
+
$('live').lastElementChild.textContent = 'Live';
|
|
184
|
+
|
|
185
|
+
const f = s.federation || {};
|
|
186
|
+
$('name').firstChild.textContent = f.name || 'Relay';
|
|
187
|
+
$('kind').textContent = f.kind ? f.kind + ' relay' : '';
|
|
188
|
+
$('url').textContent = f.url || '';
|
|
189
|
+
document.title = (f.name || 'Relay') + ' stats';
|
|
190
|
+
|
|
191
|
+
const t = s.traffic, r = s.rates, a = s.accounts;
|
|
192
|
+
$('uptime').textContent = duration(s.uptimeSeconds);
|
|
193
|
+
$('started').textContent = 'since ' + new Date(s.startedAt).toLocaleString();
|
|
194
|
+
$('conn').textContent = num(t.connectionsOpen);
|
|
195
|
+
$('conn-sub').textContent = 'peak ' + num(t.connectionsPeak) + ' · ' + num(t.connectionsOpened) + ' in all';
|
|
196
|
+
$('msgs').innerHTML = rate(r.messagesInPerSecond + r.messagesOutPerSecond) + '<small>/s</small>';
|
|
197
|
+
$('msgs-sub').textContent = num(t.messagesIn) + ' in · ' + num(t.messagesOut) + ' out';
|
|
198
|
+
$('bw').innerHTML = bytes(r.bytesInPerSecond + r.bytesOutPerSecond) + '<small>/s</small>';
|
|
199
|
+
$('bw-sub').textContent = bytes(t.bytesIn + t.httpBytesIn) + ' in · ' + bytes(t.bytesOut + t.httpBytesOut) + ' out';
|
|
200
|
+
const c = s.credit;
|
|
201
|
+
if (c) {
|
|
202
|
+
$('credit').textContent = c.total.toLocaleString(undefined, { maximumFractionDigits: c.total < 10 ? 3 : 1 });
|
|
203
|
+
$('credit-sub').textContent = (c.connectionMinutes / 60).toLocaleString(undefined, { maximumFractionDigits: c.connectionMinutes < 600 ? 1 : 0 }) + ' connection-hr · ' + num(c.messagesDelivered) + ' delivered · since ' + new Date(c.since).toLocaleDateString();
|
|
204
|
+
}
|
|
205
|
+
// Account numbers come only to this machine itself (localhost).
|
|
206
|
+
for (const id of ['acc-tile', 'acc-section', 'events-section']) $(id).hidden = !a;
|
|
207
|
+
if (a) {
|
|
208
|
+
$('acc').textContent = num(a.stored);
|
|
209
|
+
$('acc-sub').textContent = num(a.lookups) + ' looked up · ' + num(a.registrations) + ' saved';
|
|
210
|
+
|
|
211
|
+
const h = s.history || [];
|
|
212
|
+
const pick = (k) => h.map((p) => p[k]);
|
|
213
|
+
chart($('g-conn'), [pick('connections')], [SHEEN]);
|
|
214
|
+
chart($('g-msgs'), [pick('messagesInPerSecond'), pick('messagesOutPerSecond')], [SHEEN, BONE]);
|
|
215
|
+
chart($('g-bw'), [pick('bytesInPerSecond'), pick('bytesOutPerSecond')], [SHEEN, BONE]);
|
|
216
|
+
chart($('g-cpu'), [pick('cpuPercent')], [SHEEN]);
|
|
217
|
+
chart($('g-loop'), [pick('loopDelayP99Ms')], [SHEEN]);
|
|
218
|
+
chart($('g-mem'), [pick('rssMb')], [SHEEN]);
|
|
219
|
+
$('c-conn').textContent = num(t.connectionsOpen) + ' now';
|
|
220
|
+
$('c-msgs').textContent = rate(r.messagesInPerSecond) + ' in · ' + rate(r.messagesOutPerSecond) + ' out';
|
|
221
|
+
$('c-bw').textContent = bytes(r.bytesInPerSecond) + '/s in · ' + bytes(r.bytesOutPerSecond) + '/s out';
|
|
222
|
+
$('c-cpu').textContent = s.process.cpuPercent.toFixed(1) + '%';
|
|
223
|
+
$('c-loop').textContent = s.process.loopDelayP99Ms.toFixed(1) + ' ms';
|
|
224
|
+
$('c-mem').textContent = Math.round(s.process.rssMb) + ' MB';
|
|
225
|
+
$('history-span').textContent = h.length ? 'Charts: the last ' + duration(h.length * 5) + '.' : 'Charts fill in over the first minutes.';
|
|
226
|
+
|
|
227
|
+
rows($('acc-browsers'), [
|
|
228
|
+
['Accounts kept', num(a.stored)],
|
|
229
|
+
['Looked up by browsers here', num(a.lookups)],
|
|
230
|
+
['… found', num(a.found)],
|
|
231
|
+
['Saved (new or changed)', num(a.registrations)],
|
|
232
|
+
['Already up to date', num(a.unchanged)],
|
|
233
|
+
['Refused (taken, invalid, old kind)', num(a.refused)],
|
|
234
|
+
]);
|
|
235
|
+
rows($('acc-relays'), [
|
|
236
|
+
['Sent on to other relays', num(a.sentToRelays)],
|
|
237
|
+
['Asked other relays for', num(a.askedRelays)],
|
|
238
|
+
['Received from other relays', num(a.receivedFromRelays)],
|
|
239
|
+
['Looked up by other relays', num(a.askedByRelays)],
|
|
240
|
+
]);
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
$('fed-state').textContent = f.federation || 'Federation is off.';
|
|
244
|
+
rows($('fed'), [
|
|
245
|
+
['Linked local relays', num(f.linked || 0)],
|
|
246
|
+
['Post-quantum links', f.postQuantum ? 'on' : '<span class="muted">off</span>'],
|
|
247
|
+
...(a ? [['Accounts shared with relays', f.accountsShared ? 'yes' : '<span class="muted">no</span>']] : []),
|
|
248
|
+
]);
|
|
249
|
+
const events = (s.events || []).slice().reverse();
|
|
250
|
+
$('events').innerHTML = events.length
|
|
251
|
+
? events.map((x) => '<li>' + x.replace(/&/g, '&').replace(/</g, '<') + '</li>').join('')
|
|
252
|
+
: '<li class="muted">Nothing yet.</li>';
|
|
253
|
+
const relays = f.relays || [];
|
|
254
|
+
$('links').innerHTML = relays.length
|
|
255
|
+
? relays.map((x) => '<li>' + x + '</li>').join('')
|
|
256
|
+
: '<li class="muted">No other local relays linked right now.</li>';
|
|
257
|
+
|
|
258
|
+
const p = s.process, y = s.system;
|
|
259
|
+
rows($('proc'), [
|
|
260
|
+
['CPU', p.cpuPercent.toFixed(1) + '%'],
|
|
261
|
+
['Memory', Math.round(p.rssMb) + ' MB (heap ' + Math.round(p.heapUsedMb) + ' of ' + Math.round(p.heapTotalMb) + ' MB)'],
|
|
262
|
+
['Event-loop delay, p99', p.loopDelayP99Ms.toFixed(1) + ' ms'],
|
|
263
|
+
['Node', p.node],
|
|
264
|
+
['HTTP requests', num(t.httpRequests)],
|
|
265
|
+
]);
|
|
266
|
+
rows($('sys'), [
|
|
267
|
+
['Machine', y.platform],
|
|
268
|
+
['CPUs', y.cpus + (y.cpuModel ? ' · ' + y.cpuModel : '')],
|
|
269
|
+
['Load (1, 5, 15 min)', y.loadAverage.map((n) => n.toFixed(2)).join(', ')],
|
|
270
|
+
['Memory in use', Math.round(y.memoryTotalMb - y.memoryFreeMb).toLocaleString() + ' of ' + Math.round(y.memoryTotalMb).toLocaleString() + ' MB'],
|
|
271
|
+
['Machine up for', duration(y.uptimeSeconds)],
|
|
272
|
+
]);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
refresh();
|
|
276
|
+
setInterval(refresh, 2000);
|
|
277
|
+
})();
|
|
278
|
+
</script>
|
|
279
|
+
</body>
|
|
280
|
+
</html>
|
|
281
|
+
`;
|