toolroll 0.9.128 → 0.9.129
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/CHANGELOG.md +17 -0
- package/dist/accent-colors.js +3 -1
- package/dist/approval-authority.js +2 -1
- package/dist/assignment.js +55 -2
- package/dist/backup.js +6 -0
- package/dist/browser/terminal.css +1 -1
- package/dist/browser/workspace.css +1 -1
- package/dist/central-recovery-stage.js +3 -3
- package/dist/companion/access.js +161 -0
- package/dist/companion/actions.js +559 -0
- package/dist/companion/bonjour.js +45 -0
- package/dist/companion/daemon.js +1346 -0
- package/dist/companion/direct-server.js +177 -0
- package/dist/companion/framing.js +498 -0
- package/dist/companion/noise.js +461 -0
- package/dist/companion/passkey-gate.js +287 -0
- package/dist/companion/paths.js +90 -0
- package/dist/companion/reads.js +279 -0
- package/dist/companion/relay-auth.js +265 -0
- package/dist/companion/relay-server.js +870 -0
- package/dist/companion/schema.js +225 -0
- package/dist/companion/service.js +580 -0
- package/dist/companion/store.js +324 -0
- package/dist/companion/webauthn-test-support.js +44 -0
- package/dist/companion/webauthn.js +398 -0
- package/dist/contracts/console-api.js +18 -0
- package/dist/design/kit.css +30 -0
- package/dist/local-landing.js +47 -0
- package/dist/person-proof.js +5 -1
- package/dist/pull-request-flow.js +75 -2
- package/dist/qr.js +385 -0
- package/dist/release-adapters.js +2 -1
- package/dist/restore-retirement.js +2 -0
- package/dist/scope.js +67 -4
- package/dist/serve.js +31 -4
- package/dist/server/pages.js +9 -2
- package/dist/server/phone-engine-api.js +59 -0
- package/dist/server/route-table.js +11 -0
- package/dist/server/settings-phone.js +492 -0
- package/dist/server/settings-scripts.js +2 -0
- package/dist/server/settings-sections.js +6 -2
- package/dist/settings-groups-ui.js +2 -1
- package/dist/settings-proofs.js +6 -0
- package/dist/store.js +37 -4
- package/dist/tailnet.js +42 -0
- package/dist/toolroll-update.js +3 -1
- package/dist/youiyoux-intake.js +8 -0
- package/package.json +7 -2
|
@@ -0,0 +1,870 @@
|
|
|
1
|
+
import { createHash, createHmac, randomBytes, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { createServer } from "node:http";
|
|
3
|
+
import { WebSocketServer, WebSocket } from "ws";
|
|
4
|
+
import { MAX_NOISE_MESSAGE_BYTES } from "./noise.js";
|
|
5
|
+
import { checkRelayClaims, ed25519Verify, encodeRelayEnvelope, HEARTBEAT_PAYLOAD_BYTES, MAX_DAEMON_WS_FRAME_BYTES, parseRelayToken, RELAY_ENVELOPE_HEADER_BYTES, RELAY_ID_PATTERN, RelayOp, RelayReplayCache, relayTokenMaxUses, replayPrincipalOf, verifyMachineRegistration, } from "./relay-auth.js";
|
|
6
|
+
export const RELAY_LIMITS = Object.freeze({
|
|
7
|
+
phoneFirstFrameMs: 10_000,
|
|
8
|
+
phoneIdleMs: 90_000,
|
|
9
|
+
daemonSilenceMs: 60_000,
|
|
10
|
+
socketsPerMachine: 4,
|
|
11
|
+
devicesPerMachine: 32,
|
|
12
|
+
tombstonesPerMachine: 256,
|
|
13
|
+
tombstoneMs: 30 * 24 * 60 * 60 * 1000,
|
|
14
|
+
roomIdleDeleteMs: 90 * 24 * 60 * 60 * 1000,
|
|
15
|
+
phoneUp: { framesPerMin: 600, framesBurst: 120, bytesPerMin: 4 * 1024 * 1024, bytesBurst: 1024 * 1024 },
|
|
16
|
+
phoneDown: { bytesPerMin: 16 * 1024 * 1024, bytesBurst: 4 * 1024 * 1024 },
|
|
17
|
+
machineUp: { bytesPerMin: 32 * 1024 * 1024, bytesBurst: 8 * 1024 * 1024 },
|
|
18
|
+
machineDown: { bytesPerMin: 64 * 1024 * 1024, bytesBurst: 16 * 1024 * 1024 },
|
|
19
|
+
registerPerMin: 20,
|
|
20
|
+
connectPerMin: 120,
|
|
21
|
+
clientPerMin: 600,
|
|
22
|
+
registerBodyBytes: 4096,
|
|
23
|
+
putBodyBytes: 16_384,
|
|
24
|
+
postBodyBytes: 4096,
|
|
25
|
+
challengeTtlMs: 60_000,
|
|
26
|
+
});
|
|
27
|
+
export const RelayClose = Object.freeze({
|
|
28
|
+
normal: 1000,
|
|
29
|
+
protocol: 4400,
|
|
30
|
+
revoked: 4403,
|
|
31
|
+
timeout: 4408,
|
|
32
|
+
superseded: 4409,
|
|
33
|
+
rateLimited: 4429,
|
|
34
|
+
daemonGone: 4503,
|
|
35
|
+
});
|
|
36
|
+
class TokenBucket {
|
|
37
|
+
burst;
|
|
38
|
+
tokens;
|
|
39
|
+
at;
|
|
40
|
+
ratePerMs;
|
|
41
|
+
constructor(perMinute, burst, nowMs) {
|
|
42
|
+
this.burst = burst;
|
|
43
|
+
this.tokens = burst;
|
|
44
|
+
this.ratePerMs = perMinute / 60_000;
|
|
45
|
+
this.at = nowMs;
|
|
46
|
+
}
|
|
47
|
+
take(cost, nowMs) {
|
|
48
|
+
this.refill(nowMs);
|
|
49
|
+
if (this.tokens < cost)
|
|
50
|
+
return false;
|
|
51
|
+
this.tokens -= cost;
|
|
52
|
+
return true;
|
|
53
|
+
}
|
|
54
|
+
waitSec(cost, nowMs) {
|
|
55
|
+
this.refill(nowMs);
|
|
56
|
+
return Math.max(1, Math.ceil((cost - this.tokens) / this.ratePerMs / 1000));
|
|
57
|
+
}
|
|
58
|
+
full(nowMs) { this.refill(nowMs); return this.tokens >= this.burst; }
|
|
59
|
+
refill(nowMs) {
|
|
60
|
+
const elapsed = Math.max(0, nowMs - this.at);
|
|
61
|
+
this.tokens = Math.min(this.burst, this.tokens + elapsed * this.ratePerMs);
|
|
62
|
+
this.at = nowMs;
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
class KeyedBuckets {
|
|
66
|
+
perMin;
|
|
67
|
+
maxKeys;
|
|
68
|
+
buckets = new Map();
|
|
69
|
+
constructor(perMin, maxKeys = 50_000) {
|
|
70
|
+
this.perMin = perMin;
|
|
71
|
+
this.maxKeys = maxKeys;
|
|
72
|
+
}
|
|
73
|
+
take(key, nowMs) {
|
|
74
|
+
let bucket = this.buckets.get(key);
|
|
75
|
+
if (bucket === undefined) {
|
|
76
|
+
if (this.buckets.size >= this.maxKeys)
|
|
77
|
+
this.prune(nowMs);
|
|
78
|
+
bucket = new TokenBucket(this.perMin, this.perMin, nowMs);
|
|
79
|
+
this.buckets.set(key, bucket);
|
|
80
|
+
}
|
|
81
|
+
return bucket.take(1, nowMs) ? null : { status: 429, code: "rate_limited", retryAfterSec: bucket.waitSec(1, nowMs) };
|
|
82
|
+
}
|
|
83
|
+
prune(nowMs) {
|
|
84
|
+
for (const [key, bucket] of this.buckets)
|
|
85
|
+
if (bucket.full(nowMs))
|
|
86
|
+
this.buckets.delete(key);
|
|
87
|
+
while (this.buckets.size >= this.maxKeys)
|
|
88
|
+
this.buckets.delete(this.buckets.keys().next().value);
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
const STATUS_TEXT = {
|
|
92
|
+
400: "Bad Request", 401: "Unauthorized", 403: "Forbidden", 404: "Not Found", 429: "Too Many Requests", 503: "Service Unavailable",
|
|
93
|
+
};
|
|
94
|
+
function refusalHeaders(refusal) {
|
|
95
|
+
return {
|
|
96
|
+
"toolroll-relay-error": refusal.code,
|
|
97
|
+
...(refusal.retryAfterSec !== undefined ? { "retry-after": String(refusal.retryAfterSec) } : {}),
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
function sendJson(res, status, body, headers = {}) {
|
|
101
|
+
const payload = JSON.stringify(body);
|
|
102
|
+
res.writeHead(status, {
|
|
103
|
+
"content-type": "application/json; charset=utf-8",
|
|
104
|
+
"cache-control": "no-store",
|
|
105
|
+
"content-length": Buffer.byteLength(payload),
|
|
106
|
+
...headers,
|
|
107
|
+
});
|
|
108
|
+
res.end(payload);
|
|
109
|
+
}
|
|
110
|
+
function sendRefusal(res, refusal) {
|
|
111
|
+
sendJson(res, refusal.status, { error: refusal.code }, refusalHeaders(refusal));
|
|
112
|
+
}
|
|
113
|
+
function rejectUpgrade(socket, refusal) {
|
|
114
|
+
const text = JSON.stringify({ error: refusal.code });
|
|
115
|
+
const headers = { ...refusalHeaders(refusal), date: new Date().toUTCString() };
|
|
116
|
+
socket.end(`HTTP/1.1 ${refusal.status} ${STATUS_TEXT[refusal.status] ?? "Error"}\r\n`
|
|
117
|
+
+ Object.entries(headers).map(([name, value]) => `${name}: ${value}\r\n`).join("")
|
|
118
|
+
+ `content-type: application/json\r\ncontent-length: ${Buffer.byteLength(text)}\r\nconnection: close\r\n\r\n${text}`);
|
|
119
|
+
socket.destroy();
|
|
120
|
+
}
|
|
121
|
+
function rawDataToBuffer(data) {
|
|
122
|
+
if (Buffer.isBuffer(data))
|
|
123
|
+
return data;
|
|
124
|
+
if (Array.isArray(data))
|
|
125
|
+
return Buffer.concat(data);
|
|
126
|
+
return Buffer.from(data);
|
|
127
|
+
}
|
|
128
|
+
function readJsonBody(req, maxBytes) {
|
|
129
|
+
return new Promise(resolve => {
|
|
130
|
+
const declared = Number(req.headers["content-length"] ?? "0");
|
|
131
|
+
if (Number.isFinite(declared) && declared > maxBytes) {
|
|
132
|
+
resolve(null);
|
|
133
|
+
req.resume();
|
|
134
|
+
return;
|
|
135
|
+
}
|
|
136
|
+
const chunks = [];
|
|
137
|
+
let total = 0;
|
|
138
|
+
let done = false;
|
|
139
|
+
const finish = (value) => { if (!done) {
|
|
140
|
+
done = true;
|
|
141
|
+
resolve(value);
|
|
142
|
+
} };
|
|
143
|
+
req.on("data", (chunk) => {
|
|
144
|
+
if (done)
|
|
145
|
+
return;
|
|
146
|
+
total += chunk.length;
|
|
147
|
+
if (total > maxBytes) {
|
|
148
|
+
finish(null);
|
|
149
|
+
req.resume();
|
|
150
|
+
return;
|
|
151
|
+
}
|
|
152
|
+
chunks.push(chunk);
|
|
153
|
+
});
|
|
154
|
+
req.on("end", () => {
|
|
155
|
+
try {
|
|
156
|
+
const parsed = JSON.parse(Buffer.concat(chunks).toString("utf8"));
|
|
157
|
+
finish(parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null);
|
|
158
|
+
}
|
|
159
|
+
catch {
|
|
160
|
+
finish(null);
|
|
161
|
+
}
|
|
162
|
+
});
|
|
163
|
+
req.on("error", () => finish(null));
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
function relayKeyOrNull(value) {
|
|
167
|
+
if (typeof value !== "string" || value.length !== 43 || !/^[A-Za-z0-9_-]+$/.test(value))
|
|
168
|
+
return null;
|
|
169
|
+
const key = Buffer.from(value, "base64url");
|
|
170
|
+
return key.length === 32 ? key : null;
|
|
171
|
+
}
|
|
172
|
+
export function clientRateKey(ip) {
|
|
173
|
+
if (ip === null || ip === undefined || ip.length === 0)
|
|
174
|
+
return "no-ip";
|
|
175
|
+
const plain = ip.startsWith("::ffff:") && ip.includes(".") ? ip.slice(7) : ip;
|
|
176
|
+
if (!plain.includes(":"))
|
|
177
|
+
return plain;
|
|
178
|
+
const [head, tail = ""] = plain.toLowerCase().split("::");
|
|
179
|
+
const left = head.split(":").filter(Boolean);
|
|
180
|
+
const right = tail.split(":").filter(Boolean);
|
|
181
|
+
const full = [...left, ...Array(Math.max(0, 8 - left.length - right.length)).fill("0"), ...right];
|
|
182
|
+
return `${full.slice(0, 4).join(":")}::/64`;
|
|
183
|
+
}
|
|
184
|
+
function idTag(id) {
|
|
185
|
+
return createHash("sha256").update(id).digest("hex").slice(0, 8);
|
|
186
|
+
}
|
|
187
|
+
export async function startReferenceRelay(opts = {}) {
|
|
188
|
+
const nowMs = opts.nowMs ?? (() => Date.now());
|
|
189
|
+
const L = RELAY_LIMITS;
|
|
190
|
+
const phoneFirstFrameMs = opts.phoneFirstFrameMs ?? L.phoneFirstFrameMs;
|
|
191
|
+
const phoneIdleMs = opts.phoneIdleMs ?? L.phoneIdleMs;
|
|
192
|
+
const daemonSilenceMs = opts.daemonSilenceMs ?? L.daemonSilenceMs;
|
|
193
|
+
const maxRooms = opts.maxRooms ?? 1_000;
|
|
194
|
+
const maxSocketsPerIp = opts.maxSocketsPerIp ?? 64;
|
|
195
|
+
const globalFramesPerMin = opts.globalFramesPerMin ?? 0;
|
|
196
|
+
const log = opts.log ?? (() => { });
|
|
197
|
+
const challengeSecrets = [opts.challengeSecret ?? randomBytes(32).toString("base64url"), opts.previousChallengeSecret]
|
|
198
|
+
.filter((one) => typeof one === "string" && one.length > 0);
|
|
199
|
+
const registerLimit = new KeyedBuckets(opts.registerPerMin ?? L.registerPerMin);
|
|
200
|
+
const connectLimit = new KeyedBuckets(opts.connectPerMin ?? L.connectPerMin);
|
|
201
|
+
const clientLimit = new KeyedBuckets(opts.clientPerMin ?? L.clientPerMin);
|
|
202
|
+
const socketsByIp = new Map();
|
|
203
|
+
const rooms = new Map();
|
|
204
|
+
let publicHost = (opts.publicHost ?? "").toLowerCase();
|
|
205
|
+
let windowStartMs = nowMs();
|
|
206
|
+
let forwardedThisWindow = 0;
|
|
207
|
+
const breakerOpen = () => {
|
|
208
|
+
if (globalFramesPerMin <= 0)
|
|
209
|
+
return false;
|
|
210
|
+
if (nowMs() - windowStartMs >= 60_000) {
|
|
211
|
+
windowStartMs = nowMs();
|
|
212
|
+
forwardedThisWindow = 0;
|
|
213
|
+
}
|
|
214
|
+
return forwardedThisWindow >= globalFramesPerMin;
|
|
215
|
+
};
|
|
216
|
+
const countForwarded = () => { forwardedThisWindow += 1; };
|
|
217
|
+
const clientKey = (req) => {
|
|
218
|
+
if (opts.trustProxy) {
|
|
219
|
+
const forwarded = req.headers["x-forwarded-for"];
|
|
220
|
+
const list = (Array.isArray(forwarded) ? forwarded.join(",") : forwarded ?? "").split(",").map(one => one.trim()).filter(Boolean);
|
|
221
|
+
if (list.length > 0)
|
|
222
|
+
return clientRateKey(list[list.length - 1]);
|
|
223
|
+
}
|
|
224
|
+
return clientRateKey(req.socket.remoteAddress);
|
|
225
|
+
};
|
|
226
|
+
const refused = (route, refusal, extra = {}) => {
|
|
227
|
+
log({ event: "refusal", route, status: refusal.status, code: refusal.code, ...extra });
|
|
228
|
+
return refusal;
|
|
229
|
+
};
|
|
230
|
+
const challengeMac = (secret, body) => createHmac("sha256", secret).update(body).digest();
|
|
231
|
+
const mintChallenge = () => {
|
|
232
|
+
const body = Buffer.alloc(24);
|
|
233
|
+
randomBytes(16).copy(body, 0);
|
|
234
|
+
body.writeBigUInt64BE(BigInt(nowMs() + L.challengeTtlMs), 16);
|
|
235
|
+
return Buffer.concat([body, challengeMac(challengeSecrets[0], body)]).toString("base64url");
|
|
236
|
+
};
|
|
237
|
+
const challengeValid = (challenge) => {
|
|
238
|
+
if (!/^[A-Za-z0-9_-]{75}$/.test(challenge))
|
|
239
|
+
return false;
|
|
240
|
+
const raw = Buffer.from(challenge, "base64url");
|
|
241
|
+
if (raw.length !== 56)
|
|
242
|
+
return false;
|
|
243
|
+
const body = raw.subarray(0, 24), mac = raw.subarray(24);
|
|
244
|
+
if (!challengeSecrets.some(secret => timingSafeEqual(challengeMac(secret, body), mac)))
|
|
245
|
+
return false;
|
|
246
|
+
return Number(body.readBigUInt64BE(16)) > nowMs();
|
|
247
|
+
};
|
|
248
|
+
const liveDaemon = (room) => room.daemon !== null && !room.daemon.retired && room.daemon.ws.readyState === WebSocket.OPEN ? room.daemon : null;
|
|
249
|
+
const sendPeerClose = (room, connId, reason) => {
|
|
250
|
+
const daemon = liveDaemon(room);
|
|
251
|
+
if (daemon === null)
|
|
252
|
+
return;
|
|
253
|
+
daemon.ws.send(encodeRelayEnvelope({ op: RelayOp.PEER_CLOSE, connId, payload: Buffer.from(JSON.stringify({ reason }), "utf8") }), { binary: true });
|
|
254
|
+
};
|
|
255
|
+
const closePeer = (room, peer, code, reason, notifyDaemon) => {
|
|
256
|
+
if (peer.closed)
|
|
257
|
+
return;
|
|
258
|
+
peer.closed = true;
|
|
259
|
+
if (peer.timer !== null)
|
|
260
|
+
clearTimeout(peer.timer);
|
|
261
|
+
room.peers.delete(peer.connId);
|
|
262
|
+
if (peer.ws.readyState === WebSocket.OPEN || peer.ws.readyState === WebSocket.CONNECTING)
|
|
263
|
+
peer.ws.close(code, reason);
|
|
264
|
+
if (notifyDaemon)
|
|
265
|
+
sendPeerClose(room, peer.connId, reason);
|
|
266
|
+
log({ event: "close", leg: peer.role, code, reason, machine: idTag(room.machineId) });
|
|
267
|
+
};
|
|
268
|
+
const armPeerTimer = (room, peer) => {
|
|
269
|
+
if (peer.timer !== null)
|
|
270
|
+
clearTimeout(peer.timer);
|
|
271
|
+
const firstFrame = !peer.firstFrame;
|
|
272
|
+
peer.timer = setTimeout(() => {
|
|
273
|
+
closePeer(room, peer, RelayClose.timeout, firstFrame ? "first_frame_timeout" : "idle_timeout", true);
|
|
274
|
+
}, firstFrame ? phoneFirstFrameMs : phoneIdleMs);
|
|
275
|
+
peer.timer.unref?.();
|
|
276
|
+
};
|
|
277
|
+
const armDaemonTimer = (room, daemon) => {
|
|
278
|
+
if (daemon.timer !== null)
|
|
279
|
+
clearTimeout(daemon.timer);
|
|
280
|
+
daemon.timer = setTimeout(() => {
|
|
281
|
+
if (room.daemon === daemon && !daemon.retired)
|
|
282
|
+
daemon.ws.close(RelayClose.timeout, "heartbeat_timeout");
|
|
283
|
+
}, daemonSilenceMs);
|
|
284
|
+
daemon.timer.unref?.();
|
|
285
|
+
};
|
|
286
|
+
const retireDaemon = (room, code, reason) => {
|
|
287
|
+
const daemon = room.daemon;
|
|
288
|
+
if (daemon !== null) {
|
|
289
|
+
daemon.retired = true;
|
|
290
|
+
if (daemon.timer !== null)
|
|
291
|
+
clearTimeout(daemon.timer);
|
|
292
|
+
if (code !== null && (daemon.ws.readyState === WebSocket.OPEN || daemon.ws.readyState === WebSocket.CONNECTING))
|
|
293
|
+
daemon.ws.close(code, reason);
|
|
294
|
+
}
|
|
295
|
+
room.daemon = null;
|
|
296
|
+
for (const peer of [...room.peers.values()])
|
|
297
|
+
closePeer(room, peer, RelayClose.daemonGone, "daemon_gone", false);
|
|
298
|
+
};
|
|
299
|
+
const pruneRoom = (room, now) => {
|
|
300
|
+
for (const [id, stone] of room.tombstones)
|
|
301
|
+
if (stone.expiresAtMs <= now)
|
|
302
|
+
room.tombstones.delete(id);
|
|
303
|
+
room.replay.prune(Math.floor(now / 1000));
|
|
304
|
+
};
|
|
305
|
+
const addTombstone = (room, deviceId, pub, now) => {
|
|
306
|
+
room.tombstones.delete(deviceId);
|
|
307
|
+
if (room.tombstones.size >= L.tombstonesPerMachine) {
|
|
308
|
+
let oldest = null, oldestAt = Infinity;
|
|
309
|
+
for (const [id, stone] of room.tombstones)
|
|
310
|
+
if (stone.expiresAtMs < oldestAt) {
|
|
311
|
+
oldest = id;
|
|
312
|
+
oldestAt = stone.expiresAtMs;
|
|
313
|
+
}
|
|
314
|
+
if (oldest !== null)
|
|
315
|
+
room.tombstones.delete(oldest);
|
|
316
|
+
}
|
|
317
|
+
room.tombstones.set(deviceId, { pub, expiresAtMs: now + L.tombstoneMs });
|
|
318
|
+
};
|
|
319
|
+
const sweep = () => {
|
|
320
|
+
const now = nowMs();
|
|
321
|
+
for (const room of [...rooms.values()]) {
|
|
322
|
+
if (room.daemon === null && room.peers.size === 0 && now - room.lastDaemonAtMs >= L.roomIdleDeleteMs) {
|
|
323
|
+
rooms.delete(room.machineId);
|
|
324
|
+
log({ event: "room_gc", machine: idTag(room.machineId) });
|
|
325
|
+
continue;
|
|
326
|
+
}
|
|
327
|
+
pruneRoom(room, now);
|
|
328
|
+
}
|
|
329
|
+
};
|
|
330
|
+
const sweepTimer = setInterval(sweep, 60 * 60 * 1000);
|
|
331
|
+
sweepTimer.unref?.();
|
|
332
|
+
const newRoom = (machineId, pub, now) => ({
|
|
333
|
+
machineId,
|
|
334
|
+
pub,
|
|
335
|
+
devices: new Map(),
|
|
336
|
+
tombstones: new Map(),
|
|
337
|
+
replay: new RelayReplayCache(),
|
|
338
|
+
daemon: null,
|
|
339
|
+
epoch: 0,
|
|
340
|
+
peers: new Map(),
|
|
341
|
+
nextConnId: 1,
|
|
342
|
+
lastDaemonAtMs: now,
|
|
343
|
+
lastActiveMs: now,
|
|
344
|
+
up: new TokenBucket(L.machineUp.bytesPerMin, L.machineUp.bytesBurst, now),
|
|
345
|
+
down: new TokenBucket(L.machineDown.bytesPerMin, L.machineDown.bytesBurst, now),
|
|
346
|
+
});
|
|
347
|
+
const bearer = (req) => {
|
|
348
|
+
const auth = req.headers["authorization"];
|
|
349
|
+
if (typeof auth !== "string" || !auth.startsWith("Bearer "))
|
|
350
|
+
return null;
|
|
351
|
+
return auth.slice(7).trim() || null;
|
|
352
|
+
};
|
|
353
|
+
const checkClaims = (parsed, use) => {
|
|
354
|
+
const checked = checkRelayClaims(parsed, { aud: publicHost, use, nowSec: Math.floor(nowMs() / 1000), ...(use === "ws" ? {} : { role: "daemon" }) });
|
|
355
|
+
return checked.ok ? { jti: checked.claims.jti, exp: checked.claims.exp } : { refusal: { status: 401, code: checked.code } };
|
|
356
|
+
};
|
|
357
|
+
const consumeJti = (room, parsed, jti, exp) => {
|
|
358
|
+
const consumed = room.replay.consume(replayPrincipalOf(parsed), jti, exp, relayTokenMaxUses(parsed.role), Math.floor(nowMs() / 1000));
|
|
359
|
+
if (consumed === "replayed")
|
|
360
|
+
return { status: 401, code: "token_invalid" };
|
|
361
|
+
if (consumed === "full")
|
|
362
|
+
return { status: 429, code: "replay_cache_full", retryAfterSec: 30 };
|
|
363
|
+
return null;
|
|
364
|
+
};
|
|
365
|
+
const admitDaemonCall = (req, machineId, method, path) => {
|
|
366
|
+
const token = bearer(req);
|
|
367
|
+
const parsed = token === null ? null : parseRelayToken(token);
|
|
368
|
+
if (parsed === null)
|
|
369
|
+
return { refusal: { status: 401, code: "token_invalid" } };
|
|
370
|
+
const room = rooms.get(machineId);
|
|
371
|
+
if (room === undefined)
|
|
372
|
+
return { refusal: { status: 404, code: "machine_unknown" } };
|
|
373
|
+
if (parsed.machineId !== machineId || !ed25519Verify(room.pub, parsed.signingInput, parsed.signature)) {
|
|
374
|
+
return { refusal: { status: 401, code: "token_invalid" } };
|
|
375
|
+
}
|
|
376
|
+
const claims = checkClaims(parsed, { method, path });
|
|
377
|
+
if (claims.refusal !== undefined)
|
|
378
|
+
return { refusal: claims.refusal };
|
|
379
|
+
const refusal = consumeJti(room, parsed, claims.jti, claims.exp);
|
|
380
|
+
return refusal === null ? { room } : { refusal };
|
|
381
|
+
};
|
|
382
|
+
const handleHttp = async (req, res) => {
|
|
383
|
+
const url = new URL(req.url ?? "/", "http://relay.invalid");
|
|
384
|
+
const path = url.pathname;
|
|
385
|
+
const route = path.startsWith("/v1/machines/") ? path.replace(/^\/v1\/machines\/[^/]+/, "/v1/machines/:id").replace(/\/devices\/[^/]+$/, "/devices/:id") : path;
|
|
386
|
+
const refuse = (refusal, extra = {}) => sendRefusal(res, refused(route, refusal, extra));
|
|
387
|
+
if (req.method === "GET" && path === "/v1/health") {
|
|
388
|
+
const shedding = breakerOpen();
|
|
389
|
+
sendJson(res, shedding ? 503 : 200, { ok: !shedding, version: 1, runtime: "reference", build: opts.build ?? "dev", configured: { publicHost: publicHost.length > 0 } });
|
|
390
|
+
return;
|
|
391
|
+
}
|
|
392
|
+
if (breakerOpen()) {
|
|
393
|
+
refuse({ status: 429, code: "rate_limited", retryAfterSec: 60 });
|
|
394
|
+
return;
|
|
395
|
+
}
|
|
396
|
+
const ip = clientKey(req);
|
|
397
|
+
if (req.method === "POST" && (path === "/v1/challenge" || path === "/v1/machines/register")) {
|
|
398
|
+
const limited = registerLimit.take(ip, nowMs());
|
|
399
|
+
if (limited !== null) {
|
|
400
|
+
refuse(limited);
|
|
401
|
+
return;
|
|
402
|
+
}
|
|
403
|
+
if (path === "/v1/challenge") {
|
|
404
|
+
sendJson(res, 200, { challenge: mintChallenge(), expiresInSec: L.challengeTtlMs / 1000 });
|
|
405
|
+
return;
|
|
406
|
+
}
|
|
407
|
+
const body = await readJsonBody(req, L.registerBodyBytes);
|
|
408
|
+
if (body === null || typeof body["relayMachinePub"] !== "string" || typeof body["challenge"] !== "string" || typeof body["signature"] !== "string") {
|
|
409
|
+
refuse({ status: 400, code: "bad_request" });
|
|
410
|
+
return;
|
|
411
|
+
}
|
|
412
|
+
if (relayKeyOrNull(body["relayMachinePub"]) === null) {
|
|
413
|
+
refuse({ status: 400, code: "bad_request" });
|
|
414
|
+
return;
|
|
415
|
+
}
|
|
416
|
+
if (!challengeValid(body["challenge"])) {
|
|
417
|
+
refuse({ status: 401, code: "token_invalid" });
|
|
418
|
+
return;
|
|
419
|
+
}
|
|
420
|
+
const checked = verifyMachineRegistration({
|
|
421
|
+
relayMachinePubB64: body["relayMachinePub"],
|
|
422
|
+
relayHost: publicHost,
|
|
423
|
+
challenge: body["challenge"],
|
|
424
|
+
signatureB64: body["signature"],
|
|
425
|
+
});
|
|
426
|
+
if (!checked.ok) {
|
|
427
|
+
refuse({ status: 401, code: "token_invalid" });
|
|
428
|
+
return;
|
|
429
|
+
}
|
|
430
|
+
const now = nowMs();
|
|
431
|
+
const existing = rooms.get(checked.machineId);
|
|
432
|
+
if (existing !== undefined) {
|
|
433
|
+
existing.lastActiveMs = now;
|
|
434
|
+
}
|
|
435
|
+
else {
|
|
436
|
+
if (rooms.size >= maxRooms) {
|
|
437
|
+
const now = nowMs();
|
|
438
|
+
let victim = null;
|
|
439
|
+
for (const room of rooms.values()) {
|
|
440
|
+
const idle = room.daemon === null && room.peers.size === 0;
|
|
441
|
+
const empty = room.devices.size === 0 && room.tombstones.size === 0;
|
|
442
|
+
const expired = now - room.lastDaemonAtMs >= L.roomIdleDeleteMs;
|
|
443
|
+
if (idle && (empty || expired) && (victim === null || room.lastActiveMs < victim.lastActiveMs))
|
|
444
|
+
victim = room;
|
|
445
|
+
}
|
|
446
|
+
if (victim === null) {
|
|
447
|
+
refuse({ status: 429, code: "rate_limited", retryAfterSec: 60 });
|
|
448
|
+
return;
|
|
449
|
+
}
|
|
450
|
+
rooms.delete(victim.machineId);
|
|
451
|
+
}
|
|
452
|
+
rooms.set(checked.machineId, newRoom(checked.machineId, checked.publicKey, now));
|
|
453
|
+
}
|
|
454
|
+
sendJson(res, 200, { machineId: checked.machineId });
|
|
455
|
+
return;
|
|
456
|
+
}
|
|
457
|
+
const machineMatch = /^\/v1\/machines\/([a-z2-7]{26})(\/devices(?:\/([^/]*))?)?$/.exec(path);
|
|
458
|
+
const method = req.method;
|
|
459
|
+
if (machineMatch === null || (method !== "PUT" && method !== "POST" && method !== "DELETE")) {
|
|
460
|
+
refuse({ status: 400, code: "bad_request" });
|
|
461
|
+
return;
|
|
462
|
+
}
|
|
463
|
+
const machineId = machineMatch[1];
|
|
464
|
+
const devicesPath = machineMatch[2] !== undefined;
|
|
465
|
+
const deviceSegment = machineMatch[3];
|
|
466
|
+
const shapeOk = !devicesPath ? method === "DELETE"
|
|
467
|
+
: deviceSegment === undefined ? method === "PUT" || method === "POST"
|
|
468
|
+
: method === "DELETE";
|
|
469
|
+
if (!shapeOk) {
|
|
470
|
+
refuse({ status: 400, code: "bad_request" });
|
|
471
|
+
return;
|
|
472
|
+
}
|
|
473
|
+
const limited = clientLimit.take(ip, nowMs()) ?? connectLimit.take(`${machineId}|${ip}`, nowMs());
|
|
474
|
+
if (limited !== null) {
|
|
475
|
+
refuse(limited);
|
|
476
|
+
return;
|
|
477
|
+
}
|
|
478
|
+
const admitted = admitDaemonCall(req, machineId, method, path);
|
|
479
|
+
if (admitted.refusal !== undefined) {
|
|
480
|
+
refuse(admitted.refusal, { machine: idTag(machineId) });
|
|
481
|
+
return;
|
|
482
|
+
}
|
|
483
|
+
const room = admitted.room;
|
|
484
|
+
const now = nowMs();
|
|
485
|
+
room.lastActiveMs = now;
|
|
486
|
+
if (!devicesPath) {
|
|
487
|
+
retireDaemon(room, RelayClose.normal, "machine_deleted");
|
|
488
|
+
rooms.delete(machineId);
|
|
489
|
+
log({ event: "machine_deleted", machine: idTag(machineId) });
|
|
490
|
+
sendJson(res, 200, { ok: true });
|
|
491
|
+
return;
|
|
492
|
+
}
|
|
493
|
+
if (method === "DELETE") {
|
|
494
|
+
const deviceId = deviceSegment;
|
|
495
|
+
if (!RELAY_ID_PATTERN.test(deviceId)) {
|
|
496
|
+
refuse({ status: 400, code: "bad_request" });
|
|
497
|
+
return;
|
|
498
|
+
}
|
|
499
|
+
const pub = room.devices.get(deviceId);
|
|
500
|
+
if (pub !== undefined) {
|
|
501
|
+
room.devices.delete(deviceId);
|
|
502
|
+
addTombstone(room, deviceId, pub, now);
|
|
503
|
+
}
|
|
504
|
+
for (const peer of [...room.peers.values()]) {
|
|
505
|
+
if (peer.role === "device" && peer.peerId === deviceId)
|
|
506
|
+
closePeer(room, peer, RelayClose.revoked, "device_revoked", true);
|
|
507
|
+
}
|
|
508
|
+
sendJson(res, 200, { ok: true });
|
|
509
|
+
return;
|
|
510
|
+
}
|
|
511
|
+
if (method === "POST") {
|
|
512
|
+
const body = await readJsonBody(req, L.postBodyBytes);
|
|
513
|
+
const deviceId = body?.["deviceId"];
|
|
514
|
+
const pub = relayKeyOrNull(body?.["deviceRelayPub"]);
|
|
515
|
+
if (typeof deviceId !== "string" || !RELAY_ID_PATTERN.test(deviceId) || pub === null) {
|
|
516
|
+
refuse({ status: 400, code: "bad_request" });
|
|
517
|
+
return;
|
|
518
|
+
}
|
|
519
|
+
if (rooms.get(machineId) !== room) {
|
|
520
|
+
refuse({ status: 404, code: "machine_unknown" });
|
|
521
|
+
return;
|
|
522
|
+
}
|
|
523
|
+
const current = room.devices.get(deviceId);
|
|
524
|
+
if (current === undefined && room.devices.size >= L.devicesPerMachine) {
|
|
525
|
+
refuse({ status: 400, code: "bad_request" });
|
|
526
|
+
return;
|
|
527
|
+
}
|
|
528
|
+
if (current !== undefined && !current.equals(pub))
|
|
529
|
+
supersedeDevice(room, deviceId);
|
|
530
|
+
room.devices.set(deviceId, pub);
|
|
531
|
+
room.tombstones.delete(deviceId);
|
|
532
|
+
sendJson(res, 200, { ok: true });
|
|
533
|
+
return;
|
|
534
|
+
}
|
|
535
|
+
const body = await readJsonBody(req, L.putBodyBytes);
|
|
536
|
+
const list = body?.["devices"];
|
|
537
|
+
if (!Array.isArray(list) || list.length > L.devicesPerMachine) {
|
|
538
|
+
refuse({ status: 400, code: "bad_request" });
|
|
539
|
+
return;
|
|
540
|
+
}
|
|
541
|
+
const next = new Map();
|
|
542
|
+
for (const item of list) {
|
|
543
|
+
const entry = item !== null && typeof item === "object" && !Array.isArray(item) ? item : null;
|
|
544
|
+
const deviceId = entry?.["deviceId"];
|
|
545
|
+
const pub = relayKeyOrNull(entry?.["deviceRelayPub"]);
|
|
546
|
+
if (typeof deviceId !== "string" || !RELAY_ID_PATTERN.test(deviceId) || pub === null || next.has(deviceId)) {
|
|
547
|
+
refuse({ status: 400, code: "bad_request" });
|
|
548
|
+
return;
|
|
549
|
+
}
|
|
550
|
+
next.set(deviceId, pub);
|
|
551
|
+
}
|
|
552
|
+
if (rooms.get(machineId) !== room) {
|
|
553
|
+
refuse({ status: 404, code: "machine_unknown" });
|
|
554
|
+
return;
|
|
555
|
+
}
|
|
556
|
+
for (const [deviceId, pub] of room.devices) {
|
|
557
|
+
if (!next.has(deviceId))
|
|
558
|
+
addTombstone(room, deviceId, pub, now);
|
|
559
|
+
}
|
|
560
|
+
const previous = room.devices;
|
|
561
|
+
room.devices = next;
|
|
562
|
+
for (const deviceId of next.keys())
|
|
563
|
+
room.tombstones.delete(deviceId);
|
|
564
|
+
for (const peer of [...room.peers.values()]) {
|
|
565
|
+
if (peer.role !== "device")
|
|
566
|
+
continue;
|
|
567
|
+
if (!next.has(peer.peerId))
|
|
568
|
+
closePeer(room, peer, RelayClose.revoked, "device_revoked", true);
|
|
569
|
+
else if (!previous.get(peer.peerId)?.equals(next.get(peer.peerId)))
|
|
570
|
+
closePeer(room, peer, RelayClose.superseded, "superseded", true);
|
|
571
|
+
}
|
|
572
|
+
sendJson(res, 200, { ok: true, devices: next.size });
|
|
573
|
+
};
|
|
574
|
+
const supersedeDevice = (room, deviceId) => {
|
|
575
|
+
for (const peer of [...room.peers.values()]) {
|
|
576
|
+
if (peer.role === "device" && peer.peerId === deviceId)
|
|
577
|
+
closePeer(room, peer, RelayClose.superseded, "superseded", true);
|
|
578
|
+
}
|
|
579
|
+
};
|
|
580
|
+
const httpServer = createServer((req, res) => {
|
|
581
|
+
handleHttp(req, res).catch(() => {
|
|
582
|
+
if (!res.headersSent)
|
|
583
|
+
sendRefusal(res, { status: 400, code: "bad_request" });
|
|
584
|
+
else
|
|
585
|
+
res.destroy();
|
|
586
|
+
});
|
|
587
|
+
});
|
|
588
|
+
httpServer.headersTimeout = 10_000;
|
|
589
|
+
httpServer.requestTimeout = 15_000;
|
|
590
|
+
httpServer.keepAliveTimeout = 5_000;
|
|
591
|
+
const wss = new WebSocketServer({ noServer: true, maxPayload: MAX_DAEMON_WS_FRAME_BYTES * 2 });
|
|
592
|
+
httpServer.on("upgrade", (req, socket, head) => {
|
|
593
|
+
try {
|
|
594
|
+
upgrade(req, socket, head);
|
|
595
|
+
}
|
|
596
|
+
catch {
|
|
597
|
+
rejectUpgrade(socket, { status: 400, code: "bad_request" });
|
|
598
|
+
}
|
|
599
|
+
});
|
|
600
|
+
const upgrade = (req, socket, head) => {
|
|
601
|
+
const url = new URL(req.url ?? "/", "http://relay.invalid");
|
|
602
|
+
const reject = (refusal, extra = {}) => rejectUpgrade(socket, refused("/v1/connect", refusal, extra));
|
|
603
|
+
if (url.pathname !== "/v1/connect") {
|
|
604
|
+
reject({ status: 400, code: "bad_request" });
|
|
605
|
+
return;
|
|
606
|
+
}
|
|
607
|
+
if (breakerOpen()) {
|
|
608
|
+
reject({ status: 429, code: "rate_limited", retryAfterSec: 60 });
|
|
609
|
+
return;
|
|
610
|
+
}
|
|
611
|
+
const ip = clientKey(req);
|
|
612
|
+
if ((socketsByIp.get(ip) ?? 0) >= maxSocketsPerIp) {
|
|
613
|
+
reject({ status: 429, code: "rate_limited", retryAfterSec: 30 });
|
|
614
|
+
return;
|
|
615
|
+
}
|
|
616
|
+
const clientLimited = clientLimit.take(ip, nowMs());
|
|
617
|
+
if (clientLimited !== null) {
|
|
618
|
+
reject(clientLimited);
|
|
619
|
+
return;
|
|
620
|
+
}
|
|
621
|
+
const token = bearer(req);
|
|
622
|
+
const parsed = token === null ? null : parseRelayToken(token);
|
|
623
|
+
if (parsed === null) {
|
|
624
|
+
reject({ status: 401, code: "token_invalid" });
|
|
625
|
+
return;
|
|
626
|
+
}
|
|
627
|
+
const tag = { role: parsed.role, machine: idTag(parsed.machineId) };
|
|
628
|
+
const limited = connectLimit.take(`${parsed.machineId}|${ip}`, nowMs());
|
|
629
|
+
if (limited !== null) {
|
|
630
|
+
reject(limited, tag);
|
|
631
|
+
return;
|
|
632
|
+
}
|
|
633
|
+
const room = rooms.get(parsed.machineId);
|
|
634
|
+
if (room === undefined) {
|
|
635
|
+
reject({ status: 404, code: "machine_unknown" }, tag);
|
|
636
|
+
return;
|
|
637
|
+
}
|
|
638
|
+
let verifyKey;
|
|
639
|
+
let revoked = false;
|
|
640
|
+
if (parsed.role === "device") {
|
|
641
|
+
const live = room.devices.get(parsed.deviceId);
|
|
642
|
+
const stone = live === undefined ? room.tombstones.get(parsed.deviceId) : undefined;
|
|
643
|
+
if (live === undefined && stone === undefined) {
|
|
644
|
+
reject(liveDaemon(room) === null ? { status: 503, code: "daemon_unavailable" } : { status: 404, code: "device_unknown" }, tag);
|
|
645
|
+
return;
|
|
646
|
+
}
|
|
647
|
+
verifyKey = live ?? stone.pub;
|
|
648
|
+
revoked = live === undefined;
|
|
649
|
+
}
|
|
650
|
+
else {
|
|
651
|
+
verifyKey = room.pub;
|
|
652
|
+
}
|
|
653
|
+
if (!ed25519Verify(verifyKey, parsed.signingInput, parsed.signature)) {
|
|
654
|
+
reject({ status: 401, code: "token_invalid" }, tag);
|
|
655
|
+
return;
|
|
656
|
+
}
|
|
657
|
+
const claims = checkClaims(parsed, "ws");
|
|
658
|
+
if (claims.refusal !== undefined) {
|
|
659
|
+
reject(claims.refusal, tag);
|
|
660
|
+
return;
|
|
661
|
+
}
|
|
662
|
+
if (revoked) {
|
|
663
|
+
reject({ status: 403, code: "device_revoked" }, tag);
|
|
664
|
+
return;
|
|
665
|
+
}
|
|
666
|
+
const replay = consumeJti(room, parsed, claims.jti, claims.exp);
|
|
667
|
+
if (replay !== null) {
|
|
668
|
+
reject(replay, tag);
|
|
669
|
+
return;
|
|
670
|
+
}
|
|
671
|
+
if (parsed.role === "daemon") {
|
|
672
|
+
wss.handleUpgrade(req, socket, head, ws => attachDaemon(room, ws, ip));
|
|
673
|
+
return;
|
|
674
|
+
}
|
|
675
|
+
if (liveDaemon(room) === null) {
|
|
676
|
+
reject({ status: 503, code: "daemon_unavailable" }, tag);
|
|
677
|
+
return;
|
|
678
|
+
}
|
|
679
|
+
const peerId = parsed.deviceId ?? parsed.pairSessionId;
|
|
680
|
+
const others = [...room.peers.values()].filter(peer => !(parsed.role === "device" && peer.role === "device" && peer.peerId === peerId));
|
|
681
|
+
if (others.length >= L.socketsPerMachine) {
|
|
682
|
+
reject({ status: 429, code: "too_many_peers", retryAfterSec: 5 }, tag);
|
|
683
|
+
return;
|
|
684
|
+
}
|
|
685
|
+
wss.handleUpgrade(req, socket, head, ws => {
|
|
686
|
+
if (parsed.role === "device") {
|
|
687
|
+
for (const peer of [...room.peers.values()]) {
|
|
688
|
+
if (peer.role === "device" && peer.peerId === peerId)
|
|
689
|
+
closePeer(room, peer, RelayClose.superseded, "superseded", true);
|
|
690
|
+
}
|
|
691
|
+
}
|
|
692
|
+
attachPeer(room, ws, parsed.role, peerId, ip);
|
|
693
|
+
});
|
|
694
|
+
};
|
|
695
|
+
const trackIp = (ws, ip) => {
|
|
696
|
+
socketsByIp.set(ip, (socketsByIp.get(ip) ?? 0) + 1);
|
|
697
|
+
ws.once("close", () => {
|
|
698
|
+
const left = (socketsByIp.get(ip) ?? 1) - 1;
|
|
699
|
+
if (left <= 0)
|
|
700
|
+
socketsByIp.delete(ip);
|
|
701
|
+
else
|
|
702
|
+
socketsByIp.set(ip, left);
|
|
703
|
+
});
|
|
704
|
+
};
|
|
705
|
+
const attachDaemon = (room, ws, ip) => {
|
|
706
|
+
trackIp(ws, ip);
|
|
707
|
+
if (room.daemon !== null)
|
|
708
|
+
retireDaemon(room, RelayClose.superseded, "superseded");
|
|
709
|
+
room.epoch += 1;
|
|
710
|
+
const daemon = { ws, epoch: room.epoch, retired: false, timer: null };
|
|
711
|
+
room.daemon = daemon;
|
|
712
|
+
room.lastDaemonAtMs = nowMs();
|
|
713
|
+
room.lastActiveMs = room.lastDaemonAtMs;
|
|
714
|
+
armDaemonTimer(room, daemon);
|
|
715
|
+
ws.on("message", (raw, isBinary) => {
|
|
716
|
+
if (daemon.retired)
|
|
717
|
+
return;
|
|
718
|
+
armDaemonTimer(room, daemon);
|
|
719
|
+
if (!isBinary) {
|
|
720
|
+
ws.close(RelayClose.protocol, "binary_only");
|
|
721
|
+
return;
|
|
722
|
+
}
|
|
723
|
+
const buf = rawDataToBuffer(raw);
|
|
724
|
+
if (buf.length < RELAY_ENVELOPE_HEADER_BYTES || buf.length > MAX_DAEMON_WS_FRAME_BYTES) {
|
|
725
|
+
ws.close(RelayClose.protocol, "oversize");
|
|
726
|
+
return;
|
|
727
|
+
}
|
|
728
|
+
const op = buf[0];
|
|
729
|
+
const connId = buf.readUInt32BE(1);
|
|
730
|
+
const payload = buf.subarray(RELAY_ENVELOPE_HEADER_BYTES);
|
|
731
|
+
if (op === RelayOp.HEARTBEAT) {
|
|
732
|
+
if (connId !== 0 || payload.length !== HEARTBEAT_PAYLOAD_BYTES) {
|
|
733
|
+
ws.close(RelayClose.protocol, "protocol");
|
|
734
|
+
return;
|
|
735
|
+
}
|
|
736
|
+
ws.send(encodeRelayEnvelope({ op: RelayOp.HEARTBEAT_ACK, connId: 0, payload }), { binary: true });
|
|
737
|
+
return;
|
|
738
|
+
}
|
|
739
|
+
if (op === RelayOp.PEER_CLOSE) {
|
|
740
|
+
const peer = room.peers.get(connId);
|
|
741
|
+
if (peer !== undefined)
|
|
742
|
+
closePeer(room, peer, RelayClose.normal, "closed_by_daemon", false);
|
|
743
|
+
return;
|
|
744
|
+
}
|
|
745
|
+
if (op !== RelayOp.PEER_DATA) {
|
|
746
|
+
ws.close(RelayClose.protocol, "protocol");
|
|
747
|
+
return;
|
|
748
|
+
}
|
|
749
|
+
const peer = room.peers.get(connId);
|
|
750
|
+
if (peer === undefined || peer.closed)
|
|
751
|
+
return;
|
|
752
|
+
const t = nowMs();
|
|
753
|
+
if (!peer.down.take(payload.length, t) || !room.down.take(payload.length, t)) {
|
|
754
|
+
closePeer(room, peer, RelayClose.rateLimited, "rate_limited", true);
|
|
755
|
+
return;
|
|
756
|
+
}
|
|
757
|
+
countForwarded();
|
|
758
|
+
armPeerTimer(room, peer);
|
|
759
|
+
peer.ws.send(payload, { binary: true });
|
|
760
|
+
});
|
|
761
|
+
ws.on("close", () => {
|
|
762
|
+
if (daemon.timer !== null)
|
|
763
|
+
clearTimeout(daemon.timer);
|
|
764
|
+
if (room.daemon !== daemon)
|
|
765
|
+
return;
|
|
766
|
+
log({ event: "close", leg: "daemon", machine: idTag(room.machineId) });
|
|
767
|
+
retireDaemon(room, null, "daemon_gone");
|
|
768
|
+
});
|
|
769
|
+
ws.on("error", () => { });
|
|
770
|
+
};
|
|
771
|
+
const attachPeer = (room, ws, role, peerId, ip) => {
|
|
772
|
+
trackIp(ws, ip);
|
|
773
|
+
const connId = room.nextConnId;
|
|
774
|
+
room.nextConnId = room.nextConnId >= 0xffff_fff0 ? 1 : room.nextConnId + 1;
|
|
775
|
+
const t0 = nowMs();
|
|
776
|
+
const peer = {
|
|
777
|
+
connId, ws, role, peerId, closed: false, firstFrame: false, timer: null,
|
|
778
|
+
frames: new TokenBucket(L.phoneUp.framesPerMin, L.phoneUp.framesBurst, t0),
|
|
779
|
+
bytes: new TokenBucket(L.phoneUp.bytesPerMin, L.phoneUp.bytesBurst, t0),
|
|
780
|
+
down: new TokenBucket(L.phoneDown.bytesPerMin, L.phoneDown.bytesBurst, t0),
|
|
781
|
+
};
|
|
782
|
+
room.peers.set(connId, peer);
|
|
783
|
+
armPeerTimer(room, peer);
|
|
784
|
+
liveDaemon(room)?.ws.send(encodeRelayEnvelope({
|
|
785
|
+
op: RelayOp.PEER_OPEN,
|
|
786
|
+
connId,
|
|
787
|
+
payload: Buffer.from(JSON.stringify({ role, id: peerId }), "utf8"),
|
|
788
|
+
}), { binary: true });
|
|
789
|
+
ws.on("message", (raw, isBinary) => {
|
|
790
|
+
if (peer.closed)
|
|
791
|
+
return;
|
|
792
|
+
peer.firstFrame = true;
|
|
793
|
+
armPeerTimer(room, peer);
|
|
794
|
+
if (!isBinary) {
|
|
795
|
+
closePeer(room, peer, RelayClose.protocol, "binary_only", true);
|
|
796
|
+
return;
|
|
797
|
+
}
|
|
798
|
+
const buf = rawDataToBuffer(raw);
|
|
799
|
+
if (buf.length > MAX_NOISE_MESSAGE_BYTES) {
|
|
800
|
+
closePeer(room, peer, RelayClose.protocol, "oversize", true);
|
|
801
|
+
return;
|
|
802
|
+
}
|
|
803
|
+
if (breakerOpen()) {
|
|
804
|
+
closePeer(room, peer, RelayClose.rateLimited, "rate_limited", true);
|
|
805
|
+
return;
|
|
806
|
+
}
|
|
807
|
+
const t = nowMs();
|
|
808
|
+
if (!peer.frames.take(1, t) || !peer.bytes.take(buf.length, t) || !room.up.take(buf.length, t)) {
|
|
809
|
+
closePeer(room, peer, RelayClose.rateLimited, "rate_limited", true);
|
|
810
|
+
return;
|
|
811
|
+
}
|
|
812
|
+
const daemon = liveDaemon(room);
|
|
813
|
+
if (daemon === null) {
|
|
814
|
+
closePeer(room, peer, RelayClose.daemonGone, "daemon_gone", false);
|
|
815
|
+
return;
|
|
816
|
+
}
|
|
817
|
+
countForwarded();
|
|
818
|
+
daemon.ws.send(encodeRelayEnvelope({ op: RelayOp.PEER_DATA, connId, payload: buf }), { binary: true });
|
|
819
|
+
});
|
|
820
|
+
ws.on("close", () => {
|
|
821
|
+
if (peer.closed)
|
|
822
|
+
return;
|
|
823
|
+
peer.closed = true;
|
|
824
|
+
if (peer.timer !== null)
|
|
825
|
+
clearTimeout(peer.timer);
|
|
826
|
+
room.peers.delete(connId);
|
|
827
|
+
sendPeerClose(room, connId, "peer_closed");
|
|
828
|
+
});
|
|
829
|
+
ws.on("error", () => { });
|
|
830
|
+
};
|
|
831
|
+
await new Promise((resolve, reject) => {
|
|
832
|
+
httpServer.once("error", reject);
|
|
833
|
+
httpServer.listen(opts.port ?? 0, opts.host ?? "127.0.0.1", () => {
|
|
834
|
+
httpServer.off("error", reject);
|
|
835
|
+
resolve();
|
|
836
|
+
});
|
|
837
|
+
});
|
|
838
|
+
const addr = httpServer.address();
|
|
839
|
+
const port = typeof addr === "object" && addr !== null ? addr.port : 0;
|
|
840
|
+
const bindHost = opts.host ?? "127.0.0.1";
|
|
841
|
+
if (publicHost.length === 0)
|
|
842
|
+
publicHost = `${bindHost}:${port}`.toLowerCase();
|
|
843
|
+
return {
|
|
844
|
+
url: `http://${bindHost}:${port}`,
|
|
845
|
+
wsUrl: `ws://${bindHost}:${port}/v1/connect`,
|
|
846
|
+
port,
|
|
847
|
+
publicHost,
|
|
848
|
+
sweep,
|
|
849
|
+
stats: () => ({ machines: rooms.size, forwardedThisWindow }),
|
|
850
|
+
replayRows: machineId => rooms.get(machineId)?.replay.size ?? null,
|
|
851
|
+
close: async () => {
|
|
852
|
+
clearInterval(sweepTimer);
|
|
853
|
+
for (const room of rooms.values()) {
|
|
854
|
+
for (const peer of [...room.peers.values()])
|
|
855
|
+
closePeer(room, peer, 1001, "relay_shutdown", false);
|
|
856
|
+
if (room.daemon !== null) {
|
|
857
|
+
room.daemon.retired = true;
|
|
858
|
+
if (room.daemon.timer !== null)
|
|
859
|
+
clearTimeout(room.daemon.timer);
|
|
860
|
+
room.daemon.ws.close(1001, "relay_shutdown");
|
|
861
|
+
}
|
|
862
|
+
}
|
|
863
|
+
for (const client of wss.clients)
|
|
864
|
+
client.terminate();
|
|
865
|
+
await new Promise(resolve => wss.close(() => resolve()));
|
|
866
|
+
httpServer.closeAllConnections();
|
|
867
|
+
await new Promise(resolve => httpServer.close(() => resolve()));
|
|
868
|
+
},
|
|
869
|
+
};
|
|
870
|
+
}
|