toolroll 0.9.115 → 0.9.117

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 (145) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +43 -26
  3. package/dist/acp-agents.js +14 -1
  4. package/dist/acp-client.js +19 -1
  5. package/dist/agent-change-check.js +60 -0
  6. package/dist/agent-change-schema.js +19 -0
  7. package/dist/agent-detect.js +11 -1
  8. package/dist/agent-fence.js +39 -10
  9. package/dist/agent-network-request.js +108 -0
  10. package/dist/agent-requests.js +105 -0
  11. package/dist/approval-summary.js +3 -3
  12. package/dist/backup.js +17 -1
  13. package/dist/batch-checks.js +81 -18
  14. package/dist/browser/terminal.js +41 -41
  15. package/dist/browser/workspace.css +2 -2
  16. package/dist/browser/workspace.js +36 -36
  17. package/dist/builder.js +3 -1
  18. package/dist/candidate-materialize.js +119 -0
  19. package/dist/central-enrollment-contract.js +156 -0
  20. package/dist/central-recovery-stage.js +329 -0
  21. package/dist/chat-actions.js +101 -2
  22. package/dist/chat-channel.js +40 -0
  23. package/dist/check-only-standing.js +13 -0
  24. package/dist/check-only.js +25 -13
  25. package/dist/check-recovery-hold.js +199 -0
  26. package/dist/check-recovery-index-schema.js +3 -0
  27. package/dist/check-screenshots.js +83 -0
  28. package/dist/cli.js +125 -6
  29. package/dist/codex-limits.js +4 -0
  30. package/dist/connect-cli.js +257 -11
  31. package/dist/contracts/chat-actions.js +4 -0
  32. package/dist/contracts/console-api.js +15 -4
  33. package/dist/contracts/engine-api.js +344 -2
  34. package/dist/contracts/lead-tools.js +56 -2
  35. package/dist/contracts/provider.js +1 -1
  36. package/dist/contracts/route.js +1 -1
  37. package/dist/contracts/terminal-connection.js +50 -0
  38. package/dist/converse.js +80 -4
  39. package/dist/device-pair.js +280 -0
  40. package/dist/direct-chat-artifacts.js +347 -0
  41. package/dist/direct-chat-catalog.js +311 -0
  42. package/dist/direct-chat-fence.js +96 -0
  43. package/dist/direct-chat-git.js +343 -0
  44. package/dist/direct-chat-laptop.js +19 -0
  45. package/dist/direct-chat-schema.js +181 -0
  46. package/dist/direct-chat-ship.js +861 -0
  47. package/dist/direct-chat-workspace.js +389 -0
  48. package/dist/direct-chat.js +2107 -0
  49. package/dist/doctor.js +1 -1
  50. package/dist/easy-start.js +18 -0
  51. package/dist/egress.js +25 -4
  52. package/dist/engine-chat.js +454 -0
  53. package/dist/engine-reads.js +141 -13
  54. package/dist/exec.js +4 -3
  55. package/dist/flexible-agents.js +8 -16
  56. package/dist/flexible-authority-end.js +2 -0
  57. package/dist/flexible-interactive-schema.js +133 -0
  58. package/dist/flexible-interactive.js +94 -0
  59. package/dist/flexible-session.js +117 -49
  60. package/dist/flexible-ship.js +87 -7
  61. package/dist/flexible-sign-in.js +10 -0
  62. package/dist/flexible-start.js +21 -3
  63. package/dist/flexible-thread.js +2 -3
  64. package/dist/flexible-turns.js +26 -5
  65. package/dist/flexible.js +13 -0
  66. package/dist/flow-triggers.js +13 -4
  67. package/dist/flows-ui.js +54 -20
  68. package/dist/handoff-cli.js +630 -0
  69. package/dist/invoke.js +55 -13
  70. package/dist/lead-contract.js +5 -4
  71. package/dist/lead-doors.js +80 -1
  72. package/dist/lead-progress.js +9 -0
  73. package/dist/lead-tools.js +682 -10
  74. package/dist/lead.js +37 -9
  75. package/dist/live-bus.js +11 -0
  76. package/dist/live-terminal.js +132 -12
  77. package/dist/local-handoff.js +363 -0
  78. package/dist/local-owner-acts.js +264 -2
  79. package/dist/local-owner.js +16 -1
  80. package/dist/multiplayer-handoff.js +528 -0
  81. package/dist/multiplayer-presence.js +471 -0
  82. package/dist/names.js +17 -4
  83. package/dist/needs-you.js +10 -0
  84. package/dist/operate.js +280 -19
  85. package/dist/policy.js +2 -2
  86. package/dist/project-delete-ui.js +18 -11
  87. package/dist/project-delete.js +65 -4
  88. package/dist/project-tools.js +1 -1
  89. package/dist/prompt.js +1 -1
  90. package/dist/provider-connection.js +2 -0
  91. package/dist/provider-home.js +251 -8
  92. package/dist/provider.js +3 -2
  93. package/dist/publish.js +119 -64
  94. package/dist/pull-request-flow.js +35 -14
  95. package/dist/read-executor-worker.js +1 -1
  96. package/dist/read-executor.js +95 -1
  97. package/dist/restore-retirement.js +152 -0
  98. package/dist/result-follow-ups.js +116 -37
  99. package/dist/route-change.js +44 -4
  100. package/dist/scope.js +62 -5
  101. package/dist/serve.js +49 -5
  102. package/dist/server/chat.js +94 -13
  103. package/dist/server/console.css +9 -9
  104. package/dist/server/direct-chat.js +583 -0
  105. package/dist/server/engine-api.js +219 -21
  106. package/dist/server/flows.js +47 -13
  107. package/dist/server/found-repos.js +25 -0
  108. package/dist/server/guards.js +20 -6
  109. package/dist/server/live.js +81 -23
  110. package/dist/server/pages.js +67 -13
  111. package/dist/server/people-tokens.js +47 -6
  112. package/dist/server/remote.js +29 -0
  113. package/dist/server/render-results.js +6 -2
  114. package/dist/server/render-settings.js +4 -2
  115. package/dist/server/render-tasks.js +18 -17
  116. package/dist/server/route-table.js +69 -2
  117. package/dist/server/settings.js +22 -7
  118. package/dist/server/task-views.js +15 -3
  119. package/dist/server/tasks.js +39 -2
  120. package/dist/server/terminals.js +185 -11
  121. package/dist/settings-proofs.js +1 -1
  122. package/dist/spend-report.js +2 -2
  123. package/dist/spend.js +3 -3
  124. package/dist/store.js +600 -59
  125. package/dist/subagent-admin.js +23 -10
  126. package/dist/subagent-backup-schema.js +36 -0
  127. package/dist/subagent-backup.js +92 -0
  128. package/dist/subagent-week.js +2 -2
  129. package/dist/subagent-work.js +70 -47
  130. package/dist/subagents-ui.js +6 -2
  131. package/dist/subagents.js +5 -2
  132. package/dist/subscription-chat.js +36 -5
  133. package/dist/subscription-usage.js +233 -0
  134. package/dist/task-live.js +2 -1
  135. package/dist/teardown-git.js +34 -4
  136. package/dist/terminal-connection.js +159 -0
  137. package/dist/terminal-safety.js +114 -0
  138. package/dist/tui/darwin-arm64/toolroll-tui +0 -0
  139. package/dist/tui/darwin-x64/toolroll-tui +0 -0
  140. package/dist/tui/linux-arm64/toolroll-tui +0 -0
  141. package/dist/tui/linux-x64/toolroll-tui +0 -0
  142. package/dist/tui-contract.js +1 -1
  143. package/dist/tui-launch.js +32 -1
  144. package/dist/workspace-identity-schema.js +21 -0
  145. package/package.json +4 -2
package/dist/converse.js CHANGED
@@ -306,6 +306,58 @@ export function settleWithCache(price, answer) {
306
306
  return plain * price.inMicrousd + write * Math.ceil(price.inMicrousd * CACHE_WRITE_RATIO) + read * Math.ceil(price.inMicrousd * CACHE_READ_RATIO)
307
307
  + answer.tokensOut * price.outMicrousd;
308
308
  }
309
+ const LEAD_IMAGE_MEDIA_TYPES = new Set(["image/png", "image/jpeg", "image/webp", "image/gif"]);
310
+ export const LEAD_MAX_IMAGES_PER_MESSAGE = 4;
311
+ const LEAD_MAX_IMAGE_BYTES = 4 * 1024 * 1024;
312
+ function imageMagicMatches(mediaType, bytes) {
313
+ if (bytes.length < 12)
314
+ return false;
315
+ if (mediaType === "image/png")
316
+ return bytes[0] === 0x89 && bytes[1] === 0x50 && bytes[2] === 0x4e && bytes[3] === 0x47;
317
+ if (mediaType === "image/jpeg")
318
+ return bytes[0] === 0xff && bytes[1] === 0xd8 && bytes[2] === 0xff;
319
+ if (mediaType === "image/gif")
320
+ return bytes.subarray(0, 6).toString("ascii") === "GIF89a" || bytes.subarray(0, 6).toString("ascii") === "GIF87a";
321
+ if (mediaType === "image/webp")
322
+ return bytes.subarray(0, 4).toString("ascii") === "RIFF" && bytes.subarray(8, 12).toString("ascii") === "WEBP";
323
+ return false;
324
+ }
325
+ export function parseLeadImagesField(raw) {
326
+ if (typeof raw !== "string" || raw.trim() === "")
327
+ return [];
328
+ let parsed;
329
+ try {
330
+ parsed = JSON.parse(raw);
331
+ }
332
+ catch {
333
+ return [];
334
+ }
335
+ if (!Array.isArray(parsed))
336
+ return [];
337
+ const out = [];
338
+ for (const item of parsed.slice(0, LEAD_MAX_IMAGES_PER_MESSAGE)) {
339
+ if (typeof item !== "object" || item === null || Array.isArray(item))
340
+ continue;
341
+ const rec = item;
342
+ const mediaType = rec["mediaType"];
343
+ const dataBase64 = rec["dataBase64"];
344
+ if (typeof mediaType !== "string" || !LEAD_IMAGE_MEDIA_TYPES.has(mediaType))
345
+ continue;
346
+ if (typeof dataBase64 !== "string" || dataBase64.length === 0 || dataBase64.length > Math.ceil(LEAD_MAX_IMAGE_BYTES * 1.4))
347
+ continue;
348
+ if (!/^[A-Za-z0-9+/=\s]+$/.test(dataBase64))
349
+ continue;
350
+ const cleanB64 = dataBase64.replace(/\s+/g, "");
351
+ const bytes = Buffer.from(cleanB64, "base64");
352
+ if (bytes.length === 0 || bytes.length > LEAD_MAX_IMAGE_BYTES)
353
+ continue;
354
+ if (!imageMagicMatches(mediaType, bytes))
355
+ continue;
356
+ const filename = typeof rec["filename"] === "string" ? rec["filename"].trim().slice(0, 120) : undefined;
357
+ out.push({ mediaType: mediaType, dataBase64: cleanB64, ...(filename ? { filename } : {}) });
358
+ }
359
+ return out;
360
+ }
309
361
  export function parseLeadProviderWrapper(provider, bytes) {
310
362
  const parsed = strictJsonParse(bytes, WRAPPER_CAP_BYTES, 14);
311
363
  if (!parsed.ok)
@@ -440,8 +492,20 @@ export function composeLeadRequest(args) {
440
492
  const cached = args.cache !== undefined;
441
493
  const messages = [{ role: "user", content: cached ? [{ type: "text", text: opener, ...ephemeral }] : opener }];
442
494
  for (const one of args.history) {
443
- if (one.role === "operator")
444
- messages.push({ role: "user", content: one.text });
495
+ if (one.role === "operator") {
496
+ if (one.images !== undefined && one.images.length > 0) {
497
+ messages.push({
498
+ role: "user",
499
+ content: [
500
+ ...one.images.map(img => ({ type: "image", source: { type: "base64", media_type: img.mediaType, data: img.dataBase64 } })),
501
+ { type: "text", text: one.text },
502
+ ],
503
+ });
504
+ }
505
+ else {
506
+ messages.push({ role: "user", content: one.text });
507
+ }
508
+ }
445
509
  else if (one.role === "assistant") {
446
510
  const blocks = [];
447
511
  if (one.text !== "")
@@ -468,8 +532,20 @@ export function composeLeadRequest(args) {
468
532
  }
469
533
  const messages = [{ role: "system", content: args.system }, { role: "user", content: opener }];
470
534
  for (const one of args.history) {
471
- if (one.role === "operator")
472
- messages.push({ role: "user", content: one.text });
535
+ if (one.role === "operator") {
536
+ if (one.images !== undefined && one.images.length > 0) {
537
+ messages.push({
538
+ role: "user",
539
+ content: [
540
+ ...one.images.map(img => ({ type: "image_url", image_url: { url: `data:${img.mediaType};base64,${img.dataBase64}` } })),
541
+ { type: "text", text: one.text },
542
+ ],
543
+ });
544
+ }
545
+ else {
546
+ messages.push({ role: "user", content: one.text });
547
+ }
548
+ }
473
549
  else if (one.role === "assistant") {
474
550
  messages.push({
475
551
  role: "assistant",
@@ -0,0 +1,280 @@
1
+ import { randomBytes, timingSafeEqual } from "node:crypto";
2
+ import { mintApiToken } from "./api-tokens.js";
3
+ import { html, htmlString, postForm, scriptElement } from "./html.js";
4
+ import { credentialProof, freshFacts, proveAccountNow } from "./scope.js";
5
+ import { KEY_FILL_SCRIPT } from "./server/mutation-key.js";
6
+ import { withFormToken } from "./server/request-context.js";
7
+ const PAIR_TTL_MS = 5 * 60_000;
8
+ const MAX_PENDING_PAIRS = 64;
9
+ const TOKEN_TTL_MS = 90 * 24 * 60 * 60_000;
10
+ const CODE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789";
11
+ const PAIR_CODE_PATH = /^\/connect\/pair\/([A-Z2-9]{4}-[A-Z2-9]{4})$/;
12
+ const POLL_SECRET_RE = /^[a-f0-9]{64}$/;
13
+ const MAX_BODY_BYTES = 8 * 1024;
14
+ const FORBIDDEN_CLI_HEADERS = ["cookie", "origin", "referer", "sec-fetch-site", "sec-fetch-mode", "sec-fetch-dest", "sec-fetch-user"];
15
+ function sendJson(response, status, body, extraHeaders = {}) {
16
+ const payload = JSON.stringify(body);
17
+ response.writeHead(status, {
18
+ "content-type": "application/json; charset=utf-8",
19
+ "cache-control": "no-store",
20
+ "content-length": String(Buffer.byteLength(payload)),
21
+ ...extraHeaders,
22
+ });
23
+ response.end(payload);
24
+ }
25
+ function sendHtml(response, status, markup, fillKey = false) {
26
+ const nonce = fillKey ? randomBytes(16).toString("base64") : null;
27
+ const raw = htmlString(markup);
28
+ const body = nonce === null ? raw : raw.replace(/<\/body><\/html>$/, `${htmlString(scriptElement(KEY_FILL_SCRIPT, { nonce }))}</body></html>`);
29
+ response.writeHead(status, {
30
+ "content-type": "text/html; charset=utf-8",
31
+ "cache-control": "no-store",
32
+ "x-content-type-options": "nosniff",
33
+ "x-frame-options": "DENY",
34
+ "referrer-policy": "no-referrer",
35
+ "content-security-policy": `default-src 'none'; style-src 'unsafe-inline';${nonce === null ? "" : ` script-src 'nonce-${nonce}';`} form-action 'self'; base-uri 'none'; frame-ancestors 'none'`,
36
+ "content-length": String(Buffer.byteLength(body)),
37
+ });
38
+ response.end(body);
39
+ }
40
+ function hasBrowserHeaders(request) {
41
+ const keys = Object.keys(request.headers).map(k => k.toLowerCase());
42
+ return keys.some(k => FORBIDDEN_CLI_HEADERS.includes(k));
43
+ }
44
+ function generateUserCode() {
45
+ const bytes = randomBytes(8);
46
+ let raw = "";
47
+ for (let i = 0; i < 8; i += 1)
48
+ raw += CODE_ALPHABET[bytes[i] % CODE_ALPHABET.length];
49
+ return `${raw.slice(0, 4)}-${raw.slice(4, 8)}`;
50
+ }
51
+ function readRawBody(request, maxBytes = MAX_BODY_BYTES) {
52
+ return new Promise(resolve => {
53
+ const chunks = [];
54
+ let size = 0;
55
+ let over = false;
56
+ request.on("data", (chunk) => {
57
+ size += chunk.length;
58
+ if (size > maxBytes) {
59
+ over = true;
60
+ chunks.length = 0;
61
+ return;
62
+ }
63
+ chunks.push(chunk);
64
+ });
65
+ request.on("end", () => resolve(over ? null : Buffer.concat(chunks).toString("utf8")));
66
+ request.on("error", () => resolve(null));
67
+ });
68
+ }
69
+ function safeEqualHex(a, b) {
70
+ if (a.length !== b.length)
71
+ return false;
72
+ return timingSafeEqual(Buffer.from(a, "utf8"), Buffer.from(b, "utf8"));
73
+ }
74
+ export function createDevicePairHandlers(options) {
75
+ const { store, clock, allowedHost, browserKeys, identify, freshFactsOf, admitSource } = options;
76
+ const entries = new Map();
77
+ const prune = (nowMs) => {
78
+ for (const [code, entry] of entries) {
79
+ if (entry.expiresAt <= nowMs) {
80
+ entry.token = null;
81
+ entries.delete(code);
82
+ }
83
+ }
84
+ };
85
+ async function start(request, response) {
86
+ if (request.method !== "POST")
87
+ return sendJson(response, 405, { ok: false, error: "method_not_allowed" }, { allow: "POST" });
88
+ if (hasBrowserHeaders(request))
89
+ return sendJson(response, 400, { ok: false, error: "browser_headers_forbidden" });
90
+ const budget = admitSource(request);
91
+ if (!budget.ok) {
92
+ const headers = {};
93
+ if (budget.status !== 503)
94
+ headers["retry-after"] = String(budget.retryAfter);
95
+ return sendJson(response, budget.status === 503 ? 503 : 429, { ok: false, error: "rate-limited", message: "Too many pairing attempts. Try again shortly." }, headers);
96
+ }
97
+ await readRawBody(request, 1024);
98
+ const nowMs = clock().getTime();
99
+ prune(nowMs);
100
+ if (entries.size >= MAX_PENDING_PAIRS) {
101
+ return sendJson(response, 429, { ok: false, error: "too_many_pending", message: "Too many pending terminal pairings. Try again shortly." });
102
+ }
103
+ let userCode = generateUserCode();
104
+ while (entries.has(userCode))
105
+ userCode = generateUserCode();
106
+ const pollSecret = randomBytes(32).toString("hex");
107
+ const expiresAt = nowMs + PAIR_TTL_MS;
108
+ entries.set(userCode, {
109
+ userCode,
110
+ pollSecret,
111
+ createdAt: nowMs,
112
+ expiresAt,
113
+ state: "pending",
114
+ account: null,
115
+ token: null,
116
+ });
117
+ return sendJson(response, 200, {
118
+ ok: true,
119
+ userCode,
120
+ pollSecret,
121
+ verificationPath: `/connect/pair/${userCode}`,
122
+ expiresAt: new Date(expiresAt).toISOString(),
123
+ });
124
+ }
125
+ async function poll(request, response) {
126
+ if (request.method !== "POST")
127
+ return sendJson(response, 405, { ok: false, error: "method_not_allowed" }, { allow: "POST" });
128
+ if (hasBrowserHeaders(request))
129
+ return sendJson(response, 400, { ok: false, error: "browser_headers_forbidden" });
130
+ const raw = await readRawBody(request, 2048);
131
+ if (raw === null)
132
+ return sendJson(response, 413, { ok: false, error: "too_large" });
133
+ let pollSecret = "";
134
+ try {
135
+ const parsed = JSON.parse(raw);
136
+ if (typeof parsed["pollSecret"] === "string")
137
+ pollSecret = parsed["pollSecret"];
138
+ }
139
+ catch {
140
+ return sendJson(response, 400, { ok: false, error: "bad_request" });
141
+ }
142
+ if (!POLL_SECRET_RE.test(pollSecret))
143
+ return sendJson(response, 400, { ok: false, error: "bad_request" });
144
+ const nowMs = clock().getTime();
145
+ prune(nowMs);
146
+ let matched = null;
147
+ for (const entry of entries.values()) {
148
+ if (safeEqualHex(entry.pollSecret, pollSecret))
149
+ matched = entry;
150
+ }
151
+ if (matched === null)
152
+ return sendJson(response, 404, { ok: false, status: "expired", message: "Pairing expired or unknown. Start again." });
153
+ if (matched.state === "pending")
154
+ return sendJson(response, 200, { ok: true, status: "pending" });
155
+ const account = matched.account;
156
+ const token = matched.token;
157
+ matched.token = null;
158
+ entries.delete(matched.userCode);
159
+ if (account === null || token === null) {
160
+ return sendJson(response, 404, { ok: false, status: "expired", message: "Pairing was already claimed." });
161
+ }
162
+ return sendJson(response, 200, { ok: true, status: "approved", account, token });
163
+ }
164
+ function renderPage(code, who, problem, done) {
165
+ const canAct = who.role === "approver";
166
+ return html `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Connect terminal — Toolroll</title>
167
+ <style>body{font-family:system-ui,-apple-system,sans-serif;background:#0c0e12;color:#f3f4f6;margin:0;padding:32px;display:flex;justify-content:center}main{max-width:440px;width:100%;background:#141821;border:1px solid #262c3a;border-radius:12px;padding:24px}h1{font-size:20px;margin:0 0 8px}.code{font-family:ui-monospace,monospace;font-size:28px;letter-spacing:3px;background:#0c0e12;border:1px solid #2e3648;border-radius:8px;padding:12px;text-align:center;margin:16px 0}label{display:block;font-size:13px;margin:12px 0 4px;color:#cbd5e1}input,select{width:100%;box-sizing:border-box;padding:8px 10px;border-radius:6px;border:1px solid #334155;background:#0c0e12;color:#f8fafc;font-size:14px}button{margin-top:16px;width:100%;padding:10px 14px;border-radius:8px;border:none;background:#38bdf8;color:#082f49;font-weight:600;font-size:14px;cursor:pointer}.err{background:#450a0a;border:1px solid #991b1b;color:#fecaca;padding:10px;border-radius:8px;font-size:13px;margin-bottom:12px}.ok{background:#052e16;border:1px solid #166534;color:#bbf7d0;padding:12px;border-radius:8px;font-size:14px}</style></head>
168
+ <body><main>
169
+ <h1>Connect a remote terminal</h1>
170
+ <p style="font-size:13px;color:#94a3b8;margin:0 0 8px">Signed in as <strong>${who.name}</strong>. Confirm the code shown in your terminal to mint a personal API token.</p>
171
+ <div class="code">${code}</div>
172
+ ${problem !== null ? html `<p class="err" role="alert">${problem}</p>` : ""}
173
+ ${done
174
+ ? html `<p class="ok">Terminal connected. You can close this tab and return to your terminal.</p>`
175
+ : withFormToken(who.session.csrf, () => postForm(`/connect/pair/${code}`, html `
176
+ <label for="access">Access level</label>
177
+ <select id="access" name="access">
178
+ <option value="read">Read only (recommended)</option>
179
+ ${canAct ? html `<option value="act">Read &amp; act (steer, revise, hand off, attach live terminals)</option>` : ""}
180
+ </select>
181
+ <label for="password">Confirm your Toolroll password</label>
182
+ <input id="password" name="password" type="password" autocomplete="current-password" required>
183
+ <button type="submit">Approve terminal connection</button>
184
+ `))}
185
+ </main></body></html>`;
186
+ }
187
+ function page(request, response, url) {
188
+ const match = PAIR_CODE_PATH.exec(url.pathname);
189
+ if (match === null)
190
+ return sendHtml(response, 404, html `<p>Unknown pairing code.</p>`);
191
+ const code = match[1];
192
+ const who = identify(request, false);
193
+ if (who === null || who.via !== "cookie") {
194
+ response.writeHead(303, { location: `/login?return=${encodeURIComponent(url.pathname)}`, "cache-control": "no-store" });
195
+ response.end();
196
+ return;
197
+ }
198
+ if (who.authority !== "full") {
199
+ return sendHtml(response, 403, html `<p>Set a password and sign in with a full browser session to connect remote terminals.</p>`);
200
+ }
201
+ const nowMs = clock().getTime();
202
+ prune(nowMs);
203
+ const entry = entries.get(code);
204
+ if (entry === undefined || entry.state !== "pending") {
205
+ return sendHtml(response, 404, html `<p>That terminal pairing code has expired or was already used. Run <code>toolroll connect --browser</code> again.</p>`);
206
+ }
207
+ return sendHtml(response, 200, renderPage(code, who, null, false), browserKeys.required());
208
+ }
209
+ async function confirm(request, response, url) {
210
+ if (request.method !== "POST")
211
+ return sendJson(response, 405, { ok: false, error: "method_not_allowed" }, { allow: "POST" });
212
+ const match = PAIR_CODE_PATH.exec(url.pathname);
213
+ if (match === null)
214
+ return sendHtml(response, 404, html `<p>Unknown pairing code.</p>`);
215
+ const code = match[1];
216
+ const who = identify(request, true);
217
+ if (who === null || who.via !== "cookie" || who.authority !== "full") {
218
+ return sendHtml(response, 403, html `<p>Sign in with a full browser session to approve a terminal connection.</p>`);
219
+ }
220
+ const origin = request.headers.origin;
221
+ const referer = request.headers.referer;
222
+ const named = typeof origin === "string" && origin !== "null" ? origin : typeof referer === "string" ? referer : null;
223
+ if (named === null || !allowedHost(named.replace(/^https?:\/\//, "").split("/")[0])) {
224
+ return sendHtml(response, 403, html `<p>Same-origin confirmation required.</p>`);
225
+ }
226
+ const raw = await readRawBody(request, MAX_BODY_BYTES);
227
+ if (raw === null)
228
+ return sendHtml(response, 413, html `<p>Request too large.</p>`);
229
+ const form = new URLSearchParams(raw);
230
+ if (form.get("csrf") !== who.session.csrf)
231
+ return sendHtml(response, 403, renderPage(code, who, "Invalid form token. Reload and try again.", false), browserKeys.required());
232
+ const keyErr = browserKeys.check(who, request, form);
233
+ if (keyErr !== null)
234
+ return sendHtml(response, keyErr.status, renderPage(code, who, keyErr.message, false), browserKeys.required());
235
+ const now = clock();
236
+ prune(now.getTime());
237
+ const entry = entries.get(code);
238
+ if (entry === undefined || entry.state !== "pending") {
239
+ return sendHtml(response, 404, html `<p>That terminal pairing code has expired or was already used.</p>`);
240
+ }
241
+ const password = form.get("password") ?? "";
242
+ const proved = freshFacts.run(freshFactsOf(request, who), () => proveAccountNow(store, who.name, password, { credential: true }));
243
+ if (!proved.ok || !credentialProof(proved.method)) {
244
+ return sendHtml(response, 403, renderPage(code, who, "Password did not match. Nothing was connected.", false), browserKeys.required());
245
+ }
246
+ const account = store.accountOf(who.name);
247
+ if (account === null || account.revokedAt !== null || account.generation !== who.session.generation) {
248
+ return sendHtml(response, 401, html `<p>Your session has ended.</p>`);
249
+ }
250
+ const requestedAccess = form.get("access") === "act" && account.role === "approver" ? "act" : "read";
251
+ const minted = mintApiToken();
252
+ store.createApiToken({
253
+ id: minted.id,
254
+ account: who.name,
255
+ name: `remote-tui-${code.toLowerCase()}`,
256
+ secretHash: minted.hash,
257
+ access: requestedAccess,
258
+ purpose: "api",
259
+ by: who.name,
260
+ projects: account.projects,
261
+ expiresAt: new Date(now.getTime() + TOKEN_TTL_MS).toISOString(),
262
+ }, now);
263
+ entry.state = "approved";
264
+ entry.account = who.name;
265
+ entry.token = minted.token;
266
+ store.recordAction({
267
+ at: now.toISOString(),
268
+ actor: who.name,
269
+ repo: null,
270
+ taskId: null,
271
+ runId: null,
272
+ action: "connect.pair.approved",
273
+ outcome: "recorded",
274
+ source: "sign-in",
275
+ detail: `paired remote terminal (${requestedAccess}, token ${minted.id})`,
276
+ });
277
+ return sendHtml(response, 200, renderPage(code, who, null, true));
278
+ }
279
+ return { start, poll, page, confirm };
280
+ }