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