@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
@@ -2,20 +2,26 @@
2
2
  * Content-search REST route (localhost-only): `GET /api/grep`.
3
3
  *
4
4
  * Prefers `ripgrep`, falls back to a bounded in-process scan. Applies the same
5
- * security gates as `/api/file`: `cwd` must be a known session path; every
6
- * returned match path must resolve within `cwd` (traversal excluded).
5
+ * security gates as `/api/file`: `cwd` must be admitted by the shared cwd guard
6
+ * (session, pinned or workspace folder, or a worktree / main checkout of a known
7
+ * repository); every returned match path must resolve within `cwd` (and its
8
+ * canonical form; traversal excluded).
7
9
  *
8
- * See change: split-editor-workspace.
10
+ * See change: split-editor-workspace, core-file-cwd-admission.
9
11
  */
10
12
 
11
13
  import path from "node:path";
14
+ import { containmentAllows } from "@blackbelt-technology/pi-dashboard-shared/containment-guard.js";
12
15
  import type { ApiResponse } from "@blackbelt-technology/pi-dashboard-shared/types.js";
13
16
  import type { FastifyInstance } from "fastify";
14
17
  import { grantedSubjects } from "../access/access-grants.js";
15
- import { runGrep } from "../lib/grep.js";
16
- import { isAllowed, isGrantAdmitted } from "../lib/path-containment.js";
18
+ import { decidePassive } from "../access/containment-gate.js";
19
+ import { admitFileCwd, cwdAnchors } from "../lib/file-cwd-admission.js";
20
+ import { GrepTimeoutError, runGrep } from "../lib/grep.js";
21
+ import type { RouteAdmissionDeps } from "../lib/route-admission.js";
17
22
  import { detectRipgrep } from "../ripgrep-detection.js";
18
23
  import type { SessionManager } from "../session/memory-session-manager.js";
24
+ import { sendGateFailure } from "./file-routes.js";
19
25
  import type { NetworkGuard } from "./route-deps.js";
20
26
 
21
27
  /** Minimum query length (mirrors the client min-3-char guard). */
@@ -26,9 +32,16 @@ export function registerGrepRoutes(
26
32
  deps: {
27
33
  sessionManager: SessionManager;
28
34
  networkGuard: NetworkGuard;
35
+ /** Shared cwd admission. Absent → the known set is the `sessionManager`'s session cwds only. */
36
+ routeAdmission?: RouteAdmissionDeps;
37
+ /** Test seams for the fallback scan: timeout and worker entry. Default `RG_TIMEOUT_MS` + `grep-worker.ts`. */
38
+ grep?: { scanTimeoutMs?: number; scanWorkerUrl?: string };
29
39
  },
30
40
  ) {
31
41
  const { sessionManager, networkGuard } = deps;
42
+ const routeAdmission: RouteAdmissionDeps = deps.routeAdmission ?? {
43
+ knownCwds: () => sessionManager.listAll().map((s) => s.cwd),
44
+ };
32
45
 
33
46
  fastify.get<{ Querystring: { cwd?: string; q?: string; regex?: string } }>(
34
47
  "/api/grep",
@@ -47,13 +60,24 @@ export function registerGrepRoutes(
47
60
  return { success: false, error: `q must be at least ${MIN_QUERY_LEN} characters` } satisfies ApiResponse;
48
61
  }
49
62
 
50
- // Gate 1 — cwd must be a known session path (mirrors /api/file).
51
- if (!sessionManager.listAll().some((s) => s.cwd === cwd)) {
52
- reply.code(403);
53
- return { success: false, error: "unknown session path" } satisfies ApiResponse;
54
- }
63
+ // Gate 1 — cwd must be admitted by the shared guard (mirrors /api/file).
64
+ const admitted = await admitFileCwd(cwd, routeAdmission, { reply });
65
+ if (!admitted.ok) return sendGateFailure(reply, admitted.failure);
66
+ const anchors = cwdAnchors(admitted);
55
67
 
56
- let matches = await runGrep(cwd, q, { regex, rgPath: detectRipgrep() });
68
+ let matches: Awaited<ReturnType<typeof runGrep>>;
69
+ try {
70
+ matches = await runGrep(admitted.cwd, q, { regex, rgPath: detectRipgrep(), ...deps.grep });
71
+ } catch (err) {
72
+ // A fallback scan that outlived its timeout (e.g. a catastrophic regexp) → 504; any other
73
+ // scan failure (worker died) → 500. Never a 200 with stale or partial matches.
74
+ if (err instanceof GrepTimeoutError) {
75
+ reply.code(504);
76
+ return { success: false, error: "search timed out" } satisfies ApiResponse;
77
+ }
78
+ reply.code(500);
79
+ return { success: false, error: "search failed" } satisfies ApiResponse;
80
+ }
57
81
 
58
82
  // Gate 2 — containment: drop any match that resolves outside cwd. rg/JS
59
83
  // scan already stay under cwd, so this is a defensive backstop.
@@ -64,9 +88,9 @@ export function registerGrepRoutes(
64
88
  const grantSubjects = grantedSubjects();
65
89
  const contained = await Promise.all(
66
90
  matches.map(async (m) => {
67
- const resolvedMatch = path.resolve(cwd, m.path);
68
- if (await isAllowed(resolvedMatch, { anchors: [cwd] })) return m;
69
- return (await isGrantAdmitted(resolvedMatch, grantSubjects)) ? m : null;
91
+ const resolvedMatch = path.resolve(admitted.cwd, m.path);
92
+ const verdict = await decidePassive(resolvedMatch, anchors, { allowGrant: true, grantSubjects });
93
+ return containmentAllows(verdict, resolvedMatch) ? m : null;
70
94
  }),
71
95
  );
72
96
  matches = contained.filter((m): m is NonNullable<typeof m> => m !== null);
@@ -12,7 +12,13 @@
12
12
  * each write re-reads config, re-validates, and aborts if its target entry has
13
13
  * since been removed.
14
14
  *
15
- * See change: stabilize-mdns-server-identity (D6, D7).
15
+ * A server is its identity: an entry holds `routes[]` (addresses at which it
16
+ * answers) and the `host`/`port` mirror of its primary route. An add that
17
+ * proves a fingerprint attaches its route to the entry holding it (D1, D6).
18
+ * Every challenge toward an operator-supplied host is bounded: http/https only,
19
+ * no redirects, 2 s, 4 KiB response cap, normal TLS verification (D2).
20
+ *
21
+ * See change: stabilize-mdns-server-identity (D6, D7), group-servers-by-identity (D1, D2, D6, D10).
16
22
  */
17
23
  import dns from "node:dns";
18
24
  import net from "node:net";
@@ -26,12 +32,21 @@ import type {
26
32
  AddKnownServerRequest,
27
33
  DiscoveredServerInfo,
28
34
  KnownServerListEntry,
35
+ KnownServerProbeRequest,
29
36
  KnownServerProbeResult,
30
37
  RemoveKnownServerRequest,
31
38
  } from "@blackbelt-technology/pi-dashboard-shared/rest-api.js";
32
- import { loadConfig } from "@blackbelt-technology/pi-dashboard-shared/config.js";
39
+ import { knownServersNeedMigration, loadConfig, toStoredKnownServers } from "@blackbelt-technology/pi-dashboard-shared/config.js";
33
40
  import { formatHostPort, isValidHost, normalizeHostKey } from "@blackbelt-technology/pi-dashboard-shared/host-port.js";
34
41
  import { type ProveResult, proveServerIdentity } from "@blackbelt-technology/pi-dashboard-shared/server-pinning.js";
42
+ import {
43
+ findAttachTarget,
44
+ primaryRoute,
45
+ ROUTE_SCHEMES,
46
+ type Route,
47
+ type RouteScheme,
48
+ routeKey,
49
+ } from "@blackbelt-technology/pi-dashboard-shared/server-routes.js";
35
50
  import type { HostAdmissionOptions } from "../auth/host-admission.js";
36
51
  import type { LocalTrustContext } from "../auth/local-proof.js";
37
52
  import { writeConfigPartial } from "../config-api.js";
@@ -64,12 +79,14 @@ export interface KnownServersRouteDeps {
64
79
  localToken?: string;
65
80
  localTrust?: LocalTrustContext;
66
81
  hostAdmission: () => HostAdmissionOptions;
67
- /** Identity-challenge seam (default: {@link proveServerIdentity}, 2 s). */
82
+ /** Identity-challenge seam (default: {@link proveServerIdentity} over `fetchImpl`, 2 s). */
68
83
  prove?: (baseUrl: string) => Promise<ProveResult>;
69
84
  /** Name-resolution seam for the probe. */
70
85
  lookup?: (host: string) => Promise<unknown>;
71
86
  fetchImpl?: typeof fetch;
72
87
  moves?: KnownServerMoves;
88
+ /** This server's own fingerprint: an address proving it is this dashboard itself (`self_address`), never a peer. */
89
+ ownFingerprint?: () => string | undefined;
73
90
  log?: (message: string) => void;
74
91
  /** Budget overrides (tests shrink them; production uses the defaults). */
75
92
  timeouts?: { challengeMs?: number; dnsMs?: number; httpMs?: number };
@@ -79,6 +96,16 @@ const sameAddress = (a: { host: string; port: number }, b: { host: string; port:
79
96
  a.port === b.port && normalizeHostKey(a.host) === normalizeHostKey(b.host);
80
97
 
81
98
  const short = (fingerprint: string) => fingerprint.replace(/^sha256:/, "").slice(0, 16);
99
+ /** `sha256:` + the first 16 characters: enough to correlate, never the whole fingerprint (D10). */
100
+ const shortFp = (fingerprint: string) => `sha256:${short(fingerprint)}`;
101
+ /** `scheme://host:port` of a route, with the host in its normalised spelling. */
102
+ const routeUrl = (r: Pick<Route, "host" | "port" | "scheme">) =>
103
+ // Literal scheme: only the two allowlisted values ever reach the request URL.
104
+ `${r.scheme === "https" ? "https" : "http"}://${formatHostPort(r.host, r.port)}`;
105
+ const holdsRoute = (e: KnownServer, r: Route) => e.routes.some((x) => routeKey(x) === routeKey(r));
106
+ /** Body `scheme`: absent → `http`; anything but `http` / `https` → null (`400 invalid_scheme`). */
107
+ const parseScheme = (input: unknown): RouteScheme | null =>
108
+ input === undefined ? "http" : ROUTE_SCHEMES.includes(input as RouteScheme) ? (input as RouteScheme) : null;
82
109
 
83
110
  /** Reject after `ms`, clearing its timer when the race settles. */
84
111
  function withTimeout<T>(p: Promise<T>, ms: number, onTimeout: () => T): Promise<T> {
@@ -124,17 +151,56 @@ export function registerKnownServersRoutes(fastify: FastifyInstance, deps: Known
124
151
  const challengeMs = deps.timeouts?.challengeMs ?? CHALLENGE_TIMEOUT_MS;
125
152
  const dnsMs = deps.timeouts?.dnsMs ?? PROBE_DNS_TIMEOUT_MS;
126
153
  const httpMs = deps.timeouts?.httpMs ?? PROBE_HTTP_TIMEOUT_MS;
127
- const proveRaw = deps.prove ?? ((baseUrl: string) => proveServerIdentity(baseUrl, { timeoutMs: challengeMs }));
128
- /** Bounded identity challenge: a hanging target cannot hold the request. */
129
- const prove = (host: string, port: number): Promise<ProveResult> =>
130
- withTimeout(proveRaw(`http://${formatHostPort(host, port)}`), challengeMs, () => ({
154
+ const proveRaw =
155
+ deps.prove ??
156
+ ((baseUrl: string) => proveServerIdentity(baseUrl, { timeoutMs: challengeMs, ...(deps.fetchImpl ? { fetchImpl: deps.fetchImpl } : {}) }));
157
+ /** Bounded identity challenge over the route's own scheme: a hanging target cannot hold the request. */
158
+ const prove = (host: string, port: number, scheme: RouteScheme): Promise<ProveResult> =>
159
+ withTimeout(proveRaw(routeUrl({ host, port, scheme })), challengeMs, () => ({
131
160
  refused: "challenge timed out",
132
161
  }));
133
162
  const provedFingerprint = (r: ProveResult): string | undefined => ("proven" in r ? r.proven : undefined);
134
163
 
135
- const readList = (): KnownServer[] => loadConfig().knownServers.map((e) => ({ ...e }));
136
- const writeList = (list: KnownServer[]): { success: boolean; error?: string } =>
137
- writeConfigPartial({ knownServers: list });
164
+ const readList = (): KnownServer[] => loadConfig().knownServers.map((e) => ({ ...e, routes: e.routes.map((r) => ({ ...r })) }));
165
+ /** The one write: always routes shape plus the `host`/`port` mirror; logs once for the first rewrite of a previous-shape file. */
166
+ const writeList = (list: KnownServer[]): { success: boolean; error?: string } => {
167
+ const migrating = list.length > 0 && knownServersNeedMigration();
168
+ const result = writeConfigPartial({ knownServers: toStoredKnownServers(list) });
169
+ if (result.success && migrating) log(`[known-servers] first written in routes shape (${list.length} entries)`);
170
+ return result;
171
+ };
172
+
173
+ /**
174
+ * `list[idx]` just proved (or newly holds) its fingerprint: fold every other entry that holds the
175
+ * same identity on the same instance (D1 rule) into it — it keeps its routes first, then gains
176
+ * the other's, keeps its label else takes the other's.
177
+ */
178
+ /**
179
+ * One instance = a shared `http` route port, or one side has no `http` route at all (its https routes join the
180
+ * holder, D1). Two entries on different `http` ports stay two rows even though an https route could attach to either.
181
+ */
182
+ function sameInstance(a: KnownServer, b: KnownServer): boolean {
183
+ const ports = (e: KnownServer) => new Set(e.routes.filter((r) => r.scheme === "http").map((r) => r.port));
184
+ const pa = ports(a);
185
+ const pb = ports(b);
186
+ return pa.size === 0 || pb.size === 0 || [...pa].some((p) => pb.has(p));
187
+ }
188
+
189
+ function foldDuplicates(list: KnownServer[], idx: number): void {
190
+ const survivor = list[idx];
191
+ if (!survivor.fingerprint) return;
192
+ for (let j = list.length - 1; j >= 0; j--) {
193
+ if (j === idx) continue;
194
+ const other = list[j];
195
+ if (other.fingerprint !== survivor.fingerprint || !sameInstance(survivor, other)) continue;
196
+ const keys = new Set(survivor.routes.map(routeKey));
197
+ for (const r of other.routes) if (!keys.has(routeKey(r))) survivor.routes.push(r);
198
+ if (!survivor.label && other.label) survivor.label = other.label;
199
+ list.splice(j, 1);
200
+ if (j < idx) idx -= 1;
201
+ log(`[known-servers] merged duplicate identity: folded ${other.host}:${other.port} into ${survivor.host}:${survivor.port}`);
202
+ }
203
+ }
138
204
 
139
205
  // ── List ─────────────────────────────────────────────────────────────
140
206
  fastify.get("/api/known-servers", { preHandler: networkGuard }, async (request) => {
@@ -145,7 +211,7 @@ export function registerKnownServersRoutes(fastify: FastifyInstance, deps: Known
145
211
  return { success: true, data, canManage: await isOperator(request) };
146
212
  });
147
213
 
148
- // ── Add / update ─────────────────────────────────────────────────────
214
+ // ── Add / attach ─────────────────────────────────────────────────────
149
215
  fastify.post<{ Body: AddKnownServerRequest }>(
150
216
  "/api/known-servers",
151
217
  { preHandler: mutationGuard },
@@ -155,67 +221,63 @@ export function registerKnownServersRoutes(fastify: FastifyInstance, deps: Known
155
221
  if (!host || typeof host !== "string" || !Number.isInteger(port) || port < 1 || port > 65535) {
156
222
  return { success: false, error: "host and port are required" };
157
223
  }
158
- // The host is placed in an outbound URL (identity challenge): admit only DNS-name / IP-literal
159
- // characters, so no URL-authority trick (`@`, `/`, `#`, `?`) can redirect the request.
224
+ // Before ANY request: the scheme allowlist (the route is challenged over its own scheme) ...
225
+ const scheme = parseScheme((request.body as { scheme?: unknown }).scheme);
226
+ if (!scheme) return fail(reply, 400, "invalid_scheme");
227
+ // ... and the host charset: the host is placed in an outbound URL (identity challenge), so admit only
228
+ // DNS-name / IP-literal characters; no URL-authority trick (`@`, `/`, `#`, `?`) can redirect the request.
160
229
  if (!/^[A-Za-z0-9._:[\]-]+$/.test(host) || !isValidHost(host)) return fail(reply, 400, "invalid_host");
161
- // Snapshot BEFORE the challenge: an entry that existed then but is gone when the
230
+ const candidate: Route = { host, port, scheme, source: "saved" };
231
+ // Snapshot BEFORE the challenge: an entry that held the route then but is gone when the
162
232
  // write runs was deleted meanwhile and must not be recreated.
163
- const snapshot = readList();
233
+ const heldBefore = readList().some((e) => holdsRoute(e, candidate));
164
234
  // `fingerprint` in the body is a hint only and is never persisted unless proven.
165
- const proven = provedFingerprint(await prove(host, port));
235
+ const proven = provedFingerprint(await prove(host, port, scheme));
166
236
 
167
- // The holder of (proven, port) at ANOTHER address, and whether it still answers.
168
- const target0 = snapshot.find((e) => sameAddress(e, { host, port }));
169
- const holder0 = proven
170
- ? snapshot.find((e) => e.fingerprint === proven && e.port === port && !sameAddress(e, { host, port }))
171
- : undefined;
172
- const holderStillProves = holder0 && !target0 ? provedFingerprint(await prove(holder0.host, holder0.port)) === proven : false;
237
+ // The address reaches THIS dashboard (e.g. a virtual-bridge address both machines hold): never a peer.
238
+ // Takes precedence over every other post-challenge outcome (incl. identity_changed); nothing is pinned.
239
+ if (proven && proven === deps.ownFingerprint?.()) {
240
+ log(`[known-servers] route refused: address reaches this dashboard itself ${routeUrl(candidate)} fp=${shortFp(proven)}`);
241
+ return fail(reply, 409, "self_address");
242
+ }
173
243
 
174
244
  return enqueueKnownServersWrite((): ApiResponse<{ updated?: boolean }> & Record<string, unknown> => {
175
245
  const list = readList();
176
- const idx = list.findIndex((e) => sameAddress(e, { host, port }));
177
- if (target0 && idx < 0) return fail(reply, 409, "entry_removed");
178
- const target = idx >= 0 ? list[idx] : undefined;
179
-
180
- if (target?.fingerprint && proven && proven !== target.fingerprint) {
181
- reply.code(409);
182
- return { success: false, error: "identity_changed", expected: target.fingerprint, proven };
183
- }
184
-
185
- const holderIdx = proven
186
- ? list.findIndex((e) => e.fingerprint === proven && e.port === port && !sameAddress(e, { host, port }))
187
- : -1;
188
-
189
- if (target) {
190
- // Existing address: refresh label, pin when newly proven, merge a duplicate identity into it.
246
+ const idx = list.findIndex((e) => holdsRoute(e, candidate));
247
+ if (heldBefore && idx < 0) return fail(reply, 409, "entry_removed");
248
+
249
+ if (idx >= 0) {
250
+ // A route already stored: refresh the label, pin when newly proven, fold a duplicate identity into it.
251
+ const target = list[idx];
252
+ if (target.fingerprint && proven && proven !== target.fingerprint) {
253
+ log(`[known-servers] route refused: different identity at ${routeUrl(candidate)} expected=${shortFp(target.fingerprint)} proven=${shortFp(proven)}`);
254
+ reply.code(409);
255
+ return { success: false, error: "identity_changed", expected: target.fingerprint, proven };
256
+ }
191
257
  if (label) target.label = label;
192
258
  if (proven && !target.fingerprint) {
193
259
  target.fingerprint = proven;
194
- if (holderIdx >= 0) {
195
- const dropped = list.splice(holderIdx, 1)[0];
196
- if (!target.label && dropped.label) target.label = dropped.label;
197
- log(`[known-servers] merged duplicate identity: dropped ${dropped.host}:${dropped.port}`);
198
- }
260
+ foldDuplicates(list, idx);
199
261
  }
200
262
  return persist(list, reply, false);
201
263
  }
202
264
 
203
- if (holderIdx >= 0) {
204
- if (holderStillProves) {
205
- reply.code(409);
206
- return { success: false, error: "already_known", host: list[holderIdx].host, port: list[holderIdx].port };
207
- }
208
- // The holder's stored address no longer proves the identity: move it here.
209
- list[holderIdx] = { ...list[holderIdx], host, ...(label ? { label } : {}) };
210
- return persist(list, reply, true);
265
+ // A new route: it joins the entry that holds the proven identity (D1), else starts an entry.
266
+ const at = findAttachTarget(list, candidate, proven);
267
+ if (at >= 0 && proven) {
268
+ list[at].routes.push(candidate);
269
+ if (label) list[at].label = label;
270
+ const result = persist(list, reply, true);
271
+ if (result.success) log(`[known-servers] route attached fp=${shortFp(proven)} ${routeUrl(candidate)}`);
272
+ return result;
211
273
  }
212
-
213
274
  list.push({
214
275
  host,
215
276
  port,
216
277
  ...(label ? { label } : {}),
217
278
  addedAt: new Date().toISOString(),
218
279
  ...(proven ? { fingerprint: proven } : {}),
280
+ routes: [candidate],
219
281
  });
220
282
  return persist(list, reply, false);
221
283
  });
@@ -234,21 +296,39 @@ export function registerKnownServersRoutes(fastify: FastifyInstance, deps: Known
234
296
  }
235
297
 
236
298
  // ── Remove ───────────────────────────────────────────────────────────
299
+ // `{host, port, scheme?}` removes that route (and the entry with its last route);
300
+ // `{fingerprint}` removes every entry holding that identity. Idempotent.
237
301
  fastify.delete<{ Body: RemoveKnownServerRequest }>(
238
302
  "/api/known-servers",
239
303
  { preHandler: mutationGuard },
240
304
  async (request, reply): Promise<ApiResponse> => {
241
- const { host, port } = request.body ?? ({} as RemoveKnownServerRequest);
242
- if (!host || typeof port !== "number") {
305
+ const body = (request.body ?? {}) as { host?: unknown; port?: unknown; scheme?: unknown; fingerprint?: unknown };
306
+ if (typeof body.fingerprint === "string" && body.fingerprint) {
307
+ const fingerprint = body.fingerprint;
308
+ return enqueueKnownServersWrite(() => {
309
+ const list = readList();
310
+ const kept = list.filter((e) => e.fingerprint !== fingerprint);
311
+ return kept.length === list.length ? { success: true as const } : persist(kept, reply, false);
312
+ });
313
+ }
314
+ const { host, port } = body;
315
+ if (!host || typeof host !== "string" || typeof port !== "number") {
243
316
  return { success: false, error: "host and port are required" };
244
317
  }
245
- return enqueueKnownServersWrite(() =>
246
- persist(
247
- readList().filter((s) => !sameAddress(s, { host, port })),
248
- reply,
249
- false,
250
- ),
251
- );
318
+ // No scheme names the address whatever its scheme (a pre-routes client sends none).
319
+ const scheme = body.scheme === undefined ? undefined : parseScheme(body.scheme);
320
+ if (scheme === null) return fail(reply, 400, "invalid_scheme");
321
+ return enqueueKnownServersWrite(() => {
322
+ const list = readList();
323
+ let changed = false;
324
+ const kept: KnownServer[] = [];
325
+ for (const e of list) {
326
+ const routes = e.routes.filter((r) => !(sameAddress(r, { host, port }) && (scheme === undefined || r.scheme === scheme)));
327
+ if (routes.length !== e.routes.length) changed = true;
328
+ if (routes.length > 0) kept.push({ ...e, routes });
329
+ }
330
+ return changed ? persist(kept, reply, false) : { success: true as const };
331
+ });
252
332
  },
253
333
  );
254
334
 
@@ -259,17 +339,21 @@ export function registerKnownServersRoutes(fastify: FastifyInstance, deps: Known
259
339
  async (request, reply): Promise<ApiResponse> => {
260
340
  const { host, port } = request.body ?? ({} as AcceptKnownServerMoveRequest);
261
341
  if (!host || typeof port !== "number") return fail(reply, 400, "host and port are required");
342
+ // `host`/`port` name the entry's primary route (the mirror); only that route moves.
262
343
  const entry = readList().find((e) => sameAddress(e, { host, port }));
263
344
  const suggestion = entry && moves?.suggestionFor(entry);
264
345
  if (!entry?.fingerprint || !suggestion) return fail(reply, 409, "no_suggestion");
265
346
  const fingerprint = entry.fingerprint;
347
+ const primary = primaryRoute(entry.routes);
348
+ if (!primary) return fail(reply, 409, "no_suggestion");
266
349
 
267
- // Re-verify BOTH halves before touching config.
268
- if (provedFingerprint(await prove(entry.host, entry.port)) === fingerprint) {
350
+ // Re-verify BOTH halves before touching config: the stored primary route in its own scheme,
351
+ // the suggested (mDNS, always http) address over http.
352
+ if (provedFingerprint(await prove(primary.host, primary.port, primary.scheme)) === fingerprint) {
269
353
  moves?.withdraw(entry, "stored address answers again");
270
354
  return fail(reply, 409, "stale_suggestion");
271
355
  }
272
- if (provedFingerprint(await prove(suggestion.host, suggestion.port)) !== fingerprint) {
356
+ if (provedFingerprint(await prove(suggestion.host, suggestion.port, "http")) !== fingerprint) {
273
357
  return fail(reply, 409, "stale_suggestion");
274
358
  }
275
359
 
@@ -277,7 +361,19 @@ export function registerKnownServersRoutes(fastify: FastifyInstance, deps: Known
277
361
  const list = readList();
278
362
  const idx = list.findIndex((e) => sameAddress(e, entry) && e.fingerprint === fingerprint);
279
363
  if (idx < 0) return fail(reply, 409, "entry_removed");
280
- list[idx] = { ...list[idx], host: suggestion.host, port: suggestion.port };
364
+ const current = primaryRoute(list[idx].routes);
365
+ if (!current) return fail(reply, 409, "entry_removed");
366
+ const moved: Route = { host: suggestion.host, port: suggestion.port, scheme: "http", source: current.source };
367
+ // Only the primary route changes; a route that already holds the new address is not duplicated.
368
+ const seen = new Set<string>();
369
+ list[idx].routes = list[idx].routes
370
+ .map((r) => (r === current ? moved : r))
371
+ .filter((r) => {
372
+ const key = routeKey(r);
373
+ if (seen.has(key)) return false;
374
+ seen.add(key);
375
+ return true;
376
+ });
281
377
  const result = persist(list, reply, false);
282
378
  if (result.success) {
283
379
  moves?.withdraw(entry, "accepted");
@@ -293,7 +389,8 @@ export function registerKnownServersRoutes(fastify: FastifyInstance, deps: Known
293
389
  const lookup = deps.lookup ?? ((h: string) => dns.promises.lookup(h));
294
390
  const doFetch = deps.fetchImpl ?? fetch;
295
391
 
296
- async function probeOnce(host: string, port: number): Promise<KnownServerProbeResult> {
392
+ /** Reachability of one stored route, over the route's own scheme (normal TLS verification, no redirects). */
393
+ async function probeOnce(host: string, port: number, scheme: RouteScheme): Promise<KnownServerProbeResult> {
297
394
  const key = normalizeHostKey(host);
298
395
  if (!net.isIP(key)) {
299
396
  try {
@@ -307,7 +404,7 @@ export function registerKnownServersRoutes(fastify: FastifyInstance, deps: Known
307
404
  }
308
405
  }
309
406
  try {
310
- const res = await doFetch(`http://${formatHostPort(host, port)}/api/health`, {
407
+ const res = await doFetch(`${routeUrl({ host, port, scheme })}/api/health`, {
311
408
  redirect: "manual",
312
409
  signal: AbortSignal.timeout(httpMs),
313
410
  });
@@ -322,45 +419,46 @@ export function registerKnownServersRoutes(fastify: FastifyInstance, deps: Known
322
419
  }
323
420
  }
324
421
 
325
- /** Pin the identity of an unpinned reachable entry (merging a duplicate holder). */
326
- async function backfill(entry: KnownServer): Promise<void> {
327
- if (entry.fingerprint) return;
328
- const proven = provedFingerprint(await prove(entry.host, entry.port));
329
- if (!proven) return;
422
+ /** Pin the identity a reachable route proved on its still-unpinned entry (folding a duplicate holder into it). */
423
+ async function backfill(route: Route, proven: string): Promise<void> {
424
+ // An entry whose address reaches this very server must never be pinned to this server's own identity.
425
+ if (proven === deps.ownFingerprint?.()) return;
330
426
  await enqueueKnownServersWrite(() => {
331
427
  const list = readList();
332
- const idx = list.findIndex((e) => sameAddress(e, entry));
333
- if (idx < 0 || list[idx].fingerprint) return;
428
+ const idx = list.findIndex((e) => holdsRoute(e, route));
429
+ if (idx < 0 || list[idx].fingerprint) return; // removed meanwhile (never recreated), or pinned meanwhile
334
430
  list[idx].fingerprint = proven;
335
- const dup = list.findIndex((e, i) => i !== idx && e.fingerprint === proven && e.port === entry.port);
336
- if (dup >= 0) {
337
- const dropped = list.splice(dup, 1)[0];
338
- if (!list.find((e) => e.fingerprint === proven)?.label && dropped.label) {
339
- list[list.findIndex((e) => e.fingerprint === proven)].label = dropped.label;
340
- }
341
- log(`[known-servers] backfill merged duplicate identity: dropped ${dropped.host}:${dropped.port}`);
342
- }
431
+ foldDuplicates(list, idx);
343
432
  const result = writeList(list);
344
433
  if (!result.success) log(`[known-servers] backfill write failed: ${result.error ?? "unknown"}`);
345
434
  });
346
435
  }
347
436
 
348
- fastify.post<{ Body: { host?: string; port?: number } }>(
437
+ fastify.post<{ Body: KnownServerProbeRequest }>(
349
438
  "/api/known-servers/probe",
350
439
  { preHandler: mutationGuard },
351
440
  async (request, reply): Promise<ApiResponse<KnownServerProbeResult>> => {
352
- const { host, port } = request.body ?? {};
441
+ const { host, port } = request.body ?? ({} as KnownServerProbeRequest);
353
442
  if (typeof host !== "string" || typeof port !== "number") return fail(reply, 400, "host and port are required");
354
- const entry = readList().find((e) => sameAddress(e, { host, port }));
355
- if (!entry) return fail(reply, 403, "not_a_known_server");
356
-
357
- const key = `${normalizeHostKey(entry.host)}:${entry.port}`;
443
+ const scheme = parseScheme((request.body as { scheme?: unknown }).scheme);
444
+ if (!scheme) return fail(reply, 400, "invalid_scheme");
445
+ // SSRF guard: only a route that is still stored is ever contacted, in the stored spelling.
446
+ const route = readList()
447
+ .flatMap((e) => e.routes)
448
+ .find((r) => r.scheme === scheme && sameAddress(r, { host, port }));
449
+ if (!route) return fail(reply, 403, "not_a_known_server");
450
+
451
+ const key = routeKey(route);
358
452
  let pending = probesInFlight.get(key);
359
453
  if (!pending) {
360
- pending = (async () => {
361
- const result = await probeOnce(entry.host, entry.port);
362
- if (result.status === "reachable") await backfill(entry).catch(() => {});
363
- return result;
454
+ pending = (async (): Promise<KnownServerProbeResult> => {
455
+ const result = await probeOnce(route.host, route.port, route.scheme);
456
+ if (result.status !== "reachable") return { ...result, scheme: route.scheme };
457
+ const proven = provedFingerprint(await prove(route.host, route.port, route.scheme));
458
+ if (!proven) return { ...result, scheme: route.scheme };
459
+ log(`[known-servers] probe proved fp=${shortFp(proven)} ${routeUrl(route)}`);
460
+ await backfill(route, proven).catch(() => {});
461
+ return { ...result, scheme: route.scheme, fingerprint: proven };
364
462
  })().finally(() => probesInFlight.delete(key));
365
463
  probesInFlight.set(key, pending);
366
464
  }