@blackbelt-technology/pi-agent-dashboard 0.10.0 → 0.11.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 (255) hide show
  1. package/AGENTS.md +2 -2
  2. package/README.md +47 -6
  3. package/docs/architecture.md +1369 -63
  4. package/package.json +14 -9
  5. package/packages/extension/package.json +5 -3
  6. package/packages/extension/src/bridge-handlers/dispatch.ts +57 -3
  7. package/packages/extension/src/bridge-handlers/instance.ts +10 -1
  8. package/packages/extension/src/bridge-handlers/lifecycle.ts +65 -26
  9. package/packages/extension/src/bridge-ticket-client.ts +61 -7
  10. package/packages/extension/src/bridge-tls-checks.ts +79 -0
  11. package/packages/extension/src/bridge.ts +41 -28
  12. package/packages/extension/src/canvas-tool.ts +2 -0
  13. package/packages/extension/src/command-handler.ts +80 -6
  14. package/packages/extension/src/connect-target.ts +23 -0
  15. package/packages/extension/src/connection.ts +30 -7
  16. package/packages/extension/src/dashboard-http-origin.ts +88 -0
  17. package/packages/extension/src/dev-build.ts +11 -1
  18. package/packages/extension/src/git-link-builder.ts +11 -2
  19. package/packages/extension/src/inbound-limits.ts +138 -0
  20. package/packages/extension/src/local-token-header.ts +77 -6
  21. package/packages/extension/src/model-refresh.ts +69 -0
  22. package/packages/extension/src/pinned-endpoint.ts +44 -0
  23. package/packages/extension/src/project-trust-live.ts +143 -0
  24. package/packages/extension/src/project-trust.ts +159 -20
  25. package/packages/extension/src/provider-register.ts +59 -18
  26. package/packages/extension/src/remote-registration-gate.ts +21 -21
  27. package/packages/extension/src/remote-upgrade-preparer.ts +104 -0
  28. package/packages/extension/src/role-model-tools.ts +47 -6
  29. package/packages/extension/src/server-auto-start.ts +1 -1
  30. package/packages/extension/src/server-proof-probe.ts +117 -0
  31. package/packages/extension/src/session-sync.ts +42 -12
  32. package/packages/extension/src/vault-delivery.ts +11 -1
  33. package/packages/server/package.json +8 -8
  34. package/packages/server/src/access/access-grants.ts +61 -8
  35. package/packages/server/src/access/access-health.ts +10 -0
  36. package/packages/server/src/access/access-plane.ts +5 -1
  37. package/packages/server/src/access/containment-gate.ts +55 -17
  38. package/packages/server/src/access/cwd-verdict.ts +3 -3
  39. package/packages/server/src/access/pi-trust-live.ts +244 -0
  40. package/packages/server/src/access/pi-trust-mirror-service.ts +44 -11
  41. package/packages/server/src/access/planes.ts +106 -1
  42. package/packages/server/src/access/preview-egress-store.ts +153 -0
  43. package/packages/server/src/access/prompt-channel.ts +5 -0
  44. package/packages/server/src/access/provisioning-wiring.ts +113 -0
  45. package/packages/server/src/access/provisioning.ts +763 -0
  46. package/packages/server/src/access/yolo-session.ts +54 -2
  47. package/packages/server/src/acp-bridge/acp-session-adapter.ts +8 -3
  48. package/packages/server/src/agent-events/agent-event-hub.ts +158 -0
  49. package/packages/server/src/auth/audit-log.ts +80 -0
  50. package/packages/server/src/auth/auth-plugin.ts +44 -25
  51. package/packages/server/src/auth/auth.ts +24 -4
  52. package/packages/server/src/auth/bearer-auth.ts +52 -12
  53. package/packages/server/src/auth/cors-origin.ts +76 -29
  54. package/packages/server/src/auth/csp-report-paths.ts +31 -0
  55. package/packages/server/src/auth/csp-report-sink.ts +302 -0
  56. package/packages/server/src/auth/csp-report-store.ts +406 -0
  57. package/packages/server/src/auth/csp.ts +105 -9
  58. package/packages/server/src/auth/dashboard-credential-store.ts +4 -0
  59. package/packages/server/src/auth/dashboard-state-caller.ts +29 -0
  60. package/packages/server/src/auth/local-proof-refusal-log.ts +89 -0
  61. package/packages/server/src/auth/local-proof.ts +69 -18
  62. package/packages/server/src/auth/localhost-guard.ts +48 -10
  63. package/packages/server/src/auth/nav-intent.ts +72 -0
  64. package/packages/server/src/auth/passkey/passkey-assets.ts +99 -0
  65. package/packages/server/src/auth/passkey/passkey-pages.ts +17 -81
  66. package/packages/server/src/auth/passkey/passkey-routes.ts +8 -0
  67. package/packages/server/src/auth/pi-legacy-credentials.ts +3 -0
  68. package/packages/server/src/auth/plugin-server-trust.ts +29 -0
  69. package/packages/server/src/auth/plugin-trust-store.ts +103 -0
  70. package/packages/server/src/auth/proven-tls.ts +45 -0
  71. package/packages/server/src/auth/provider-auth-storage.ts +6 -1
  72. package/packages/server/src/auth/radius-mcp.ts +1 -1
  73. package/packages/server/src/auth/request-principal.ts +32 -0
  74. package/packages/server/src/auth/secret-rotation.ts +246 -0
  75. package/packages/server/src/auth/secure-origin.ts +56 -0
  76. package/packages/server/src/auth/serve-app-host.ts +111 -11
  77. package/packages/server/src/auth/ws-ticket.ts +39 -1
  78. package/packages/server/src/auth/ws-upgrade-reject-log.ts +4 -1
  79. package/packages/server/src/browser-handlers/directory-handler.ts +23 -0
  80. package/packages/server/src/browser-handlers/folder-gate.ts +55 -0
  81. package/packages/server/src/browser-handlers/handler-context.ts +25 -2
  82. package/packages/server/src/browser-handlers/session-action-handler.ts +9 -1
  83. package/packages/server/src/browser-handlers/subscription-handler.ts +100 -2
  84. package/packages/server/src/browser-handlers/terminal-handler.ts +108 -10
  85. package/packages/server/src/canvas/canvas-accumulator.ts +35 -7
  86. package/packages/server/src/cli.ts +210 -39
  87. package/packages/server/src/config-api.ts +23 -1
  88. package/packages/server/src/config-snapshot.ts +48 -1
  89. package/packages/server/src/directory-service.ts +160 -54
  90. package/packages/server/src/event-wiring.ts +143 -108
  91. package/packages/server/src/git-worktree/git-operations.ts +44 -10
  92. package/packages/server/src/git-worktree/redact-git-text.ts +124 -0
  93. package/packages/server/src/git-worktree/ref-arg.ts +39 -0
  94. package/packages/server/src/git-worktree/worktree-init-trust.ts +43 -1
  95. package/packages/server/src/identity/http-road-classification.ts +13 -1
  96. package/packages/server/src/identity/ws-message-scope.ts +1 -0
  97. package/packages/server/src/identity/ws-road-classification.ts +1 -0
  98. package/packages/server/src/known-server-moves.ts +36 -15
  99. package/packages/server/src/lib/browse-roots.ts +118 -17
  100. package/packages/server/src/lib/client-dist.ts +36 -21
  101. package/packages/server/src/lib/dashboard-state-guard.ts +230 -0
  102. package/packages/server/src/lib/diagram-render.ts +4 -6
  103. package/packages/server/src/lib/eml.ts +3 -8
  104. package/packages/server/src/lib/file-cwd-admission.ts +145 -0
  105. package/packages/server/src/lib/grep-worker.ts +23 -0
  106. package/packages/server/src/lib/grep.ts +93 -7
  107. package/packages/server/src/lib/index-html.ts +81 -0
  108. package/packages/server/src/lib/office-preview.ts +2 -3
  109. package/packages/server/src/lib/path-containment.ts +7 -0
  110. package/packages/server/src/lib/resolve-file-mention.ts +11 -9
  111. package/packages/server/src/lib/route-admission.ts +80 -0
  112. package/packages/server/src/lib/writable-md-target.ts +4 -0
  113. package/packages/server/src/lifecycle/recovery-server.ts +65 -18
  114. package/packages/server/src/live-server/capability-redact.ts +15 -0
  115. package/packages/server/src/live-server/live-browser-gate.ts +22 -0
  116. package/packages/server/src/live-server/live-capability.ts +224 -17
  117. package/packages/server/src/live-server/live-csp-report.ts +63 -0
  118. package/packages/server/src/live-server/live-csp.ts +93 -0
  119. package/packages/server/src/live-server/live-egress.ts +435 -0
  120. package/packages/server/src/live-server/live-exposure.ts +149 -0
  121. package/packages/server/src/live-server/live-log.ts +21 -0
  122. package/packages/server/src/live-server/live-origin-scan.ts +298 -0
  123. package/packages/server/src/live-server/live-server-manager.ts +209 -33
  124. package/packages/server/src/live-server/live-server-proxy.ts +162 -17
  125. package/packages/server/src/live-server/live-static.ts +228 -0
  126. package/packages/server/src/openspec/dependencies-file.ts +122 -0
  127. package/packages/server/src/openspec/openspec-change-watcher.ts +3 -1
  128. package/packages/server/src/openspec/openspec-dependency-inputs.ts +281 -0
  129. package/packages/server/src/openspec/openspec-poll-fs-helpers.ts +72 -26
  130. package/packages/server/src/openspec/openspec-poll-worker-pool.ts +48 -12
  131. package/packages/server/src/openspec/openspec-poll-worker.ts +95 -9
  132. package/packages/server/src/openspec/workflow-schema-status.ts +379 -0
  133. package/packages/server/src/openspec/workflow-schema.ts +141 -267
  134. package/packages/server/src/package/npm-search-proxy.ts +5 -2
  135. package/packages/server/src/package/provider-probe.ts +8 -2
  136. package/packages/server/src/pairing/browser-gateway.ts +188 -12
  137. package/packages/server/src/pairing/device-token-services.ts +26 -0
  138. package/packages/server/src/pairing/paired-devices.ts +335 -22
  139. package/packages/server/src/pairing/pairing.ts +34 -4
  140. package/packages/server/src/pairing/socket-locality.ts +26 -0
  141. package/packages/server/src/persistence/preferences-store.ts +9 -0
  142. package/packages/server/src/pi/bridge-channel.ts +33 -0
  143. package/packages/server/src/pi/bridge-upgrade-auth.ts +18 -3
  144. package/packages/server/src/pi/gateway-listeners.ts +9 -3
  145. package/packages/server/src/pi/host-project-trust.ts +14 -6
  146. package/packages/server/src/pi/pi-gateway.ts +191 -21
  147. package/packages/server/src/pi/resource-toggle-trust.ts +1 -1
  148. package/packages/server/src/plugin-discovery-wiring.ts +142 -0
  149. package/packages/server/src/plugin-event-seam.ts +116 -4
  150. package/packages/server/src/plugin-runtime-clients.ts +89 -0
  151. package/packages/server/src/routes/access-routes.ts +159 -9
  152. package/packages/server/src/routes/agent-event-stream-routes.ts +137 -0
  153. package/packages/server/src/routes/canvas-types-routes.ts +20 -6
  154. package/packages/server/src/routes/csp-violations-routes.ts +162 -0
  155. package/packages/server/src/routes/file-routes.ts +329 -209
  156. package/packages/server/src/routes/file-write-binary-routes.ts +77 -20
  157. package/packages/server/src/routes/folder-project-routes.ts +18 -12
  158. package/packages/server/src/routes/git-routes.ts +319 -203
  159. package/packages/server/src/routes/grep-routes.ts +38 -14
  160. package/packages/server/src/routes/known-servers-routes.ts +189 -91
  161. package/packages/server/src/routes/live-server-routes.ts +378 -15
  162. package/packages/server/src/routes/local-proof-routes.ts +14 -0
  163. package/packages/server/src/routes/nav-intent-routes.ts +46 -0
  164. package/packages/server/src/routes/openspec-group-routes.ts +53 -44
  165. package/packages/server/src/routes/openspec-routes.ts +379 -28
  166. package/packages/server/src/routes/package-routes.ts +58 -10
  167. package/packages/server/src/routes/pairing-routes.ts +146 -10
  168. package/packages/server/src/routes/pi-trust-query-routes.ts +330 -0
  169. package/packages/server/src/routes/plugin-activation-routes.ts +59 -0
  170. package/packages/server/src/routes/plugin-runtime-client-routes.ts +149 -0
  171. package/packages/server/src/routes/provider-auth-routes.ts +15 -2
  172. package/packages/server/src/routes/resource-activation-routes.ts +18 -4
  173. package/packages/server/src/routes/session-routes.ts +51 -4
  174. package/packages/server/src/routes/system-routes.ts +84 -15
  175. package/packages/server/src/routes/ui-link-base.ts +88 -0
  176. package/packages/server/src/runtime-overlay/runtime-io.ts +2 -9
  177. package/packages/server/src/server.ts +648 -137
  178. package/packages/server/src/session/hydration-state.ts +148 -0
  179. package/packages/server/src/session/memory-session-manager.ts +7 -0
  180. package/packages/server/src/session/replay-exit-controller.ts +221 -0
  181. package/packages/server/src/session/retained-transcript.ts +9 -2
  182. package/packages/server/src/session/session-load-worker.ts +11 -2
  183. package/packages/server/src/spawn-process/headless-pid-registry.ts +14 -9
  184. package/packages/server/src/terminal/terminal-manager.ts +54 -46
  185. package/packages/server/src/tls/tls-bridge-route.ts +61 -0
  186. package/packages/server/src/tls/tls-config-validation.ts +2 -0
  187. package/packages/server/src/vault/device-expiry-sweep.ts +36 -0
  188. package/packages/server/src/vault/vault-delivery-hub.ts +155 -25
  189. package/packages/server/src/watch-files-handler.ts +66 -0
  190. package/packages/shared/package.json +1 -1
  191. package/packages/shared/src/browser-protocol.ts +148 -2
  192. package/packages/shared/src/canvas-declare.ts +27 -0
  193. package/packages/shared/src/config.ts +372 -53
  194. package/packages/shared/src/containment-guard.ts +35 -0
  195. package/packages/shared/src/dashboard-plugin/anthropic-peer-names.ts +9 -0
  196. package/packages/shared/src/dashboard-plugin/event-type-owners.ts +50 -0
  197. package/packages/shared/src/dashboard-plugin/file-handler.ts +2 -0
  198. package/packages/shared/src/dashboard-plugin/host-api.ts +61 -0
  199. package/packages/shared/src/dashboard-plugin/host-fx-classes.ts +23 -0
  200. package/packages/shared/src/dashboard-plugin/host-import-map.ts +38 -0
  201. package/packages/shared/src/dashboard-plugin/index.ts +2 -0
  202. package/packages/shared/src/dashboard-plugin/manifest-types.ts +54 -1
  203. package/packages/shared/src/dashboard-plugin/plugin-status.ts +54 -0
  204. package/packages/shared/src/dashboard-plugin/slot-props.ts +45 -3
  205. package/packages/shared/src/dashboard-plugin/slot-types.ts +8 -0
  206. package/packages/shared/src/dashboard-plugin/subagent-types.ts +219 -0
  207. package/packages/shared/src/dashboard-plugin/ui-primitives.ts +28 -0
  208. package/packages/shared/src/display-prefs.ts +13 -0
  209. package/packages/shared/src/doctor-core.ts +94 -27
  210. package/packages/shared/src/live-server.ts +141 -0
  211. package/packages/shared/src/local-proof-signal.ts +16 -0
  212. package/packages/shared/src/loopback-host.ts +26 -0
  213. package/packages/shared/src/mcp/verb-tiers.generated.ts +178 -0
  214. package/packages/shared/src/mdns-discovery.ts +25 -6
  215. package/packages/shared/src/nav-intent.ts +29 -0
  216. package/packages/shared/src/openspec-dependencies.ts +760 -0
  217. package/packages/shared/src/openspec-poller.ts +3 -2
  218. package/packages/shared/src/pairing-knock-client.ts +44 -4
  219. package/packages/shared/src/pi-trust-live-query.ts +93 -0
  220. package/packages/shared/src/pi-trust-mirror-snapshot.ts +5 -7
  221. package/packages/shared/src/pi-trust-mirror-types.ts +36 -3
  222. package/packages/shared/src/pi-trust-mirror.ts +29 -3
  223. package/packages/shared/src/pi-trust-resource-digest.ts +255 -0
  224. package/packages/shared/src/platform/ensure-bundled-git.ts +57 -34
  225. package/packages/shared/src/platform/git-source.ts +88 -26
  226. package/packages/shared/src/platform/git.ts +14 -8
  227. package/packages/shared/src/platform/process.ts +48 -4
  228. package/packages/shared/src/platform/resolve-pi-shell.ts +76 -0
  229. package/packages/shared/src/platform/select-git-source.ts +7 -0
  230. package/packages/shared/src/plugin-route-cwd.ts +95 -0
  231. package/packages/shared/src/preview-egress.ts +138 -0
  232. package/packages/shared/src/project-root.ts +16 -0
  233. package/packages/shared/src/protocol.ts +40 -1
  234. package/packages/shared/src/recommended-extensions.ts +18 -0
  235. package/packages/shared/src/recovery-timing.ts +27 -0
  236. package/packages/shared/src/remote-credentials.ts +63 -0
  237. package/packages/shared/src/rest-api.ts +55 -8
  238. package/packages/shared/src/route-tiers.ts +55 -1
  239. package/packages/shared/src/runtime-overlay/archive-safety.d.mts +2 -0
  240. package/packages/shared/src/runtime-overlay/archive-safety.mjs +33 -0
  241. package/packages/shared/src/runtime-overlay/manifest.d.mts +7 -0
  242. package/packages/shared/src/runtime-overlay/manifest.mjs +22 -2
  243. package/packages/shared/src/safe-local-path.ts +24 -0
  244. package/packages/shared/src/sanitize-profiles.ts +98 -0
  245. package/packages/shared/src/server-launcher.ts +9 -1
  246. package/packages/shared/src/server-pinning.ts +55 -2
  247. package/packages/shared/src/server-routes.ts +462 -0
  248. package/packages/shared/src/session-ui-path.ts +11 -0
  249. package/packages/shared/src/tls-only-token.ts +16 -0
  250. package/packages/shared/src/tool-registry/definitions.ts +5 -5
  251. package/packages/shared/src/tool-registry/strategies.ts +12 -11
  252. package/packages/shared/src/types.ts +66 -0
  253. package/packages/shared/src/url-policy.ts +96 -0
  254. package/packages/shared/src/vault-delivery.ts +15 -0
  255. package/packages/shared/src/ws-message-tiers.ts +1 -0
@@ -27,6 +27,8 @@ import type { GitStatus } from "@blackbelt-technology/pi-dashboard-shared/types.
27
27
  // are otherwise un-spyable). `pruneWorktrees` calls `self.resolveMainPath`.
28
28
  // See change: support-non-git-init-hook.
29
29
  import * as self from "./git-operations.js";
30
+ import { redactGitText } from "./redact-git-text.js";
31
+ import { assertRefArg, isValidRefArg } from "./ref-arg.js";
30
32
  import {
31
33
  ensureWorktreeExcludeLine,
32
34
  isOrphanWorktreePath,
@@ -325,12 +327,12 @@ export async function commitFiles(opts: {
325
327
 
326
328
  const staged = await runGitCapture(["add", "--", ...safePaths], cwd);
327
329
  if (staged.code !== 0) {
328
- throw new GitCommitError("stage-failed", staged.stderr.trim() || "git add failed");
330
+ throw new GitCommitError("stage-failed", redactGitText(staged.stderr.trim() || "git add failed", { root: cwd }));
329
331
  }
330
332
 
331
333
  const committed = await runGitCapture(["commit", "-F", "-", "--", ...safePaths], cwd, message);
332
334
  if (committed.code !== 0) {
333
- throw new GitCommitError("commit-failed", committed.stderr.trim() || "git commit failed");
335
+ throw new GitCommitError("commit-failed", redactGitText(committed.stderr.trim() || "git commit failed", { root: cwd }));
334
336
  }
335
337
 
336
338
  const head = await runGitCapture(["rev-parse", "HEAD"], cwd);
@@ -354,7 +356,7 @@ export async function getChangedFiles(cwd: string): Promise<GitChangedFile[]> {
354
356
  // Propagate a real git failure instead of masking it as "no changes". A
355
357
  // clean tree still exits 0 with empty stdout → `[]` below.
356
358
  if (statusRes.code !== 0) {
357
- throw new GitCommitError("not-a-repo", statusRes.stderr.trim() || "git status failed");
359
+ throw new GitCommitError("not-a-repo", redactGitText(statusRes.stderr.trim() || "git status failed", { root: cwd }));
358
360
  }
359
361
 
360
362
  const files: GitChangedFile[] = [];
@@ -480,12 +482,24 @@ export interface CheckoutDirty {
480
482
  files: string[];
481
483
  }
482
484
 
483
- /** Checkout a branch. Returns dirty info if working tree is dirty and stash=false. */
485
+ /**
486
+ * Checkout a branch. Returns dirty info if working tree is dirty and stash=false.
487
+ * Throws `InvalidRefError` (before ANY git process starts) when `branch`, or the local name
488
+ * derived from it by stripping the remote prefix, is not a safe positional git argument.
489
+ * See change: harden-git-terminal-plugin-boundaries (B1r).
490
+ */
484
491
  export function checkoutBranch(
485
492
  cwd: string,
486
493
  branch: string,
487
494
  stash: boolean
488
495
  ): CheckoutResult | CheckoutDirty {
496
+ assertRefArg(branch, "branch");
497
+ // Check if this is a remote branch that needs a local tracking branch
498
+ const isRemote = branch.includes("/");
499
+ const localName = isRemote ? branch.replace(/^[^/]+\//, "") : branch;
500
+ // The derived name reaches `git checkout [-b] <localName>`: validate it too (`origin/-x`, `origin/`).
501
+ if (isRemote) assertRefArg(localName, "local branch name");
502
+
489
503
  // Already on this branch?
490
504
  const headRef = tryRun(["git", "rev-parse", "--abbrev-ref", "HEAD"], cwd);
491
505
  if (headRef === branch) return { success: true };
@@ -502,10 +516,7 @@ export function checkoutBranch(
502
516
  stashed = true;
503
517
  }
504
518
 
505
- // Check if this is a remote branch that needs a local tracking branch
506
- const isRemote = branch.includes("/");
507
519
  if (isRemote) {
508
- const localName = branch.replace(/^[^/]+\//, "");
509
520
  // Check if local branch exists
510
521
  const localExists = tryRun(["git", "rev-parse", "--verify", `refs/heads/${localName}`], cwd);
511
522
  if (!localExists) {
@@ -691,6 +702,8 @@ export function pruneWorktrees(
691
702
  export type AddWorktreeError =
692
703
  | "not_a_repo"
693
704
  | "cwd_invalid"
705
+ /** A caller-supplied ref / path is option-like or has control characters (B1r). */
706
+ | "invalid_ref"
694
707
  | "branch_in_use"
695
708
  | "branch_exists"
696
709
  | "path_exists"
@@ -722,6 +735,10 @@ export interface AddWorktreeFailure {
722
735
  orphanLikely?: boolean;
723
736
  }
724
737
 
738
+ function invalidRef(what: string): { ok: false; error: "invalid_ref"; message: string } {
739
+ return { ok: false, error: "invalid_ref", message: `invalid ${what}` };
740
+ }
741
+
725
742
  export interface AddWorktreeOptions {
726
743
  /** Cwd inside the parent repo (any worktree's path resolves to the same parent). */
727
744
  cwd: string;
@@ -750,6 +767,12 @@ export interface AddWorktreeOptions {
750
767
  */
751
768
  export function addWorktree(opts: AddWorktreeOptions): AddWorktreeSuccess | AddWorktreeFailure {
752
769
  const { cwd, base, newBranch, force } = opts;
770
+ // B1r: every caller-supplied argument is validated before any git process starts. `path` is
771
+ // optional (absent → derived default); `newBranch` absent → checkout mode.
772
+ // See change: harden-git-terminal-plugin-boundaries.
773
+ if (!isValidRefArg(base)) return invalidRef("base");
774
+ if (newBranch !== undefined && !isValidRefArg(newBranch)) return invalidRef("newBranch");
775
+ if (opts.path !== undefined && opts.path !== "" && !isValidRefArg(opts.path)) return invalidRef("path");
753
776
  // Checkout mode = no newBranch. `base` is the existing branch ref to
754
777
  // check out. See change: worktree-checkout-existing-branch.
755
778
  const checkoutMode = newBranch === undefined;
@@ -780,6 +803,8 @@ export function addWorktree(opts: AddWorktreeOptions): AddWorktreeSuccess | AddW
780
803
  // branch name (bare name triggers DWIM for remote-only refs); fork mode
781
804
  // forks from `base`.
782
805
  const checkoutCommitish = resolvedBranch;
806
+ // The derived local name (`origin/-x` → `-x`) reaches git as a positional argument too.
807
+ if (!isValidRefArg(resolvedBranch)) return invalidRef("derived branch name");
783
808
  // Derive worktree path when not supplied. Fork mode slugs the new
784
809
  // branch name; checkout mode slugs the local name of the base ref so
785
810
  // `origin/foo` lands at `.worktrees/foo`, not `.worktrees/origin-foo`.
@@ -1275,7 +1300,8 @@ export function resolveDefaultBase(
1275
1300
 
1276
1301
  /** `resolveDefaultBase` that throws `GitMissingError` instead of swallowing a missing binary. */
1277
1302
  function resolveDefaultBaseStrict(cwd: string, hint?: string): string | null {
1278
- if (hint && tryRunStrict(["git", "rev-parse", "--verify", hint], cwd)) return hint;
1303
+ // B1r: a stored hint is untrusted (WS-supplied) — an option-like hint is ignored, never passed to git.
1304
+ if (isValidRefArg(hint) && tryRunStrict(["git", "rev-parse", "--verify", hint], cwd)) return hint;
1279
1305
  for (const name of BASE_FALLBACKS) {
1280
1306
  if (tryRunStrict(["git", "rev-parse", "--verify", `refs/heads/${name}`], cwd)) return name;
1281
1307
  }
@@ -1315,8 +1341,8 @@ export function resolveRemoteBase(
1315
1341
  /** `resolveRemoteBase` that throws `GitMissingError` instead of swallowing a missing binary. */
1316
1342
  function resolveRemoteBaseStrict(cwd: string, hint?: string): string | null {
1317
1343
  const stripOrigin = (n: string) => n.replace(/^origin\//, "");
1318
- const hintBare = hint ? stripOrigin(hint) : undefined;
1319
- if (hintBare && tryRunStrict(["git", "rev-parse", "--verify", `refs/remotes/origin/${hintBare}`], cwd)) {
1344
+ const hintBare = isValidRefArg(hint) ? stripOrigin(hint) : undefined;
1345
+ if (isValidRefArg(hintBare) && tryRunStrict(["git", "rev-parse", "--verify", `refs/remotes/origin/${hintBare}`], cwd)) {
1320
1346
  return hintBare;
1321
1347
  }
1322
1348
  for (const name of BASE_FALLBACKS) {
@@ -1645,6 +1671,7 @@ function computeOrphanLikely(cwd: string, worktreePath: string, mainPath?: strin
1645
1671
  }
1646
1672
 
1647
1673
  export type OrphanCleanupError =
1674
+ | "invalid_ref"
1648
1675
  | "outside_repo"
1649
1676
  | "not_a_directory"
1650
1677
  | "not_orphan"
@@ -1701,6 +1728,11 @@ export function orphanCleanup(
1701
1728
  const maxFiles = opts.maxFiles ?? 20;
1702
1729
  const maxFileSize = opts.maxFileSize ?? 1_048_576; // 1 MB
1703
1730
 
1731
+ // B1r: an option-like / control-character path is refused before anything touches git or the fs.
1732
+ if (!isValidRefArg(targetPath)) {
1733
+ return { ok: false, error: "invalid_ref", message: "invalid path" };
1734
+ }
1735
+
1704
1736
  // ── (i) Resolve the anchor: the RESOLVED main checkout (D6) — an orphan
1705
1737
  // can be cleaned from any worktree of the repo. `null` is a refusal.
1706
1738
  const repoRoot = resolveMainPath(cwd);
@@ -1955,6 +1987,8 @@ export function addWorktreeFromPr(opts: {
1955
1987
  path?: string;
1956
1988
  }): AddWorktreeFromPrSuccess | AddWorktreeFromPrFailure {
1957
1989
  const { cwd, prNumber } = opts;
1990
+ // B1r: an option-like `path` is refused before any git process starts.
1991
+ if (opts.path !== undefined && opts.path !== "" && !isValidRefArg(opts.path)) return invalidRef("path");
1958
1992
  // D2: one resolution proves repo-ness and anchors the derived path. The
1959
1993
  // refusal happens BEFORE any fetch — an unresolvable checkout never
1960
1994
  // touches the network.
@@ -0,0 +1,124 @@
1
+ /**
2
+ * Redaction of git-derived text (error / message / stderr) before it reaches a client.
3
+ *
4
+ * Rules, applied in this order:
5
+ * 1. strip URL userinfo from `http(s)://user:pw@host` (password-less `user@` too);
6
+ * `ssh://user:pw@host` keeps the user, drops the password; scp-form is untouched;
7
+ * 2. mask specific token shapes only (`sk-`, `ghp_`, `github_pat_`, `glpat-`, `Bearer`) to
8
+ * their prefix + `***` — deliberately NOT a generic long-blob rule, so 40-hex commit SHAs
9
+ * survive;
10
+ * 3. absolute paths under the operation's repository root become repo-relative (root → `.`);
11
+ * 4. absolute paths under the home directory become `~/…`;
12
+ * 5. any other absolute path (POSIX or drive-letter) becomes `<path>`.
13
+ *
14
+ * Pure and linear-time: every pattern is anchored on a literal prefix and uses bounded or
15
+ * single-pass character classes (no nested quantifiers). Never throws.
16
+ *
17
+ * See change: harden-git-terminal-plugin-boundaries (B20).
18
+ */
19
+
20
+ import os from "node:os";
21
+
22
+ export interface RedactContext {
23
+ /** The repository / worktree root the git operation ran in. Captured at operation time. */
24
+ root?: string;
25
+ /** Home directory (default: `os.homedir()`). Pass `""` to disable the `~` rule. */
26
+ home?: string;
27
+ }
28
+
29
+ /** `http(s)://[userinfo@]host` — userinfo runs to the LAST `@` of the authority (a raw `@` may sit in a password). */
30
+ const HTTP_USERINFO = /(https?:\/\/)[^\s/]*@/gi;
31
+ /** `ssh://user:password@host` → `ssh://user@host`. */
32
+ const SSH_PASSWORD = /(ssh:\/\/[^\s/:@]*):[^\s/]*@/gi;
33
+ /** Token shapes: prefix + >= 20 `[A-Za-z0-9_-]`, with a non-word character (or start) before the prefix. */
34
+ const TOKEN = /(?<![A-Za-z0-9_])(sk-|ghp_|github_pat_|glpat-)[A-Za-z0-9_-]{20,}/g;
35
+ const BEARER = /\b(Bearer)[ \t]+[A-Za-z0-9._~+/=-]+/gi;
36
+ /**
37
+ * An absolute path: POSIX `/…` after start / whitespace / an opening or quoting character (never
38
+ * after `:` or a word character, so `https://host/x`, `git@h:o/r.git` and `a/b` are not paths), or a
39
+ * drive-letter `D:\…` / `D:/…`. The body stops at whitespace, quotes, brackets and `:` so a
40
+ * `path:line:col` suffix survives.
41
+ */
42
+ const ABS_PATH =
43
+ /(?<=^|[\s"'`(\[{=,;<>|]|file:\/\/)\/[^\s"'`<>|*?:,;()[\]{}]*|(?<![A-Za-z0-9_])[A-Za-z]:[\\/][^\s"'`<>|*?:,;()[\]{}]*/g;
44
+ const TRAILING_PUNCT = /[.!?]+$/;
45
+
46
+ function stripTrailingSep(p: string): string {
47
+ return p.length > 1 ? p.replace(/[\\/]+$/, "") || p.slice(0, 1) : p;
48
+ }
49
+
50
+ /** If `p` is `base` or lies inside it, the remainder (without a leading separator); else `undefined`. */
51
+ function under(p: string, base: string | undefined): string | undefined {
52
+ if (!base) return undefined;
53
+ const b = stripTrailingSep(base);
54
+ if (b.length === 0) return undefined;
55
+ const windows = /^[A-Za-z]:/.test(b) || b.includes("\\");
56
+ const norm = (s: string) => (windows ? s.replace(/\\/g, "/").toLowerCase() : s);
57
+ const np = norm(p);
58
+ const nb = norm(b);
59
+ if (np === nb) return "";
60
+ const prefix = nb.endsWith("/") ? nb : `${nb}/`;
61
+ if (np.startsWith(prefix)) return p.slice(prefix.length);
62
+ return undefined;
63
+ }
64
+
65
+ function redactPath(p: string, root: string | undefined, home: string | undefined): string {
66
+ const rel = under(p, root);
67
+ if (rel !== undefined) return rel === "" ? "." : rel;
68
+ const homeRel = under(p, home);
69
+ if (homeRel !== undefined) return homeRel === "" ? "~" : `~/${homeRel}`;
70
+ return "<path>";
71
+ }
72
+
73
+ /** Best-effort text of an unknown thrown value (Error → message, string as is, else empty). */
74
+ export function gitErrorText(err: unknown): string {
75
+ if (typeof err === "string") return err;
76
+ if (err && typeof err === "object") {
77
+ const m = (err as { message?: unknown }).message;
78
+ if (typeof m === "string") return m;
79
+ }
80
+ return "";
81
+ }
82
+
83
+ function toText(input: unknown): string {
84
+ if (input === undefined || input === null) return "";
85
+ if (typeof input === "string") return input;
86
+ if (Buffer.isBuffer(input)) return input.toString("utf-8");
87
+ if (input instanceof Error) return input.message ?? "";
88
+ return gitErrorText(input);
89
+ }
90
+
91
+ function homeDir(ctx: RedactContext): string | undefined {
92
+ if (ctx.home !== undefined) return ctx.home || undefined;
93
+ try {
94
+ return os.homedir() || undefined;
95
+ } catch {
96
+ return undefined;
97
+ }
98
+ }
99
+
100
+ /** Redact `input` per the module rules. Never throws; `""`/nullish → `""`. */
101
+ export function redactGitText(input: unknown, ctx: RedactContext = {}): string {
102
+ try {
103
+ let text = toText(input);
104
+ if (text.length === 0) return "";
105
+ const root = ctx.root || undefined;
106
+ const home = homeDir(ctx);
107
+ if (text.includes("://")) {
108
+ text = text.replace(HTTP_USERINFO, "$1").replace(SSH_PASSWORD, "$1@");
109
+ }
110
+ text = text.replace(TOKEN, "$1***").replace(BEARER, "$1 ***");
111
+ if (text.includes("/") || text.includes(":\\")) {
112
+ text = text.replace(ABS_PATH, (match) => {
113
+ const tail = TRAILING_PUNCT.exec(match)?.[0] ?? "";
114
+ const body = tail ? match.slice(0, match.length - tail.length) : match;
115
+ if (body.length <= 1) return match; // a lone "/" is not a path
116
+ return redactPath(body, root, home) + tail;
117
+ });
118
+ }
119
+ return text;
120
+ } catch {
121
+ // Fail closed: never echo the unredacted text if redaction itself failed.
122
+ return "";
123
+ }
124
+ }
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Validator for caller-supplied git arguments (refs, commit-ishes, new branch names, base hints,
3
+ * worktree paths). A PRESENT value must be a non-empty string that does not begin with `-` and
4
+ * contains no C0 control character (0x00–0x1F) or DEL (0x7F); otherwise it could be parsed by git
5
+ * as an option (`--upload-pack=…`, `--orphan=…`) or smuggle a line break.
6
+ *
7
+ * The validator IS the control — no `--end-of-options`. Precedent: `packages/kb/src/sources.ts`.
8
+ *
9
+ * See change: harden-git-terminal-plugin-boundaries (B1r).
10
+ */
11
+
12
+ /** Stable error `code` carried by `InvalidRefError` and the HTTP 400 body. */
13
+ export const INVALID_REF_CODE = "invalid_ref";
14
+
15
+ export class InvalidRefError extends Error {
16
+ readonly code = INVALID_REF_CODE;
17
+ constructor(message = "invalid git ref") {
18
+ super(message);
19
+ this.name = "InvalidRefError";
20
+ }
21
+ }
22
+
23
+ const CONTROL_CHARS = /[\u0000-\u001f\u007f]/;
24
+
25
+ /** True iff `v` is a string safe to hand to git as a positional ref/path argument. */
26
+ export function isValidRefArg(v: unknown): v is string {
27
+ return typeof v === "string" && v.length > 0 && v.charCodeAt(0) !== 0x2d && !CONTROL_CHARS.test(v);
28
+ }
29
+
30
+ /** Returns `v` when valid, else throws `InvalidRefError`. */
31
+ export function assertRefArg(v: unknown, label = "ref"): string {
32
+ if (!isValidRefArg(v)) throw new InvalidRefError(`invalid ${label}`);
33
+ return v;
34
+ }
35
+
36
+ /** A required field that is absent, `null` or `""` (the endpoint's existing "missing parameter" case). */
37
+ export function isMissingArg(v: unknown): boolean {
38
+ return v === undefined || v === null || v === "";
39
+ }
@@ -43,6 +43,24 @@ export function setTrustChangedListener(fn: (() => void) | undefined): void {
43
43
  trustChanged = fn;
44
44
  }
45
45
 
46
+ /**
47
+ * Notified SYNCHRONOUSLY when the in-memory session set changes (record / revoke
48
+ * of a `session` entry). Separate from {@link setTrustChangedListener}: that one
49
+ * fires only after a persisted write, and a session entry must never reach disk.
50
+ * Feeds the pi-trust live count. See change: mirror-dashboard-trust-live-remote.
51
+ */
52
+ let sessionTrustChanged: (() => void) | undefined;
53
+ export function setSessionTrustChangedListener(fn: (() => void) | undefined): void {
54
+ sessionTrustChanged = fn;
55
+ }
56
+ function notifySessionTrustChanged(): void {
57
+ try {
58
+ sessionTrustChanged?.();
59
+ } catch {
60
+ /* a listener never fails a grant */
61
+ }
62
+ }
63
+
46
64
  /** Trust scope. `session` = memory-only; `project` = persisted JSON store. */
47
65
  export type TrustScope = "session" | "project";
48
66
 
@@ -106,6 +124,22 @@ export function listPersistedTrust(): Array<{ repoRoot: string; hash: string }>
106
124
  return out;
107
125
  }
108
126
 
127
+ /**
128
+ * The IN-MEMORY session entries as `{ repoRoot, hash }` ("until the dashboard
129
+ * restarts"). Live pi-trust source only: never persisted, never in the snapshot.
130
+ * Keys are `path.resolve`d; the live provider translates them to pi's key form.
131
+ * See change: mirror-dashboard-trust-live-remote.
132
+ */
133
+ export function listSessionTrust(): Array<{ repoRoot: string; hash: string }> {
134
+ const out: Array<{ repoRoot: string; hash: string }> = [];
135
+ for (const key of sessionTrust) {
136
+ const i = key.indexOf("\u0000");
137
+ if (i <= 0) continue;
138
+ out.push({ repoRoot: key.slice(0, i), hash: key.slice(i + 1) });
139
+ }
140
+ return out;
141
+ }
142
+
109
143
  /**
110
144
  * True iff trust was recorded for this `repoRoot + hash` in EITHER the in-memory
111
145
  * session set OR the persisted project store (OR-combine).
@@ -131,6 +165,7 @@ export function recordTrust(
131
165
  const key = trustKey(repoRoot, hash);
132
166
  if (scope === "session") {
133
167
  sessionTrust.add(key);
168
+ notifySessionTrustChanged();
134
169
  return;
135
170
  }
136
171
  const map = load();
@@ -162,7 +197,14 @@ export function revokeTrust(repoRoot: string, hash?: string, opts: { strict?: bo
162
197
  const matches = (key: string): boolean =>
163
198
  hash ? key === trustKey(repoRoot, hash) : key.startsWith(trustKey(repoRoot, ""));
164
199
 
165
- for (const key of [...sessionTrust]) if (matches(key)) sessionTrust.delete(key);
200
+ let sessionRemoved = false;
201
+ for (const key of [...sessionTrust]) {
202
+ if (matches(key)) {
203
+ sessionTrust.delete(key);
204
+ sessionRemoved = true;
205
+ }
206
+ }
207
+ if (sessionRemoved) notifySessionTrustChanged();
166
208
 
167
209
  const map = load();
168
210
  let changed = false;
@@ -124,9 +124,17 @@ const FAMILY_BY_SEGMENT: Readonly<Record<string, Family>> = {
124
124
  doctor: "system",
125
125
  "spawn-failures": "system",
126
126
  "live-server": "system",
127
+ // Trusted Types / CSP violation counters + signed navigation intents
128
+ // (change: harden-client-sinks).
129
+ "csp-violations": "system",
130
+ // Operator reset of the persisted baseline CSP report counters (change: harden-cors-and-csp-reporting).
131
+ "csp-reports": "system",
132
+ "nav-intent": "system",
127
133
  };
128
134
 
129
- const IDENTITY_ROUTES: ReadonlySet<string> = new Set(["/api/health", "/api/ws-ticket"]);
135
+ // `/api/pi-trust/query` is the bridge's own credentialed call, classified like the ticket mint
136
+ // (change: mirror-dashboard-trust-live-remote).
137
+ const IDENTITY_ROUTES: ReadonlySet<string> = new Set(["/api/health", "/api/ws-ticket", "/api/pi-trust/query"]);
130
138
 
131
139
  const verbOf = (method: string): "read" | "write" =>
132
140
  method.toUpperCase() === "GET" || method.toUpperCase() === "HEAD" ? "read" : "write";
@@ -179,6 +187,8 @@ export function classifyHttpRoad(
179
187
  return { road: "session-handler" }; // list, archived list, archived/:id
180
188
  }
181
189
  if (seg === "events" || seg === "session-change") {
190
+ // The agent event stream filters every event by owner itself (change: add-agent-event-stream).
191
+ if (seg === "events" && second === "stream") return { road: "session-handler" };
182
192
  return second === ":sessionId" ? { road: "session", param: "sessionId" } : undefined;
183
193
  }
184
194
  if (seg === "session-diff" || seg === "session-file") return { road: "session-handler" };
@@ -187,6 +197,8 @@ export function classifyHttpRoad(
187
197
  if (seg === "plugins") {
188
198
  if (second === undefined) return core("plugins", method, route);
189
199
  if (second === ":id") return core("plugins", method, route);
200
+ // The runtime-client listing is core plugin management, not a plugin named "runtime-clients".
201
+ if (second === "runtime-clients") return core("plugins", method, route);
190
202
  return plugin(second, method, route);
191
203
  }
192
204
  if (seg === "config" && second === "plugins") return core("plugins", method, route);
@@ -102,6 +102,7 @@ export const NON_SESSION_MESSAGES: ReadonlySet<string> = new Set([
102
102
  "pin_directory",
103
103
  "plugin_action",
104
104
  "plugin_config_write",
105
+ "provision_response",
105
106
  "recovery_dismiss",
106
107
  "remove_folder_from_workspace",
107
108
  "remove_tag_globally",
@@ -69,6 +69,7 @@ const WS_ROADS: Readonly<Record<string, readonly [HostAction, string]>> = {
69
69
  request_commands: ["packages.read", "packages"],
70
70
  // access
71
71
  grant_response: ["access.write", "access"],
72
+ provision_response: ["access.write", "access"],
72
73
  // system
73
74
  recovery_dismiss: ["system.write", "system"],
74
75
  // plugins (core management)
@@ -13,17 +13,25 @@
13
13
  * be on one of this server's own subnets and not loopback / link-local /
14
14
  * unspecified / multicast.
15
15
  *
16
- * See change: stabilize-mdns-server-identity (D6).
16
+ * An entry is evaluated on its PRIMARY route only (the first `http` route, else the
17
+ * first route — the `host`/`port` mirror): the stored address is re-proved in that
18
+ * route's own scheme and a suggestion moves that route alone; the entry's other
19
+ * routes are untouched. Peers found by mDNS are always `http`.
20
+ *
21
+ * See change: stabilize-mdns-server-identity (D6), group-servers-by-identity (D2).
17
22
  */
18
23
  import net from "node:net";
19
24
  import os from "node:os";
20
25
  import type { KnownServer } from "@blackbelt-technology/pi-dashboard-shared/config.js";
21
26
  import { formatHostPort, normalizeHostKey } from "@blackbelt-technology/pi-dashboard-shared/host-port.js";
22
27
  import type { DiscoveredServer } from "@blackbelt-technology/pi-dashboard-shared/mdns-discovery.js";
28
+ import { primaryRoute, type Route } from "@blackbelt-technology/pi-dashboard-shared/server-routes.js";
23
29
  import type { ProveResult } from "@blackbelt-technology/pi-dashboard-shared/server-pinning.js";
24
30
 
25
31
  /** Min gap between evaluations of one (fingerprint, port). */
26
32
  const MOVE_CHALLENGE_INTERVAL_MS = 60_000;
33
+ /** At most this many addresses of one advert are challenged per evaluation (a shared bridge address may answer as another machine). */
34
+ const MOVE_MAX_CHALLENGES = 4;
27
35
  /** A suggestion not re-verified for this long is withdrawn. */
28
36
  const MOVE_SUGGESTION_TTL_MS = 10 * 60_000;
29
37
 
@@ -58,6 +66,8 @@ export interface KnownServerMoves {
58
66
  }
59
67
 
60
68
  const keyOf = (fingerprint: string, port: number) => `${fingerprint}|${port}`;
69
+ /** The entry's primary route (`routes` is never empty: `parseKnownServers` guarantees one). */
70
+ const primaryOf = (entry: KnownServer): Route => primaryRoute(entry.routes) as Route;
61
71
  const short = (fingerprint: string) => fingerprint.replace(/^sha256:/, "").slice(0, 16);
62
72
 
63
73
  function isSpecial(address: string): boolean {
@@ -109,11 +119,11 @@ export function createKnownServerMoves(deps: KnownServerMovesDeps): KnownServerM
109
119
  }
110
120
  };
111
121
 
112
- /** First advertised address that is safe and on-link to challenge. */
113
- const challengeableAddress = (peer: DiscoveredServer): string | undefined => {
122
+ /** Advertised addresses that are safe and on-link to challenge, in advert order. */
123
+ const challengeableAddresses = (peer: DiscoveredServer): string[] => {
114
124
  const candidates = peer.addresses?.length ? peer.addresses : net.isIP(peer.host) ? [peer.host] : [];
115
125
  const ifaces = interfaces();
116
- return candidates.find((a) => net.isIP(a) && !isSpecial(a) && isOnLink(a, ifaces));
126
+ return candidates.filter((a) => net.isIP(a) && !isSpecial(a) && isOnLink(a, ifaces));
117
127
  };
118
128
 
119
129
  return {
@@ -122,9 +132,10 @@ export function createKnownServerMoves(deps: KnownServerMovesDeps): KnownServerM
122
132
  if (!fingerprint) return;
123
133
  expire();
124
134
  for (const entry of deps.loadKnown()) {
125
- if (entry.fingerprint !== fingerprint || entry.port !== peer.port) continue;
135
+ const primary = primaryOf(entry);
136
+ if (entry.fingerprint !== fingerprint || primary.port !== peer.port) continue;
126
137
  const key = keyOf(fingerprint, peer.port);
127
- const storedKey = normalizeHostKey(entry.host);
138
+ const storedKey = normalizeHostKey(primary.host);
128
139
  // The entry already points at where this peer lives — not a move.
129
140
  if (storedKey === normalizeHostKey(peer.host) || peer.addresses?.some((a) => normalizeHostKey(a) === storedKey)) {
130
141
  drop(key, fingerprint, "peer is at the stored address");
@@ -134,24 +145,33 @@ export function createKnownServerMoves(deps: KnownServerMovesDeps): KnownServerM
134
145
  if (last !== undefined && now() - last < MOVE_CHALLENGE_INTERVAL_MS) continue;
135
146
  lastEvaluated.set(key, now());
136
147
 
137
- const stored = await deps.prove(`http://${formatHostPort(entry.host, entry.port)}`);
148
+ const stored = await deps.prove(`${primary.scheme}://${formatHostPort(primary.host, primary.port)}`);
138
149
  if ("proven" in stored && stored.proven === fingerprint) {
139
150
  drop(key, fingerprint, "stored address answers again");
140
151
  continue;
141
152
  }
142
- const target = challengeableAddress(peer);
143
- if (!target) {
153
+ const eligible = challengeableAddresses(peer);
154
+ if (eligible.length === 0) {
144
155
  log(
145
156
  `[known-servers] move-skipped fp=${short(fingerprint)}: no on-link address among ${(peer.addresses ?? [peer.host]).join(", ")}`,
146
157
  );
147
158
  continue;
148
159
  }
149
- const proof = await deps.prove(`http://${formatHostPort(target, peer.port)}`);
150
- if (!("proven" in proof) || proof.proven !== fingerprint) continue;
160
+ // An advertised address may reach this very machine or another one (shared virtual-bridge IPs):
161
+ // walk them in order and suggest only an address that itself proves the pinned identity.
162
+ let target: string | undefined;
163
+ for (const address of eligible.slice(0, MOVE_MAX_CHALLENGES)) {
164
+ const proof = await deps.prove(`http://${formatHostPort(address, peer.port)}`);
165
+ if ("proven" in proof && proof.proven === fingerprint) {
166
+ target = address;
167
+ break;
168
+ }
169
+ }
170
+ if (!target) continue;
151
171
  const existing = suggestions.get(key);
152
172
  suggestions.set(key, { host: normalizeHostKey(target), port: peer.port, fromHost: storedKey, verifiedAt: now() });
153
173
  if (!existing || existing.host !== normalizeHostKey(target)) {
154
- log(`[known-servers] move-suggested fp=${short(fingerprint)} ${entry.host} -> ${target}:${peer.port}`);
174
+ log(`[known-servers] move-suggested fp=${short(fingerprint)} ${primary.host} -> ${target}:${peer.port}`);
155
175
  }
156
176
  }
157
177
  },
@@ -164,12 +184,13 @@ export function createKnownServerMoves(deps: KnownServerMovesDeps): KnownServerM
164
184
  suggestionFor(entry) {
165
185
  if (!entry.fingerprint) return undefined;
166
186
  expire();
167
- const s = suggestions.get(keyOf(entry.fingerprint, entry.port));
168
- return s && s.fromHost === normalizeHostKey(entry.host) ? { host: s.host, port: s.port } : undefined;
187
+ const primary = primaryOf(entry);
188
+ const s = suggestions.get(keyOf(entry.fingerprint, primary.port));
189
+ return s && s.fromHost === normalizeHostKey(primary.host) ? { host: s.host, port: s.port } : undefined;
169
190
  },
170
191
 
171
192
  withdraw(entry, reason) {
172
- if (entry.fingerprint) drop(keyOf(entry.fingerprint, entry.port), entry.fingerprint, reason);
193
+ if (entry.fingerprint) drop(keyOf(entry.fingerprint, primaryOf(entry).port), entry.fingerprint, reason);
173
194
  },
174
195
  };
175
196
  }