toolroll 0.9.127 → 0.9.129
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +36 -0
- package/README.md +2 -1
- package/dist/accent-colors.js +3 -1
- package/dist/approval-authority.js +2 -1
- package/dist/assignment.js +55 -2
- package/dist/backup.js +6 -0
- package/dist/browser/terminal.css +1 -1
- package/dist/browser/workspace.css +2 -2
- package/dist/browser/workspace.js +9 -9
- package/dist/central-recovery-stage.js +3 -3
- package/dist/companion/access.js +161 -0
- package/dist/companion/actions.js +559 -0
- package/dist/companion/bonjour.js +45 -0
- package/dist/companion/daemon.js +1346 -0
- package/dist/companion/direct-server.js +177 -0
- package/dist/companion/framing.js +498 -0
- package/dist/companion/noise.js +461 -0
- package/dist/companion/passkey-gate.js +287 -0
- package/dist/companion/paths.js +90 -0
- package/dist/companion/reads.js +279 -0
- package/dist/companion/relay-auth.js +265 -0
- package/dist/companion/relay-server.js +870 -0
- package/dist/companion/schema.js +225 -0
- package/dist/companion/service.js +580 -0
- package/dist/companion/store.js +324 -0
- package/dist/companion/webauthn-test-support.js +44 -0
- package/dist/companion/webauthn.js +398 -0
- package/dist/contracts/console-api.js +18 -0
- package/dist/demo.js +1 -1
- package/dist/design/kit.css +36 -3
- package/dist/local-landing.js +47 -0
- package/dist/models-ui.js +5 -2
- package/dist/operate.js +19 -3
- package/dist/person-proof.js +5 -1
- package/dist/pull-request-flow.js +75 -2
- package/dist/qr.js +385 -0
- package/dist/release-adapters.js +2 -1
- package/dist/restore-retirement.js +2 -0
- package/dist/scope.js +67 -4
- package/dist/serve.js +31 -4
- package/dist/server/pages.js +9 -2
- package/dist/server/phone-engine-api.js +59 -0
- package/dist/server/route-table.js +11 -0
- package/dist/server/settings-phone.js +492 -0
- package/dist/server/settings-scripts.js +2 -0
- package/dist/server/settings-sections.js +6 -2
- package/dist/server/settings.js +8 -2
- package/dist/settings-groups-ui.js +2 -1
- package/dist/settings-proofs.js +6 -0
- package/dist/skills-ui.js +11 -6
- package/dist/spend-ui.js +3 -2
- package/dist/spend.js +8 -1
- package/dist/store.js +37 -4
- package/dist/tailnet.js +42 -0
- package/dist/toolroll-update.js +3 -1
- package/dist/youiyoux-intake.js +8 -0
- package/package.json +7 -2
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
import { consumePasskeyChallenge, deviceAccountStands, getAccountPasskey, getPairedDevice, getPasskeyChallenge, updateAccountPasskeyUsage, } from "./store.js";
|
|
2
|
+
import { canonicalJson, derivePasskeyUserHandle, PASSKEY_CHALLENGE_TTL_MS, PASSKEY_ORIGIN, PASSKEY_RP_ID, verifyAssertionResponse, } from "./webauthn.js";
|
|
3
|
+
export const PASSKEY_WINDOW_OPTIONS = [0, 15, 60];
|
|
4
|
+
export const DEFAULT_PASSKEY_WINDOW_MINUTES = 15;
|
|
5
|
+
export function parsePasskeyWindowMinutes(raw) {
|
|
6
|
+
const n = typeof raw === "number" ? raw : typeof raw === "string" && /^\d+$/.test(raw.trim()) ? Number(raw.trim()) : NaN;
|
|
7
|
+
return n === 0 || n === 15 || n === 60 ? n : null;
|
|
8
|
+
}
|
|
9
|
+
export function usesPasskeyLease(proof) {
|
|
10
|
+
return proof.kind === "lease";
|
|
11
|
+
}
|
|
12
|
+
const CHECKED = new WeakSet();
|
|
13
|
+
function standingProblem(store, input) {
|
|
14
|
+
const identity = store.workspaceIdentity();
|
|
15
|
+
const account = store.accountOf(input.accountName);
|
|
16
|
+
if (account === null || account.revokedAt !== null || account.role !== "approver") {
|
|
17
|
+
return { code: "not_an_approver", message: "Only an active approver account can authorize this act." };
|
|
18
|
+
}
|
|
19
|
+
if (input.anyProject !== true && (input.repo === null || !store.accountCanAccess(input.accountName, input.repo))) {
|
|
20
|
+
return { code: "not_an_approver", message: "You don't have access to this project." };
|
|
21
|
+
}
|
|
22
|
+
const device = getPairedDevice(store.handle, input.deviceId);
|
|
23
|
+
if (device === null ||
|
|
24
|
+
device.revokedAt !== null ||
|
|
25
|
+
device.activatedAt === null ||
|
|
26
|
+
device.accountName !== input.accountName ||
|
|
27
|
+
device.recoveryGeneration !== identity.recoveryGeneration ||
|
|
28
|
+
!deviceAccountStands(device, account)) {
|
|
29
|
+
return { code: "device_revoked", message: "This iPhone is no longer paired or your account changed." };
|
|
30
|
+
}
|
|
31
|
+
const cred = getAccountPasskey(store.handle, input.credentialId);
|
|
32
|
+
if (cred === null ||
|
|
33
|
+
cred.revokedAt !== null ||
|
|
34
|
+
cred.workspaceId !== identity.id ||
|
|
35
|
+
cred.accountName !== input.accountName ||
|
|
36
|
+
cred.recoveryGeneration !== identity.recoveryGeneration) {
|
|
37
|
+
return { code: "credential_not_allowed", message: "That passkey is not active for your account on this Mac." };
|
|
38
|
+
}
|
|
39
|
+
return { account };
|
|
40
|
+
}
|
|
41
|
+
export function checkPasskeyAction(store, input) {
|
|
42
|
+
const identity = store.workspaceIdentity();
|
|
43
|
+
const proof = input.proof;
|
|
44
|
+
if (proof === null || typeof proof !== "object" || (proof.kind !== undefined && proof.kind !== "assertion") || typeof proof.deviceId !== "string"
|
|
45
|
+
|| typeof proof.challenge !== "string" || proof.assertion === null || typeof proof.assertion !== "object" || typeof proof.assertion.credentialId !== "string") {
|
|
46
|
+
return { ok: false, code: "invalid_proof", message: "That passkey confirmation isn't valid." };
|
|
47
|
+
}
|
|
48
|
+
const standing = standingProblem(store, { ...input, deviceId: input.proof.deviceId, credentialId: input.proof.assertion.credentialId });
|
|
49
|
+
if (!("account" in standing))
|
|
50
|
+
return { ok: false, ...standing };
|
|
51
|
+
const challengeRow = getPasskeyChallenge(store.handle, input.proof.challenge);
|
|
52
|
+
if (challengeRow === null) {
|
|
53
|
+
return { ok: false, code: "challenge_unknown", message: "Approval challenge not found. Request a fresh approval." };
|
|
54
|
+
}
|
|
55
|
+
if (challengeRow.consumedAt !== null) {
|
|
56
|
+
return { ok: false, code: "challenge_used", message: "That approval challenge was already used." };
|
|
57
|
+
}
|
|
58
|
+
if (Date.parse(challengeRow.expiresAt) <= input.now.getTime()) {
|
|
59
|
+
return { ok: false, code: "challenge_expired", message: "That approval challenge expired. Try again." };
|
|
60
|
+
}
|
|
61
|
+
if (challengeRow.kind !== input.verb) {
|
|
62
|
+
return { ok: false, code: "verb_mismatch", message: "That passkey challenge belongs to a different action." };
|
|
63
|
+
}
|
|
64
|
+
if (challengeRow.workspaceId !== identity.id ||
|
|
65
|
+
challengeRow.accountName !== input.accountName ||
|
|
66
|
+
challengeRow.deviceId !== input.proof.deviceId ||
|
|
67
|
+
challengeRow.recoveryGeneration !== identity.recoveryGeneration) {
|
|
68
|
+
return { ok: false, code: "challenge_binding_mismatch", message: "Approval challenge does not match this device or account." };
|
|
69
|
+
}
|
|
70
|
+
if (challengeRow.bindingJson !== canonicalJson(input.expectedBinding)) {
|
|
71
|
+
return { ok: false, code: "binding_mismatch", message: "The target changed since the approval challenge was issued." };
|
|
72
|
+
}
|
|
73
|
+
const cred = getAccountPasskey(store.handle, input.proof.assertion.credentialId);
|
|
74
|
+
const verified = verifyAssertionResponse({
|
|
75
|
+
payload: input.proof.assertion,
|
|
76
|
+
expectedChallenge: challengeRow.challenge,
|
|
77
|
+
expectedUserHandle: derivePasskeyUserHandle(identity.id, input.accountName),
|
|
78
|
+
storedPublicKeySpki: cred.publicKeySpki,
|
|
79
|
+
storedSignCount: cred.signCount,
|
|
80
|
+
rpId: input.proof.rpId ?? PASSKEY_RP_ID,
|
|
81
|
+
expectedOrigin: input.proof.expectedOrigin ?? PASSKEY_ORIGIN,
|
|
82
|
+
});
|
|
83
|
+
if (!verified.ok)
|
|
84
|
+
return verified;
|
|
85
|
+
const checked = {
|
|
86
|
+
ok: true,
|
|
87
|
+
accountName: input.accountName,
|
|
88
|
+
accountGeneration: standing.account.generation,
|
|
89
|
+
deviceId: input.proof.deviceId,
|
|
90
|
+
credentialId: cred.credentialId,
|
|
91
|
+
be: verified.be,
|
|
92
|
+
bs: verified.bs,
|
|
93
|
+
provedAtMs: input.now.getTime(),
|
|
94
|
+
verb: input.verb,
|
|
95
|
+
challenge: challengeRow.challenge,
|
|
96
|
+
storedSignCount: cred.signCount,
|
|
97
|
+
newSignCount: verified.newSignCount,
|
|
98
|
+
};
|
|
99
|
+
CHECKED.add(checked);
|
|
100
|
+
return checked;
|
|
101
|
+
}
|
|
102
|
+
export function consumePasskeyAction(store, checked, input) {
|
|
103
|
+
if (!CHECKED.has(checked))
|
|
104
|
+
return { ok: false, code: "not_verified", message: "That passkey confirmation wasn't verified." };
|
|
105
|
+
CHECKED.delete(checked);
|
|
106
|
+
const pending = registry(PENDING, store);
|
|
107
|
+
pending.delete(checked.challenge);
|
|
108
|
+
const standing = standingProblem(store, { ...checked, repo: input.repo, ...(input.anyProject === true ? { anyProject: true } : {}) });
|
|
109
|
+
if (!("account" in standing))
|
|
110
|
+
return { ok: false, ...standing };
|
|
111
|
+
if (standing.account.generation !== checked.accountGeneration) {
|
|
112
|
+
return { ok: false, code: "device_revoked", message: "This iPhone is no longer paired or your account changed." };
|
|
113
|
+
}
|
|
114
|
+
const refusedWith = (code, message) => Object.assign(new Error(message), { refusal: { ok: false, code, message } });
|
|
115
|
+
try {
|
|
116
|
+
store.savepoint(() => {
|
|
117
|
+
if (!consumePasskeyChallenge(store.handle, checked.challenge, input.now))
|
|
118
|
+
throw refusedWith("challenge_used", "That approval challenge was already used or expired.");
|
|
119
|
+
if (!updateAccountPasskeyUsage(store.handle, checked.credentialId, checked.storedSignCount, checked.newSignCount, input.now))
|
|
120
|
+
throw refusedWith("sign_count_regression", "Passkey signCount did not advance.");
|
|
121
|
+
});
|
|
122
|
+
}
|
|
123
|
+
catch (error) {
|
|
124
|
+
const refusal = error.refusal;
|
|
125
|
+
if (refusal !== undefined)
|
|
126
|
+
return refusal;
|
|
127
|
+
throw error;
|
|
128
|
+
}
|
|
129
|
+
const provedAtMs = input.now.getTime();
|
|
130
|
+
if (input.startsLease !== undefined && (checked.verb === "approve" || checked.verb === "accept" || checked.verb === "unlock")) {
|
|
131
|
+
for (const [k, one] of pending)
|
|
132
|
+
if (provedAtMs - one.provedAtMs > PASSKEY_CHALLENGE_TTL_MS)
|
|
133
|
+
pending.delete(k);
|
|
134
|
+
pending.set(checked.challenge, {
|
|
135
|
+
deviceId: checked.deviceId,
|
|
136
|
+
accountName: checked.accountName,
|
|
137
|
+
credentialId: checked.credentialId,
|
|
138
|
+
recoveryGeneration: store.workspaceIdentity().recoveryGeneration,
|
|
139
|
+
accountGeneration: checked.accountGeneration,
|
|
140
|
+
provedAtMs,
|
|
141
|
+
expiresAtMs: provedAtMs + input.startsLease.minutes * 60_000,
|
|
142
|
+
be: checked.be,
|
|
143
|
+
bs: checked.bs,
|
|
144
|
+
});
|
|
145
|
+
}
|
|
146
|
+
const { verb: _verb, challenge: _challenge, storedSignCount: _s, newSignCount: _n, ...result } = checked;
|
|
147
|
+
return { ...result, provedAtMs };
|
|
148
|
+
}
|
|
149
|
+
export function verifyPasskeyAction(store, input) {
|
|
150
|
+
const checked = checkPasskeyAction(store, input);
|
|
151
|
+
if (!checked.ok)
|
|
152
|
+
return checked;
|
|
153
|
+
return consumePasskeyAction(store, checked, {
|
|
154
|
+
repo: input.repo,
|
|
155
|
+
now: input.now,
|
|
156
|
+
...(input.anyProject === true ? { anyProject: true } : {}),
|
|
157
|
+
...(input.startsLease === undefined ? {} : { startsLease: input.startsLease }),
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
const LEASES = new WeakMap();
|
|
161
|
+
const PENDING = new WeakMap();
|
|
162
|
+
function registry(of, store) {
|
|
163
|
+
let map = of.get(store);
|
|
164
|
+
if (map === undefined) {
|
|
165
|
+
map = new Map();
|
|
166
|
+
of.set(store, map);
|
|
167
|
+
}
|
|
168
|
+
return map;
|
|
169
|
+
}
|
|
170
|
+
const leaseKey = (deviceId, accountName) => `${deviceId}\0${accountName}`;
|
|
171
|
+
export function startPasskeyLease(store, input) {
|
|
172
|
+
const pending = registry(PENDING, store);
|
|
173
|
+
const grant = pending.get(input.challenge);
|
|
174
|
+
pending.delete(input.challenge);
|
|
175
|
+
if (grant === undefined || grant.deviceId !== input.deviceId || grant.accountName !== input.accountName)
|
|
176
|
+
return null;
|
|
177
|
+
const row = getPasskeyChallenge(store.handle, input.challenge);
|
|
178
|
+
if (row === null || row.consumedAt === null || row.deviceId !== input.deviceId || row.accountName !== input.accountName)
|
|
179
|
+
return null;
|
|
180
|
+
const windowMinutes = passkeyApprovalWindowMinutes(store);
|
|
181
|
+
if (windowMinutes <= 0)
|
|
182
|
+
return null;
|
|
183
|
+
const lease = { ...grant, expiresAtMs: Math.min(grant.expiresAtMs, grant.provedAtMs + windowMinutes * 60_000) };
|
|
184
|
+
registry(LEASES, store).set(leaseKey(input.deviceId, input.accountName), lease);
|
|
185
|
+
return new Date(lease.expiresAtMs).toISOString();
|
|
186
|
+
}
|
|
187
|
+
export function activePasskeyLease(store, deviceId, accountName, now) {
|
|
188
|
+
const leases = registry(LEASES, store);
|
|
189
|
+
const key = leaseKey(deviceId, accountName);
|
|
190
|
+
const lease = leases.get(key);
|
|
191
|
+
if (lease === undefined)
|
|
192
|
+
return null;
|
|
193
|
+
const windowMinutes = passkeyApprovalWindowMinutes(store);
|
|
194
|
+
const expiresAtMs = Math.min(lease.expiresAtMs, lease.provedAtMs + windowMinutes * 60_000);
|
|
195
|
+
const standing = standingProblem(store, { accountName, repo: null, anyProject: true, deviceId, credentialId: lease.credentialId });
|
|
196
|
+
if (windowMinutes <= 0 ||
|
|
197
|
+
now.getTime() >= expiresAtMs ||
|
|
198
|
+
lease.recoveryGeneration !== store.workspaceIdentity().recoveryGeneration ||
|
|
199
|
+
!("account" in standing) ||
|
|
200
|
+
standing.account.generation !== lease.accountGeneration) {
|
|
201
|
+
leases.delete(key);
|
|
202
|
+
return null;
|
|
203
|
+
}
|
|
204
|
+
return { ...lease, expiresAtMs };
|
|
205
|
+
}
|
|
206
|
+
export function verifyPasskeyLease(store, input) {
|
|
207
|
+
const lease = activePasskeyLease(store, input.proof.deviceId, input.accountName, input.now);
|
|
208
|
+
if (lease === null) {
|
|
209
|
+
return { ok: false, code: "step_up_required", message: "Your approvals window ended. Confirm with your passkey." };
|
|
210
|
+
}
|
|
211
|
+
const standing = standingProblem(store, { accountName: input.accountName, repo: input.repo, deviceId: lease.deviceId, credentialId: lease.credentialId });
|
|
212
|
+
if (!("account" in standing))
|
|
213
|
+
return { ok: false, ...standing };
|
|
214
|
+
return {
|
|
215
|
+
ok: true,
|
|
216
|
+
accountName: input.accountName,
|
|
217
|
+
accountGeneration: lease.accountGeneration,
|
|
218
|
+
deviceId: lease.deviceId,
|
|
219
|
+
credentialId: lease.credentialId,
|
|
220
|
+
be: lease.be,
|
|
221
|
+
bs: lease.bs,
|
|
222
|
+
provedAtMs: lease.provedAtMs,
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
export function clearPasskeyLeases(store, accountName, deviceId) {
|
|
226
|
+
for (const map of [registry(LEASES, store), registry(PENDING, store)]) {
|
|
227
|
+
for (const [k, lease] of map) {
|
|
228
|
+
if ((accountName === undefined || lease.accountName === accountName) && (deviceId === undefined || lease.deviceId === deviceId))
|
|
229
|
+
map.delete(k);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
export const PASSKEY_REQUIRED_WORKSPACE_SCOPE = "*";
|
|
234
|
+
export function passkeyRequiredForApprovals(store, repo) {
|
|
235
|
+
const workspaceVal = store.handle
|
|
236
|
+
.prepare("SELECT required FROM passkey_approval_policy WHERE scope = ?")
|
|
237
|
+
.get(PASSKEY_REQUIRED_WORKSPACE_SCOPE)?.["required"];
|
|
238
|
+
if (Number(workspaceVal) === 1)
|
|
239
|
+
return true;
|
|
240
|
+
if (repo !== null) {
|
|
241
|
+
const projectVal = store.handle
|
|
242
|
+
.prepare("SELECT required FROM passkey_approval_policy WHERE scope = ?")
|
|
243
|
+
.get(repo)?.["required"];
|
|
244
|
+
if (Number(projectVal) === 1)
|
|
245
|
+
return true;
|
|
246
|
+
}
|
|
247
|
+
return false;
|
|
248
|
+
}
|
|
249
|
+
export function setPasskeyRequiredForApprovals(store, enabled, repo) {
|
|
250
|
+
const scope = repo ?? PASSKEY_REQUIRED_WORKSPACE_SCOPE;
|
|
251
|
+
const existing = store.handle
|
|
252
|
+
.prepare("SELECT window_minutes FROM passkey_approval_policy WHERE scope = ?")
|
|
253
|
+
.get(scope);
|
|
254
|
+
const windowMinutes = existing !== undefined
|
|
255
|
+
? (parsePasskeyWindowMinutes(Number(existing["window_minutes"])) ?? DEFAULT_PASSKEY_WINDOW_MINUTES)
|
|
256
|
+
: DEFAULT_PASSKEY_WINDOW_MINUTES;
|
|
257
|
+
if (enabled) {
|
|
258
|
+
store.handle
|
|
259
|
+
.prepare("INSERT INTO passkey_approval_policy (scope, required, window_minutes) VALUES (?, 1, ?) ON CONFLICT(scope) DO UPDATE SET required = 1")
|
|
260
|
+
.run(scope, windowMinutes);
|
|
261
|
+
}
|
|
262
|
+
else if (scope === PASSKEY_REQUIRED_WORKSPACE_SCOPE && existing !== undefined) {
|
|
263
|
+
store.handle.prepare("UPDATE passkey_approval_policy SET required = 0 WHERE scope = ?").run(scope);
|
|
264
|
+
}
|
|
265
|
+
else {
|
|
266
|
+
store.handle.prepare("DELETE FROM passkey_approval_policy WHERE scope = ?").run(scope);
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
export function passkeyApprovalWindowMinutes(store) {
|
|
270
|
+
const row = store.handle
|
|
271
|
+
.prepare("SELECT window_minutes FROM passkey_approval_policy WHERE scope = ?")
|
|
272
|
+
.get(PASSKEY_REQUIRED_WORKSPACE_SCOPE);
|
|
273
|
+
if (row === undefined)
|
|
274
|
+
return DEFAULT_PASSKEY_WINDOW_MINUTES;
|
|
275
|
+
return parsePasskeyWindowMinutes(Number(row["window_minutes"])) ?? DEFAULT_PASSKEY_WINDOW_MINUTES;
|
|
276
|
+
}
|
|
277
|
+
export function setPasskeyApprovalWindowMinutes(store, minutes) {
|
|
278
|
+
const before = passkeyApprovalWindowMinutes(store);
|
|
279
|
+
store.handle
|
|
280
|
+
.prepare(`
|
|
281
|
+
INSERT INTO passkey_approval_policy (scope, required, window_minutes)
|
|
282
|
+
VALUES (?, 0, ?)
|
|
283
|
+
ON CONFLICT(scope) DO UPDATE SET window_minutes = excluded.window_minutes
|
|
284
|
+
`)
|
|
285
|
+
.run(PASSKEY_REQUIRED_WORKSPACE_SCOPE, minutes);
|
|
286
|
+
return before;
|
|
287
|
+
}
|
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
import { networkInterfaces } from "node:os";
|
|
2
|
+
export const MAX_DIRECT_PATHS = 4;
|
|
3
|
+
const MAX_URL = 200;
|
|
4
|
+
function ipv4Parts(host) {
|
|
5
|
+
const m = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/.exec(host);
|
|
6
|
+
if (m === null)
|
|
7
|
+
return null;
|
|
8
|
+
const parts = m.slice(1).map(Number);
|
|
9
|
+
return parts.every(p => p <= 255) ? parts : null;
|
|
10
|
+
}
|
|
11
|
+
export function isLanIpv4(host) {
|
|
12
|
+
const p = ipv4Parts(host);
|
|
13
|
+
if (p === null)
|
|
14
|
+
return false;
|
|
15
|
+
return p[0] === 10 || (p[0] === 172 && p[1] >= 16 && p[1] <= 31) || (p[0] === 192 && p[1] === 168);
|
|
16
|
+
}
|
|
17
|
+
export function isTailnetIpv4(host) {
|
|
18
|
+
const p = ipv4Parts(host);
|
|
19
|
+
return p !== null && p[0] === 100 && p[1] >= 64 && p[1] <= 127;
|
|
20
|
+
}
|
|
21
|
+
export function lanAddressesOf(interfaces = networkInterfaces()) {
|
|
22
|
+
return lanInterfacesOf(interfaces).map(one => one.address);
|
|
23
|
+
}
|
|
24
|
+
export function lanInterfacesOf(interfaces = networkInterfaces()) {
|
|
25
|
+
const found = [];
|
|
26
|
+
for (const [name, infos] of Object.entries(interfaces)) {
|
|
27
|
+
for (const info of infos ?? []) {
|
|
28
|
+
if (info.family === "IPv4" && !info.internal && isLanIpv4(info.address))
|
|
29
|
+
found.push({ name, address: info.address });
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
found.sort((a, b) => Number(!a.name.startsWith("en")) - Number(!b.name.startsWith("en")) || a.name.localeCompare(b.name));
|
|
33
|
+
const seen = new Set();
|
|
34
|
+
return found.filter(f => !seen.has(f.address) && seen.add(f.address)).slice(0, 3).map(f => ({ address: f.address, interface: f.name }));
|
|
35
|
+
}
|
|
36
|
+
export function interfaceOf(address, interfaces = networkInterfaces()) {
|
|
37
|
+
for (const [name, infos] of Object.entries(interfaces)) {
|
|
38
|
+
if ((infos ?? []).some(info => info.family === "IPv4" && info.address === address))
|
|
39
|
+
return name;
|
|
40
|
+
}
|
|
41
|
+
return null;
|
|
42
|
+
}
|
|
43
|
+
const OCTET = "(?:25[0-5]|2[0-4]\\d|1\\d\\d|[1-9]?\\d)";
|
|
44
|
+
const PORT = "(?:[1-9]\\d{0,4})";
|
|
45
|
+
const DIRECT = new RegExp(`^ws://(${OCTET}\\.${OCTET}\\.${OCTET}\\.${OCTET}):(${PORT})/v1/direct$`);
|
|
46
|
+
const HOSTED = new RegExp(`^wss://([a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*)(?::(${PORT}))?/v1/connect$`);
|
|
47
|
+
const HOSTED_LOCAL = new RegExp(`^ws://(?:127\\.0\\.0\\.1|localhost):(${PORT})/v1/connect$`);
|
|
48
|
+
const portOk = (port) => port === undefined || Number(port) <= 65_535;
|
|
49
|
+
export function pathAllowed(path) {
|
|
50
|
+
if (path === null || typeof path !== "object" || typeof path.url !== "string" || path.url.length > MAX_URL)
|
|
51
|
+
return false;
|
|
52
|
+
if (path.kind === "direct") {
|
|
53
|
+
const m = DIRECT.exec(path.url);
|
|
54
|
+
return m !== null && portOk(m[2]) && (isLanIpv4(m[1]) || isTailnetIpv4(m[1]));
|
|
55
|
+
}
|
|
56
|
+
if (path.kind === "hosted") {
|
|
57
|
+
const m = HOSTED.exec(path.url) ?? HOSTED_LOCAL.exec(path.url);
|
|
58
|
+
return m !== null && portOk(m[m.length - 1]);
|
|
59
|
+
}
|
|
60
|
+
return false;
|
|
61
|
+
}
|
|
62
|
+
export function pathsAllowed(paths) {
|
|
63
|
+
if (paths.length < 1 || paths.length > MAX_DIRECT_PATHS + 1)
|
|
64
|
+
return false;
|
|
65
|
+
const direct = paths.filter(p => p.kind === "direct").length, hosted = paths.filter(p => p.kind === "hosted").length;
|
|
66
|
+
if (direct > MAX_DIRECT_PATHS || hosted > 1)
|
|
67
|
+
return false;
|
|
68
|
+
if (hosted === 1 && paths[paths.length - 1].kind !== "hosted")
|
|
69
|
+
return false;
|
|
70
|
+
if (new Set(paths.map(p => p.url)).size !== paths.length)
|
|
71
|
+
return false;
|
|
72
|
+
return paths.every(pathAllowed);
|
|
73
|
+
}
|
|
74
|
+
export function buildPaths(opts) {
|
|
75
|
+
const direct = [];
|
|
76
|
+
if (opts.port !== null) {
|
|
77
|
+
for (const host of [...opts.lan, ...(opts.tailnet === null ? [] : [opts.tailnet])]) {
|
|
78
|
+
const path = { kind: "direct", url: `ws://${host}:${opts.port}/v1/direct` };
|
|
79
|
+
if (pathAllowed(path) && !direct.some(d => d.url === path.url))
|
|
80
|
+
direct.push(path);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
const out = direct.slice(0, MAX_DIRECT_PATHS);
|
|
84
|
+
if (opts.hosted !== null) {
|
|
85
|
+
const hosted = { kind: "hosted", url: opts.hosted };
|
|
86
|
+
if (pathAllowed(hosted))
|
|
87
|
+
out.push(hosted);
|
|
88
|
+
}
|
|
89
|
+
return out;
|
|
90
|
+
}
|
|
@@ -0,0 +1,279 @@
|
|
|
1
|
+
import { IncomingMessage, ServerResponse } from "node:http";
|
|
2
|
+
import { Socket } from "node:net";
|
|
3
|
+
import { checkEngineResponse, ENGINE_API_VERSION } from "../contracts/engine-api.js";
|
|
4
|
+
import { isProtectedWork, protectedChanges } from "../approval-policy.js";
|
|
5
|
+
import { resultDiffFileOf, resultDiffOf, resultRunsOf, stepCardsOf } from "../engine-reads.js";
|
|
6
|
+
import { readMainWindow } from "../live-main-read.js";
|
|
7
|
+
import { runLiveCommands } from "../store.js";
|
|
8
|
+
import { requestContext } from "../server/request-context.js";
|
|
9
|
+
import { ROUTES } from "../server/route-table.js";
|
|
10
|
+
import { deviceAccountStands, getPairedDevice } from "./store.js";
|
|
11
|
+
export class CompanionReadError extends Error {
|
|
12
|
+
code;
|
|
13
|
+
constructor(code, message) {
|
|
14
|
+
super(message);
|
|
15
|
+
this.code = code;
|
|
16
|
+
}
|
|
17
|
+
}
|
|
18
|
+
const TASK_ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$/;
|
|
19
|
+
const RUN_ID = /^[1-9][0-9]{0,14}$/;
|
|
20
|
+
const WORK_VIEWS = new Map([["all", "all"], ["needs-you", "needs-you"], ["running", "running"], ["queued", "queued"], ["ready", "ready"], ["completed", "completed"], ["done", "completed"]]);
|
|
21
|
+
const MAX_CURSOR = 4_096;
|
|
22
|
+
const WORK_ROUTE = ROUTES.find(route => route.id === "work.rows");
|
|
23
|
+
const stringParam = (params, key) => {
|
|
24
|
+
const value = params[key];
|
|
25
|
+
if (value === undefined || value === null)
|
|
26
|
+
return null;
|
|
27
|
+
if (typeof value !== "string")
|
|
28
|
+
throw new CompanionReadError("invalid_params", `${key} must be a string`);
|
|
29
|
+
return value;
|
|
30
|
+
};
|
|
31
|
+
export function createCompanionReads(deps) {
|
|
32
|
+
const { runtime } = deps;
|
|
33
|
+
const store = runtime.store;
|
|
34
|
+
const cursorKey = globalThis.crypto.getRandomValues(new Uint8Array(32));
|
|
35
|
+
const cursorKeyBuf = Buffer.from(cursorKey);
|
|
36
|
+
function stands(principal) {
|
|
37
|
+
const device = getPairedDevice(store.handle, principal.deviceId);
|
|
38
|
+
const identity = store.workspaceIdentity();
|
|
39
|
+
if (device === null || device.revokedAt !== null || device.activatedAt === null || device.recoveryGeneration !== identity.recoveryGeneration
|
|
40
|
+
|| device.accountName !== principal.accountName || identity.recoveryGeneration !== principal.recoveryGeneration)
|
|
41
|
+
return false;
|
|
42
|
+
return deviceAccountStands(device, store.accountOf(principal.accountName));
|
|
43
|
+
}
|
|
44
|
+
function accessSignature(principal) {
|
|
45
|
+
const account = store.accountOf(principal.accountName);
|
|
46
|
+
const ceiling = runtime.liveCeiling();
|
|
47
|
+
return JSON.stringify([stands(principal), account?.generation ?? null, account?.revokedAt ?? null, account?.projects ?? null,
|
|
48
|
+
[...ceiling.repos].sort(), [...ceiling.roots].sort()]);
|
|
49
|
+
}
|
|
50
|
+
async function asDevice(principal, work) {
|
|
51
|
+
if (!stands(principal))
|
|
52
|
+
throw new CompanionReadError("standing_revoked", "This iPhone is no longer paired.");
|
|
53
|
+
const result = await requestContext.run({ csrf: "", returnTo: "/", actor: principal.accountName }, work);
|
|
54
|
+
if (!stands(principal))
|
|
55
|
+
throw new CompanionReadError("standing_revoked", "This iPhone is no longer paired.");
|
|
56
|
+
return result;
|
|
57
|
+
}
|
|
58
|
+
function familyInView(params) {
|
|
59
|
+
const task = stringParam(params, "task");
|
|
60
|
+
if (task === null || !TASK_ID.test(task))
|
|
61
|
+
throw new CompanionReadError("invalid_params", "task is required");
|
|
62
|
+
const family = runtime.familyOf(task);
|
|
63
|
+
if (family === null || family.problem !== null || !runtime.visible(family.current.repo) || !runtime.visible(family.root.repo)) {
|
|
64
|
+
throw new CompanionReadError("not_found", "No such task.");
|
|
65
|
+
}
|
|
66
|
+
return family;
|
|
67
|
+
}
|
|
68
|
+
function passkeyHintsOf(family) {
|
|
69
|
+
const scope = store.getScope(family.current.id);
|
|
70
|
+
if (family.current.repo === null)
|
|
71
|
+
return { protectedWork: false, release: scope?.releaseTerms != null, protectedPaths: [] };
|
|
72
|
+
const rules = store.approvalRules(family.current.repo);
|
|
73
|
+
const touches = scope === null ? [] : [...scope.touches];
|
|
74
|
+
return {
|
|
75
|
+
protectedWork: isProtectedWork(rules, touches),
|
|
76
|
+
release: scope?.releaseTerms != null,
|
|
77
|
+
protectedPaths: rules.protectProject ? [] : protectedChanges(rules, touches).slice(0, 5),
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
function runInView(runParam) {
|
|
81
|
+
if (runParam === null || !RUN_ID.test(runParam))
|
|
82
|
+
throw new CompanionReadError("invalid_params", "run is required");
|
|
83
|
+
const run = store.getRun(Number(runParam));
|
|
84
|
+
const repo = run === null ? null : runtime.taskRepoOf(run.taskRef);
|
|
85
|
+
const actor = requestContext.getStore()?.actor;
|
|
86
|
+
if (run === null || repo === null || actor === undefined || !runtime.runVisible(run) || !runtime.visible(repo) || !store.accountCanAccess(actor, repo)) {
|
|
87
|
+
throw new CompanionReadError("not_found", "No such run.");
|
|
88
|
+
}
|
|
89
|
+
return run;
|
|
90
|
+
}
|
|
91
|
+
function liveWindowOf(runParam, cursor) {
|
|
92
|
+
const run = runInView(runParam);
|
|
93
|
+
const local = runtime.options.localRunner !== undefined && run.runner === runtime.options.localRunner;
|
|
94
|
+
const window = local ? readMainWindow(runtime.evidenceRoot, run.id, cursor, { key: cursorKeyBuf, commands: runLiveCommands(store, run.id) }) : null;
|
|
95
|
+
runInView(runParam);
|
|
96
|
+
return { run, window };
|
|
97
|
+
}
|
|
98
|
+
return {
|
|
99
|
+
accessSignature,
|
|
100
|
+
deviceHello: principal => asDevice(principal, () => ({
|
|
101
|
+
version: ENGINE_API_VERSION,
|
|
102
|
+
workspaceId: principal.workspaceId,
|
|
103
|
+
workspaceLabel: deps.workspaceLabel(),
|
|
104
|
+
account: principal.accountName,
|
|
105
|
+
deviceId: principal.deviceId,
|
|
106
|
+
toolroll: deps.toolrollVersion,
|
|
107
|
+
})),
|
|
108
|
+
workRows: (principal, params) => asDevice(principal, async () => {
|
|
109
|
+
if (WORK_ROUTE === undefined)
|
|
110
|
+
throw new CompanionReadError("unavailable", "Work isn't available.");
|
|
111
|
+
const view = WORK_VIEWS.get(stringParam(params, "view") ?? "all");
|
|
112
|
+
const cursor = stringParam(params, "cursor");
|
|
113
|
+
if (view === undefined)
|
|
114
|
+
throw new CompanionReadError("invalid_params", "Unknown view.");
|
|
115
|
+
if (cursor !== null && (cursor.length === 0 || cursor.length > MAX_CURSOR))
|
|
116
|
+
throw new CompanionReadError("invalid_cursor", "Open the first page.");
|
|
117
|
+
if (params["project"] !== undefined)
|
|
118
|
+
throw new CompanionReadError("invalid_params", "Project filters aren't available on the phone yet.");
|
|
119
|
+
const url = new URL("http://companion.invalid/work/rows");
|
|
120
|
+
if (view !== "all")
|
|
121
|
+
url.searchParams.set("view", view);
|
|
122
|
+
if (cursor !== null)
|
|
123
|
+
url.searchParams.set("cursor", cursor);
|
|
124
|
+
const account = store.accountOf(principal.accountName);
|
|
125
|
+
const request = new IncomingMessage(new Socket());
|
|
126
|
+
request.method = "GET";
|
|
127
|
+
request.url = url.pathname + url.search;
|
|
128
|
+
const response = new ServerResponse(request);
|
|
129
|
+
const ctx = {
|
|
130
|
+
url, request, response, route: WORK_ROUTE, now: runtime.clock(), project: null, chosenProject: null, posted: new URLSearchParams(),
|
|
131
|
+
who: { name: principal.accountName, via: "bearer", role: "viewer", generation: account.generation },
|
|
132
|
+
};
|
|
133
|
+
const rows = await deps.readWorkRows(ctx);
|
|
134
|
+
if (rows === null) {
|
|
135
|
+
if (cursor !== null)
|
|
136
|
+
throw new CompanionReadError("invalid_cursor", "This page has expired. Open the first page.");
|
|
137
|
+
throw new CompanionReadError("invalid_params", "Work refused that view.");
|
|
138
|
+
}
|
|
139
|
+
const nextCursor = rows.next === null ? null : new URL(rows.next, "http://companion.invalid").searchParams.get("cursor");
|
|
140
|
+
return { ...rows, next: nextCursor, spend: null, limits: null };
|
|
141
|
+
}),
|
|
142
|
+
taskSteps: (principal, params) => asDevice(principal, () => {
|
|
143
|
+
const family = familyInView(params);
|
|
144
|
+
const cards = stepCardsOf({ store, family, now: runtime.clock(), access: runtime.workAccess(), evidenceRoot: runtime.evidenceRoot, viewer: principal.accountName, withChoices: false });
|
|
145
|
+
const passkey = passkeyHintsOf(family);
|
|
146
|
+
familyInView(params);
|
|
147
|
+
return { ...checkEngineResponse("stepCards", cards), passkey };
|
|
148
|
+
}),
|
|
149
|
+
taskDiff: (principal, params) => asDevice(principal, () => {
|
|
150
|
+
const runParam = stringParam(params, "run");
|
|
151
|
+
const fileRaw = params["file"];
|
|
152
|
+
if (runParam !== null && !RUN_ID.test(runParam))
|
|
153
|
+
throw new CompanionReadError("invalid_params", "run must be a run id");
|
|
154
|
+
if (fileRaw !== undefined && (typeof fileRaw !== "number" || !Number.isInteger(fileRaw) || fileRaw < 0 || fileRaw > 999_999)) {
|
|
155
|
+
throw new CompanionReadError("invalid_params", "file must be a file index");
|
|
156
|
+
}
|
|
157
|
+
if (fileRaw !== undefined && runParam === null)
|
|
158
|
+
throw new CompanionReadError("invalid_params", "file needs run");
|
|
159
|
+
const family = familyInView(params);
|
|
160
|
+
const results = resultRunsOf(store, family).filter(run => runtime.runVisible(run));
|
|
161
|
+
const run = runParam === null ? results[0] ?? null : results.find(one => one.id === Number(runParam)) ?? null;
|
|
162
|
+
if (runParam !== null && run === null)
|
|
163
|
+
throw new CompanionReadError("not_found", "No such run.");
|
|
164
|
+
if (fileRaw === undefined) {
|
|
165
|
+
const list = resultDiffOf(store, runtime.evidenceRoot, family.root.id, run);
|
|
166
|
+
familyInView(params);
|
|
167
|
+
return checkEngineResponse("resultDiff", list);
|
|
168
|
+
}
|
|
169
|
+
const one = resultDiffFileOf(store, runtime.evidenceRoot, family.root.id, run, fileRaw);
|
|
170
|
+
familyInView(params);
|
|
171
|
+
if (one === null)
|
|
172
|
+
throw new CompanionReadError("not_found", "No such file.");
|
|
173
|
+
return checkEngineResponse("resultDiffFile", one);
|
|
174
|
+
}),
|
|
175
|
+
taskApprovalRead: (principal, params) => asDevice(principal, () => {
|
|
176
|
+
const family = familyInView(params);
|
|
177
|
+
return { version: ENGINE_API_VERSION, task: family.current.id, key: null, digest: null, nonce: null, terms: [], problem: "Approve on your Mac." };
|
|
178
|
+
}),
|
|
179
|
+
runWindowRead: (principal, params) => asDevice(principal, () => {
|
|
180
|
+
const cursor = stringParam(params, "cursor");
|
|
181
|
+
if (cursor !== null && cursor.length > MAX_CURSOR)
|
|
182
|
+
throw new CompanionReadError("invalid_cursor", "Start again.");
|
|
183
|
+
const { run, window } = liveWindowOf(stringParam(params, "run"), cursor);
|
|
184
|
+
return checkEngineResponse("liveSessionWindow", {
|
|
185
|
+
version: ENGINE_API_VERSION,
|
|
186
|
+
session: { kind: "run", id: run.id, task: null },
|
|
187
|
+
room: `run:${run.id}`,
|
|
188
|
+
live: run.finishedAt === null,
|
|
189
|
+
file: "main",
|
|
190
|
+
window: window === null ? { ok: false, reason: "off" } : window.ok
|
|
191
|
+
? { ok: true, records: window.records, cursor: window.cursor, restarted: window.restarted, earlier: window.earlier,
|
|
192
|
+
quarantined: window.quarantined, skipped: window.skipped, more: window.more }
|
|
193
|
+
: { ok: false, reason: window.reason },
|
|
194
|
+
});
|
|
195
|
+
}),
|
|
196
|
+
runWatchSubscribe: (principal, params, emit, end) => {
|
|
197
|
+
let cursor;
|
|
198
|
+
let runParam;
|
|
199
|
+
try {
|
|
200
|
+
runParam = stringParam(params, "run");
|
|
201
|
+
cursor = stringParam(params, "cursor");
|
|
202
|
+
if (!stands(principal))
|
|
203
|
+
return { ok: false, code: "standing_revoked", message: "This iPhone is no longer paired." };
|
|
204
|
+
requestContext.run({ csrf: "", returnTo: "/", actor: principal.accountName }, () => runInView(runParam));
|
|
205
|
+
}
|
|
206
|
+
catch (error) {
|
|
207
|
+
const code = error instanceof CompanionReadError ? error.code : "invalid_params";
|
|
208
|
+
return { ok: false, code, message: error instanceof Error ? error.message : "Can't watch that run." };
|
|
209
|
+
}
|
|
210
|
+
let closed = false, reading = false, again = false;
|
|
211
|
+
const tick = () => {
|
|
212
|
+
if (closed)
|
|
213
|
+
return;
|
|
214
|
+
if (reading) {
|
|
215
|
+
again = true;
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
reading = true;
|
|
219
|
+
try {
|
|
220
|
+
if (!stands(principal)) {
|
|
221
|
+
stop();
|
|
222
|
+
end?.("denied");
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
const read = requestContext.run({ csrf: "", returnTo: "/", actor: principal.accountName }, () => {
|
|
226
|
+
try {
|
|
227
|
+
return liveWindowOf(runParam, cursor);
|
|
228
|
+
}
|
|
229
|
+
catch {
|
|
230
|
+
return null;
|
|
231
|
+
}
|
|
232
|
+
});
|
|
233
|
+
if (read === null) {
|
|
234
|
+
stop();
|
|
235
|
+
end?.("denied");
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
const window = read.window;
|
|
239
|
+
if (window !== null && window.ok) {
|
|
240
|
+
cursor = window.cursor;
|
|
241
|
+
for (const record of window.records) {
|
|
242
|
+
if (closed)
|
|
243
|
+
return;
|
|
244
|
+
if (!stands(principal)) {
|
|
245
|
+
stop();
|
|
246
|
+
end?.("denied");
|
|
247
|
+
return;
|
|
248
|
+
}
|
|
249
|
+
emit(Buffer.from(JSON.stringify(record), "utf8"));
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
if (read.run.finishedAt !== null && (window === null || !window.ok || !window.more)) {
|
|
253
|
+
stop();
|
|
254
|
+
end?.();
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
finally {
|
|
258
|
+
reading = false;
|
|
259
|
+
if (again && !closed) {
|
|
260
|
+
again = false;
|
|
261
|
+
queueMicrotask(tick);
|
|
262
|
+
}
|
|
263
|
+
}
|
|
264
|
+
};
|
|
265
|
+
const timer = setInterval(tick, deps.watchPollMs ?? 2_000);
|
|
266
|
+
timer.unref?.();
|
|
267
|
+
const unsubscribeBus = deps.subscribeBus?.(() => tick()) ?? (() => { });
|
|
268
|
+
function stop() {
|
|
269
|
+
if (closed)
|
|
270
|
+
return;
|
|
271
|
+
closed = true;
|
|
272
|
+
clearInterval(timer);
|
|
273
|
+
unsubscribeBus();
|
|
274
|
+
}
|
|
275
|
+
queueMicrotask(tick);
|
|
276
|
+
return { ok: true, unsubscribe: stop };
|
|
277
|
+
},
|
|
278
|
+
};
|
|
279
|
+
}
|