@mmerterden/multi-agent-pipeline 23.2.0 → 23.4.0

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 (230) hide show
  1. package/CHANGELOG.md +50 -0
  2. package/README.md +25 -6
  3. package/README.tr.md +26 -7
  4. package/docs/adr/0008-installer-modularization-and-secret-leak-defense.md +1 -1
  5. package/docs/adr/0010-own-code-graph.md +299 -8
  6. package/docs/architecture.md +3 -3
  7. package/docs/ecosystem.md +10 -10
  8. package/docs/engineering.md +4 -4
  9. package/docs/facts.json +8 -8
  10. package/docs/features.md +6 -6
  11. package/docs/performance.md +17 -17
  12. package/install/_dev-only-files.mjs +9 -0
  13. package/install/claude.mjs +28 -2
  14. package/install/templates/claude-hooks.json +32 -1
  15. package/manifest.json +229 -161
  16. package/package.json +11 -3
  17. package/pipeline/commands/multi-agent/SKILL.md +1 -1
  18. package/pipeline/commands/multi-agent/design-check/SKILL.md +2 -2
  19. package/pipeline/commands/multi-agent/diff-explain/SKILL.md +3 -3
  20. package/pipeline/commands/multi-agent/fable-status/SKILL.md +1 -1
  21. package/pipeline/commands/multi-agent/graph/SKILL.md +57 -24
  22. package/pipeline/commands/multi-agent/pair/SKILL.md +92 -0
  23. package/pipeline/commands/multi-agent/prune-prompts/SKILL.md +1 -1
  24. package/pipeline/commands/multi-agent/search/SKILL.md +7 -1
  25. package/pipeline/commands/multi-agent/status/SKILL.md +4 -0
  26. package/pipeline/commands/multi-agent/sync/SKILL.md +3 -3
  27. package/pipeline/contract/CHANGELOG.md +49 -0
  28. package/pipeline/contract/build.mjs +13 -1
  29. package/pipeline/contract/fixtures/error-invalid-request.json +1 -1
  30. package/pipeline/contract/fixtures/error-unauthorized.json +1 -1
  31. package/pipeline/contract/fixtures/runs-awaiting-question.json +4 -1
  32. package/pipeline/contract/fixtures/runs-empty.json +1 -1
  33. package/pipeline/contract/fixtures/runs-failed.json +4 -1
  34. package/pipeline/contract/fixtures/runs-old-schema.json +3 -0
  35. package/pipeline/contract/fixtures/runs-pr-opened-redacted.json +4 -1
  36. package/pipeline/contract/fixtures/runs-pr-opened.json +4 -1
  37. package/pipeline/contract/fixtures/runs-running.json +4 -1
  38. package/pipeline/contract/manifest.json +28 -15
  39. package/pipeline/contract/types/index.d.ts +55 -3
  40. package/pipeline/lib/detach-self.mjs +95 -0
  41. package/pipeline/lib/model-rung.sh +1 -1
  42. package/pipeline/lib/public-mcp-servers.mjs +33 -0
  43. package/pipeline/lib/rotated-log.mjs +93 -0
  44. package/pipeline/lib/tls-trust.mjs +29 -0
  45. package/pipeline/lib/usage-lifecycle.mjs +9 -11
  46. package/pipeline/lib/usage-names.generated.mjs +614 -0
  47. package/pipeline/lib/usage-run-key.mjs +235 -0
  48. package/pipeline/lib/usage-vocab.mjs +210 -0
  49. package/pipeline/multi-agent-refs/analysis/intake.md +2 -2
  50. package/pipeline/multi-agent-refs/analysis/render.md +1 -1
  51. package/pipeline/multi-agent-refs/channels/generator.md +4 -5
  52. package/pipeline/multi-agent-refs/cross-cli-contract.md +4 -4
  53. package/pipeline/multi-agent-refs/design-check/scope-and-ledger.md +1 -1
  54. package/pipeline/multi-agent-refs/features/code-graph.md +146 -11
  55. package/pipeline/multi-agent-refs/features/code-intelligence.md +16 -14
  56. package/pipeline/multi-agent-refs/features/dev-critic.md +7 -7
  57. package/pipeline/multi-agent-refs/features/model-fallback.md +9 -7
  58. package/pipeline/multi-agent-refs/features/remote-control.md +252 -0
  59. package/pipeline/multi-agent-refs/features/review-delta.md +1 -1
  60. package/pipeline/multi-agent-refs/features/review-file-set.md +3 -3
  61. package/pipeline/multi-agent-refs/features/review-multi-repo.md +1 -1
  62. package/pipeline/multi-agent-refs/features/session-brief.md +42 -0
  63. package/pipeline/multi-agent-refs/features/skill-conformance.md +3 -3
  64. package/pipeline/multi-agent-refs/features/usage-reporting.md +252 -24
  65. package/pipeline/multi-agent-refs/help/en.md +3 -2
  66. package/pipeline/multi-agent-refs/help/tr.md +3 -2
  67. package/pipeline/multi-agent-refs/knowledge.md +1 -1
  68. package/pipeline/multi-agent-refs/orchestrator/copilot-pipeline.md +1 -1
  69. package/pipeline/multi-agent-refs/orchestrator/dispatcher.md +1 -1
  70. package/pipeline/multi-agent-refs/phases/operations.md +2 -2
  71. package/pipeline/multi-agent-refs/phases/phase-0-init.md +13 -12
  72. package/pipeline/multi-agent-refs/phases/phase-1-plan.md +4 -4
  73. package/pipeline/multi-agent-refs/phases/phase-3-review.md +5 -3
  74. package/pipeline/multi-agent-refs/phases/phase-5-report.md +1 -1
  75. package/pipeline/multi-agent-refs/platform-parity.md +2 -2
  76. package/pipeline/multi-agent-refs/review/panel.md +1 -1
  77. package/pipeline/multi-agent-refs/wiki-capture.md +3 -17
  78. package/pipeline/office/index.html +1207 -233
  79. package/pipeline/office/toolkit.json +1 -1
  80. package/pipeline/rules/outside-the-pipeline.md +1 -1
  81. package/pipeline/schemas/activity.schema.json +23 -0
  82. package/pipeline/schemas/agent-state.schema.json +6 -1
  83. package/pipeline/schemas/code-graph-calls.schema.json +254 -0
  84. package/pipeline/schemas/code-graph-docs.schema.json +223 -0
  85. package/pipeline/schemas/code-graph-infra.schema.json +227 -0
  86. package/pipeline/schemas/code-graph.schema.json +2 -2
  87. package/pipeline/schemas/examples/design-check-config.json +27 -0
  88. package/pipeline/schemas/learning-curve.schema.json +67 -0
  89. package/pipeline/schemas/office-jobs.json +69 -2
  90. package/pipeline/schemas/office-jobs.schema.json +8 -1
  91. package/pipeline/schemas/phases.json +5 -0
  92. package/pipeline/schemas/phases.schema.json +8 -0
  93. package/pipeline/schemas/prefs.schema.json +46 -12
  94. package/pipeline/schemas/runs-index.schema.json +17 -0
  95. package/pipeline/schemas/toolkit-path-params.json +84 -8
  96. package/pipeline/scripts/README.md +1 -0
  97. package/pipeline/scripts/_code-graph.mjs +184 -103
  98. package/pipeline/scripts/_contract-core.mjs +1 -1
  99. package/pipeline/scripts/_contract-routes-office.mjs +21 -0
  100. package/pipeline/scripts/_diff-impact.mjs +21 -2
  101. package/pipeline/scripts/_graph-sidecars.mjs +372 -0
  102. package/pipeline/scripts/_http-post.mjs +103 -115
  103. package/pipeline/scripts/_safe-read.mjs +57 -0
  104. package/pipeline/scripts/_skill-practices.mjs +26 -0
  105. package/pipeline/scripts/_strip-code.mjs +380 -0
  106. package/pipeline/scripts/activity-snapshot.mjs +13 -1
  107. package/pipeline/scripts/aggregate-metrics.mjs +3 -5
  108. package/pipeline/scripts/call-graph/index.mjs +78 -0
  109. package/pipeline/scripts/call-graph/lang/cpp.mjs +308 -0
  110. package/pipeline/scripts/call-graph/lang/csharp.mjs +130 -0
  111. package/pipeline/scripts/call-graph/lang/go.mjs +303 -0
  112. package/pipeline/scripts/call-graph/lang/java.mjs +370 -0
  113. package/pipeline/scripts/call-graph/lang/kotlin.mjs +397 -0
  114. package/pipeline/scripts/call-graph/lang/python.mjs +399 -0
  115. package/pipeline/scripts/call-graph/lang/rust.mjs +345 -0
  116. package/pipeline/scripts/call-graph/lang/shared.mjs +230 -0
  117. package/pipeline/scripts/call-graph/lang/swift.mjs +432 -0
  118. package/pipeline/scripts/call-graph/lang/typescript.mjs +692 -0
  119. package/pipeline/scripts/call-graph/lex.mjs +396 -0
  120. package/pipeline/scripts/call-graph/platform.mjs +86 -0
  121. package/pipeline/scripts/call-graph/profiles.mjs +89 -0
  122. package/pipeline/scripts/call-graph/resolve.mjs +1125 -0
  123. package/pipeline/scripts/call-graph/scan.mjs +267 -0
  124. package/pipeline/scripts/code-graph-rules/android.json +7 -2
  125. package/pipeline/scripts/code-graph-rules/cpp.json +99 -0
  126. package/pipeline/scripts/code-graph-rules/csharp.json +102 -0
  127. package/pipeline/scripts/code-graph-rules/go.json +2 -1
  128. package/pipeline/scripts/code-graph-rules/ios.json +3 -1
  129. package/pipeline/scripts/code-graph-rules/java.json +76 -0
  130. package/pipeline/scripts/code-graph-rules/node.json +7 -2
  131. package/pipeline/scripts/code-graph-rules/python.json +6 -2
  132. package/pipeline/scripts/code-graph-rules/rust.json +105 -0
  133. package/pipeline/scripts/contract-server.mjs +1 -0
  134. package/pipeline/scripts/cost-table.json +6 -5
  135. package/pipeline/scripts/feedback-send.mjs +26 -26
  136. package/pipeline/scripts/gate-ledger.mjs +2 -1
  137. package/pipeline/scripts/gen-usage-names.mjs +124 -0
  138. package/pipeline/scripts/graph-affected.mjs +109 -20
  139. package/pipeline/scripts/graph-build.mjs +95 -15
  140. package/pipeline/scripts/graph-export.mjs +272 -0
  141. package/pipeline/scripts/graph-hint.mjs +15 -2
  142. package/pipeline/scripts/graph-query.mjs +305 -26
  143. package/pipeline/scripts/graph-report.mjs +187 -1
  144. package/pipeline/scripts/health-report.mjs +3 -4
  145. package/pipeline/scripts/infra/docs.mjs +317 -0
  146. package/pipeline/scripts/infra/extract.mjs +998 -0
  147. package/pipeline/scripts/infra/graph.mjs +245 -0
  148. package/pipeline/scripts/infra/yaml-lite.mjs +311 -0
  149. package/pipeline/scripts/job-launch.mjs +67 -2
  150. package/pipeline/scripts/learning-curve.mjs +288 -178
  151. package/pipeline/scripts/log-metric.sh +10 -1
  152. package/pipeline/scripts/note-agent-event.mjs +3 -4
  153. package/pipeline/scripts/note-command-use.mjs +333 -0
  154. package/pipeline/scripts/note-command-use.sh +126 -0
  155. package/pipeline/scripts/note-mcp-call.sh +89 -0
  156. package/pipeline/scripts/note-mcp-failure.mjs +272 -1
  157. package/pipeline/scripts/note-session.sh +62 -3
  158. package/pipeline/scripts/note-skill-use.mjs +58 -2
  159. package/pipeline/scripts/office-build.mjs +115 -1
  160. package/pipeline/scripts/office-memory.mjs +14 -5
  161. package/pipeline/scripts/pair.mjs +333 -0
  162. package/pipeline/scripts/pre-push-check.sh +1 -1
  163. package/pipeline/scripts/remote/cbor.mjs +128 -0
  164. package/pipeline/scripts/remote/contract.mjs +98 -0
  165. package/pipeline/scripts/remote/handler.mjs +317 -0
  166. package/pipeline/scripts/remote/handles.mjs +57 -0
  167. package/pipeline/scripts/remote/lifecycle.mjs +186 -0
  168. package/pipeline/scripts/remote/listener.mjs +204 -0
  169. package/pipeline/scripts/remote/lockout.mjs +103 -0
  170. package/pipeline/scripts/remote/nonces.mjs +61 -0
  171. package/pipeline/scripts/remote/pairing.mjs +519 -0
  172. package/pipeline/scripts/remote/qr-encode.mjs +459 -0
  173. package/pipeline/scripts/remote/store.mjs +188 -0
  174. package/pipeline/scripts/remote/transport.mjs +211 -0
  175. package/pipeline/scripts/remote/verbs.json +70 -0
  176. package/pipeline/scripts/remote/verbs.mjs +217 -0
  177. package/pipeline/scripts/remote/webauthn.mjs +169 -0
  178. package/pipeline/scripts/remote/wire.mjs +364 -0
  179. package/pipeline/scripts/remote-listener.mjs +83 -0
  180. package/pipeline/scripts/route-learn.mjs +4 -4
  181. package/pipeline/scripts/run-kill.mjs +1 -1
  182. package/pipeline/scripts/run-write.mjs +13 -2
  183. package/pipeline/scripts/runs-index.mjs +30 -3
  184. package/pipeline/scripts/search-logs.sh +9 -0
  185. package/pipeline/scripts/session-brief.mjs +458 -0
  186. package/pipeline/scripts/session-brief.sh +130 -0
  187. package/pipeline/scripts/test-gap-rules/cpp.json +25 -0
  188. package/pipeline/scripts/test-gap-rules/csharp.json +20 -0
  189. package/pipeline/scripts/test-gap-rules/java.json +20 -0
  190. package/pipeline/scripts/test-gap-rules/rust.json +14 -0
  191. package/pipeline/scripts/token-budget-report.mjs +3 -2
  192. package/pipeline/scripts/uninstall.mjs +29 -0
  193. package/pipeline/scripts/usage-access.mjs +16 -31
  194. package/pipeline/scripts/usage-health.mjs +31 -62
  195. package/pipeline/scripts/usage-register-beacon.mjs +11 -22
  196. package/pipeline/scripts/usage-register.mjs +39 -29
  197. package/pipeline/scripts/usage-report.mjs +579 -178
  198. package/pipeline/scripts/validate-code-graph.mjs +361 -111
  199. package/pipeline/scripts/write-state.mjs +39 -0
  200. package/pipeline/skills/.skill-manifest.json +22 -18
  201. package/pipeline/skills/.skills-index.json +13 -2
  202. package/pipeline/skills/shared/README.md +5 -4
  203. package/pipeline/skills/shared/core/multi-agent-design-check/SKILL.md +1 -1
  204. package/pipeline/skills/shared/core/multi-agent-diff-explain/SKILL.md +3 -3
  205. package/pipeline/skills/shared/core/multi-agent-fable-status/SKILL.md +1 -1
  206. package/pipeline/skills/shared/core/multi-agent-graph/SKILL.md +55 -21
  207. package/pipeline/skills/shared/core/multi-agent-pair/SKILL.md +41 -0
  208. package/pipeline/skills/shared/core/multi-agent-prune-prompts/SKILL.md +1 -1
  209. package/pipeline/skills/shared/core/multi-agent-sync/SKILL.md +3 -3
  210. package/pipeline/skills/shared/external/app-store-optimization/SKILL.md +2 -3
  211. package/pipeline/skills/shared/external/app-store-optimization/references/keyword-research-methodology.md +2 -2
  212. package/pipeline/skills/shared/external/app-store-optimization/references/product-page-variants.md +2 -2
  213. package/pipeline/skills/shared/external/app-store-review/SKILL.md +11 -4
  214. package/pipeline/skills/shared/external/build-settings-audit/SKILL.md +1 -1
  215. package/pipeline/skills/shared/external/build-time-benchmark/SKILL.md +5 -5
  216. package/pipeline/skills/shared/external/build-time-fixes/SKILL.md +5 -5
  217. package/pipeline/skills/shared/external/build-time-optimizer/SKILL.md +6 -6
  218. package/pipeline/skills/shared/external/free-llm-apis/references/providers.md +1 -0
  219. package/pipeline/skills/shared/external/ios-coding-standard/references/STANDARD.md +2 -2
  220. package/pipeline/skills/shared/external/ios-haptics/references/core-haptics.md +1 -1
  221. package/pipeline/skills/shared/external/localization-reuse-map/references/publish-and-snapshot.md +1 -1
  222. package/pipeline/skills/shared/external/package-build-audit/SKILL.md +3 -3
  223. package/pipeline/skills/shared/external/reverse-engineer-own-app/SKILL.md +2 -3
  224. package/pipeline/skills/shared/external/swift-compile-hotspots/SKILL.md +2 -2
  225. package/pipeline/skills/shared/external/weatherkit/SKILL.md +5 -6
  226. package/pipeline/skills/skills-index.md +3 -2
  227. package/docs/FIGMA_PIPELINE.md +0 -137
  228. package/pipeline/lib/identifier-scan.mjs +0 -156
  229. package/pipeline/scripts/publish-staged.mjs +0 -324
  230. package/pipeline/skills/shared/external/ios-coding-standard/scripts/check_structure.py +0 -765
@@ -0,0 +1,519 @@
1
+ /**
2
+ * pairing.mjs - the pairing ceremony on the computer's side, in the four
3
+ * steps the command runs: begin, wait, confirm, cancel.
4
+ *
5
+ * begin makes the pairing secret and the ephemeral key on this machine,
6
+ * registers the pairing with the site (which never learns the
7
+ * secret), and returns the code and the QR payload to show. If the
8
+ * site says the feature is off for this user it returns an error
9
+ * and no code.
10
+ * wait waits for the phone to register its passkey and key, then
11
+ * checks what the site relays: the keys must be valid, the passkey
12
+ * must be an ES256 P-256 key.
13
+ * confirm takes the six-digit number the person read off the phone and
14
+ * compares it with the one derived here from the transcript. Only
15
+ * an equal number pins the device; the number is never sent to the
16
+ * site and never printed here. A different number rejects the
17
+ * pairing for good.
18
+ * cancel abandons a pending pairing.
19
+ *
20
+ * Between the steps the state is one 0600 file (pending.json) that holds the
21
+ * secret and the private key for at most the code's five minutes; it is
22
+ * deleted on every way out of the ceremony. The pairing always needs the
23
+ * person: every step refuses under MULTI_AGENT_UNATTENDED=1.
24
+ *
25
+ * @module pipeline/scripts/remote/pairing
26
+ */
27
+
28
+ import { timingSafeEqual } from "node:crypto";
29
+ import { rmSync } from "node:fs";
30
+ import { join } from "node:path";
31
+ import { writeFileSafe } from "../../lib/safe-write.mjs";
32
+ import { readRegularJson } from "../../lib/regular-file.mjs";
33
+ import { isUnattended } from "../../lib/unattended.mjs";
34
+ import { SiteError } from "./transport.mjs";
35
+ import {
36
+ MAX_DEVICES,
37
+ audit,
38
+ ensureDir,
39
+ pinDevice,
40
+ readDevices,
41
+ remoteDir,
42
+ removeAllDevices,
43
+ removeDevice,
44
+ } from "./store.mjs";
45
+ import {
46
+ b64uDecode,
47
+ b64uEncode,
48
+ deriveSessionKeys,
49
+ formatPairingCode,
50
+ generateEcdhKeyPair,
51
+ newPairingSecret,
52
+ pairingKeys,
53
+ SAS_PATTERN,
54
+ sasText,
55
+ transcriptHash,
56
+ validPublicRaw,
57
+ } from "./wire.mjs";
58
+ import { lockoutVerdict, recordMatch, recordMismatch } from "./lockout.mjs";
59
+ import { registerUrlAllowed } from "../../lib/usage-endpoint.mjs";
60
+ import { WebAuthnError, publicKeyFromCose } from "./webauthn.mjs";
61
+
62
+ export const PAIRING_TTL_MS = 5 * 60 * 1000;
63
+ const ID = /^[A-Za-z0-9-]{8,64}$/;
64
+
65
+ export class PairError extends Error {
66
+ /** @param {string} code a fixed identifier the command maps to a message */
67
+ constructor(code, message) {
68
+ super(message ?? code);
69
+ this.name = "PairError";
70
+ this.code = code;
71
+ }
72
+ }
73
+
74
+ function humanWait(ms) {
75
+ const minutes = Math.max(1, Math.ceil(ms / 60000));
76
+ if (minutes < 120) return `${minutes} minute(s)`;
77
+ return `${Math.ceil(minutes / 60)} hour(s)`;
78
+ }
79
+
80
+ /**
81
+ * Where the phone opens the pairing page, from the site's answer. It decides
82
+ * the origin and relying party the passkey is bound to, so it must be https,
83
+ * carry no credentials, name the relying party's own host, and be a host this
84
+ * computer trusts under the same rule as the site itself, with the path
85
+ * /remote/pair and no query. This computer never sends a request to it.
86
+ */
87
+ function phonePageOf(pairUrl, rpId, site) {
88
+ let url;
89
+ try {
90
+ url = new URL(String(pairUrl));
91
+ } catch {
92
+ throw new PairError("site-invalid", "the site's pairing page address is not a URL");
93
+ }
94
+ const trusted = registerUrlAllowed(url.origin, site.trustedHosts ?? []);
95
+ if (url.protocol !== "https:" || url.username || url.password || !trusted) {
96
+ throw new PairError(
97
+ "untrusted-phone-origin",
98
+ `the pairing page host (${printable(url.hostname, 60)}) is not a trusted host; add it to usageLog.trustedHosts if it is yours`,
99
+ );
100
+ }
101
+ if (url.pathname !== "/remote/pair" || url.search) {
102
+ throw new PairError("site-invalid", "the pairing page address is not the pairing page");
103
+ }
104
+ if (rpId !== url.hostname) {
105
+ throw new PairError("rp-mismatch", "the site's relying party is not the pairing page's host");
106
+ }
107
+ return { origin: url.origin, base: `${url.origin}${url.pathname}` };
108
+ }
109
+
110
+ /**
111
+ * Said before the code is shown. Pairing trusts the page the site serves to
112
+ * the phone while it runs; the number check does not cover a hostile page.
113
+ */
114
+ export const PAIRING_NOTICE =
115
+ "Remote control trusts the JavaScript your site serves to the phone while pairing: enable it only for a site you operate or trust as much as this computer.";
116
+
117
+ export const pendingFile = (env) => join(remoteDir(env), "pending.json");
118
+
119
+ /** Text a site supplied, reduced to printable ASCII so it cannot carry terminal control sequences. */
120
+ export const printable = (text, max = 40) =>
121
+ String(text ?? "")
122
+ .replace(/[^\x20-\x7e]/g, "?")
123
+ .trim()
124
+ .slice(0, max);
125
+
126
+ /**
127
+ * A name the site supplied (this computer's, or a phone's label), limited to
128
+ * letters, digits, space, dot, underscore and hyphen; anything else becomes
129
+ * "?" and the result is clipped to `max`.
130
+ */
131
+ export const safeName = (text, max = 40) =>
132
+ String(text ?? "")
133
+ .replace(/[^A-Za-z0-9 ._-]/g, "?")
134
+ .trim()
135
+ .slice(0, max);
136
+
137
+ function requireHuman(env) {
138
+ if (isUnattended(env)) {
139
+ throw new PairError(
140
+ "unattended",
141
+ "pairing needs a person at the keyboard; it is refused in an unattended run",
142
+ );
143
+ }
144
+ }
145
+
146
+ function readPending(env) {
147
+ const p = readRegularJson(pendingFile(env), null);
148
+ if (!p || p.v !== 1) return null;
149
+ if (typeof p.expiresAt !== "number" || Date.now() > p.expiresAt) {
150
+ rmSync(pendingFile(env), { force: true });
151
+ return null;
152
+ }
153
+ return p;
154
+ }
155
+
156
+ const dropPending = (env) => rmSync(pendingFile(env), { force: true });
157
+
158
+ function writePending(env, doc) {
159
+ ensureDir(env);
160
+ writeFileSafe(pendingFile(env), `${JSON.stringify(doc)}\n`, { mode: 0o600 });
161
+ }
162
+
163
+ function mapStatus(status, json) {
164
+ if (status === 404)
165
+ return new PairError(
166
+ "not-enabled",
167
+ "remote control is not enabled for this account (the site gives the same answer when it does not accept this machine's usage token)",
168
+ );
169
+ if (status === 401)
170
+ return new PairError("token-rejected", "the site did not accept this machine's usage token");
171
+ if (status === 429) {
172
+ return new PairError(
173
+ json?.error === "locked" ? "locked" : "rate-limited",
174
+ "too many attempts; try later",
175
+ );
176
+ }
177
+ if (status === 409 && json?.error === "device_limit") {
178
+ return new PairError("device-limit", "the maximum number of devices is already paired");
179
+ }
180
+ return new PairError("site-error", `the site answered ${status}`);
181
+ }
182
+
183
+ async function call(client, path, body, opts) {
184
+ try {
185
+ return await client.post(path, body, opts);
186
+ } catch (err) {
187
+ if (err instanceof SiteError) throw new PairError(`site-${err.code}`, err.message);
188
+ throw err;
189
+ }
190
+ }
191
+
192
+ /**
193
+ * Asks machine/status, which answers truthfully to a valid token, so the
194
+ * person is told which of three situations they are in: the site has not
195
+ * enabled the feature, their account lacks the permission, or the token was
196
+ * not accepted (the site answers an invalid token with an empty 404).
197
+ */
198
+ async function requireEnabled(client) {
199
+ const { status, json } = await call(client, "machine/status", {});
200
+ if (status === 404 || status === 401) {
201
+ throw new PairError(
202
+ "token-not-accepted",
203
+ "the site did not accept this machine's usage token (a revoked, unregistered or unapproved token is answered the same way)",
204
+ );
205
+ }
206
+ if (status !== 200 || !json) throw mapStatus(status, json);
207
+ if (json.enabled !== true) {
208
+ throw new PairError("not-enabled", "remote control is not enabled on the site");
209
+ }
210
+ if (json.permitted !== true) {
211
+ throw new PairError(
212
+ "no-permission",
213
+ "your account does not have the remote control permission",
214
+ );
215
+ }
216
+ }
217
+
218
+ /** Step 1. Returns what to show; throws PairError("not-enabled") before any code exists when the feature is off. */
219
+ export async function beginPairing({ env, client, site }) {
220
+ requireHuman(env);
221
+ if (Object.keys(readDevices(env).devices).length >= MAX_DEVICES) {
222
+ throw new PairError("device-limit", `${MAX_DEVICES} devices are already paired`);
223
+ }
224
+ const verdict = lockoutVerdict(env);
225
+ if (!verdict.allowed) {
226
+ throw new PairError(
227
+ "locked-local",
228
+ `pairing is locked on this computer after a wrong number (${verdict.reason === "daily_cap" ? "daily limit reached" : "cooldown"}); try again in ${humanWait(verdict.waitMs)}`,
229
+ );
230
+ }
231
+ await requireEnabled(client);
232
+ if (readPending(env)) await cancelPairing({ env, client });
233
+
234
+ const secret = newPairingSecret();
235
+ const { lookup } = pairingKeys(secret);
236
+ const machine = generateEcdhKeyPair();
237
+ const { status, json } = await call(client, "pair/start", {
238
+ lookup,
239
+ machinePub: b64uEncode(machine.publicRaw),
240
+ });
241
+ if (status !== 200 || !json) throw mapStatus(status, json);
242
+
243
+ const { pairingId, userId, machineId, machineName, rpId, expiresAt, pairUrl } = json;
244
+ for (const v of [pairingId, userId, machineId]) {
245
+ if (typeof v !== "string" || !ID.test(v))
246
+ throw new PairError("site-invalid", "the site's pairing answer is malformed");
247
+ }
248
+ const phonePage = phonePageOf(pairUrl, rpId, site);
249
+ const siteExpiry = Date.parse(expiresAt);
250
+ const expires = Math.min(
251
+ Number.isFinite(siteExpiry) ? siteExpiry : Infinity,
252
+ Date.now() + PAIRING_TTL_MS,
253
+ );
254
+
255
+ writePending(env, {
256
+ v: 1,
257
+ stage: "waiting",
258
+ expiresAt: expires,
259
+ secret: secret.toString("hex"),
260
+ machinePrivate: machine.privateKey.toString("hex"),
261
+ machinePub: b64uEncode(machine.publicRaw),
262
+ pairingId,
263
+ userId,
264
+ machineId,
265
+ rpId,
266
+ origin: phonePage.origin,
267
+ });
268
+ const code = formatPairingCode(secret);
269
+ return {
270
+ code,
271
+ url: `${phonePage.base}#p=${code}`,
272
+ expiresAt: new Date(expires).toISOString(),
273
+ machineName: safeName(machineName, 64),
274
+ };
275
+ }
276
+
277
+ function checkRegistered(json) {
278
+ const { deviceId, label, phonePub, credentialId, credentialPublicKey, signCount } = json;
279
+ if (typeof deviceId !== "string" || !ID.test(deviceId))
280
+ throw new PairError("site-invalid", "device id");
281
+ let phone;
282
+ let cred;
283
+ let cose;
284
+ try {
285
+ phone = b64uDecode(phonePub);
286
+ cred = b64uDecode(credentialId);
287
+ cose = b64uDecode(credentialPublicKey);
288
+ publicKeyFromCose(cose);
289
+ } catch (err) {
290
+ if (err instanceof WebAuthnError || err?.name === "WireError") {
291
+ throw new PairError("site-invalid", "the phone's key or passkey is not acceptable");
292
+ }
293
+ throw err;
294
+ }
295
+ if (!validPublicRaw(phone))
296
+ throw new PairError("site-invalid", "the phone's key is not a P-256 point");
297
+ if (cred.length < 16 || cred.length > 255)
298
+ throw new PairError("site-invalid", "credential id length");
299
+ if (!Number.isInteger(signCount) || signCount < 0 || signCount > 0xffffffff) {
300
+ throw new PairError("site-invalid", "the passkey counter at registration is missing");
301
+ }
302
+ return { deviceId, label: safeName(label, 40), phone, cred, cose, signCount };
303
+ }
304
+
305
+ /**
306
+ * Step 2. Waits up to `timeoutMs` for the phone. Resolves to
307
+ * { state: "waiting" | "registered", label? }; anything else throws.
308
+ */
309
+ export async function waitPairing({ env, client, timeoutMs = 90_000, onTick = () => {} }) {
310
+ requireHuman(env);
311
+ const pending = readPending(env);
312
+ if (!pending)
313
+ throw new PairError("no-pending", "there is no pairing in progress (or it expired)");
314
+ if (pending.stage === "registered") return { state: "registered", label: pending.reg.label };
315
+
316
+ const until = Date.now() + timeoutMs;
317
+ for (;;) {
318
+ const remaining = Math.min(until, pending.expiresAt) - Date.now();
319
+ if (remaining <= 0) {
320
+ if (Date.now() >= pending.expiresAt) {
321
+ dropPending(env);
322
+ throw new PairError("expired", "the code expired");
323
+ }
324
+ return { state: "waiting" };
325
+ }
326
+ const waitMs = Math.min(20_000, remaining);
327
+ const { status, json } = await call(
328
+ client,
329
+ "pair/wait",
330
+ { pairingId: pending.pairingId, waitMs },
331
+ { waitMs },
332
+ );
333
+ if (status !== 200 || !json) {
334
+ dropPending(env);
335
+ throw mapStatus(status, json);
336
+ }
337
+ if (json.state === "registered") {
338
+ let reg;
339
+ try {
340
+ reg = checkRegistered(json);
341
+ } catch (err) {
342
+ await cancelPairing({ env, client });
343
+ throw err;
344
+ }
345
+ writePending(env, {
346
+ ...pending,
347
+ stage: "registered",
348
+ reg: {
349
+ deviceId: reg.deviceId,
350
+ label: reg.label,
351
+ phonePub: b64uEncode(reg.phone),
352
+ credentialId: b64uEncode(reg.cred),
353
+ credentialPublicKey: b64uEncode(reg.cose),
354
+ signCount: reg.signCount,
355
+ },
356
+ });
357
+ return { state: "registered", label: reg.label };
358
+ }
359
+ if (
360
+ json.state === "expired" ||
361
+ json.state === "rejected" ||
362
+ json.state === "superseded" ||
363
+ json.state === "bound"
364
+ ) {
365
+ dropPending(env);
366
+ throw new PairError(
367
+ json.state === "expired" ? "expired" : "rejected",
368
+ `the pairing is ${json.state}`,
369
+ );
370
+ }
371
+ onTick(json.state);
372
+ }
373
+ }
374
+
375
+ const sameDigits = (a, b) =>
376
+ a.length === b.length && timingSafeEqual(Buffer.from(a), Buffer.from(b));
377
+
378
+ /**
379
+ * Step 3. `typed` is what the person read off the phone. Resolves to
380
+ * { paired: true, deviceId, label }; throws PairError("mismatch") after
381
+ * rejecting the pairing when the number differs.
382
+ */
383
+ export async function confirmPairing(args) {
384
+ try {
385
+ return await confirmStep(args);
386
+ } catch (err) {
387
+ const retryable =
388
+ err instanceof PairError && (err.code === "format" || err.code === "not-ready");
389
+ if (!retryable) dropPending(args.env);
390
+ throw err;
391
+ }
392
+ }
393
+
394
+ async function confirmStep({ env, client, typed }) {
395
+ requireHuman(env);
396
+ const pending = readPending(env);
397
+ if (!pending || pending.stage !== "registered") {
398
+ throw new PairError("not-ready", "the phone has not registered yet; run the wait step first");
399
+ }
400
+ const digits = String(typed ?? "").trim();
401
+ if (!SAS_PATTERN.test(digits)) throw new PairError("format", "that is not a confirmation number");
402
+
403
+ const reg = pending.reg;
404
+ const phone = b64uDecode(reg.phonePub);
405
+ const transcript = transcriptHash({
406
+ pairingId: pending.pairingId,
407
+ deviceId: reg.deviceId,
408
+ userId: pending.userId,
409
+ machineId: pending.machineId,
410
+ rpId: pending.rpId,
411
+ machinePub: b64uDecode(pending.machinePub),
412
+ phonePub: phone,
413
+ credentialId: b64uDecode(reg.credentialId),
414
+ credentialPublicKey: b64uDecode(reg.credentialPublicKey),
415
+ });
416
+ const expected = sasText(pairingKeys(Buffer.from(pending.secret, "hex")).sasKey, transcript);
417
+
418
+ if (!sameDigits(digits, expected)) {
419
+ await call(client, "pair/confirm", {
420
+ pairingId: pending.pairingId,
421
+ accept: false,
422
+ reason: "mismatch",
423
+ }).catch(() => {});
424
+ dropPending(env);
425
+ audit(env, { device: reg.deviceId, outcome: "pair-mismatch" });
426
+ const { verdict } = recordMismatch(env);
427
+ throw new PairError(
428
+ "mismatch",
429
+ `the number does not match; the pairing was rejected. Someone may be interfering with this pairing. Do not retry unless you started it yourself; the next attempt is blocked for ${humanWait(verdict.waitMs)}.`,
430
+ );
431
+ }
432
+
433
+ if (readDevices(env).devices[reg.deviceId]) {
434
+ await call(client, "pair/confirm", {
435
+ pairingId: pending.pairingId,
436
+ accept: false,
437
+ reason: "cancel",
438
+ }).catch(() => {});
439
+ throw new PairError(
440
+ "device-exists",
441
+ "a device with this id is already paired; revoke it first (pair --revoke) and pair again",
442
+ );
443
+ }
444
+ recordMatch(env);
445
+ const keys = deriveSessionKeys(Buffer.from(pending.machinePrivate, "hex"), phone, transcript);
446
+ const { status, json } = await call(client, "pair/confirm", {
447
+ pairingId: pending.pairingId,
448
+ accept: true,
449
+ });
450
+ if (status !== 200 || !json || json.state !== "bound" || json.deviceId !== reg.deviceId) {
451
+ dropPending(env);
452
+ throw status === 200
453
+ ? new PairError("site-error", "the site did not bind the device")
454
+ : mapStatus(status, json);
455
+ }
456
+ pinDevice(env, reg.deviceId, {
457
+ label: reg.label,
458
+ userId: pending.userId,
459
+ machineId: pending.machineId,
460
+ rpId: pending.rpId,
461
+ origin: pending.origin,
462
+ credentialId: reg.credentialId,
463
+ credentialPublicKey: reg.credentialPublicKey,
464
+ phonePub: reg.phonePub,
465
+ lastCounter: reg.signCount,
466
+ keys: { p2m: b64uEncode(keys.p2m), m2p: b64uEncode(keys.m2p), tag: b64uEncode(keys.tag) },
467
+ });
468
+ dropPending(env);
469
+ audit(env, { device: reg.deviceId, outcome: "paired" });
470
+ return { paired: true, deviceId: reg.deviceId, label: reg.label };
471
+ }
472
+
473
+ /** Abandons a pending pairing; tells the site when it can, and always forgets the local secret. */
474
+ export async function cancelPairing({ env, client }) {
475
+ const pending = readPending(env);
476
+ dropPending(env);
477
+ if (!pending) return { cancelled: false };
478
+ await call(client, "pair/confirm", {
479
+ pairingId: pending.pairingId,
480
+ accept: false,
481
+ reason: "cancel",
482
+ }).catch(() => {});
483
+ audit(env, { outcome: "pair-cancelled" });
484
+ return { cancelled: true };
485
+ }
486
+
487
+ /** The devices pinned here, without keys. */
488
+ export function listPinned(env) {
489
+ return Object.entries(readDevices(env).devices).map(([id, d]) => ({
490
+ id,
491
+ label: safeName(d.label, 40),
492
+ pairedAt: d.pairedAt,
493
+ machineId: d.machineId,
494
+ rpId: d.rpId,
495
+ }));
496
+ }
497
+
498
+ /** Forgets one device here, by id or a unique prefix of at least 4 characters. */
499
+ export function revokeDevice(env, ref) {
500
+ const matches = Object.keys(readDevices(env).devices).filter(
501
+ (id) => id === ref || (ref.length >= 4 && id.startsWith(ref)),
502
+ );
503
+ if (matches.length !== 1) {
504
+ throw new PairError(
505
+ matches.length ? "ambiguous" : "unknown-device",
506
+ matches.length ? "more than one device matches" : "no such device",
507
+ );
508
+ }
509
+ removeDevice(env, matches[0]);
510
+ audit(env, { device: matches[0], outcome: "revoked", reason: "local" });
511
+ return matches[0];
512
+ }
513
+
514
+ /** Forgets every device and any pending pairing. Works offline. */
515
+ export function forgetEverything(env) {
516
+ removeAllDevices(env);
517
+ dropPending(env);
518
+ audit(env, { outcome: "off" });
519
+ }