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.
Files changed (48) hide show
  1. package/CHANGELOG.md +17 -0
  2. package/dist/accent-colors.js +3 -1
  3. package/dist/approval-authority.js +2 -1
  4. package/dist/assignment.js +55 -2
  5. package/dist/backup.js +6 -0
  6. package/dist/browser/terminal.css +1 -1
  7. package/dist/browser/workspace.css +1 -1
  8. package/dist/central-recovery-stage.js +3 -3
  9. package/dist/companion/access.js +161 -0
  10. package/dist/companion/actions.js +559 -0
  11. package/dist/companion/bonjour.js +45 -0
  12. package/dist/companion/daemon.js +1346 -0
  13. package/dist/companion/direct-server.js +177 -0
  14. package/dist/companion/framing.js +498 -0
  15. package/dist/companion/noise.js +461 -0
  16. package/dist/companion/passkey-gate.js +287 -0
  17. package/dist/companion/paths.js +90 -0
  18. package/dist/companion/reads.js +279 -0
  19. package/dist/companion/relay-auth.js +265 -0
  20. package/dist/companion/relay-server.js +870 -0
  21. package/dist/companion/schema.js +225 -0
  22. package/dist/companion/service.js +580 -0
  23. package/dist/companion/store.js +324 -0
  24. package/dist/companion/webauthn-test-support.js +44 -0
  25. package/dist/companion/webauthn.js +398 -0
  26. package/dist/contracts/console-api.js +18 -0
  27. package/dist/design/kit.css +30 -0
  28. package/dist/local-landing.js +47 -0
  29. package/dist/person-proof.js +5 -1
  30. package/dist/pull-request-flow.js +75 -2
  31. package/dist/qr.js +385 -0
  32. package/dist/release-adapters.js +2 -1
  33. package/dist/restore-retirement.js +2 -0
  34. package/dist/scope.js +67 -4
  35. package/dist/serve.js +31 -4
  36. package/dist/server/pages.js +9 -2
  37. package/dist/server/phone-engine-api.js +59 -0
  38. package/dist/server/route-table.js +11 -0
  39. package/dist/server/settings-phone.js +492 -0
  40. package/dist/server/settings-scripts.js +2 -0
  41. package/dist/server/settings-sections.js +6 -2
  42. package/dist/settings-groups-ui.js +2 -1
  43. package/dist/settings-proofs.js +6 -0
  44. package/dist/store.js +37 -4
  45. package/dist/tailnet.js +42 -0
  46. package/dist/toolroll-update.js +3 -1
  47. package/dist/youiyoux-intake.js +8 -0
  48. package/package.json +7 -2
@@ -0,0 +1,1346 @@
1
+ import { randomUUID, timingSafeEqual } from "node:crypto";
2
+ import { pathsAllowed } from "./paths.js";
3
+ import { buildPairingPrologue, buildSessionPrologue, deriveConfirmationCode, deriveDevicePsk, MAX_SESSION_AGE_MS, MAX_SESSION_MESSAGES, NoiseIKpsk2Responder, NoiseTransportSession, randomPsk32, } from "./noise.js";
4
+ import { CompanionStreamGuard, decodeCreditPayload, decodeFrame, encodeErrorPayload, encodeFrame, FRAME_HEADER_BYTES, FrameType, GlobalBufferBudget, LiveWatchBuffer, MAX_FRAME_PAYLOAD_BYTES, PACING_PER_CONNECTION, TokenBucket, WATCH_IDLE_DEADLINE_MS, UnaryResponsePacer, } from "./framing.js";
5
+ import { decodeRelayEnvelope, encodeRelayEnvelope, RelayOp, signRelayToken } from "./relay-auth.js";
6
+ import { activatePendingDevice, deletePendingDevice, deviceAccountStands, getPairedDevice, livePairedDevices, loadOrCreateCompanionHostKeys, MAX_PHONES_PER_MAC, PENDING_ACTIVATION_MS, phoneCount, revokePairedDeviceRecord, sanitizeDeviceName, savePendingDevice, sweepCompanionRecords, touchPairedDeviceLastSeen, } from "./store.js";
7
+ export const PAIRING_TTL_MS = 5 * 60 * 1000;
8
+ export const DAEMON_HANDSHAKE_DEADLINE_MS = 5_000;
9
+ export const PAIR_READY_DEADLINE_MS = 10_000;
10
+ export const HELLO_DEADLINE_MS = 10_000;
11
+ export const MSG2_PLAINTEXT_BYTES = 160;
12
+ export const PAIRING_TERMINAL_KEEP_MS = 60_000;
13
+ export const MAX_PEERS_PER_RELAY_LINK = 8;
14
+ export const MSG1_REPLAY_WINDOW_MS = 15 * 60 * 1000;
15
+ export const MSG1_REPLAY_PER_ID = 64;
16
+ export const MSG1_REPLAY_TOTAL = 4096;
17
+ const PEER_ID = /^[A-Za-z0-9_-]{1,128}$/;
18
+ const PAIR_READY_STREAM = 1;
19
+ const PAIR_DONE_STREAM = 3;
20
+ const REKEY_MARGIN_MS = 60_000;
21
+ const REKEY_MARGIN_MESSAGES = 16n;
22
+ const STANDING_CACHE_MS = 250;
23
+ const CLOSE_NORMAL = 1000;
24
+ const CLOSE_REVOKED = 4403;
25
+ const CLOSE_TIMEOUT = 4408;
26
+ export const PAIRED_DEVICE_GATE1_ROUTES = new Set([
27
+ "device.hello",
28
+ "work.rows",
29
+ "task.steps",
30
+ "task.diff",
31
+ "task.approval.read",
32
+ "run.window.read",
33
+ "run.watch.subscribe",
34
+ "device.self.revoke",
35
+ ]);
36
+ export const PAIRED_DEVICE_GATE2_ROUTES = new Set([
37
+ "passkey.status",
38
+ "passkey.lock",
39
+ "passkey.unlock",
40
+ "passkey.register.begin",
41
+ "passkey.register.finish",
42
+ "approval.challenge",
43
+ "task.approve",
44
+ "task.accept",
45
+ "task.land",
46
+ "task.ship",
47
+ ]);
48
+ const TERMINAL = new Set(["paired", "cancelled", "expired", "contested", "failed"]);
49
+ const PAIRING_ERROR_MESSAGE = {
50
+ pairing_cancelled: "Pairing was cancelled on your Mac.",
51
+ pairing_expired: "The code expired. Start again on your Mac.",
52
+ pairing_contested: "Another device used this code. Pair again.",
53
+ pairing_failed: "Pairing didn't finish. Start again on your Mac.",
54
+ };
55
+ const errorCodeOf = (status) => status === "cancelled" ? "pairing_cancelled" : status === "expired" ? "pairing_expired" : status === "failed" ? "pairing_failed" : "pairing_contested";
56
+ export function relayEnvelopeLink(id, sendEnvelope, opts = {}) {
57
+ return {
58
+ id,
59
+ maxPeers: MAX_PEERS_PER_RELAY_LINK,
60
+ ...(opts.backlog === undefined ? {} : { backlog: opts.backlog.bytes, backlogLimit: opts.backlog.limit }),
61
+ ...(opts.pacing === undefined ? {} : { pacing: opts.pacing }),
62
+ send: (connId, payload) => sendEnvelope(encodeRelayEnvelope({ op: RelayOp.PEER_DATA, connId, payload })),
63
+ close: (connId, reason, code) => sendEnvelope(encodeRelayEnvelope({
64
+ op: RelayOp.PEER_CLOSE, connId, payload: Buffer.from(JSON.stringify(code === undefined ? { reason } : { reason, code }), "utf8"),
65
+ })),
66
+ };
67
+ }
68
+ const peerKeyOf = (link, connId) => `${link.id}:${connId}`;
69
+ const MAX_UNPROVEN_PER_PEER_ID = 2;
70
+ const MAX_PING_PAYLOAD_BYTES = 64;
71
+ const DEADLINE_SWEEP_MS = 1_000;
72
+ export function paddedMsg2(fields) {
73
+ const unpadded = Buffer.byteLength(JSON.stringify({ ...fields, pad: "" }), "utf8");
74
+ if (unpadded > MSG2_PLAINTEXT_BYTES)
75
+ throw new Error("message 2 payload exceeds its padded size");
76
+ return Buffer.from(JSON.stringify({ ...fields, pad: "0".repeat(MSG2_PLAINTEXT_BYTES - unpadded) }), "utf8");
77
+ }
78
+ class Msg1ReplayCache {
79
+ entries = new Map();
80
+ perId = new Map();
81
+ forget(key) {
82
+ this.entries.delete(key);
83
+ const id = key.slice(0, key.indexOf("\0"));
84
+ const list = this.perId.get(id);
85
+ if (list === undefined)
86
+ return;
87
+ const at = list.indexOf(key);
88
+ if (at >= 0)
89
+ list.splice(at, 1);
90
+ if (list.length === 0)
91
+ this.perId.delete(id);
92
+ }
93
+ prune(nowMs) {
94
+ for (const [key, expiry] of this.entries) {
95
+ if (expiry > nowMs)
96
+ break;
97
+ this.forget(key);
98
+ }
99
+ }
100
+ seen(id, ephemeral, nowMs) {
101
+ this.prune(nowMs);
102
+ return this.entries.has(`${id}\0${ephemeral.toString("hex")}`);
103
+ }
104
+ remember(id, ephemeral, nowMs) {
105
+ this.prune(nowMs);
106
+ const key = `${id}\0${ephemeral.toString("hex")}`;
107
+ if (this.entries.has(key))
108
+ return;
109
+ this.entries.set(key, nowMs + MSG1_REPLAY_WINDOW_MS);
110
+ const list = this.perId.get(id) ?? [];
111
+ list.push(key);
112
+ this.perId.set(id, list);
113
+ while (list.length > MSG1_REPLAY_PER_ID)
114
+ this.forget(list[0]);
115
+ while (this.entries.size > MSG1_REPLAY_TOTAL)
116
+ this.forget(this.entries.keys().next().value);
117
+ }
118
+ }
119
+ export class CompanionDaemonEngine {
120
+ hostKeys;
121
+ store;
122
+ handlers;
123
+ actions;
124
+ defaultLink;
125
+ onDeviceRegistered;
126
+ onDeviceRevoked;
127
+ handshakeDeadlineMs;
128
+ helloDeadlineMs;
129
+ readyDeadlineMs;
130
+ nowMs;
131
+ consoleUrl;
132
+ pacingPerConnection;
133
+ globalBudget = new GlobalBufferBudget();
134
+ replay = new Msg1ReplayCache();
135
+ pairings = new Map();
136
+ peers = new Map();
137
+ pathsOf = () => [];
138
+ sweepTimer = null;
139
+ constructor(opts) {
140
+ this.store = opts.store;
141
+ this.handlers = opts.handlers;
142
+ this.actions = opts.actions ?? null;
143
+ this.defaultLink = opts.sendToRelay === undefined ? null : relayEnvelopeLink("relay", opts.sendToRelay);
144
+ this.onDeviceRegistered = opts.onDeviceRegistered;
145
+ this.onDeviceRevoked = opts.onDeviceRevoked;
146
+ this.handshakeDeadlineMs = opts.handshakeDeadlineMs ?? DAEMON_HANDSHAKE_DEADLINE_MS;
147
+ this.helloDeadlineMs = opts.helloDeadlineMs ?? HELLO_DEADLINE_MS;
148
+ this.readyDeadlineMs = opts.readyDeadlineMs ?? PAIR_READY_DEADLINE_MS;
149
+ this.nowMs = opts.nowMs ?? (() => Date.now());
150
+ this.consoleUrl = opts.consoleUrl ?? (() => null);
151
+ this.pacingPerConnection = opts.pacingPerConnection ?? PACING_PER_CONNECTION;
152
+ if (opts.paths !== undefined)
153
+ this.pathsOf = opts.paths;
154
+ this.hostKeys = loadOrCreateCompanionHostKeys(this.store.handle, new Date(this.nowMs()));
155
+ }
156
+ setPathsProvider(provider) {
157
+ this.pathsOf = provider;
158
+ }
159
+ startPairing(accountName, binding, accountGeneration) {
160
+ const account = this.store.accountOf(accountName);
161
+ if (account === null || account.revokedAt !== null || account.role !== "approver" || account.generation !== accountGeneration) {
162
+ return { ok: false, error: "Only an active approver account can start pairing." };
163
+ }
164
+ const now = this.nowMs();
165
+ if (phoneCount(this.store.handle, new Date(now)) >= MAX_PHONES_PER_MAC) {
166
+ return { ok: false, error: `This Mac already has ${MAX_PHONES_PER_MAC} phones. Remove one first.` };
167
+ }
168
+ for (const p of [...this.pairings.values()]) {
169
+ if (p.binding !== binding)
170
+ continue;
171
+ if (TERMINAL.has(p.status))
172
+ this.pairings.delete(p.pairSessionId);
173
+ else if (p.status !== "finishing") {
174
+ this.endPairing(p, "cancelled");
175
+ this.pairings.delete(p.pairSessionId);
176
+ }
177
+ }
178
+ const paths = this.pathsOf();
179
+ if (!pathsAllowed(paths))
180
+ return { ok: false, error: "A phone has no way to reach this Mac yet: join a Wi-Fi network or turn on Connect from anywhere." };
181
+ const hosted = paths.find(path => path.kind === "hosted");
182
+ const identity = this.store.workspaceIdentity();
183
+ const pairSessionId = `pair_${randomUUID().replace(/-/g, "").slice(0, 16)}`;
184
+ const pairPsk = randomPsk32();
185
+ const expiresAtMs = now + PAIRING_TTL_MS;
186
+ const pairConnToken = hosted === undefined ? undefined : signRelayToken(this.hostKeys.relayPriv, {
187
+ role: "pair",
188
+ machineId: this.hostKeys.machineId,
189
+ aud: new URL(hosted.url).host.toLowerCase(),
190
+ pairSessionId,
191
+ nowSec: Math.floor(now / 1000),
192
+ ttlSec: Math.floor(PAIRING_TTL_MS / 1000),
193
+ });
194
+ this.pairings.set(pairSessionId, {
195
+ pairSessionId, accountName, binding, accountGeneration, pairPsk, expiresAtMs,
196
+ status: "awaiting_scan", terminalAtMs: null, attachedKey: null, confirmCode: null, deviceName: null,
197
+ phoneStaticPub: null, deviceRelayPub: null, handshakeHash: null, deviceId: null, pendingCreatedAtMs: null, error: null,
198
+ });
199
+ this.ensureSweep();
200
+ return {
201
+ ok: true,
202
+ expiresAtMs,
203
+ qr: {
204
+ v: 2,
205
+ paths,
206
+ machineId: this.hostKeys.machineId,
207
+ workspaceId: identity.id,
208
+ macStaticPub: this.hostKeys.noiseStaticPub.toString("base64url"),
209
+ pairSessionId,
210
+ pairPsk: pairPsk.toString("base64url"),
211
+ expiresAtMs,
212
+ ...(pairConnToken === undefined ? {} : { pairConnToken }),
213
+ },
214
+ };
215
+ }
216
+ pairingView(pairSessionId, binding) {
217
+ const p = this.pairings.get(pairSessionId);
218
+ if (p === undefined || p.binding !== binding)
219
+ return null;
220
+ this.expireIfDue(p);
221
+ return {
222
+ pairSessionId: p.pairSessionId,
223
+ status: p.status,
224
+ expiresAtMs: p.expiresAtMs,
225
+ confirmCode: p.status === "awaiting_confirm" || p.status === "confirming" ? p.confirmCode : null,
226
+ deviceName: p.deviceName,
227
+ deviceId: p.deviceId,
228
+ error: p.error,
229
+ };
230
+ }
231
+ async confirmPairing(pairSessionId, binding) {
232
+ const p = this.pairings.get(pairSessionId);
233
+ if (p === undefined || p.binding !== binding)
234
+ return { ok: false, error: "Unknown pairing session." };
235
+ this.expireIfDue(p);
236
+ if (p.status !== "awaiting_confirm" || p.attachedKey === null || p.phoneStaticPub === null || p.deviceRelayPub === null || p.handshakeHash === null) {
237
+ return { ok: false, error: p.status === "expired" ? "That pairing code expired. Pair again." : "That pairing can't be confirmed now. Pair again." };
238
+ }
239
+ const attached = this.peers.get(p.attachedKey);
240
+ if (attached === undefined || attached.state !== "pair_attached") {
241
+ this.endPairing(p, "failed", "The iPhone disconnected. Pair again.");
242
+ return { ok: false, error: "The iPhone disconnected. Pair again." };
243
+ }
244
+ const account = this.store.accountOf(p.accountName);
245
+ if (account === null || account.revokedAt !== null || account.role !== "approver" || account.generation !== p.accountGeneration) {
246
+ this.endPairing(p, "failed", "Your account changed while pairing. Pair again.");
247
+ return { ok: false, error: "Your account changed while pairing. Pair again." };
248
+ }
249
+ const now = this.nowMs();
250
+ if (phoneCount(this.store.handle, new Date(now)) >= MAX_PHONES_PER_MAC) {
251
+ const error = `This Mac already has ${MAX_PHONES_PER_MAC} phones. Remove one first.`;
252
+ this.endPairing(p, "failed", error);
253
+ return { ok: false, error };
254
+ }
255
+ const identity = this.store.workspaceIdentity();
256
+ const deviceId = `dev_${randomUUID().replace(/-/g, "").slice(0, 16)}`;
257
+ const pskEntropy = randomPsk32();
258
+ const devicePsk = deriveDevicePsk(pskEntropy, p.handshakeHash, identity.id, deviceId);
259
+ p.status = "confirming";
260
+ p.pairPsk.fill(0);
261
+ p.deviceId = deviceId;
262
+ p.pendingCreatedAtMs = now;
263
+ savePendingDevice(this.store.handle, {
264
+ deviceId,
265
+ accountName: p.accountName,
266
+ deviceName: p.deviceName ?? "iPhone",
267
+ phoneStaticPub: p.phoneStaticPub,
268
+ deviceRelayPub: p.deviceRelayPub,
269
+ devicePsk,
270
+ recoveryGeneration: identity.recoveryGeneration,
271
+ accountGeneration: p.accountGeneration,
272
+ createdAt: new Date(now).toISOString(),
273
+ });
274
+ let admissionError = null;
275
+ try {
276
+ await this.onDeviceRegistered?.(deviceId, p.deviceRelayPub.toString("base64url"));
277
+ }
278
+ catch (error) {
279
+ admissionError = error instanceof Error ? error.message : String(error);
280
+ }
281
+ const statusNow = () => p.status;
282
+ const after = this.store.accountOf(p.accountName);
283
+ const row = getPairedDevice(this.store.handle, deviceId);
284
+ const still = this.peers.get(attached.key);
285
+ const holds = admissionError === null && statusNow() === "confirming" && this.nowMs() <= p.expiresAtMs
286
+ && after !== null && after.revokedAt === null && after.role === "approver" && after.generation === p.accountGeneration
287
+ && identity.recoveryGeneration === this.store.workspaceIdentity().recoveryGeneration
288
+ && still === attached && still.state === "pair_attached" && row !== null && row.activatedAt === null && row.revokedAt === null;
289
+ if (!holds) {
290
+ deletePendingDevice(this.store.handle, deviceId);
291
+ this.forgetOnRelays(deviceId);
292
+ const error = admissionError !== null ? "The relay didn't accept the phone. Check phone access in Settings and pair again."
293
+ : statusNow() === "contested" ? "Another device used this code. Pair again."
294
+ : statusNow() === "cancelled" ? "Pairing was cancelled."
295
+ : statusNow() === "expired" || this.nowMs() > p.expiresAtMs ? "That pairing code expired. Pair again."
296
+ : "Pairing was interrupted. Pair again.";
297
+ if (statusNow() === "confirming")
298
+ this.endPairing(p, this.nowMs() > p.expiresAtMs ? "expired" : "failed", error);
299
+ return { ok: false, error };
300
+ }
301
+ p.status = "finishing";
302
+ attached.state = "pair_finishing";
303
+ const delivered = this.sendControl(attached, {
304
+ type: FrameType.RES, streamId: PAIR_READY_STREAM, seq: 0,
305
+ payload: Buffer.from(JSON.stringify({ ok: true, result: { deviceId, recoveryGeneration: identity.recoveryGeneration, pskEntropy: pskEntropy.toString("base64url") } }), "utf8"),
306
+ });
307
+ pskEntropy.fill(0);
308
+ if (!delivered) {
309
+ deletePendingDevice(this.store.handle, deviceId);
310
+ this.forgetOnRelays(deviceId);
311
+ const error = "The phone disconnected before pairing finished. Pair again.";
312
+ p.status = "confirming";
313
+ this.endPairing(p, "failed", error);
314
+ return { ok: false, error };
315
+ }
316
+ return { ok: true, deviceId };
317
+ }
318
+ cancelPairing(pairSessionId, binding) {
319
+ const p = this.pairings.get(pairSessionId);
320
+ if (p === undefined || p.binding !== binding)
321
+ return false;
322
+ this.expireIfDue(p);
323
+ if (TERMINAL.has(p.status) || p.status === "finishing")
324
+ return false;
325
+ this.endPairing(p, "cancelled");
326
+ return true;
327
+ }
328
+ endPairing(p, status, error = null) {
329
+ p.status = status;
330
+ p.terminalAtMs = this.nowMs();
331
+ p.error = error;
332
+ p.pairPsk.fill(0);
333
+ const code = errorCodeOf(status);
334
+ for (const peer of [...this.peers.values()]) {
335
+ if (peer.role !== "pair" || peer.peerId !== p.pairSessionId)
336
+ continue;
337
+ if (peer.state === "pair_attached" || peer.state === "pair_awaiting_ready")
338
+ this.sendPairingError(peer, PAIR_READY_STREAM, code);
339
+ this.dropPeer(peer, code, CLOSE_NORMAL);
340
+ }
341
+ p.attachedKey = null;
342
+ p.handshakeHash = null;
343
+ }
344
+ expireIfDue(p) {
345
+ const now = this.nowMs();
346
+ if (TERMINAL.has(p.status))
347
+ return;
348
+ if (p.status === "finishing") {
349
+ if (p.pendingCreatedAtMs !== null && now > p.pendingCreatedAtMs + PENDING_ACTIVATION_MS) {
350
+ if (p.deviceId !== null && deletePendingDevice(this.store.handle, p.deviceId))
351
+ this.forgetOnRelays(p.deviceId);
352
+ p.status = "failed";
353
+ p.terminalAtMs = now;
354
+ p.error = "The iPhone didn't finish pairing. Pair again.";
355
+ }
356
+ return;
357
+ }
358
+ if (p.status !== "confirming" && now > p.expiresAtMs)
359
+ this.endPairing(p, "expired");
360
+ }
361
+ admittedDevices() {
362
+ return livePairedDevices(this.store, { includePending: true, now: new Date(this.nowMs()) })
363
+ .map(d => ({ deviceId: d.deviceId, deviceRelayPub: d.deviceRelayPub.toString("base64url") }));
364
+ }
365
+ revokeDevice(deviceId, reason = "removed") {
366
+ const revoked = revokePairedDeviceRecord(this.store.handle, deviceId, new Date(this.nowMs()), reason);
367
+ for (const peer of [...this.peers.values()]) {
368
+ if (peer.role === "device" && peer.peerId === deviceId) {
369
+ if (peer.state === "authenticated" || peer.state === "awaiting_hello")
370
+ this.refuseLive(peer, standingCodeOf(reason));
371
+ else
372
+ this.dropPeer(peer, "device_revoked", CLOSE_REVOKED);
373
+ }
374
+ }
375
+ if (revoked)
376
+ this.forgetOnRelays(deviceId);
377
+ return revoked;
378
+ }
379
+ sweepRecords() {
380
+ const swept = sweepCompanionRecords(this.store.handle, new Date(this.nowMs()));
381
+ for (const deviceId of swept.pending)
382
+ this.forgetOnRelays(deviceId);
383
+ this.actions?.sweep();
384
+ return swept;
385
+ }
386
+ forgetOnRelays(deviceId) {
387
+ if (this.onDeviceRevoked === undefined)
388
+ return;
389
+ void Promise.resolve().then(() => this.onDeviceRevoked(deviceId)).catch(() => { });
390
+ }
391
+ handleRelayDisconnected(link) {
392
+ for (const peer of [...this.peers.values()]) {
393
+ if (link !== undefined && peer.link !== link)
394
+ continue;
395
+ this.cleanupPeerLocal(peer);
396
+ }
397
+ if (link !== undefined)
398
+ return;
399
+ for (const p of this.pairings.values()) {
400
+ if (!TERMINAL.has(p.status) && p.status !== "finishing")
401
+ this.endPairing(p, "failed", "Phone access restarted. Pair again.");
402
+ }
403
+ if (this.sweepTimer !== null)
404
+ clearInterval(this.sweepTimer);
405
+ this.sweepTimer = null;
406
+ }
407
+ async handleRelayEnvelope(raw, link = this.defaultLink) {
408
+ if (link === null)
409
+ throw new Error("no relay link");
410
+ const env = decodeRelayEnvelope(raw);
411
+ if (env.op === RelayOp.PEER_OPEN) {
412
+ let meta;
413
+ try {
414
+ meta = JSON.parse(env.payload.toString("utf8"));
415
+ }
416
+ catch {
417
+ meta = {};
418
+ }
419
+ if ((meta.role !== "pair" && meta.role !== "device") || typeof meta.id !== "string" || !PEER_ID.test(meta.id)) {
420
+ link.close(env.connId, "invalid_peer");
421
+ return;
422
+ }
423
+ this.openPeer(link, env.connId, meta.role, meta.id);
424
+ return;
425
+ }
426
+ if (env.op === RelayOp.PEER_CLOSE) {
427
+ this.closePeer(link, env.connId);
428
+ return;
429
+ }
430
+ if (env.op === RelayOp.PEER_DATA) {
431
+ await this.peerData(link, env.connId, env.payload);
432
+ }
433
+ }
434
+ openPeer(link, connId, role, peerId) {
435
+ const key = peerKeyOf(link, connId);
436
+ const existing = this.peers.get(key);
437
+ if (existing !== undefined)
438
+ this.cleanupPeerLocal(existing);
439
+ const reject = (reason) => link.close(connId, reason);
440
+ if (!PEER_ID.test(peerId)) {
441
+ reject("invalid_peer");
442
+ return;
443
+ }
444
+ if (link.maxPeers !== undefined && [...this.peers.values()].filter(peer => peer.link === link).length >= link.maxPeers) {
445
+ reject("too_many_peers");
446
+ return;
447
+ }
448
+ if (role === "pair") {
449
+ const pairing = this.pairings.get(peerId);
450
+ if (pairing !== undefined)
451
+ this.expireIfDue(pairing);
452
+ if (pairing === undefined || (pairing.status !== "awaiting_scan" && pairing.status !== "awaiting_ready" && pairing.status !== "awaiting_confirm")) {
453
+ reject("invalid_pairing");
454
+ return;
455
+ }
456
+ }
457
+ const unproven = [...this.peers.values()].filter(peer => peer.role === role && peer.peerId === peerId && peer.state === "awaiting_msg1");
458
+ for (const stale of unproven.slice(0, Math.max(0, unproven.length - MAX_UNPROVEN_PER_PEER_ID + 1)))
459
+ this.dropPeer(stale, "superseded_handshake");
460
+ const now = this.nowMs();
461
+ const peer = {
462
+ key, link, connId, role, peerId,
463
+ state: "awaiting_msg1",
464
+ openedAtMs: now,
465
+ timer: null,
466
+ session: null,
467
+ principal: null,
468
+ pairProof: null,
469
+ streamGuard: new CompanionStreamGuard(this.globalBudget),
470
+ unaryPacers: new Map(),
471
+ watchStreams: new Map(),
472
+ streamAccess: new Map(),
473
+ bucket: link.pacing === undefined ? null : new TokenBucket(this.pacingPerConnection.ratePerMin, this.pacingPerConnection.burst, now),
474
+ waiting: [],
475
+ draining: false,
476
+ pacingTimer: null,
477
+ cache: { standingAt: -Infinity, standing: null },
478
+ };
479
+ this.peers.set(key, peer);
480
+ this.armTimer(peer, this.handshakeDeadlineMs, "handshake_timeout");
481
+ this.ensureSweep();
482
+ }
483
+ closePeer(link, connId) {
484
+ const peer = this.peers.get(peerKeyOf(link, connId));
485
+ if (peer !== undefined)
486
+ this.cleanupPeerLocal(peer);
487
+ }
488
+ async peerData(link, connId, data) {
489
+ const peer = this.peers.get(peerKeyOf(link, connId));
490
+ if (peer === undefined)
491
+ return;
492
+ if (peer.state === "awaiting_msg1") {
493
+ if (peer.role === "pair")
494
+ this.handlePairingMsg1(peer, data);
495
+ else
496
+ this.handleSessionMsg1(peer, data);
497
+ return;
498
+ }
499
+ if (peer.state === "refusing") {
500
+ this.dropPeer(peer, "decrypt_failed");
501
+ return;
502
+ }
503
+ if (peer.session === null) {
504
+ this.dropPeer(peer, "no_session");
505
+ return;
506
+ }
507
+ if (peer.role === "device" && this.needsRekey(peer.session)) {
508
+ this.endForRekey(peer);
509
+ return;
510
+ }
511
+ let plaintext;
512
+ try {
513
+ plaintext = peer.session.decrypt(data, this.nowMs());
514
+ }
515
+ catch {
516
+ this.dropPeer(peer, "decrypt_failed");
517
+ return;
518
+ }
519
+ let frame;
520
+ try {
521
+ frame = decodeFrame(plaintext);
522
+ }
523
+ catch {
524
+ this.dropPeer(peer, "invalid_frame");
525
+ return;
526
+ }
527
+ if (peer.role === "pair")
528
+ this.handlePairingFrame(peer, frame);
529
+ else
530
+ await this.handleSessionFrame(peer, frame);
531
+ }
532
+ armTimer(peer, ms, reason) {
533
+ if (peer.timer !== null)
534
+ clearTimeout(peer.timer);
535
+ peer.timer = setTimeout(() => {
536
+ peer.timer = null;
537
+ if (this.peers.get(peer.key) === peer)
538
+ this.dropPeer(peer, reason, CLOSE_TIMEOUT);
539
+ }, ms);
540
+ peer.timer.unref?.();
541
+ }
542
+ clearTimer(peer) {
543
+ if (peer.timer !== null)
544
+ clearTimeout(peer.timer);
545
+ peer.timer = null;
546
+ }
547
+ freshEphemeral(peer, msg1) {
548
+ if (msg1.length < 32)
549
+ return null;
550
+ const ephemeral = Buffer.from(msg1.subarray(0, 32));
551
+ return this.replay.seen(peer.peerId, ephemeral, this.nowMs()) ? null : ephemeral;
552
+ }
553
+ handlePairingMsg1(peer, msg1) {
554
+ const pairing = this.pairings.get(peer.peerId);
555
+ if (pairing !== undefined)
556
+ this.expireIfDue(pairing);
557
+ if (pairing === undefined || (pairing.status !== "awaiting_scan" && pairing.status !== "awaiting_ready" && pairing.status !== "awaiting_confirm")) {
558
+ this.dropPeer(peer, "pairing_invalid");
559
+ return;
560
+ }
561
+ const ephemeral = this.freshEphemeral(peer, msg1);
562
+ if (ephemeral === null) {
563
+ this.dropPeer(peer, "handshake_failed");
564
+ return;
565
+ }
566
+ const identity = this.store.workspaceIdentity();
567
+ const responder = new NoiseIKpsk2Responder({
568
+ localStatic: { privateKey: this.hostKeys.noiseStaticPriv, publicKey: this.hostKeys.noiseStaticPub },
569
+ psk: pairing.pairPsk,
570
+ prologue: buildPairingPrologue(identity.id, pairing.pairSessionId),
571
+ });
572
+ let payload;
573
+ let remoteStaticPublicKey;
574
+ try {
575
+ ({ payload, remoteStaticPublicKey } = responder.readMessage1(msg1));
576
+ }
577
+ catch {
578
+ this.dropPeer(peer, "handshake_failed");
579
+ return;
580
+ }
581
+ this.replay.remember(peer.peerId, ephemeral, this.nowMs());
582
+ let meta;
583
+ try {
584
+ meta = JSON.parse(payload.toString("utf8"));
585
+ }
586
+ catch {
587
+ this.dropPeer(peer, "invalid_msg1_payload");
588
+ return;
589
+ }
590
+ if (meta === null || typeof meta !== "object" || meta.protocolVersion !== 1 || meta.mode !== "pair" || typeof meta.deviceRelayPub !== "string") {
591
+ this.dropPeer(peer, "invalid_msg1_payload");
592
+ return;
593
+ }
594
+ const deviceRelayPub = Buffer.from(meta.deviceRelayPub, "base64url");
595
+ if (deviceRelayPub.length !== 32) {
596
+ this.dropPeer(peer, "invalid_device_relay_pub");
597
+ return;
598
+ }
599
+ const { message: msg2, session } = responder.writeMessage2(paddedMsg2({ protocolVersion: 1, status: "awaiting_ready" }), this.nowMs());
600
+ peer.session = session;
601
+ peer.state = "pair_awaiting_ready";
602
+ peer.pairProof = { phoneStaticPub: remoteStaticPublicKey, deviceRelayPub, handshakeHash: Buffer.from(session.handshakeHash) };
603
+ if (pairing.status === "awaiting_scan")
604
+ pairing.status = "awaiting_ready";
605
+ this.armTimer(peer, this.readyDeadlineMs, "pair_ready_timeout");
606
+ peer.link.send(peer.connId, msg2);
607
+ }
608
+ handlePairingFrame(peer, frame) {
609
+ const pairing = this.pairings.get(peer.peerId);
610
+ if (peer.state === "pair_awaiting_ready") {
611
+ const req = frame.type === FrameType.REQ && frame.streamId === PAIR_READY_STREAM && frame.seq === 0 ? parseRequest(frame.payload) : null;
612
+ if (req === null || req.method !== "pair.ready") {
613
+ this.dropPeer(peer, "pair_ready_required");
614
+ return;
615
+ }
616
+ this.onPairReady(peer, pairing, req.params);
617
+ return;
618
+ }
619
+ if (frame.type === FrameType.PING) {
620
+ if (frame.payload.length > MAX_PING_PAYLOAD_BYTES) {
621
+ this.dropPeer(peer, "ping_too_large");
622
+ return;
623
+ }
624
+ this.sendControl(peer, { type: FrameType.PONG, streamId: 0, seq: frame.seq, payload: frame.payload });
625
+ return;
626
+ }
627
+ if (frame.type === FrameType.PONG || frame.type === FrameType.CREDIT || frame.type === FrameType.ERROR || frame.type === FrameType.CANCEL)
628
+ return;
629
+ if (frame.type === FrameType.REQ && frame.streamId === PAIR_DONE_STREAM && frame.seq === 0) {
630
+ const req = parseRequest(frame.payload);
631
+ if (req !== null && req.method === "pair.done") {
632
+ this.onPairDone(peer, pairing, req.params);
633
+ return;
634
+ }
635
+ }
636
+ this.dropPeer(peer, "protocol_error");
637
+ }
638
+ onPairReady(peer, pairing, params) {
639
+ if (pairing === undefined || peer.pairProof === null) {
640
+ this.dropPeer(peer, "pairing_invalid");
641
+ return;
642
+ }
643
+ this.expireIfDue(pairing);
644
+ switch (pairing.status) {
645
+ case "awaiting_scan":
646
+ case "awaiting_ready": {
647
+ this.clearTimer(peer);
648
+ peer.state = "pair_attached";
649
+ pairing.status = "awaiting_confirm";
650
+ pairing.attachedKey = peer.key;
651
+ pairing.phoneStaticPub = peer.pairProof.phoneStaticPub;
652
+ pairing.deviceRelayPub = peer.pairProof.deviceRelayPub;
653
+ pairing.handshakeHash = peer.pairProof.handshakeHash;
654
+ pairing.confirmCode = deriveConfirmationCode(peer.pairProof.handshakeHash);
655
+ pairing.deviceName = sanitizeDeviceName(params["deviceName"]);
656
+ return;
657
+ }
658
+ case "awaiting_confirm":
659
+ case "confirming": {
660
+ this.sendPairingError(peer, PAIR_READY_STREAM, "pairing_contested");
661
+ this.dropPeer(peer, "pairing_contested", CLOSE_NORMAL);
662
+ this.endPairing(pairing, "contested", "Another device used this code. Pair again.");
663
+ return;
664
+ }
665
+ case "finishing": {
666
+ this.sendPairingError(peer, PAIR_READY_STREAM, "pairing_contested");
667
+ this.dropPeer(peer, "pairing_contested", CLOSE_NORMAL);
668
+ if (pairing.deviceId !== null && revokePairedDeviceRecord(this.store.handle, pairing.deviceId, new Date(this.nowMs()), "contested"))
669
+ this.forgetOnRelays(pairing.deviceId);
670
+ pairing.status = "contested";
671
+ pairing.terminalAtMs = this.nowMs();
672
+ pairing.error = "Another device used this code. Pair again.";
673
+ return;
674
+ }
675
+ default:
676
+ this.sendPairingError(peer, PAIR_READY_STREAM, errorCodeOf(pairing.status));
677
+ this.dropPeer(peer, errorCodeOf(pairing.status), CLOSE_NORMAL);
678
+ }
679
+ }
680
+ onPairDone(peer, pairing, params) {
681
+ const ok = () => {
682
+ this.sendControl(peer, { type: FrameType.RES, streamId: PAIR_DONE_STREAM, seq: 0, payload: Buffer.from(JSON.stringify({ ok: true, result: { ok: true } }), "utf8") });
683
+ this.dropPeer(peer, "paired", CLOSE_NORMAL);
684
+ };
685
+ if (pairing === undefined || pairing.attachedKey !== peer.key) {
686
+ this.sendPairingError(peer, PAIR_DONE_STREAM, "pairing_failed");
687
+ this.dropPeer(peer, "pairing_failed", CLOSE_NORMAL);
688
+ return;
689
+ }
690
+ const deviceId = params["deviceId"];
691
+ if (pairing.status === "paired" && deviceId === pairing.deviceId) {
692
+ ok();
693
+ return;
694
+ }
695
+ if (pairing.status !== "finishing") {
696
+ this.sendPairingError(peer, PAIR_DONE_STREAM, errorCodeOf(pairing.status));
697
+ this.dropPeer(peer, errorCodeOf(pairing.status), CLOSE_NORMAL);
698
+ return;
699
+ }
700
+ if (typeof deviceId !== "string" || deviceId !== pairing.deviceId) {
701
+ this.sendPairingError(peer, PAIR_DONE_STREAM, "pairing_failed");
702
+ return;
703
+ }
704
+ const activated = activatePendingDevice(this.store, deviceId, new Date(this.nowMs()));
705
+ if (activated === "refused") {
706
+ if (deletePendingDevice(this.store.handle, deviceId))
707
+ this.forgetOnRelays(deviceId);
708
+ pairing.status = "failed";
709
+ pairing.terminalAtMs = this.nowMs();
710
+ pairing.error = "Pairing didn't finish. Pair again.";
711
+ this.sendPairingError(peer, PAIR_DONE_STREAM, "pairing_failed");
712
+ this.dropPeer(peer, "pairing_failed", CLOSE_NORMAL);
713
+ return;
714
+ }
715
+ pairing.status = "paired";
716
+ pairing.terminalAtMs = this.nowMs();
717
+ ok();
718
+ }
719
+ sendPairingError(peer, streamId, code) {
720
+ this.sendControl(peer, { type: FrameType.ERROR, streamId, seq: 0, payload: encodeErrorPayload(code, PAIRING_ERROR_MESSAGE[code]) });
721
+ }
722
+ handleSessionMsg1(peer, msg1) {
723
+ const identity = this.store.workspaceIdentity();
724
+ const dev = getPairedDevice(this.store.handle, peer.peerId);
725
+ if (dev === null || dev.recoveryGeneration !== identity.recoveryGeneration
726
+ || (dev.activatedAt === null && dev.revokedAt === null && Date.parse(dev.createdAt) <= this.nowMs() - PENDING_ACTIVATION_MS)) {
727
+ this.dropPeer(peer, "device_invalid_or_restored");
728
+ return;
729
+ }
730
+ const ephemeral = this.freshEphemeral(peer, msg1);
731
+ if (ephemeral === null) {
732
+ this.dropPeer(peer, "handshake_failed");
733
+ return;
734
+ }
735
+ const responder = new NoiseIKpsk2Responder({
736
+ localStatic: { privateKey: this.hostKeys.noiseStaticPriv, publicKey: this.hostKeys.noiseStaticPub },
737
+ psk: dev.devicePsk,
738
+ prologue: buildSessionPrologue(identity.id, dev.deviceId, identity.recoveryGeneration),
739
+ });
740
+ let payload;
741
+ let remoteStaticPublicKey;
742
+ try {
743
+ ({ payload, remoteStaticPublicKey } = responder.readMessage1(msg1));
744
+ }
745
+ catch {
746
+ this.dropPeer(peer, "handshake_failed");
747
+ return;
748
+ }
749
+ if (remoteStaticPublicKey.length !== dev.phoneStaticPub.length || !timingSafeEqual(remoteStaticPublicKey, dev.phoneStaticPub)) {
750
+ this.dropPeer(peer, "static_key_mismatch");
751
+ return;
752
+ }
753
+ this.replay.remember(peer.peerId, ephemeral, this.nowMs());
754
+ let meta;
755
+ try {
756
+ meta = JSON.parse(payload.toString("utf8"));
757
+ }
758
+ catch {
759
+ this.dropPeer(peer, "invalid_msg1_payload");
760
+ return;
761
+ }
762
+ if (meta === null || typeof meta !== "object" || meta.protocolVersion !== 1 || meta.mode !== "session" || meta.deviceId !== dev.deviceId) {
763
+ this.dropPeer(peer, "invalid_msg1_payload");
764
+ return;
765
+ }
766
+ const refusal = this.refusalOf(dev);
767
+ const { message: msg2, session } = responder.writeMessage2(paddedMsg2(refusal === null ? { protocolVersion: 1, status: "awaiting_hello" } : { protocolVersion: 1, status: "refused", reason: refusal }), this.nowMs());
768
+ if (refusal === null) {
769
+ peer.session = session;
770
+ peer.state = "awaiting_hello";
771
+ peer.principal = {
772
+ kind: "paired-device",
773
+ deviceId: dev.deviceId,
774
+ accountName: dev.accountName,
775
+ workspaceId: identity.id,
776
+ recoveryGeneration: identity.recoveryGeneration,
777
+ requestFromThisComputer: false,
778
+ };
779
+ }
780
+ else {
781
+ session.close();
782
+ peer.state = "refusing";
783
+ }
784
+ this.armTimer(peer, this.helloDeadlineMs, "hello_timeout");
785
+ peer.link.send(peer.connId, msg2);
786
+ }
787
+ refusalOf(dev) {
788
+ if (dev.revokedAt !== null)
789
+ return standingCodeOf(dev.revokedReason ?? "removed");
790
+ if (!deviceAccountStands(dev, this.store.accountOf(dev.accountName)))
791
+ return "account_revoked";
792
+ return null;
793
+ }
794
+ standingOf(peer, skipCache = false) {
795
+ const now = this.nowMs();
796
+ if (!skipCache && now - peer.cache.standingAt < STANDING_CACHE_MS)
797
+ return peer.cache.standing;
798
+ const principal = peer.principal;
799
+ let code;
800
+ if (principal === null)
801
+ code = "device_revoked";
802
+ else {
803
+ const identity = this.store.workspaceIdentity();
804
+ const dev = getPairedDevice(this.store.handle, principal.deviceId);
805
+ if (dev === null || identity.id !== principal.workspaceId || identity.recoveryGeneration !== principal.recoveryGeneration || dev.recoveryGeneration !== identity.recoveryGeneration)
806
+ code = "device_revoked";
807
+ else if (dev.activatedAt === null && dev.revokedAt === null && Date.parse(dev.createdAt) <= now - PENDING_ACTIVATION_MS)
808
+ code = "device_revoked";
809
+ else
810
+ code = this.refusalOf(dev);
811
+ }
812
+ peer.cache.standingAt = now;
813
+ peer.cache.standing = code;
814
+ return code;
815
+ }
816
+ refuseLive(peer, code) {
817
+ const message = code === "account_revoked" ? "Your account on this Mac changed. Pair again." : "Your Mac removed this iPhone.";
818
+ this.sendControl(peer, { type: FrameType.ERROR, streamId: 0, seq: 0, payload: encodeErrorPayload(code, message) });
819
+ this.dropPeer(peer, code, CLOSE_REVOKED);
820
+ }
821
+ needsRekey(session) {
822
+ return this.nowMs() - session.createdAtMs >= MAX_SESSION_AGE_MS - REKEY_MARGIN_MS
823
+ || session.sendCipher.nonce >= MAX_SESSION_MESSAGES - REKEY_MARGIN_MESSAGES
824
+ || session.recvCipher.nonce >= MAX_SESSION_MESSAGES - REKEY_MARGIN_MESSAGES;
825
+ }
826
+ endForRekey(peer) {
827
+ this.emit(peer, { type: FrameType.ERROR, streamId: 0, seq: 0, payload: encodeErrorPayload("rekey", "Reconnecting for fresh keys.") });
828
+ this.dropPeer(peer, "rekey", CLOSE_NORMAL);
829
+ }
830
+ accessHolds(peer, streamId) {
831
+ const taken = peer.streamAccess.get(streamId);
832
+ if (taken === undefined || this.handlers.accessSignature === undefined || peer.principal === null)
833
+ return true;
834
+ return this.handlers.accessSignature(peer.principal) === taken;
835
+ }
836
+ denyStream(peer, streamId) {
837
+ this.dropStreamState(peer, streamId);
838
+ this.sendControl(peer, { type: FrameType.ERROR, streamId, seq: 0, payload: encodeErrorPayload("not_found", "That's no longer available to you.") });
839
+ }
840
+ dropStreamState(peer, streamId) {
841
+ const watch = peer.watchStreams.get(streamId);
842
+ if (watch !== undefined) {
843
+ watch.unsubscribe();
844
+ watch.buffer.clear();
845
+ peer.watchStreams.delete(streamId);
846
+ }
847
+ peer.unaryPacers.delete(streamId);
848
+ peer.streamAccess.delete(streamId);
849
+ peer.waiting = peer.waiting.filter(id => id !== streamId);
850
+ peer.streamGuard.closeStream(streamId);
851
+ }
852
+ async handleSessionFrame(peer, frame) {
853
+ const standing = this.standingOf(peer);
854
+ if (standing !== null) {
855
+ this.refuseLive(peer, standing);
856
+ return;
857
+ }
858
+ if (peer.state === "awaiting_hello" && frame.type !== FrameType.PING && frame.type !== FrameType.REQ && frame.type !== FrameType.REQ_CHUNK && frame.type !== FrameType.END) {
859
+ this.dropPeer(peer, "protocol_error");
860
+ return;
861
+ }
862
+ if (frame.type === FrameType.PING) {
863
+ if (frame.payload.length > MAX_PING_PAYLOAD_BYTES) {
864
+ this.dropPeer(peer, "ping_too_large");
865
+ return;
866
+ }
867
+ this.sendControl(peer, { type: FrameType.PONG, streamId: 0, seq: frame.seq, payload: frame.payload });
868
+ return;
869
+ }
870
+ if (frame.type === FrameType.PONG)
871
+ return;
872
+ if (frame.type === FrameType.CANCEL || frame.type === FrameType.ERROR) {
873
+ this.dropStreamState(peer, frame.streamId);
874
+ return;
875
+ }
876
+ if (frame.type === FrameType.CREDIT) {
877
+ let grant;
878
+ try {
879
+ grant = decodeCreditPayload(frame.payload);
880
+ }
881
+ catch {
882
+ this.dropPeer(peer, "invalid_credit");
883
+ return;
884
+ }
885
+ const pacer = peer.unaryPacers.get(frame.streamId);
886
+ if (pacer !== undefined) {
887
+ pacer.grantCredit(grant);
888
+ this.pumpUnaryPacer(peer, frame.streamId, pacer);
889
+ return;
890
+ }
891
+ const watch = peer.watchStreams.get(frame.streamId);
892
+ if (watch !== undefined) {
893
+ watch.buffer.grantCredit(grant);
894
+ watch.lastCreditAtMs = this.nowMs();
895
+ this.pumpWatchStream(peer, frame.streamId, watch);
896
+ }
897
+ return;
898
+ }
899
+ const ingested = peer.streamGuard.ingestRequestFrame(frame, this.nowMs());
900
+ if (!ingested.ok) {
901
+ this.sendControl(peer, { type: FrameType.ERROR, streamId: frame.streamId, seq: 0, payload: encodeErrorPayload(ingested.code, ingested.message) });
902
+ if (ingested.closeSession)
903
+ this.dropPeer(peer, ingested.code);
904
+ return;
905
+ }
906
+ if (ingested.completePayload === undefined)
907
+ return;
908
+ const req = parseRequest(ingested.completePayload);
909
+ if (req === null) {
910
+ this.sendRpcError(peer, frame.streamId, "invalid_json", "RPC payload must be valid JSON");
911
+ return;
912
+ }
913
+ const { method, params } = req;
914
+ if (peer.state === "awaiting_hello") {
915
+ if (method !== "device.hello") {
916
+ this.sendRpcError(peer, frame.streamId, "hello_required", "First transport RPC must be device.hello");
917
+ this.dropPeer(peer, "hello_required");
918
+ return;
919
+ }
920
+ const principal = peer.principal;
921
+ const row = getPairedDevice(this.store.handle, principal.deviceId);
922
+ if (row !== null && row.activatedAt === null) {
923
+ if (activatePendingDevice(this.store, principal.deviceId, new Date(this.nowMs())) === "refused") {
924
+ this.dropPeer(peer, "activation_refused");
925
+ return;
926
+ }
927
+ for (const p of this.pairings.values()) {
928
+ if (p.deviceId === principal.deviceId && p.status === "finishing") {
929
+ p.status = "paired";
930
+ p.terminalAtMs = this.nowMs();
931
+ }
932
+ }
933
+ }
934
+ this.clearTimer(peer);
935
+ peer.state = "authenticated";
936
+ for (const other of [...this.peers.values()]) {
937
+ if (other !== peer && other.state === "authenticated" && other.principal?.deviceId === principal.deviceId)
938
+ this.dropPeer(other, "superseded");
939
+ }
940
+ touchPairedDeviceLastSeen(this.store.handle, principal.deviceId, new Date(this.nowMs()));
941
+ }
942
+ const isGate1 = PAIRED_DEVICE_GATE1_ROUTES.has(method);
943
+ const isGate2 = this.actions !== null && PAIRED_DEVICE_GATE2_ROUTES.has(method);
944
+ if (!isGate1 && !isGate2) {
945
+ this.sendRpcError(peer, frame.streamId, "route_not_allowed", `Method '${method}' is not on the paired-device allowlist`);
946
+ return;
947
+ }
948
+ await this.dispatchMethod(peer, frame.streamId, method, params);
949
+ }
950
+ async dispatchMethod(peer, streamId, method, params) {
951
+ const principal = peer.principal;
952
+ if (this.handlers.accessSignature !== undefined)
953
+ peer.streamAccess.set(streamId, this.handlers.accessSignature(principal));
954
+ try {
955
+ if (method === "device.self.revoke") {
956
+ this.sendRpcResult(peer, streamId, { ok: true, revoked: true });
957
+ this.revokeDevice(principal.deviceId, "removed");
958
+ return;
959
+ }
960
+ if (method === "run.watch.subscribe") {
961
+ if (this.handlers.runWatchSubscribe === undefined) {
962
+ this.sendRpcError(peer, streamId, "unsupported", "Live watch not configured");
963
+ return;
964
+ }
965
+ const promoted = peer.streamGuard.promoteToWatchStream(streamId);
966
+ if (!promoted.ok) {
967
+ this.sendRpcError(peer, streamId, promoted.code, promoted.message);
968
+ return;
969
+ }
970
+ const buffer = new LiveWatchBuffer({ reserve: bytes => peer.streamGuard.reserveWatch(bytes), release: bytes => peer.streamGuard.releaseWatch(bytes) });
971
+ const watchEntry = { buffer, unsubscribe: () => { }, seq: 0, ending: false, lastCreditAtMs: this.nowMs() };
972
+ peer.watchStreams.set(streamId, watchEntry);
973
+ let unsubscribed = false;
974
+ const sub = this.handlers.runWatchSubscribe(principal, params, record => {
975
+ if (peer.watchStreams.get(streamId) !== watchEntry)
976
+ return;
977
+ buffer.push(record);
978
+ this.pumpWatchStream(peer, streamId, watchEntry);
979
+ }, reason => {
980
+ if (peer.watchStreams.get(streamId) !== watchEntry)
981
+ return;
982
+ if (reason === "denied") {
983
+ this.denyStream(peer, streamId);
984
+ return;
985
+ }
986
+ watchEntry.ending = true;
987
+ this.pumpWatchStream(peer, streamId, watchEntry);
988
+ });
989
+ if (!sub.ok) {
990
+ if (peer.watchStreams.get(streamId) === watchEntry) {
991
+ buffer.clear();
992
+ peer.watchStreams.delete(streamId);
993
+ }
994
+ this.sendRpcError(peer, streamId, sub.code, sub.message);
995
+ return;
996
+ }
997
+ if (peer.watchStreams.get(streamId) !== watchEntry) {
998
+ unsubscribed = true;
999
+ sub.unsubscribe();
1000
+ }
1001
+ if (!unsubscribed)
1002
+ watchEntry.unsubscribe = sub.unsubscribe;
1003
+ return;
1004
+ }
1005
+ let result;
1006
+ switch (method) {
1007
+ case "device.hello": {
1008
+ const hello = await this.handlers.deviceHello(principal);
1009
+ const paths = this.pathsOf();
1010
+ result = hello !== null && typeof hello === "object"
1011
+ ? { ...hello, consoleUrl: this.consoleUrl(), ...(pathsAllowed(paths) ? { paths } : {}) }
1012
+ : hello;
1013
+ break;
1014
+ }
1015
+ case "work.rows":
1016
+ result = await this.handlers.workRows(principal, params);
1017
+ break;
1018
+ case "task.steps":
1019
+ result = await this.handlers.taskSteps(principal, params);
1020
+ break;
1021
+ case "task.diff":
1022
+ result = await this.handlers.taskDiff(principal, params);
1023
+ break;
1024
+ case "task.approval.read":
1025
+ result = await this.handlers.taskApprovalRead(principal, params);
1026
+ break;
1027
+ case "run.window.read":
1028
+ result = await this.handlers.runWindowRead(principal, params);
1029
+ break;
1030
+ case "passkey.status":
1031
+ result = await this.actions.passkeyStatus(principal);
1032
+ break;
1033
+ case "passkey.lock":
1034
+ result = await this.actions.passkeyLock(principal);
1035
+ break;
1036
+ case "passkey.unlock":
1037
+ result = await this.actions.passkeyUnlock(principal, params);
1038
+ break;
1039
+ case "passkey.register.begin":
1040
+ result = await this.actions.passkeyRegisterBegin(principal, params);
1041
+ break;
1042
+ case "passkey.register.finish":
1043
+ result = await this.actions.passkeyRegisterFinish(principal, params);
1044
+ break;
1045
+ case "approval.challenge":
1046
+ result = await this.actions.approvalChallenge(principal, params);
1047
+ break;
1048
+ case "task.approve":
1049
+ result = await this.actions.taskApprove(principal, params);
1050
+ break;
1051
+ case "task.accept":
1052
+ result = await this.actions.taskAccept(principal, params);
1053
+ break;
1054
+ case "task.land":
1055
+ result = await this.actions.taskLand(principal, params);
1056
+ break;
1057
+ case "task.ship":
1058
+ result = await this.actions.taskShip(principal, params);
1059
+ break;
1060
+ default:
1061
+ this.sendRpcError(peer, streamId, "route_not_allowed", "Not allowed");
1062
+ return;
1063
+ }
1064
+ this.sendRpcResult(peer, streamId, result);
1065
+ }
1066
+ catch (err) {
1067
+ const raw = err instanceof Error ? err.code : undefined;
1068
+ const code = typeof raw === "string" && /^[a-z_]{1,40}$/.test(raw) ? raw : "handler_error";
1069
+ const msg = code === "handler_error" ? "Something went wrong reading that on your Mac." : err.message;
1070
+ this.sendRpcError(peer, streamId, code, msg);
1071
+ if (code === "standing_revoked" && this.peers.get(peer.key) === peer)
1072
+ this.refuseLive(peer, this.standingOf(peer, true) ?? "account_revoked");
1073
+ }
1074
+ }
1075
+ sendRpcResult(peer, streamId, result) {
1076
+ if (!peer.streamGuard.isOpen(streamId) || this.peers.get(peer.key) !== peer)
1077
+ return;
1078
+ const payload = Buffer.from(JSON.stringify({ ok: true, result }), "utf8");
1079
+ if (!peer.streamGuard.reserveResponse(streamId, payload.length)) {
1080
+ this.sendRpcError(peer, streamId, "memory_limit", "Too much is waiting for your phone to read. Try again in a moment.");
1081
+ return;
1082
+ }
1083
+ const pacer = new UnaryResponsePacer(streamId, payload, this.nowMs());
1084
+ peer.unaryPacers.set(streamId, pacer);
1085
+ this.pumpUnaryPacer(peer, streamId, pacer);
1086
+ }
1087
+ pumpUnaryPacer(peer, streamId, pacer) {
1088
+ if (!this.accessHolds(peer, streamId)) {
1089
+ this.denyStream(peer, streamId);
1090
+ return false;
1091
+ }
1092
+ const gate = this.pacingGate(peer, streamId);
1093
+ const pulled = pacer.pullAvailable(this.nowMs(), gate.allow);
1094
+ if (!pulled.ok) {
1095
+ this.dropStreamState(peer, streamId);
1096
+ this.sendControl(peer, { type: FrameType.ERROR, streamId, seq: 0, payload: encodeErrorPayload(pulled.code, "Unary response exceeded 30s deadline") });
1097
+ return false;
1098
+ }
1099
+ for (const f of pulled.frames)
1100
+ this.emit(peer, f);
1101
+ if (pacer.done) {
1102
+ peer.unaryPacers.delete(streamId);
1103
+ peer.streamAccess.delete(streamId);
1104
+ peer.waiting = peer.waiting.filter(id => id !== streamId);
1105
+ peer.streamGuard.closeStream(streamId);
1106
+ return false;
1107
+ }
1108
+ if (!gate.held())
1109
+ return false;
1110
+ this.holdForPacing(peer, streamId);
1111
+ return true;
1112
+ }
1113
+ pumpWatchStream(peer, streamId, watch) {
1114
+ if (!this.accessHolds(peer, streamId)) {
1115
+ this.denyStream(peer, streamId);
1116
+ return false;
1117
+ }
1118
+ const gate = this.pacingGate(peer, streamId);
1119
+ for (const rec of watch.buffer.drainAvailable(bytes => gate.allow(FRAME_HEADER_BYTES + bytes))) {
1120
+ this.emit(peer, { type: FrameType.CHUNK, streamId, seq: watch.seq++, payload: rec });
1121
+ }
1122
+ if (watch.ending && watch.buffer.length === 0 && watch.buffer.pendingCut === 0 && peer.watchStreams.get(streamId) === watch && gate.allow(FRAME_HEADER_BYTES)) {
1123
+ peer.watchStreams.delete(streamId);
1124
+ peer.streamAccess.delete(streamId);
1125
+ peer.waiting = peer.waiting.filter(id => id !== streamId);
1126
+ peer.streamGuard.closeStream(streamId);
1127
+ this.emit(peer, { type: FrameType.END, streamId, seq: watch.seq++, payload: Buffer.alloc(0) });
1128
+ return false;
1129
+ }
1130
+ if (!gate.held())
1131
+ return false;
1132
+ this.holdForPacing(peer, streamId);
1133
+ return true;
1134
+ }
1135
+ pacingGate(peer, streamId) {
1136
+ let held = false;
1137
+ const allow = (bytes) => {
1138
+ if (peer.bucket === null)
1139
+ return true;
1140
+ if (held)
1141
+ return false;
1142
+ const now = this.nowMs();
1143
+ const queuedAhead = peer.waiting.length > 0 && !(peer.draining && peer.waiting[0] === streamId);
1144
+ if (queuedAhead || peer.bucket.available(now) < bytes || (peer.link.pacing !== undefined && peer.link.pacing.available(now) < bytes)) {
1145
+ held = true;
1146
+ return false;
1147
+ }
1148
+ peer.bucket.take(bytes, now);
1149
+ peer.link.pacing?.take(bytes, now);
1150
+ return true;
1151
+ };
1152
+ return { allow, held: () => held };
1153
+ }
1154
+ holdForPacing(peer, streamId) {
1155
+ if (!peer.waiting.includes(streamId))
1156
+ peer.waiting.push(streamId);
1157
+ if (peer.pacingTimer !== null || peer.bucket === null)
1158
+ return;
1159
+ const now = this.nowMs();
1160
+ const frame = FRAME_HEADER_BYTES + MAX_FRAME_PAYLOAD_BYTES;
1161
+ const wait = Math.max(1, peer.bucket.waitFor(frame, now), peer.link.pacing?.waitFor(frame, now) ?? 0);
1162
+ peer.pacingTimer = setTimeout(() => { peer.pacingTimer = null; this.drainPaced(peer); }, wait);
1163
+ peer.pacingTimer.unref?.();
1164
+ }
1165
+ drainPaced(peer) {
1166
+ while (peer.waiting.length > 0 && this.peers.get(peer.key) === peer) {
1167
+ const streamId = peer.waiting[0];
1168
+ const pacer = peer.unaryPacers.get(streamId);
1169
+ const watch = peer.watchStreams.get(streamId);
1170
+ let held = false;
1171
+ peer.draining = true;
1172
+ try {
1173
+ if (pacer !== undefined)
1174
+ held = this.pumpUnaryPacer(peer, streamId, pacer);
1175
+ else if (watch !== undefined)
1176
+ held = this.pumpWatchStream(peer, streamId, watch);
1177
+ }
1178
+ finally {
1179
+ peer.draining = false;
1180
+ }
1181
+ if (peer.waiting[0] !== streamId)
1182
+ continue;
1183
+ if (held)
1184
+ return;
1185
+ peer.waiting.shift();
1186
+ }
1187
+ }
1188
+ sendRpcError(peer, streamId, code, message) {
1189
+ peer.streamAccess.delete(streamId);
1190
+ peer.waiting = peer.waiting.filter(id => id !== streamId);
1191
+ peer.streamGuard.closeStream(streamId);
1192
+ this.sendControl(peer, { type: FrameType.ERROR, streamId, seq: 0, payload: encodeErrorPayload(code, message) });
1193
+ }
1194
+ sendControl(peer, frame) {
1195
+ return this.emit(peer, frame);
1196
+ }
1197
+ emit(peer, frame) {
1198
+ if (peer.session === null || this.peers.get(peer.key) !== peer)
1199
+ return false;
1200
+ if (peer.link.backlog !== undefined && peer.link.backlogLimit !== undefined && peer.link.backlog() > peer.link.backlogLimit) {
1201
+ this.dropPeer(peer, "not_reading");
1202
+ return false;
1203
+ }
1204
+ if (peer.role === "device" && peer.state === "authenticated" && this.needsRekey(peer.session) && !(frame.type === FrameType.ERROR && frame.streamId === 0)) {
1205
+ this.endForRekey(peer);
1206
+ return false;
1207
+ }
1208
+ try {
1209
+ const ct = peer.session.encrypt(encodeFrame(frame), this.nowMs());
1210
+ peer.link.send(peer.connId, ct);
1211
+ return true;
1212
+ }
1213
+ catch {
1214
+ this.dropPeer(peer, "encrypt_failed");
1215
+ return false;
1216
+ }
1217
+ }
1218
+ ensureSweep() {
1219
+ if (this.sweepTimer !== null)
1220
+ return;
1221
+ this.sweepTimer = setInterval(() => {
1222
+ try {
1223
+ this.sweepDeadlines();
1224
+ }
1225
+ catch {
1226
+ if (this.sweepTimer !== null)
1227
+ clearInterval(this.sweepTimer);
1228
+ this.sweepTimer = null;
1229
+ for (const peer of [...this.peers.values()]) {
1230
+ try {
1231
+ this.dropPeer(peer, "unavailable");
1232
+ }
1233
+ catch {
1234
+ this.cleanupPeerLocal(peer);
1235
+ }
1236
+ }
1237
+ }
1238
+ }, DEADLINE_SWEEP_MS);
1239
+ this.sweepTimer.unref?.();
1240
+ }
1241
+ sweepDeadlines() {
1242
+ const now = this.nowMs();
1243
+ for (const p of [...this.pairings.values()]) {
1244
+ this.expireIfDue(p);
1245
+ if (p.terminalAtMs !== null && now - p.terminalAtMs > PAIRING_TERMINAL_KEEP_MS) {
1246
+ p.pairPsk.fill(0);
1247
+ this.pairings.delete(p.pairSessionId);
1248
+ }
1249
+ }
1250
+ if (this.peers.size === 0 && this.pairings.size === 0) {
1251
+ if (this.sweepTimer !== null)
1252
+ clearInterval(this.sweepTimer);
1253
+ this.sweepTimer = null;
1254
+ return;
1255
+ }
1256
+ for (const peer of [...this.peers.values()]) {
1257
+ if (this.peers.get(peer.key) !== peer)
1258
+ continue;
1259
+ if (peer.role === "pair") {
1260
+ const pairing = this.pairings.get(peer.peerId);
1261
+ if (pairing === undefined || (TERMINAL.has(pairing.status) && pairing.status !== "paired") || (pairing.status === "paired" && peer.state !== "pair_finishing"))
1262
+ this.dropPeer(peer, "pairing_over");
1263
+ continue;
1264
+ }
1265
+ if (peer.state !== "authenticated" || peer.session === null)
1266
+ continue;
1267
+ const standing = this.standingOf(peer, true);
1268
+ if (standing !== null) {
1269
+ this.refuseLive(peer, standing);
1270
+ continue;
1271
+ }
1272
+ if (this.needsRekey(peer.session)) {
1273
+ this.endForRekey(peer);
1274
+ continue;
1275
+ }
1276
+ for (const streamId of peer.streamGuard.expireAssemblies(now)) {
1277
+ this.sendRpcError(peer, streamId, "deadline_exceeded", "The request didn't arrive in time.");
1278
+ }
1279
+ for (const [streamId, pacer] of [...peer.unaryPacers]) {
1280
+ if (pacer.isTimedOut(now))
1281
+ this.pumpUnaryPacer(peer, streamId, pacer);
1282
+ }
1283
+ for (const [streamId, watch] of [...peer.watchStreams]) {
1284
+ if (watch.buffer.length > 0 && now - watch.lastCreditAtMs > WATCH_IDLE_DEADLINE_MS) {
1285
+ this.dropStreamState(peer, streamId);
1286
+ this.sendControl(peer, { type: FrameType.ERROR, streamId, seq: 0, payload: encodeErrorPayload("idle_timeout", "Stopped watching: your phone stopped reading.") });
1287
+ }
1288
+ }
1289
+ }
1290
+ }
1291
+ dropPeer(peer, reason, code) {
1292
+ if (this.peers.get(peer.key) !== peer)
1293
+ return;
1294
+ this.cleanupPeerLocal(peer);
1295
+ peer.link.close(peer.connId, reason, code);
1296
+ }
1297
+ cleanupPeerLocal(peer) {
1298
+ if (this.peers.get(peer.key) !== peer)
1299
+ return;
1300
+ this.clearTimer(peer);
1301
+ if (peer.pacingTimer !== null)
1302
+ clearTimeout(peer.pacingTimer);
1303
+ peer.pacingTimer = null;
1304
+ for (const w of peer.watchStreams.values()) {
1305
+ w.unsubscribe();
1306
+ w.buffer.clear();
1307
+ }
1308
+ peer.watchStreams.clear();
1309
+ peer.unaryPacers.clear();
1310
+ peer.waiting = [];
1311
+ peer.streamGuard.releaseAll();
1312
+ peer.session?.close();
1313
+ peer.session = null;
1314
+ peer.pairProof = null;
1315
+ this.peers.delete(peer.key);
1316
+ for (const p of this.pairings.values()) {
1317
+ if (p.attachedKey !== peer.key)
1318
+ continue;
1319
+ if (p.status === "awaiting_confirm") {
1320
+ if (this.nowMs() > p.expiresAtMs)
1321
+ this.endPairing(p, "expired");
1322
+ else
1323
+ this.endPairing(p, "failed", "The iPhone disconnected. Pair again.");
1324
+ }
1325
+ if (p.attachedKey === peer.key)
1326
+ p.attachedKey = null;
1327
+ }
1328
+ }
1329
+ }
1330
+ function standingCodeOf(reason) {
1331
+ return reason === "password_changed" || reason === "access_changed" ? "account_revoked" : "device_revoked";
1332
+ }
1333
+ function parseRequest(payload) {
1334
+ let req;
1335
+ try {
1336
+ req = JSON.parse(payload.toString("utf8"));
1337
+ }
1338
+ catch {
1339
+ return null;
1340
+ }
1341
+ if (req === null || typeof req !== "object")
1342
+ return null;
1343
+ const method = typeof req.method === "string" ? req.method : "";
1344
+ const params = req.params !== null && typeof req.params === "object" && !Array.isArray(req.params) ? req.params : {};
1345
+ return { method, params };
1346
+ }