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.
Files changed (129) hide show
  1. package/CHANGELOG.md +41 -0
  2. package/dist/accent-colors.js +3 -1
  3. package/dist/agent-fence.js +0 -2
  4. package/dist/agents-board.js +0 -3
  5. package/dist/approval-authority.js +2 -1
  6. package/dist/assignment.js +56 -2
  7. package/dist/backup-ui.js +6 -3
  8. package/dist/backup.js +6 -0
  9. package/dist/bounded-spawn.js +0 -1
  10. package/dist/browser/manifest.json +57 -0
  11. package/dist/browser/terminal.2a682d0b91a35288271c73b7ee253e524cca0917d17fbaf6733e80b7a767a37c.js.br +0 -0
  12. package/dist/browser/terminal.2a682d0b91a35288271c73b7ee253e524cca0917d17fbaf6733e80b7a767a37c.js.gz +0 -0
  13. package/dist/browser/{terminal.css → terminal.4d1cf20c32ad7c2099df657358d540d5fd92bb55195a88121e74b28467238b42.css} +1 -1
  14. package/dist/browser/terminal.4d1cf20c32ad7c2099df657358d540d5fd92bb55195a88121e74b28467238b42.css.br +0 -0
  15. package/dist/browser/terminal.4d1cf20c32ad7c2099df657358d540d5fd92bb55195a88121e74b28467238b42.css.gz +0 -0
  16. package/dist/browser/{workspace.js → workspace.9bd1db81d3c897045a5d82d4804e374e41e78b1b2cfd05d37b982a4ea0d02626.js} +25 -25
  17. package/dist/browser/workspace.9bd1db81d3c897045a5d82d4804e374e41e78b1b2cfd05d37b982a4ea0d02626.js.br +0 -0
  18. package/dist/browser/workspace.9bd1db81d3c897045a5d82d4804e374e41e78b1b2cfd05d37b982a4ea0d02626.js.gz +0 -0
  19. package/dist/browser/{workspace.css → workspace.a0752f935cfeaf16758d1085fe8f3e1719a7cd525b91a9c9943c789d65879a54.css} +1 -1
  20. package/dist/browser/workspace.a0752f935cfeaf16758d1085fe8f3e1719a7cd525b91a9c9943c789d65879a54.css.br +0 -0
  21. package/dist/browser/workspace.a0752f935cfeaf16758d1085fe8f3e1719a7cd525b91a9c9943c789d65879a54.css.gz +0 -0
  22. package/dist/browser-shell.js +271 -25
  23. package/dist/canvas-freshness.js +122 -0
  24. package/dist/canvas-fs.js +273 -0
  25. package/dist/canvas-reads.js +747 -0
  26. package/dist/canvas-state-key.js +45 -0
  27. package/dist/canvas-state-worker.js +12 -0
  28. package/dist/central-recovery-stage.js +3 -3
  29. package/dist/chat-actions.js +26 -0
  30. package/dist/chat-channel.js +4 -3
  31. package/dist/chat-task-actions.js +1 -1
  32. package/dist/chat-warmth.js +0 -1
  33. package/dist/check-report.js +0 -6
  34. package/dist/commit-extract.js +79 -40
  35. package/dist/companion/access.js +162 -0
  36. package/dist/companion/actions.js +622 -0
  37. package/dist/companion/bonjour.js +45 -0
  38. package/dist/companion/canvas.js +141 -0
  39. package/dist/companion/chat-origin.js +92 -0
  40. package/dist/companion/chat.js +571 -0
  41. package/dist/companion/daemon.js +1387 -0
  42. package/dist/companion/direct-server.js +177 -0
  43. package/dist/companion/finish.js +51 -0
  44. package/dist/companion/framing.js +498 -0
  45. package/dist/companion/noise.js +461 -0
  46. package/dist/companion/passkey-gate.js +287 -0
  47. package/dist/companion/paths.js +90 -0
  48. package/dist/companion/reads.js +283 -0
  49. package/dist/companion/relay-auth.js +265 -0
  50. package/dist/companion/relay-server.js +870 -0
  51. package/dist/companion/schema.js +289 -0
  52. package/dist/companion/service.js +581 -0
  53. package/dist/companion/store.js +325 -0
  54. package/dist/companion/webauthn.js +407 -0
  55. package/dist/console-instance.js +0 -4
  56. package/dist/contracts/console-api.js +18 -0
  57. package/dist/converse.js +0 -1
  58. package/dist/coordinator.js +1 -1
  59. package/dist/design/kit.css +30 -0
  60. package/dist/desktop-config.js +156 -0
  61. package/dist/desktop-host.js +6 -152
  62. package/dist/desktop-update.js +1 -1
  63. package/dist/finished-task-sql.js +14 -0
  64. package/dist/flexible-answers.js +0 -1
  65. package/dist/github-read.js +41 -0
  66. package/dist/guides.js +4 -3
  67. package/dist/lead-doors.js +50 -3
  68. package/dist/lead-queue-runtime.js +11 -2
  69. package/dist/lead-queue.js +25 -0
  70. package/dist/live-backup-change.js +93 -0
  71. package/dist/live-backup.js +75 -31
  72. package/dist/live-bus.js +3 -2
  73. package/dist/live-records.js +0 -1
  74. package/dist/local-landing.js +47 -0
  75. package/dist/local-owner.js +0 -1
  76. package/dist/model-choices.js +0 -11
  77. package/dist/nightly-check.js +0 -3
  78. package/dist/nightly-github.js +1 -2
  79. package/dist/notification-retention.js +119 -0
  80. package/dist/observations.js +0 -1
  81. package/dist/operate.js +17 -4
  82. package/dist/person-proof.js +5 -1
  83. package/dist/pull-request-flow.js +116 -2
  84. package/dist/qr.js +360 -0
  85. package/dist/release-adapters.js +14 -43
  86. package/dist/release-auto.js +17 -13
  87. package/dist/release-card.js +0 -4
  88. package/dist/release-cli.js +37 -2
  89. package/dist/release.js +13 -2
  90. package/dist/restore-retirement.js +6 -1
  91. package/dist/result-review.js +0 -3
  92. package/dist/retention-ui.js +1 -1
  93. package/dist/retention.js +14 -21
  94. package/dist/review-context.js +0 -5
  95. package/dist/route-rules.js +1 -5
  96. package/dist/sandbox-runtime.js +0 -1
  97. package/dist/scope.js +68 -17
  98. package/dist/scout.js +0 -6
  99. package/dist/serve.js +60 -9
  100. package/dist/server/kit.js +1 -0
  101. package/dist/server/live.js +9 -2
  102. package/dist/server/pages.js +12 -4
  103. package/dist/server/phone-engine-api.js +79 -0
  104. package/dist/server/render-pages.js +1 -11
  105. package/dist/server/render-results.js +0 -1
  106. package/dist/server/render-tasks.js +0 -68
  107. package/dist/server/route-table.js +12 -1
  108. package/dist/server/settings-phone.js +515 -0
  109. package/dist/server/settings-scripts.js +2 -0
  110. package/dist/server/settings-section-table.js +0 -3
  111. package/dist/server/settings-sections.js +10 -4
  112. package/dist/server/settings.js +20 -5
  113. package/dist/server/terminals.js +2 -1
  114. package/dist/settings-groups-ui.js +2 -1
  115. package/dist/settings-proofs.js +6 -0
  116. package/dist/store.js +52 -4
  117. package/dist/structured-output.js +0 -1
  118. package/dist/style-asset.js +20 -7
  119. package/dist/tailnet.js +39 -0
  120. package/dist/task-control.js +5 -0
  121. package/dist/task-sizing.js +0 -1
  122. package/dist/toolroll-update-cli.js +19 -3
  123. package/dist/toolroll-update-ui.js +2 -2
  124. package/dist/toolroll-update.js +98 -16
  125. package/dist/youiyoux-intake.js +8 -0
  126. package/package.json +7 -2
  127. package/dist/contracts/contract-test.js +0 -55
  128. package/dist/unfenced-test-support.js +0 -6
  129. /package/dist/browser/{terminal.js → terminal.2a682d0b91a35288271c73b7ee253e524cca0917d17fbaf6733e80b7a767a37c.js} +0 -0
@@ -0,0 +1,407 @@
1
+ import { createHash, createPublicKey, randomBytes, timingSafeEqual, verify as cryptoVerify } from "node:crypto";
2
+ export const PASSKEY_RP_ID = "toolroll.dev";
3
+ export const PASSKEY_RP_NAME = "Toolroll";
4
+ export const PASSKEY_ORIGIN = "https://toolroll.dev";
5
+ export const PASSKEY_CHALLENGE_TTL_MS = 120_000;
6
+ const P256_SPKI_PREFIX = Buffer.from("3059301306072a8648ce3d020106082a8648ce3d030107034200", "hex");
7
+ const P256_P = BigInt("0xffffffff00000001000000000000000000000000ffffffffffffffffffffffff");
8
+ const P256_B = BigInt("0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b");
9
+ export function sha256(data) {
10
+ return createHash("sha256").update(data).digest();
11
+ }
12
+ export function randomChallenge32() {
13
+ return randomBytes(32).toString("base64url");
14
+ }
15
+ export function canonicalJson(value) {
16
+ if (value === null || typeof value !== "object")
17
+ return JSON.stringify(value);
18
+ if (Array.isArray(value))
19
+ return `[${value.map(canonicalJson).join(",")}]`;
20
+ const obj = value;
21
+ const keys = Object.keys(obj).filter(k => obj[k] !== undefined).sort();
22
+ return `{${keys.map(k => `${JSON.stringify(k)}:${canonicalJson(obj[k])}`).join(",")}}`;
23
+ }
24
+ export function derivePasskeyUserHandle(workspaceId, accountName) {
25
+ return sha256(Buffer.concat([
26
+ Buffer.from("toolroll-passkey-user-v1\0", "utf8"),
27
+ Buffer.from(workspaceId, "utf8"),
28
+ Buffer.from("\0", "utf8"),
29
+ Buffer.from(accountName, "utf8"),
30
+ ]));
31
+ }
32
+ export function normalizeAcceptNote(note) {
33
+ return typeof note === "string" && note.trim().length > 0 ? note.trim() : null;
34
+ }
35
+ export function publishDestinationOf(grant) {
36
+ return grant === null ? null : { githubRepo: grant.githubRepo, remote: grant.remote, base: grant.base, headPrefix: grant.headPrefix, draft: grant.draft };
37
+ }
38
+ export function publishDestinationForRun(store, runId) {
39
+ const run = store.getRun(runId);
40
+ const repo = run === null ? null : store.refById(run.taskRef)?.repo ?? null;
41
+ return publishDestinationOf(repo === null ? null : store.publicationGrantFor(repo));
42
+ }
43
+ export function acceptBindingOf(input, receiptRunId) {
44
+ return {
45
+ verb: "accept",
46
+ taskId: input.taskId,
47
+ runId: input.runId ?? receiptRunId,
48
+ receiptDigest: input.receiptDigest,
49
+ noteHash: sha256(normalizeAcceptNote(input.note) ?? "").toString("hex"),
50
+ publish: input.publish,
51
+ ...(input.publish ? { destination: input.destination ?? null } : {}),
52
+ };
53
+ }
54
+ export function buildActionChallenge(input) {
55
+ const nonce = input.nonce ?? randomChallenge32();
56
+ const payload = {
57
+ v: 1,
58
+ verb: input.binding.verb,
59
+ workspaceId: input.workspaceId,
60
+ recoveryGeneration: input.recoveryGeneration,
61
+ accountName: input.accountName,
62
+ deviceId: input.deviceId,
63
+ binding: input.binding,
64
+ nonce,
65
+ };
66
+ const canonicalPayload = canonicalJson(payload);
67
+ const challenge = sha256(canonicalPayload).toString("base64url");
68
+ const bindingJson = canonicalJson(input.binding);
69
+ const wording = wordingForBinding(input.binding);
70
+ return { challenge, canonicalPayload, bindingJson, wording };
71
+ }
72
+ function wordingForBinding(binding) {
73
+ switch (binding.verb) {
74
+ case "approve":
75
+ return `Approve task ${binding.taskId} plan (${binding.sawDigest.slice(0, 12)})`;
76
+ case "accept":
77
+ return `Accept task ${binding.taskId} result (${binding.receiptDigest.slice(0, 12)})${binding.publish ? ` and open pull request${binding.destination == null ? "" : ` on ${binding.destination.githubRepo} into ${binding.destination.base}`}` : ""}`;
78
+ case "land":
79
+ return `${binding.undo ? "Undo landing" : "Land"} task ${binding.taskId} (${binding.planKey})`;
80
+ case "ship":
81
+ return `Merge PR #${binding.prNumber} into ${binding.base} for task ${binding.taskId} at ${binding.headSha.slice(0, 10)} (${binding.method})`;
82
+ case "unlock":
83
+ return `Unlock approvals for ${minutesWords(binding.minutes)}`;
84
+ }
85
+ }
86
+ export function minutesWords(minutes) {
87
+ return minutes === 60 ? "1 hour" : minutes === 1 ? "1 minute" : `${minutes} minutes`;
88
+ }
89
+ export function passkeyProofDetail(input) {
90
+ return JSON.stringify({
91
+ v: 1,
92
+ at: input.at.toISOString(),
93
+ ...(input.provedAtMs === undefined ? {} : { provedAt: new Date(input.provedAtMs).toISOString() }),
94
+ generation: input.generation,
95
+ digest: input.digest,
96
+ verb: input.verb,
97
+ cred: sha256(input.credentialId).toString("hex").slice(0, 16),
98
+ dev: input.pairedDeviceId.slice(0, 40),
99
+ be: input.be,
100
+ bs: input.bs,
101
+ });
102
+ }
103
+ function constantTimeStringEqual(a, b) {
104
+ const ba = Buffer.from(a, "utf8");
105
+ const bb = Buffer.from(b, "utf8");
106
+ if (ba.length !== bb.length)
107
+ return false;
108
+ return timingSafeEqual(ba, bb);
109
+ }
110
+ function decodeBase64UrlStrict(raw) {
111
+ if (typeof raw !== "string" || raw.length === 0 || !/^[A-Za-z0-9_-]+$/.test(raw))
112
+ return null;
113
+ return Buffer.from(raw, "base64url");
114
+ }
115
+ function bytesToBigInt(buf) {
116
+ let out = 0n;
117
+ for (const byte of buf)
118
+ out = (out << 8n) | BigInt(byte);
119
+ return out;
120
+ }
121
+ function isOnP256Curve(xBuf, yBuf) {
122
+ if (xBuf.length !== 32 || yBuf.length !== 32)
123
+ return false;
124
+ const x = bytesToBigInt(xBuf);
125
+ const y = bytesToBigInt(yBuf);
126
+ if (x <= 0n || x >= P256_P || y <= 0n || y >= P256_P)
127
+ return false;
128
+ const lhs = (y * y) % P256_P;
129
+ const rhs = (((x * x) % P256_P) * x - 3n * x + P256_B) % P256_P;
130
+ const normalizedRhs = rhs < 0n ? rhs + P256_P : rhs;
131
+ return lhs === normalizedRhs;
132
+ }
133
+ export function p256CoordsToSpkiDer(x, y) {
134
+ if (!isOnP256Curve(x, y))
135
+ return null;
136
+ const spki = Buffer.concat([P256_SPKI_PREFIX, Buffer.from([0x04]), x, y]);
137
+ try {
138
+ const key = createPublicKey({ key: spki, format: "der", type: "spki" });
139
+ if (key.asymmetricKeyType !== "ec")
140
+ return null;
141
+ return spki;
142
+ }
143
+ catch {
144
+ return null;
145
+ }
146
+ }
147
+ function decodeCborItem(buf, offset, depth) {
148
+ if (depth > 8 || offset >= buf.length)
149
+ throw new Error("cbor_bounds");
150
+ const initial = buf[offset++];
151
+ const major = initial >> 5;
152
+ const ai = initial & 0x1f;
153
+ let arg = 0;
154
+ if (ai < 24) {
155
+ arg = ai;
156
+ }
157
+ else if (ai === 24) {
158
+ if (offset + 1 > buf.length)
159
+ throw new Error("cbor_eof");
160
+ arg = buf[offset++];
161
+ }
162
+ else if (ai === 25) {
163
+ if (offset + 2 > buf.length)
164
+ throw new Error("cbor_eof");
165
+ arg = buf.readUInt16BE(offset);
166
+ offset += 2;
167
+ }
168
+ else if (ai === 26) {
169
+ if (offset + 4 > buf.length)
170
+ throw new Error("cbor_eof");
171
+ arg = buf.readUInt32BE(offset);
172
+ offset += 4;
173
+ }
174
+ else {
175
+ throw new Error("cbor_unsupported");
176
+ }
177
+ switch (major) {
178
+ case 0:
179
+ return { value: arg, next: offset };
180
+ case 1:
181
+ return { value: -1 - arg, next: offset };
182
+ case 2: {
183
+ if (offset + arg > buf.length)
184
+ throw new Error("cbor_eof");
185
+ return { value: Buffer.from(buf.subarray(offset, offset + arg)), next: offset + arg };
186
+ }
187
+ case 3: {
188
+ if (offset + arg > buf.length)
189
+ throw new Error("cbor_eof");
190
+ return { value: buf.subarray(offset, offset + arg).toString("utf8"), next: offset + arg };
191
+ }
192
+ case 4: {
193
+ if (arg > 256)
194
+ throw new Error("cbor_limit");
195
+ const arr = [];
196
+ for (let i = 0; i < arg; i++) {
197
+ const item = decodeCborItem(buf, offset, depth + 1);
198
+ arr.push(item.value);
199
+ offset = item.next;
200
+ }
201
+ return { value: arr, next: offset };
202
+ }
203
+ case 5: {
204
+ if (arg > 256)
205
+ throw new Error("cbor_limit");
206
+ const map = new Map();
207
+ for (let i = 0; i < arg; i++) {
208
+ const k = decodeCborItem(buf, offset, depth + 1);
209
+ if (typeof k.value !== "number" && typeof k.value !== "string")
210
+ throw new Error("cbor_key_type");
211
+ const v = decodeCborItem(buf, k.next, depth + 1);
212
+ map.set(k.value, v.value);
213
+ offset = v.next;
214
+ }
215
+ return { value: map, next: offset };
216
+ }
217
+ case 7:
218
+ if (ai === 20)
219
+ return { value: false, next: offset };
220
+ if (ai === 21)
221
+ return { value: true, next: offset };
222
+ if (ai === 22)
223
+ return { value: null, next: offset };
224
+ throw new Error("cbor_simple");
225
+ default:
226
+ throw new Error("cbor_major");
227
+ }
228
+ }
229
+ function parseClientData(rawB64) {
230
+ const raw = decodeBase64UrlStrict(rawB64);
231
+ if (raw === null || raw.length > 8_192)
232
+ return { ok: false, code: "invalid_client_data", message: "Invalid WebAuthn clientDataJSON." };
233
+ let parsed;
234
+ try {
235
+ parsed = JSON.parse(raw.toString("utf8"));
236
+ }
237
+ catch {
238
+ return { ok: false, code: "invalid_client_data", message: "WebAuthn clientDataJSON is not valid JSON." };
239
+ }
240
+ if (parsed === null || typeof parsed !== "object" || typeof parsed["type"] !== "string" || typeof parsed["challenge"] !== "string" || typeof parsed["origin"] !== "string") {
241
+ return { ok: false, code: "invalid_client_data", message: "WebAuthn clientDataJSON is missing required fields." };
242
+ }
243
+ return { ok: true, raw, type: parsed["type"], challenge: parsed["challenge"], origin: parsed["origin"] };
244
+ }
245
+ export function verifyRegistrationResponse(input) {
246
+ const rpId = input.rpId ?? PASSKEY_RP_ID;
247
+ const expectedOrigin = input.expectedOrigin ?? PASSKEY_ORIGIN;
248
+ const client = parseClientData(input.payload.clientDataJSON);
249
+ if (!client.ok)
250
+ return client;
251
+ if (client.type !== "webauthn.create") {
252
+ return { ok: false, code: "invalid_type", message: "Expected webauthn.create clientData type." };
253
+ }
254
+ if (!constantTimeStringEqual(client.challenge, input.expectedChallenge)) {
255
+ return { ok: false, code: "challenge_mismatch", message: "Registration challenge does not match." };
256
+ }
257
+ if (client.origin !== expectedOrigin) {
258
+ return { ok: false, code: "origin_mismatch", message: `Passkey origin must be ${expectedOrigin}.` };
259
+ }
260
+ const attRaw = decodeBase64UrlStrict(input.payload.attestationObject);
261
+ if (attRaw === null || attRaw.length > 16_384) {
262
+ return { ok: false, code: "invalid_attestation", message: "Invalid WebAuthn attestationObject." };
263
+ }
264
+ let attObj;
265
+ try {
266
+ const decoded = decodeCborItem(attRaw, 0, 0);
267
+ if (decoded.next !== attRaw.length)
268
+ return { ok: false, code: "invalid_attestation", message: "Trailing bytes in attestationObject." };
269
+ attObj = decoded.value;
270
+ }
271
+ catch {
272
+ return { ok: false, code: "invalid_attestation", message: "Could not decode WebAuthn attestationObject CBOR." };
273
+ }
274
+ if (!(attObj instanceof Map))
275
+ return { ok: false, code: "invalid_attestation", message: "attestationObject must be a CBOR map." };
276
+ const authData = attObj.get("authData");
277
+ if (!Buffer.isBuffer(authData) || authData.length < 55) {
278
+ return { ok: false, code: "invalid_auth_data", message: "Authenticator data is missing or truncated." };
279
+ }
280
+ const expectedRpHash = sha256(rpId);
281
+ if (!timingSafeEqual(authData.subarray(0, 32), expectedRpHash)) {
282
+ return { ok: false, code: "rp_id_mismatch", message: "Passkey rpIdHash does not match toolroll.dev." };
283
+ }
284
+ const flags = authData[32];
285
+ const up = (flags & 0x01) !== 0;
286
+ const uv = (flags & 0x04) !== 0;
287
+ const be = (flags & 0x08) !== 0;
288
+ const bs = (flags & 0x10) !== 0;
289
+ const at = (flags & 0x40) !== 0;
290
+ const ed = (flags & 0x80) !== 0;
291
+ if (!up)
292
+ return { ok: false, code: "user_presence_required", message: "Passkey registration requires user presence (UP=1)." };
293
+ if (!uv)
294
+ return { ok: false, code: "user_verification_required", message: "Passkey registration requires user verification (UV=1)." };
295
+ if (!at)
296
+ return { ok: false, code: "attested_credential_missing", message: "Passkey registration requires attested credential data (AT=1)." };
297
+ const signCount = authData.readUInt32BE(33);
298
+ const credIdLen = authData.readUInt16BE(53);
299
+ if (credIdLen === 0 || credIdLen > 1023 || 55 + credIdLen >= authData.length) {
300
+ return { ok: false, code: "invalid_credential_id", message: "Invalid passkey credentialId length." };
301
+ }
302
+ const credentialIdBuf = authData.subarray(55, 55 + credIdLen);
303
+ const credentialId = credentialIdBuf.toString("base64url");
304
+ if (input.payload.credentialId !== undefined && !constantTimeStringEqual(input.payload.credentialId, credentialId)) {
305
+ return { ok: false, code: "credential_id_mismatch", message: "Credential ID does not match attested authData." };
306
+ }
307
+ let coseKey;
308
+ let coseEnd;
309
+ try {
310
+ const decoded = decodeCborItem(authData, 55 + credIdLen, 0);
311
+ coseKey = decoded.value;
312
+ coseEnd = decoded.next;
313
+ }
314
+ catch {
315
+ return { ok: false, code: "invalid_cose_key", message: "Could not decode COSE public key." };
316
+ }
317
+ if (!ed && coseEnd !== authData.length) {
318
+ return { ok: false, code: "invalid_auth_data", message: "Unexpected trailing bytes in authData." };
319
+ }
320
+ if (!(coseKey instanceof Map)) {
321
+ return { ok: false, code: "invalid_cose_key", message: "COSE public key must be a CBOR map." };
322
+ }
323
+ const kty = coseKey.get(1);
324
+ const alg = coseKey.get(3);
325
+ const crv = coseKey.get(-1);
326
+ const x = coseKey.get(-2);
327
+ const y = coseKey.get(-3);
328
+ if (kty !== 2 || alg !== -7 || crv !== 1 || !Buffer.isBuffer(x) || !Buffer.isBuffer(y)) {
329
+ return { ok: false, code: "unsupported_algorithm", message: "Only ES256 (P-256) passkeys are supported." };
330
+ }
331
+ const spki = p256CoordsToSpkiDer(x, y);
332
+ if (spki === null) {
333
+ return { ok: false, code: "invalid_public_key", message: "Passkey public key is not a valid point on P-256." };
334
+ }
335
+ return {
336
+ ok: true,
337
+ credentialId,
338
+ publicKeySpki: spki.toString("base64url"),
339
+ signCount,
340
+ be,
341
+ bs,
342
+ };
343
+ }
344
+ export function verifyAssertionResponse(input) {
345
+ const rpId = input.rpId ?? PASSKEY_RP_ID;
346
+ const expectedOrigin = input.expectedOrigin ?? PASSKEY_ORIGIN;
347
+ const client = parseClientData(input.payload.clientDataJSON);
348
+ if (!client.ok)
349
+ return client;
350
+ if (client.type !== "webauthn.get") {
351
+ return { ok: false, code: "invalid_type", message: "Expected webauthn.get clientData type." };
352
+ }
353
+ if (!constantTimeStringEqual(client.challenge, input.expectedChallenge)) {
354
+ return { ok: false, code: "challenge_mismatch", message: "Assertion challenge does not match." };
355
+ }
356
+ if (client.origin !== expectedOrigin) {
357
+ return { ok: false, code: "origin_mismatch", message: `Passkey origin must be ${expectedOrigin}.` };
358
+ }
359
+ const authData = decodeBase64UrlStrict(input.payload.authenticatorData);
360
+ const signature = decodeBase64UrlStrict(input.payload.signature);
361
+ const userHandle = decodeBase64UrlStrict(input.payload.userHandle);
362
+ if (authData === null || authData.length < 37 || authData.length > 8_192) {
363
+ return { ok: false, code: "invalid_auth_data", message: "Invalid authenticatorData." };
364
+ }
365
+ if (signature === null || signature.length === 0 || signature.length > 256) {
366
+ return { ok: false, code: "invalid_signature", message: "Invalid WebAuthn signature." };
367
+ }
368
+ if (userHandle === null || userHandle.length !== input.expectedUserHandle.length || !timingSafeEqual(userHandle, input.expectedUserHandle)) {
369
+ return { ok: false, code: "user_handle_mismatch", message: "Passkey userHandle does not match this Workspace account." };
370
+ }
371
+ const expectedRpHash = sha256(rpId);
372
+ if (!timingSafeEqual(authData.subarray(0, 32), expectedRpHash)) {
373
+ return { ok: false, code: "rp_id_mismatch", message: "Passkey rpIdHash does not match toolroll.dev." };
374
+ }
375
+ const flags = authData[32];
376
+ const up = (flags & 0x01) !== 0;
377
+ const uv = (flags & 0x04) !== 0;
378
+ const be = (flags & 0x08) !== 0;
379
+ const bs = (flags & 0x10) !== 0;
380
+ if (!up)
381
+ return { ok: false, code: "user_presence_required", message: "Passkey approval requires user presence (UP=1)." };
382
+ if (!uv)
383
+ return { ok: false, code: "user_verification_required", message: "Passkey approval requires user verification (UV=1)." };
384
+ const newSignCount = authData.readUInt32BE(33);
385
+ if (!(input.storedSignCount === 0 && newSignCount === 0) && newSignCount <= input.storedSignCount) {
386
+ return { ok: false, code: "sign_count_regression", message: "Passkey signCount did not advance." };
387
+ }
388
+ let publicKey;
389
+ try {
390
+ publicKey = createPublicKey({ key: Buffer.from(input.storedPublicKeySpki, "base64url"), format: "der", type: "spki" });
391
+ }
392
+ catch {
393
+ return { ok: false, code: "invalid_public_key", message: "Stored passkey public key is unreadable." };
394
+ }
395
+ const signedData = Buffer.concat([authData, sha256(client.raw)]);
396
+ const validSig = cryptoVerify("sha256", signedData, publicKey, signature);
397
+ if (!validSig) {
398
+ return { ok: false, code: "signature_invalid", message: "Passkey signature verification failed." };
399
+ }
400
+ return {
401
+ ok: true,
402
+ credentialId: input.payload.credentialId,
403
+ newSignCount,
404
+ be,
405
+ bs,
406
+ };
407
+ }
@@ -45,10 +45,6 @@ export function readInstance(store) {
45
45
  const read = readInstanceState(store);
46
46
  return read.state === "ok" ? read.record : null;
47
47
  }
48
- export function instanceKeyEpoch(store) {
49
- const row = store.handle.prepare("SELECT key_epoch FROM console_instance WHERE id = 1").get();
50
- return row === undefined || row["key_epoch"] == null ? null : String(row["key_epoch"]);
51
- }
52
48
  export function clearInstance(store, secret) {
53
49
  store.handle.prepare("DELETE FROM console_instance WHERE id = 1 AND secret = ?").run(secret);
54
50
  }
@@ -117,6 +117,14 @@ export const CONSOLE_FORMS = {
117
117
  slack: formContract("POST /settings/slack/connect|pair|unpair|disconnect|alerts", ["password", "app-token", "bot-token"]),
118
118
  chatApproval: formContract("POST /settings/chat-approval/confirm, /settings/chat-approval/save, /settings/chat-approval/off", ["scope", "full-access", "cap-usd", "nonce", "digest", "token"]),
119
119
  telegramPair: formContract("POST /settings/telegram/pair, /settings/telegram/unpair", ["password"]),
120
+ phoneAccess: formContract("POST /settings/phone/access", ["password", "act", "hosted"]),
121
+ phonePair: formContract("POST /settings/phone/pair", ["password"]),
122
+ phonePairing: formContract("POST /settings/phone/confirm, /settings/phone/cancel", ["pairing", "setup"]),
123
+ phoneRemove: formContract("POST /settings/phone/remove", ["password", "device"]),
124
+ phonePasskeyEnable: formContract("POST /settings/phone/passkey/enable", ["password"]),
125
+ phonePasskeyRevoke: formContract("POST /settings/phone/passkey/revoke", ["password", "credential"]),
126
+ phonePasskeyWindow: formContract("POST /settings/phone/passkey/window", ["password", "window"]),
127
+ phoneRename: formContract("POST /settings/phone/rename", ["device", "name"]),
120
128
  teams: formContract("POST /settings/teams/connect|pair|unpair|disconnect|alerts", ["password", "app-id", "tenant", "secret"]),
121
129
  discord: formContract("POST /settings/discord/connect|pair|unpair|disconnect|alerts", ["password", "bot-token"]),
122
130
  messaging: formContract("POST /settings/messaging", ["primary"]),
@@ -293,10 +301,20 @@ export const flowViewSchema = z.looseObject({
293
301
  kinds: z.array(z.looseObject({ kind: z.string(), label: z.string() })),
294
302
  colors: z.array(z.string()),
295
303
  });
304
+ export const phonePairingViewSchema = z.looseObject({
305
+ pairSessionId: z.string(),
306
+ status: z.enum(["awaiting_scan", "awaiting_ready", "awaiting_confirm", "confirming", "finishing", "paired", "cancelled", "expired", "contested", "failed"]),
307
+ expiresAtMs: z.number(),
308
+ confirmCode: z.string().nullable(),
309
+ deviceName: z.string().nullable(),
310
+ deviceId: z.string().nullable(),
311
+ error: z.string().nullable(),
312
+ });
296
313
  export const CONSOLE_RESPONSES = {
297
314
  ledgerPage: { route: "GET /ledger?format=json", schema: ledgerPageSchema },
298
315
  evidencePack: { route: "GET /t/<task>/evidence?format=json", schema: evidencePackSchema },
299
316
  flowView: { route: "GET /flows/<id>?format=json", schema: flowViewSchema },
317
+ phonePairingView: { route: "GET /settings/phone/pairings/<id>", schema: phonePairingViewSchema },
300
318
  };
301
319
  export function checkResponse(name, payload, report = toStderr) {
302
320
  const { route, schema } = CONSOLE_RESPONSES[name];
package/dist/converse.js CHANGED
@@ -11,7 +11,6 @@ export const MAX_PROPOSALS = 3;
11
11
  export const MAX_DEPTH = 6;
12
12
  export const MAX_OUTPUT_TOKENS = 2_048;
13
13
  export const TURN_WALL_CLOCK_MS = 120_000;
14
- export const PRICE_VERSION = 1;
15
14
  const PRICES = {
16
15
  "claude-sonnet-5": { inMicrousd: 3, outMicrousd: 15 },
17
16
  "claude-opus-5": { inMicrousd: 15, outMicrousd: 75 },
@@ -3,7 +3,7 @@ import { hashSecret, mintCredential } from "./api-tokens.js";
3
3
  import { canonicalRepos } from "./runner.js";
4
4
  import { fileTaskProposal } from "./proposal.js";
5
5
  import { describeScope, summaryContextOf } from "./approval-summary.js";
6
- import { reportSummaryFor } from "./lead-tools.js";
6
+ import { reportSummaryFor } from "./report-summary.js";
7
7
  import { claimedNowSql, markedRunningSql } from "./task-moves.js";
8
8
  import { taskWorkSummaryOf } from "./work-summary.js";
9
9
  import { assignmentOf, assignmentBrief } from "./assignment.js";
@@ -821,3 +821,33 @@ html.k-js .k-sform[data-k-gate]:not([data-dirty]) .k-ssave:has(.k-ssave-said:emp
821
821
  .k-srec-a .k-ssave { min-height: 0; padding: 0; background: none; }
822
822
  .k-srec-a .k-ssave-said:empty { display: none; }
823
823
  pre.k-scode { white-space: pre-wrap; }
824
+ /* Settings → Phone (settings-phone.ts): addresses, the pairing panel, the code to compare, phones. */
825
+ .k-phone-addrs { display: grid; gap: 4px; margin: 8px 0 4px; padding: 0; list-style: none; }
826
+ .k-phone-addrs li { display: flex; flex-wrap: wrap; gap: 4px 10px; align-items: baseline; }
827
+ .k-phone-addr-k { min-width: 120px; font-size: 12.5px; color: var(--so-muted); }
828
+ .k-phone-addrs .k-mono { font-size: 12.5px; color: var(--so-ink); }
829
+ .k-phone-line { display: block; margin-top: 6px; }
830
+ .k-phone-hosted { display: flex; gap: 8px; align-items: flex-start; margin: 0 0 12px; font-size: 12.5px; line-height: 1.45; color: var(--so-muted); }
831
+ .k-phone-hosted input { margin-top: 2px; flex: none; }
832
+ .k-phone-pairing { display: grid; gap: 0; }
833
+ .k-phone-pairing [hidden] { display: none !important; }
834
+ .k-phone-steps { margin: 0 0 12px; padding-left: 1.2em; font-size: 12.5px; line-height: 1.55; color: var(--so-muted); }
835
+ .k-phone-steps strong { color: var(--so-ink); font-weight: 600; }
836
+ .k-phone-qr { margin: 0 0 12px; max-width: 280px; }
837
+ .k-phone-qr svg { display: block; width: 100%; height: auto; background: #fff; border-radius: 8px; }
838
+ .k-phone-paste { margin: 0 0 8px; }
839
+ .k-phone-paste summary { cursor: pointer; }
840
+ .k-phone-paste textarea { box-sizing: border-box; width: 100%; margin-top: 8px; padding: 8px 10px; border: 1px solid var(--so-field-line); border-radius: 7px; background: var(--so-raised); color: var(--so-ink); font: 12px/1.45 var(--so-font-mono); resize: vertical; }
841
+ .k-phone-code { margin: 8px 0 12px; font: 600 32px/1.2 var(--so-font-mono); letter-spacing: .08em; color: var(--so-ink); font-variant-numeric: tabular-nums; }
842
+ .k-phone-wait { margin: 0 0 6px; font-size: 13.5px; color: var(--so-ink); }
843
+ .k-phone-pairing .k-acts { margin-top: 12px; }
844
+ .k-phone-pairing .k-acts form { display: inline; }
845
+ .k-phone-sub { margin: 18px 0 0; font-size: 12px; font-weight: 500; color: var(--so-muted); }
846
+ details.k-phone-rename { margin: 2px 0 6px; padding: 0; border: 0; border-radius: 0; background: none; }
847
+ details.k-phone-rename > summary { display: inline-block; min-height: 0; padding: 2px 0; font-size: 12.5px; font-weight: 400; cursor: pointer; }
848
+ .k-phone-rename form { display: flex; flex-wrap: wrap; gap: 8px; align-items: center; margin-top: 8px; }
849
+ .k-phone-rename-f { flex: 1 1 200px; max-width: 320px; }
850
+ @media (max-width: 760px) {
851
+ .k-phone-code { font-size: 28px; }
852
+ .k-phone-rename .k-input { height: 44px; font-size: 16px; }
853
+ }
@@ -0,0 +1,156 @@
1
+ import { createHmac, randomBytes } from "node:crypto";
2
+ import { existsSync, readFileSync, realpathSync, writeFileSync } from "node:fs";
3
+ import { dirname, join, resolve } from "node:path";
4
+ import { homedir } from "node:os";
5
+ import { createRequire } from "node:module";
6
+ import { openStoreNoMigrate, readSchemaVersion, SCHEMA_VERSION } from "./store.js";
7
+ import { daemonStatus, installLaunchdService, planDesktopService, stopLaunchdService } from "./daemon.js";
8
+ import { run as execRun } from "./exec.js";
9
+ import { containmentStatus, effectiveContainment, parseContainmentPolicy, probeContainmentCapability } from "./containment.js";
10
+ import { validRunnerName } from "./runner.js";
11
+ import { updateAdmissionPaused, updateGateOwned, UPDATE_PAUSED } from "./desktop-update-gate.js";
12
+ import { envTwins, envValue } from "./names.js";
13
+ export function readDesktopConfig(stateDir) {
14
+ const config = JSON.parse(readFileSync(join(stateDir, "desktop.json"), "utf8"));
15
+ if (config.version !== 1 || typeof config.databaseFile !== "string" || !Array.isArray(config.repos) || config.repos.some(repo => typeof repo !== "string") || !Number.isInteger(config.port) || config.port < 1024 || config.port > 65535 || !/^[a-f0-9]{64}$/.test(config.identity))
16
+ throw new Error("Desktop configuration is invalid.");
17
+ if (config.runnerName !== undefined && (typeof config.runnerName !== "string" || !validRunnerName(config.runnerName)))
18
+ throw new Error("Desktop worker identity is invalid.");
19
+ if (config.containment !== undefined && (typeof config.containment !== "string" || !parseContainmentPolicy(config.containment).ok))
20
+ throw new Error("Desktop containment policy is invalid.");
21
+ if (config.databaseInitialized !== undefined && typeof config.databaseInitialized !== "boolean")
22
+ throw new Error("Desktop database setup state is invalid.");
23
+ config.repos = [...new Set(config.repos.map(repo => {
24
+ try {
25
+ return realpathSync(repo);
26
+ }
27
+ catch (error) {
28
+ if (["ENOENT", "EACCES", "EPERM"].includes(error.code ?? ""))
29
+ return resolve(repo);
30
+ throw error;
31
+ }
32
+ }))];
33
+ return config;
34
+ }
35
+ export function desktopDatabaseStatus(file) {
36
+ let db;
37
+ const result = (ready, message) => ({ ready, message, expectedSchema: SCHEMA_VERSION });
38
+ try {
39
+ db = new createRequire(import.meta.url)("node:sqlite").DatabaseSync(file, { readOnly: true });
40
+ db.exec("PRAGMA busy_timeout = 1000");
41
+ const schema = readSchemaVersion(db);
42
+ if (!schema.ok)
43
+ return result(false, `This app cannot use the saved task database: ${schema.problem}. Keep the database; use a compatible release or restore a verified backup separately.`);
44
+ if (schema.version === SCHEMA_VERSION)
45
+ return result(true, "The saved task database is compatible with this app.");
46
+ if (schema.version === null)
47
+ return result(false, "The task database has not been set up. Complete setup before starting work.");
48
+ if (schema.version < 0)
49
+ return result(false, "A database update did not finish. Keep the service stopped and complete the documented database upgrade before starting work.");
50
+ return result(false, `The saved tasks need a database upgrade (version ${schema.version} → ${SCHEMA_VERSION}). Keep the service stopped, back up the database, then complete the documented upgrade. This check changes nothing.`);
51
+ }
52
+ catch {
53
+ return result(false, "The saved task database cannot be read. Check that its disk is connected and accessible. If the file is damaged, keep it and restore a verified backup separately; do not create a replacement queue.");
54
+ }
55
+ finally {
56
+ db?.close();
57
+ }
58
+ }
59
+ export function desktopServiceDefinition(stateDir, args) {
60
+ const runtimeDir = dirname(args.node);
61
+ const home = args.home ?? homedir();
62
+ return planDesktopService({
63
+ node: args.node,
64
+ helper: args.helper,
65
+ stateDir,
66
+ label: args.label,
67
+ associatedBundleId: args.bundleId ?? "com.standing-orders.desktop",
68
+ home,
69
+ environment: { ...envTwins("CONTAINMENT", args.containment ?? "observed"), ...(args.buildId ? envTwins("DESKTOP_BUILD", args.buildId) : {}) },
70
+ pathEnv: [runtimeDir, ...(args.providerBin ? [args.providerBin] : []), join(home, ".local", "bin"), "/opt/homebrew/bin", "/usr/local/bin", "/usr/bin", "/bin", "/usr/sbin", "/sbin"].join(":"),
71
+ });
72
+ }
73
+ export async function verifyDesktopLiveness(config, fetchImpl = fetch) {
74
+ const challenge = randomBytes(32).toString("hex");
75
+ try {
76
+ const response = await fetchImpl(`http://127.0.0.1:${config.port}/desktop/health?challenge=${challenge}`, { signal: AbortSignal.timeout(2_000) });
77
+ if (response.status !== 200)
78
+ return { alive: false, port: config.port, problem: `the controller answered ${response.status} on port ${config.port}` };
79
+ const body = (await response.json());
80
+ const expected = createHmac("sha256", Buffer.from(config.identity, "hex")).update(challenge).digest("hex");
81
+ if (body.proof !== expected)
82
+ return { alive: false, port: config.port, problem: `something on port ${config.port} is not this installation's controller` };
83
+ return { alive: true, port: config.port };
84
+ }
85
+ catch (error) {
86
+ return { alive: false, port: config.port, problem: `no controller answered on port ${config.port} (${error instanceof Error ? error.message : String(error)})` };
87
+ }
88
+ }
89
+ export async function desktopServiceCommand(verb, stateDir, config, argv, supervise = execRun) {
90
+ const read = (name) => {
91
+ const at = argv.indexOf(`--${name}`);
92
+ const value = at >= 0 ? argv[at + 1] : undefined;
93
+ if (value === undefined || value.startsWith("--"))
94
+ throw new Error(`${verb} needs --${name}.`);
95
+ return value;
96
+ };
97
+ const parsed = parseContainmentPolicy(config.containment ?? envValue(process.env, "CONTAINMENT"));
98
+ if (!parsed.ok)
99
+ throw new Error(parsed.problem);
100
+ const providerAt = argv.indexOf("--provider-bin");
101
+ const bundleAt = argv.indexOf("--bundle-id");
102
+ const buildAt = argv.indexOf("--build-id");
103
+ const definition = desktopServiceDefinition(stateDir, { node: read("node"), helper: read("helper"), label: read("label"), containment: parsed.policy, ...(providerAt >= 0 ? { providerBin: read("provider-bin") } : {}), ...(bundleAt >= 0 ? { bundleId: read("bundle-id") } : {}), ...(buildAt >= 0 ? { buildId: read("build-id") } : {}) });
104
+ if (verb === "service-start") {
105
+ if (argv.includes("--update-id")) {
106
+ const update = await import("./desktop-update.js");
107
+ const journal = update.readUpdateJournal(stateDir);
108
+ if (!journal || journal.id !== read("update-id") || update.updateStopRequested(journal))
109
+ throw new Error("This update is no longer allowed to start the background service.");
110
+ }
111
+ if (config.repos.length === 0)
112
+ throw new Error("Choose a repository in the desktop app first.");
113
+ const database = desktopDatabaseStatus(config.databaseFile);
114
+ if (!database.ready)
115
+ throw new Error(database.message);
116
+ const opened = openStoreNoMigrate(config.databaseFile);
117
+ if (!opened.ok)
118
+ throw new Error(opened.message);
119
+ try {
120
+ const updateAt = argv.indexOf("--update-id");
121
+ if (updateAdmissionPaused(opened.store.raw()) && (updateAt < 0 || !updateGateOwned(opened.store.raw(), read("update-id"))))
122
+ throw new Error(UPDATE_PAUSED);
123
+ }
124
+ finally {
125
+ opened.store.close();
126
+ }
127
+ if (!existsSync(definition.logPath))
128
+ writeFileSync(definition.logPath, "", { mode: 0o600 });
129
+ const started = await installLaunchdService(definition, supervise);
130
+ if (!started.ok)
131
+ throw new Error(started.message);
132
+ return { ok: true, action: started.action, changed: started.changed, label: definition.label, unit: definition.unitPath };
133
+ }
134
+ if (verb === "service-stop") {
135
+ if (!argv.includes("--update-id") && existsSync(join(stateDir, "desktop-update.json"))) {
136
+ try {
137
+ await (await import("./desktop-update.js")).requestUpdateStop(stateDir);
138
+ }
139
+ catch {
140
+ const recoveryLabel = `${definition.label}.update`;
141
+ const recoveryStopped = await stopLaunchdService({ ...definition, label: recoveryLabel, unitPath: join(dirname(definition.unitPath), `${recoveryLabel}.plist`) }, supervise);
142
+ console.error(recoveryStopped.ok ? "The update stop request could not be recorded, so automatic update recovery was disabled. Preserve the update files and check Update status before restarting." : "The update stop request and recovery-service stop could not be confirmed. Check Update status and service logs before leaving this installation unattended.");
143
+ }
144
+ }
145
+ const stopped = await stopLaunchdService(definition, supervise);
146
+ if (!stopped.ok)
147
+ throw new Error(stopped.message);
148
+ return { ok: true, wasLoaded: stopped.wasLoaded, label: definition.label };
149
+ }
150
+ if (verb === "service-status") {
151
+ const status = await daemonStatus(definition, supervise);
152
+ const liveness = status.state === "running" ? await verifyDesktopLiveness(config) : null;
153
+ return { ok: true, ...status, label: definition.label, liveness, database: desktopDatabaseStatus(config.databaseFile), containment: containmentStatus(effectiveContainment(parsed.policy, probeContainmentCapability())) };
154
+ }
155
+ throw new Error("Unknown desktop service operation.");
156
+ }