toolroll 0.9.127 → 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.
Files changed (57) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +2 -1
  3. package/dist/accent-colors.js +3 -1
  4. package/dist/approval-authority.js +2 -1
  5. package/dist/assignment.js +55 -2
  6. package/dist/backup.js +6 -0
  7. package/dist/browser/terminal.css +1 -1
  8. package/dist/browser/workspace.css +2 -2
  9. package/dist/browser/workspace.js +9 -9
  10. package/dist/central-recovery-stage.js +3 -3
  11. package/dist/companion/access.js +161 -0
  12. package/dist/companion/actions.js +559 -0
  13. package/dist/companion/bonjour.js +45 -0
  14. package/dist/companion/daemon.js +1346 -0
  15. package/dist/companion/direct-server.js +177 -0
  16. package/dist/companion/framing.js +498 -0
  17. package/dist/companion/noise.js +461 -0
  18. package/dist/companion/passkey-gate.js +287 -0
  19. package/dist/companion/paths.js +90 -0
  20. package/dist/companion/reads.js +279 -0
  21. package/dist/companion/relay-auth.js +265 -0
  22. package/dist/companion/relay-server.js +870 -0
  23. package/dist/companion/schema.js +225 -0
  24. package/dist/companion/service.js +580 -0
  25. package/dist/companion/store.js +324 -0
  26. package/dist/companion/webauthn-test-support.js +44 -0
  27. package/dist/companion/webauthn.js +398 -0
  28. package/dist/contracts/console-api.js +18 -0
  29. package/dist/demo.js +1 -1
  30. package/dist/design/kit.css +36 -3
  31. package/dist/local-landing.js +47 -0
  32. package/dist/models-ui.js +5 -2
  33. package/dist/operate.js +19 -3
  34. package/dist/person-proof.js +5 -1
  35. package/dist/pull-request-flow.js +75 -2
  36. package/dist/qr.js +385 -0
  37. package/dist/release-adapters.js +2 -1
  38. package/dist/restore-retirement.js +2 -0
  39. package/dist/scope.js +67 -4
  40. package/dist/serve.js +31 -4
  41. package/dist/server/pages.js +9 -2
  42. package/dist/server/phone-engine-api.js +59 -0
  43. package/dist/server/route-table.js +11 -0
  44. package/dist/server/settings-phone.js +492 -0
  45. package/dist/server/settings-scripts.js +2 -0
  46. package/dist/server/settings-sections.js +6 -2
  47. package/dist/server/settings.js +8 -2
  48. package/dist/settings-groups-ui.js +2 -1
  49. package/dist/settings-proofs.js +6 -0
  50. package/dist/skills-ui.js +11 -6
  51. package/dist/spend-ui.js +3 -2
  52. package/dist/spend.js +8 -1
  53. package/dist/store.js +37 -4
  54. package/dist/tailnet.js +42 -0
  55. package/dist/toolroll-update.js +3 -1
  56. package/dist/youiyoux-intake.js +8 -0
  57. package/package.json +7 -2
@@ -0,0 +1,580 @@
1
+ import { WebSocket } from "ws";
2
+ import { CompanionDaemonEngine, relayEnvelopeLink } from "./daemon.js";
3
+ import { startDirectServer } from "./direct-server.js";
4
+ import { startBonjour } from "./bonjour.js";
5
+ import { PACING_PER_HOSTED_LINK, TokenBucket } from "./framing.js";
6
+ import { buildPaths, interfaceOf, lanInterfacesOf } from "./paths.js";
7
+ import { encodeRelayEnvelope, RelayOp, signRegistrationPop, signRelayToken } from "./relay-auth.js";
8
+ import { getPairedDevice, livePairedDevices } from "./store.js";
9
+ import { readTailnetStatus } from "../tailnet.js";
10
+ export function relayAddressesOf(url) {
11
+ const parsed = new URL(url);
12
+ if (parsed.protocol !== "wss:" && parsed.protocol !== "ws:" && parsed.protocol !== "https:" && parsed.protocol !== "http:") {
13
+ throw new Error("A relay URL starts with wss:// (or ws:// on this computer).");
14
+ }
15
+ const secure = parsed.protocol === "wss:" || parsed.protocol === "https:";
16
+ const loopback = parsed.hostname === "127.0.0.1" || parsed.hostname === "localhost" || parsed.hostname === "[::1]";
17
+ if (!secure && !loopback)
18
+ throw new Error("A relay off this computer needs TLS (wss://).");
19
+ const base = `${secure ? "https" : "http"}://${parsed.host}`;
20
+ return { http: base, ws: `${secure ? "wss" : "ws"}://${parsed.host}/v1/connect`, host: parsed.host.toLowerCase() };
21
+ }
22
+ const TAILNET_REFRESH_MS = 10_000;
23
+ const RELAY_BACKLOG_CAP = 16 * 1024 * 1024;
24
+ const HEARTBEAT = { intervalMs: 20_000, timeoutMs: 45_000 };
25
+ const REPUSH_MS = 10 * 60 * 1000;
26
+ const SWEEP_MS = 60 * 60 * 1000;
27
+ const SUPERSEDED_BACKOFF = { first: 30_000, max: 10 * 60 * 1000 };
28
+ const SUPERSEDED_SETTLED_MS = 10 * 60 * 1000;
29
+ const CLOSE_SUPERSEDED = 4409;
30
+ const RELAY_CALL_MS = 10_000;
31
+ const FORGET_MACHINE_MS = 5_000;
32
+ export class RelayHttpError extends Error {
33
+ status;
34
+ code;
35
+ retryAfterMs;
36
+ constructor(status, code, retryAfterMs) {
37
+ super(`the relay answered ${status}: ${describeRelayCode(code)}`);
38
+ this.status = status;
39
+ this.code = code;
40
+ this.retryAfterMs = retryAfterMs;
41
+ }
42
+ }
43
+ export function describeRelayCode(code) {
44
+ switch (code) {
45
+ case "token_expired":
46
+ case "token_not_yet_valid": return "this Mac's clock looks wrong — check Date & Time";
47
+ case "token_invalid": return "it didn't accept this Mac's credentials";
48
+ case "rate_limited":
49
+ case "too_many_peers":
50
+ case "replay_cache_full": return "it asked Toolroll to slow down";
51
+ case "machine_unknown": return "it doesn't know this Mac yet";
52
+ case "bad_request": return "it refused the request";
53
+ case "daemon_unavailable": return "it has no connection from this Mac";
54
+ default: return /^[a-z_]{1,40}$/.test(code) ? code.replace(/_/g, " ") : "an unexpected answer";
55
+ }
56
+ }
57
+ function refusalOf(status, headers, body, nowMs) {
58
+ let code = headers.get("toolroll-relay-error")?.trim() ?? "";
59
+ if (code === "") {
60
+ try {
61
+ const parsed = JSON.parse(body);
62
+ if (typeof parsed.error === "string")
63
+ code = parsed.error;
64
+ }
65
+ catch { }
66
+ }
67
+ if (!/^[a-z_]{1,40}$/.test(code))
68
+ code = `http_${status}`;
69
+ const retryAfter = headers.get("retry-after");
70
+ let retryAfterMs = null;
71
+ if (retryAfter !== null) {
72
+ const seconds = Number(retryAfter);
73
+ if (Number.isFinite(seconds) && seconds >= 0)
74
+ retryAfterMs = Math.min(seconds, 3600) * 1000;
75
+ else if (!Number.isNaN(Date.parse(retryAfter)))
76
+ retryAfterMs = Math.max(0, Math.min(Date.parse(retryAfter) - nowMs, 3_600_000));
77
+ }
78
+ return new RelayHttpError(status, code, retryAfterMs);
79
+ }
80
+ const machineUnknown = (error) => error instanceof RelayHttpError && ((error.status === 404 && error.code === "machine_unknown") || error.code === "unknown_machine");
81
+ function daemonTokenFor(keys, aud, call) {
82
+ return signRelayToken(keys.relayPriv, { role: "daemon", machineId: keys.machineId, aud, ...(call ?? {}), ttlSec: 60 });
83
+ }
84
+ export async function forgetMachineOnRelay(relayUrl, keys, timeoutMs = FORGET_MACHINE_MS) {
85
+ try {
86
+ const addresses = relayAddressesOf(relayUrl);
87
+ const path = `/v1/machines/${keys.machineId}`;
88
+ const response = await fetch(`${addresses.http}${path}`, {
89
+ method: "DELETE",
90
+ headers: { authorization: `Bearer ${daemonTokenFor(keys, addresses.host, { htm: "DELETE", htu: path })}` },
91
+ signal: AbortSignal.timeout(timeoutMs),
92
+ redirect: "error",
93
+ });
94
+ await response.arrayBuffer().catch(() => null);
95
+ return response.ok || response.status === 404;
96
+ }
97
+ catch {
98
+ return false;
99
+ }
100
+ }
101
+ export class CompanionService {
102
+ engine;
103
+ store;
104
+ opts;
105
+ log;
106
+ nowMs;
107
+ backoff;
108
+ supersededBackoff;
109
+ heartbeat;
110
+ addresses;
111
+ directServer = null;
112
+ bonjour = null;
113
+ directPort = null;
114
+ directError = null;
115
+ socket = null;
116
+ link = null;
117
+ keepalive = null;
118
+ retry = null;
119
+ sweep = null;
120
+ attempt = 0;
121
+ supersededAttempt = 0;
122
+ superseded = false;
123
+ connectGeneration = 0;
124
+ stopped = true;
125
+ hostedState = { state: "off", superseded: false };
126
+ admission = Promise.resolve();
127
+ reconcileOwed = false;
128
+ reconcileTimer = null;
129
+ reconcileAttempt = 0;
130
+ tailnet = { ip: null, found: false, at: -Infinity };
131
+ constructor(opts) {
132
+ this.store = opts.store;
133
+ this.opts = opts;
134
+ this.log = opts.log ?? (() => { });
135
+ this.nowMs = opts.nowMs ?? (() => Date.now());
136
+ this.backoff = opts.backoff ?? { first: 1_000, max: 60_000 };
137
+ this.supersededBackoff = opts.supersededBackoff ?? SUPERSEDED_BACKOFF;
138
+ this.heartbeat = opts.heartbeat ?? HEARTBEAT;
139
+ this.addresses = opts.hosted === null ? null : relayAddressesOf(opts.hosted);
140
+ this.engine = new CompanionDaemonEngine({
141
+ store: opts.store,
142
+ handlers: opts.reads,
143
+ ...(opts.actions === undefined ? {} : { actions: opts.actions }),
144
+ onDeviceRegistered: async (deviceId, deviceRelayPub) => {
145
+ if (this.addresses === null)
146
+ return;
147
+ if (this.socket === null || this.link === null) {
148
+ this.oweReconcile();
149
+ return;
150
+ }
151
+ await this.admit(() => this.relayRequest("POST", `/v1/machines/${this.engine.hostKeys.machineId}/devices`, { deviceId, deviceRelayPub }));
152
+ },
153
+ onDeviceRevoked: async (deviceId) => {
154
+ if (this.addresses === null)
155
+ return;
156
+ try {
157
+ await this.admit(() => this.relayRequest("DELETE", `/v1/machines/${this.engine.hostKeys.machineId}/devices/${encodeURIComponent(deviceId)}`));
158
+ }
159
+ catch (error) {
160
+ if (!(error instanceof RelayHttpError && error.status === 404))
161
+ this.oweReconcile();
162
+ }
163
+ },
164
+ ...(opts.nowMs === undefined ? {} : { nowMs: opts.nowMs }),
165
+ ...(opts.consoleUrl === undefined ? {} : { consoleUrl: opts.consoleUrl }),
166
+ });
167
+ this.engine.setPathsProvider(() => this.paths());
168
+ }
169
+ status() {
170
+ return { running: !this.stopped, direct: this.directStatus(), hosted: this.hostedState };
171
+ }
172
+ directStatus() {
173
+ void this.refreshTailnet();
174
+ const tailscale = this.tailnet.found ? "found" : "not_found";
175
+ if (this.directServer !== null && this.directPort !== null) {
176
+ return { state: "listening", port: this.directPort, error: null, addresses: this.directAddressList(), tailscale };
177
+ }
178
+ if (this.directError !== null)
179
+ return { state: "failed", port: null, error: this.directError, addresses: [], tailscale };
180
+ return { state: "off", port: null, error: null, addresses: [], tailscale };
181
+ }
182
+ directAddressList() {
183
+ const lan = this.opts.lanAddresses === undefined
184
+ ? lanInterfacesOf()
185
+ : this.opts.lanAddresses().map(address => ({ address, interface: interfaceOf(address) ?? "unknown" }));
186
+ const out = lan.map(one => ({ address: one.address, kind: "lan", interface: one.interface }));
187
+ if (this.tailnet.ip !== null)
188
+ out.push({ address: this.tailnet.ip, kind: "tailnet", interface: interfaceOf(this.tailnet.ip) ?? "tailscale" });
189
+ return out;
190
+ }
191
+ directAddresses() {
192
+ return this.paths().filter(path => path.kind === "direct").map(path => new URL(path.url).host);
193
+ }
194
+ paths() {
195
+ void this.refreshTailnet();
196
+ const lan = this.opts.lanAddresses === undefined ? lanInterfacesOf().map(one => one.address) : this.opts.lanAddresses();
197
+ return buildPaths({
198
+ port: this.directServer === null ? null : this.directPort,
199
+ lan,
200
+ tailnet: this.tailnet.ip,
201
+ hosted: this.addresses?.ws ?? null,
202
+ });
203
+ }
204
+ async start() {
205
+ if (!this.stopped)
206
+ return;
207
+ this.stopped = false;
208
+ await this.refreshTailnet(true);
209
+ this.runSweep();
210
+ this.sweep = setInterval(() => this.runSweep(), this.opts.sweepMs ?? SWEEP_MS);
211
+ this.sweep.unref?.();
212
+ if (this.opts.direct !== null)
213
+ await this.startDirect(this.opts.direct);
214
+ if (this.addresses !== null) {
215
+ this.hostedState = { state: "starting", relay: this.addresses.ws, superseded: this.superseded };
216
+ void this.connect();
217
+ }
218
+ }
219
+ runSweep() {
220
+ try {
221
+ this.engine.sweepRecords();
222
+ }
223
+ catch (error) {
224
+ this.log(`phone access: record sweep failed: ${error instanceof Error ? error.message : String(error)}`);
225
+ }
226
+ }
227
+ async startDirect(direct) {
228
+ const candidates = [direct.port, ...(direct.fallbackPorts ?? [])];
229
+ const order = direct.preferredPort != null && candidates.includes(direct.preferredPort) ? [direct.preferredPort, ...candidates] : candidates;
230
+ const ports = [...new Set(order)];
231
+ const busy = [];
232
+ this.directError = null;
233
+ for (const port of ports) {
234
+ try {
235
+ const server = await startDirectServer({
236
+ engine: this.engine, port, log: this.log,
237
+ ...(direct.host === undefined ? {} : { host: direct.host }),
238
+ ...(this.opts.directPeerAddressOf === undefined ? {} : { peerAddressOf: this.opts.directPeerAddressOf }),
239
+ });
240
+ if (this.stopped) {
241
+ await server.close();
242
+ return;
243
+ }
244
+ this.directServer = server;
245
+ this.directPort = server.port;
246
+ direct.onBound?.(server.port);
247
+ this.startBonjour(server.port);
248
+ return;
249
+ }
250
+ catch (error) {
251
+ if (error.code === "EADDRINUSE") {
252
+ busy.push(port);
253
+ continue;
254
+ }
255
+ this.directError = error instanceof Error ? error.message : String(error);
256
+ break;
257
+ }
258
+ }
259
+ if (this.directError === null) {
260
+ this.directError = busy.length === 1
261
+ ? `Port ${busy[0]} on this computer is in use. Set TOOLROLL_PHONE_PORT to another port and restart Toolroll.`
262
+ : `Ports ${busy[0]} and ${busy.slice(1).join(", ")} on this computer are all in use. Set TOOLROLL_PHONE_PORT to a free port and restart Toolroll.`;
263
+ }
264
+ this.log(`phone access: direct listener didn't start (${this.directError})`);
265
+ }
266
+ startBonjour(port) {
267
+ const want = this.opts.bonjour;
268
+ if (want === undefined || want === false)
269
+ return;
270
+ this.bonjour = startBonjour({
271
+ port, machineId: this.engine.hostKeys.machineId, log: this.log,
272
+ ...(typeof want === "object" && want.spawn !== undefined ? { spawn: want.spawn } : {}),
273
+ ...(typeof want === "object" && want.platform !== undefined ? { platform: want.platform } : {}),
274
+ });
275
+ }
276
+ async stop() {
277
+ this.stopped = true;
278
+ this.connectGeneration += 1;
279
+ if (this.retry !== null)
280
+ clearTimeout(this.retry);
281
+ this.retry = null;
282
+ if (this.reconcileTimer !== null)
283
+ clearTimeout(this.reconcileTimer);
284
+ this.reconcileTimer = null;
285
+ if (this.sweep !== null)
286
+ clearInterval(this.sweep);
287
+ this.sweep = null;
288
+ this.closeSocket("stopping");
289
+ this.engine.handleRelayDisconnected();
290
+ await this.admission;
291
+ this.bonjour?.stop();
292
+ this.bonjour = null;
293
+ if (this.directServer !== null) {
294
+ const server = this.directServer;
295
+ this.directServer = null;
296
+ await server.close();
297
+ }
298
+ this.directPort = null;
299
+ this.directError = null;
300
+ this.hostedState = { state: "off", superseded: false };
301
+ }
302
+ async forgetHostedMachine() {
303
+ if (this.opts.hosted === null)
304
+ return false;
305
+ return forgetMachineOnRelay(this.opts.hosted, this.engine.hostKeys);
306
+ }
307
+ startPairing(accountName, binding, accountGeneration) {
308
+ if (this.directServer === null && this.hostedState.state !== "connected") {
309
+ return { ok: false, error: this.hostedState.state === "starting" ? "Phone access is still starting. Try again in a moment." : "A phone has no way to reach this Mac right now." };
310
+ }
311
+ return this.engine.startPairing(accountName, binding, accountGeneration);
312
+ }
313
+ removePhone(deviceId, accountName) {
314
+ const device = getPairedDevice(this.store.handle, deviceId);
315
+ if (device === null || device.accountName !== accountName || device.revokedAt !== null)
316
+ return false;
317
+ return this.engine.revokeDevice(deviceId, "removed");
318
+ }
319
+ devices() {
320
+ return livePairedDevices(this.store, { now: new Date(this.nowMs()) });
321
+ }
322
+ refreshTailnet(wait = false) {
323
+ if (!wait && this.nowMs() - this.tailnet.at < TAILNET_REFRESH_MS)
324
+ return Promise.resolve();
325
+ this.tailnet.at = this.nowMs();
326
+ const probe = this.opts.tailnetIpv4 !== undefined
327
+ ? this.opts.tailnetIpv4().then(ip => ({ found: ip !== null, ipv4: ip }))
328
+ : readTailnetStatus();
329
+ const read = probe.then(found => { this.tailnet.ip = found.ipv4; this.tailnet.found = found.found; }, () => { });
330
+ return wait ? read : Promise.resolve();
331
+ }
332
+ admit(work) {
333
+ const fenced = () => this.stopped ? Promise.reject(new Error("phone access stopped")) : work();
334
+ const run = this.admission.then(fenced, fenced);
335
+ this.admission = run.then(() => { }, () => { });
336
+ return run;
337
+ }
338
+ oweReconcile() {
339
+ this.reconcileOwed = true;
340
+ if (this.reconcileTimer !== null || this.stopped || this.socket === null)
341
+ return;
342
+ const wait = Math.min(30_000, 1_000 * 2 ** Math.min(this.reconcileAttempt, 5));
343
+ this.reconcileTimer = setTimeout(() => {
344
+ this.reconcileTimer = null;
345
+ if (this.stopped || this.socket === null || !this.reconcileOwed)
346
+ return;
347
+ this.reconcile().then(() => { this.reconcileAttempt = 0; }, () => { this.reconcileAttempt += 1; this.oweReconcile(); });
348
+ }, wait);
349
+ this.reconcileTimer.unref?.();
350
+ }
351
+ async connect() {
352
+ if (this.stopped || this.addresses === null)
353
+ return;
354
+ const generation = ++this.connectGeneration;
355
+ const current = () => !this.stopped && generation === this.connectGeneration;
356
+ const relay = this.addresses.ws;
357
+ try {
358
+ await this.reconcile();
359
+ if (!current())
360
+ return;
361
+ const socket = await this.openSocket();
362
+ if (!current()) {
363
+ socket.close(1000, "stopping");
364
+ return;
365
+ }
366
+ const send = (envelope) => {
367
+ if (socket.readyState !== WebSocket.OPEN)
368
+ return;
369
+ if (socket.bufferedAmount > RELAY_BACKLOG_CAP) {
370
+ socket.close(1013, "relay_backlog");
371
+ return;
372
+ }
373
+ socket.send(envelope, { binary: true });
374
+ };
375
+ const link = relayEnvelopeLink(`hosted#${generation}`, send, { pacing: new TokenBucket(PACING_PER_HOSTED_LINK.ratePerMin, PACING_PER_HOSTED_LINK.burst, this.nowMs()) });
376
+ this.socket = socket;
377
+ this.link = link;
378
+ this.attempt = 0;
379
+ const connectedAt = this.nowMs();
380
+ this.superseded = false;
381
+ this.hostedState = { state: "connected", relay, since: new Date(connectedAt).toISOString(), superseded: false };
382
+ this.log(`phone access: connected to ${relay}`);
383
+ let lastAckAt = connectedAt;
384
+ const firstStamp = Buffer.alloc(8);
385
+ firstStamp.writeBigUInt64BE(BigInt(Math.max(0, Math.floor(connectedAt))));
386
+ send(encodeRelayEnvelope({ op: RelayOp.HEARTBEAT, connId: 0, payload: firstStamp }));
387
+ let lastBeatAt = connectedAt;
388
+ let lastRepushAt = connectedAt;
389
+ let lastAdmissionCheckAt = connectedAt;
390
+ let admitted = JSON.stringify(this.engine.admittedDevices());
391
+ const tickMs = Math.max(5, Math.min(5_000, Math.floor(this.heartbeat.intervalMs / 4)));
392
+ this.keepalive = setInterval(() => {
393
+ const now = this.nowMs();
394
+ if (now - lastAckAt > this.heartbeat.timeoutMs) {
395
+ this.log("phone access: the relay stopped answering heartbeats; reconnecting");
396
+ socket.terminate();
397
+ return;
398
+ }
399
+ if (now - lastBeatAt >= this.heartbeat.intervalMs) {
400
+ lastBeatAt = now;
401
+ const stamp = Buffer.alloc(8);
402
+ stamp.writeBigUInt64BE(BigInt(Math.max(0, Math.floor(now))));
403
+ send(encodeRelayEnvelope({ op: RelayOp.HEARTBEAT, connId: 0, payload: stamp }));
404
+ }
405
+ if (now - lastRepushAt >= (this.opts.repushMs ?? REPUSH_MS)) {
406
+ lastRepushAt = now;
407
+ this.oweReconcile();
408
+ }
409
+ if (now - lastAdmissionCheckAt >= this.heartbeat.intervalMs) {
410
+ lastAdmissionCheckAt = now;
411
+ const nowAdmitted = JSON.stringify(this.engine.admittedDevices());
412
+ if (nowAdmitted !== admitted) {
413
+ admitted = nowAdmitted;
414
+ this.oweReconcile();
415
+ }
416
+ }
417
+ }, tickMs);
418
+ this.keepalive.unref?.();
419
+ if (this.reconcileOwed)
420
+ this.oweReconcile();
421
+ socket.on("message", (raw, isBinary) => {
422
+ if (!isBinary)
423
+ return;
424
+ const buf = Buffer.isBuffer(raw) ? raw : Array.isArray(raw) ? Buffer.concat(raw) : Buffer.from(raw);
425
+ if (buf.length >= 5 && buf[0] === RelayOp.HEARTBEAT_ACK) {
426
+ lastAckAt = this.nowMs();
427
+ return;
428
+ }
429
+ this.engine.handleRelayEnvelope(buf, link).catch(error => this.log(`phone access: envelope failed: ${error instanceof Error ? error.message : String(error)}`));
430
+ });
431
+ socket.on("close", (code, reason) => {
432
+ if (this.socket !== socket)
433
+ return;
434
+ this.socket = null;
435
+ this.link = null;
436
+ if (this.keepalive !== null)
437
+ clearInterval(this.keepalive);
438
+ this.keepalive = null;
439
+ if (this.reconcileTimer !== null)
440
+ clearTimeout(this.reconcileTimer);
441
+ this.reconcileTimer = null;
442
+ this.engine.handleRelayDisconnected(link);
443
+ if (this.stopped)
444
+ return;
445
+ if (code === CLOSE_SUPERSEDED) {
446
+ if (this.nowMs() - connectedAt >= SUPERSEDED_SETTLED_MS)
447
+ this.supersededAttempt = 0;
448
+ this.scheduleSuperseded();
449
+ return;
450
+ }
451
+ this.scheduleRetry(`the relay closed the connection${reason.length > 0 ? ` (${reason.toString("utf8")})` : ""}`);
452
+ });
453
+ socket.on("error", () => { });
454
+ }
455
+ catch (error) {
456
+ if (current())
457
+ this.scheduleRetry(error instanceof Error ? error.message : String(error), error instanceof RelayHttpError ? error.retryAfterMs : null);
458
+ }
459
+ }
460
+ scheduleRetry(error, retryAfterMs = null) {
461
+ if (this.stopped || this.addresses === null)
462
+ return;
463
+ this.attempt += 1;
464
+ const ceiling = Math.min(this.backoff.max, this.backoff.first * 2 ** Math.min(this.attempt - 1, 16));
465
+ const wait = Math.max(Math.round(ceiling / 2 + Math.random() * (ceiling / 2)), retryAfterMs ?? 0);
466
+ this.hostedState = { state: "unreachable", relay: this.addresses.ws, error, retryAt: new Date(this.nowMs() + wait).toISOString(), superseded: this.superseded };
467
+ this.log(`phone access: relay unreachable (${error}); retrying in ${Math.round(wait / 1000)} s`);
468
+ this.armRetry(wait);
469
+ }
470
+ scheduleSuperseded() {
471
+ if (this.stopped || this.addresses === null)
472
+ return;
473
+ this.superseded = true;
474
+ this.supersededAttempt += 1;
475
+ const wait = Math.min(this.supersededBackoff.max, this.supersededBackoff.first * 2 ** Math.min(this.supersededAttempt - 1, 16));
476
+ const error = "Another Toolroll with this workspace's keys is connected to the relay.";
477
+ this.hostedState = { state: "unreachable", relay: this.addresses.ws, error, retryAt: new Date(this.nowMs() + wait).toISOString(), superseded: true };
478
+ this.log(`phone access: ${error} Trying again in ${Math.round(wait / 1000)} s`);
479
+ this.armRetry(wait);
480
+ }
481
+ armRetry(wait) {
482
+ if (this.retry !== null)
483
+ clearTimeout(this.retry);
484
+ this.retry = setTimeout(() => { this.retry = null; void this.connect(); }, wait);
485
+ this.retry.unref?.();
486
+ }
487
+ closeSocket(reason) {
488
+ const socket = this.socket;
489
+ this.socket = null;
490
+ this.link = null;
491
+ if (this.keepalive !== null)
492
+ clearInterval(this.keepalive);
493
+ this.keepalive = null;
494
+ if (socket !== null && (socket.readyState === WebSocket.OPEN || socket.readyState === WebSocket.CONNECTING))
495
+ socket.close(1000, reason);
496
+ }
497
+ daemonToken(call) {
498
+ return daemonTokenFor(this.engine.hostKeys, this.addresses.host, call);
499
+ }
500
+ async register() {
501
+ const challenge = await this.relayRequest("POST", "/v1/challenge", undefined, false);
502
+ if (typeof challenge.challenge !== "string")
503
+ throw new Error("the relay sent no registration challenge");
504
+ const keys = this.engine.hostKeys;
505
+ const registered = await this.relayRequest("POST", "/v1/machines/register", {
506
+ relayMachinePub: keys.relayPub.toString("base64url"),
507
+ challenge: challenge.challenge,
508
+ signature: signRegistrationPop(keys.relayPriv, this.addresses.host, challenge.challenge),
509
+ }, false);
510
+ if (registered.machineId !== keys.machineId)
511
+ throw new Error("the relay derived a different machine id");
512
+ }
513
+ reconcile() {
514
+ return this.admit(async () => {
515
+ this.reconcileOwed = false;
516
+ const put = () => this.relayRequest("PUT", `/v1/machines/${this.engine.hostKeys.machineId}/devices`, { devices: this.engine.admittedDevices() });
517
+ try {
518
+ try {
519
+ await put();
520
+ }
521
+ catch (error) {
522
+ if (!machineUnknown(error))
523
+ throw error;
524
+ await this.register();
525
+ await put();
526
+ }
527
+ }
528
+ catch (error) {
529
+ this.reconcileOwed = true;
530
+ throw error;
531
+ }
532
+ });
533
+ }
534
+ openSocket() {
535
+ return new Promise((resolve, reject) => {
536
+ const socket = new WebSocket(this.addresses.ws, { headers: { authorization: `Bearer ${this.daemonToken()}` }, handshakeTimeout: 10_000, maxPayload: 70_000 });
537
+ socket.once("open", () => resolve(socket));
538
+ socket.once("unexpected-response", (_req, res) => {
539
+ const headers = { get: (name) => { const value = res.headers[name.toLowerCase()]; return typeof value === "string" ? value : null; } };
540
+ const refusal = refusalOf(res.statusCode ?? 0, headers, "", this.nowMs());
541
+ res.resume();
542
+ if (machineUnknown(refusal))
543
+ this.reconcileOwed = true;
544
+ reject(refusal);
545
+ });
546
+ socket.once("error", error => reject(error));
547
+ });
548
+ }
549
+ async relayRequest(method, path, body, authorized = true) {
550
+ if (this.addresses === null)
551
+ throw new Error("no hosted relay is configured");
552
+ const response = await fetch(`${this.addresses.http}${path}`, {
553
+ method,
554
+ headers: {
555
+ ...(body === undefined ? {} : { "content-type": "application/json" }),
556
+ ...(authorized ? { authorization: `Bearer ${this.daemonToken({ htm: method, htu: path })}` } : {}),
557
+ },
558
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
559
+ signal: AbortSignal.timeout(RELAY_CALL_MS),
560
+ redirect: "error",
561
+ }).catch((error) => {
562
+ const cause = error instanceof Error && error.cause instanceof Error ? error.cause : null;
563
+ const rawCode = cause === null ? undefined : cause.code;
564
+ const code = typeof rawCode === "string" ? ` (${rawCode})` : "";
565
+ throw new Error(`couldn't reach ${this.addresses.http}: ${cause?.message ?? (error instanceof Error ? error.message : String(error))}${code}`);
566
+ });
567
+ const text = await response.text();
568
+ if (!response.ok)
569
+ throw refusalOf(response.status, response.headers, text, this.nowMs());
570
+ try {
571
+ return text.length === 0 ? {} : JSON.parse(text);
572
+ }
573
+ catch {
574
+ throw new Error("the relay sent something that isn't JSON");
575
+ }
576
+ }
577
+ get owesReconcile() {
578
+ return this.reconcileOwed;
579
+ }
580
+ }