@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
@@ -28,6 +28,8 @@
28
28
 
29
29
  import type { ApiResponse } from "@blackbelt-technology/pi-dashboard-shared/types.js";
30
30
  import type { FastifyInstance } from "fastify";
31
+ import { admitOptionalCwd, sendCwdFailure } from "../lib/file-cwd-admission.js";
32
+ import type { RouteAdmissionDeps } from "../lib/route-admission.js";
31
33
  import type { PiGateway } from "../pi/pi-gateway.js";
32
34
  import { AGENT_DIR } from "../pi/pi-resource-activation.js";
33
35
  import {
@@ -114,9 +116,15 @@ export function registerResourceActivationRoutes(
114
116
  dispatchReload: (sessionId: string) => Promise<string>;
115
117
  /** Sessions the headless PID registry knows are alive, with their cwd. */
116
118
  registrySessions: () => ReadonlyArray<{ sessionId: string; cwd: string }>;
119
+ /**
120
+ * Shared cwd admission (change: core-file-cwd-admission): a supplied toggle `cwd` must be
121
+ * admitted; no `cwd` keeps the global scope. Absent → fail-closed (nothing is known).
122
+ */
123
+ routeAdmission?: RouteAdmissionDeps;
117
124
  },
118
125
  ) {
119
126
  const { networkGuard, piGateway, sessionManager } = deps;
127
+ const routeAdmission: RouteAdmissionDeps = deps.routeAdmission ?? {};
120
128
 
121
129
  // ── Toggle a resource's activation ──────────────────────────────
122
130
  fastify.post<{
@@ -136,11 +144,17 @@ export function registerResourceActivationRoutes(
136
144
  return { success: false, error: "scope must be 'local' or 'global'" } satisfies ApiResponse;
137
145
  }
138
146
 
139
- const key = settingsPathForScope(scope, body.cwd);
147
+ // A supplied cwd is admitted for BOTH scopes before the settings path is computed, so every trust
148
+ // challenge this route registers is for an admitted cwd. No cwd → the constant `undefined`.
149
+ const admitted = await admitOptionalCwd(body.cwd, routeAdmission, reply);
150
+ if (!admitted.ok) return sendCwdFailure(reply, admitted.failure);
151
+ const cwd = admitted.cwd;
152
+
153
+ const key = settingsPathForScope(scope, cwd);
140
154
  const result = await withSettingsWriteLock(key, () =>
141
155
  applyResourceToggle({
142
156
  scope,
143
- cwd: body.cwd,
157
+ cwd,
144
158
  type: body.type as ToggleType,
145
159
  filePath: body.filePath as string,
146
160
  enabled: body.enabled as boolean,
@@ -151,7 +165,7 @@ export function registerResourceActivationRoutes(
151
165
  if (!result.ok) {
152
166
  reply.code(result.status);
153
167
  if (result.trustRequired) {
154
- if (body.cwd) registerTrustChallenge(body.cwd);
168
+ if (cwd) registerTrustChallenge(cwd);
155
169
  return {
156
170
  success: false,
157
171
  error: result.error,
@@ -171,7 +185,7 @@ export function registerResourceActivationRoutes(
171
185
  piGateway,
172
186
  sessionManager,
173
187
  scope,
174
- body.cwd,
188
+ cwd,
175
189
  deps.registrySessions(),
176
190
  );
177
191
  return { success: true, data: { affectedSessions } } satisfies ApiResponse;
@@ -3,11 +3,14 @@
3
3
  */
4
4
  import { readFile } from "node:fs/promises";
5
5
  import { isAbsolute, relative, resolve } from "node:path";
6
+ import { containmentAllows } from "@blackbelt-technology/pi-dashboard-shared/containment-guard.js";
7
+ import type { SessionListItem } from "@blackbelt-technology/pi-dashboard-shared/rest-api.js";
8
+ import { sessionUiPath } from "@blackbelt-technology/pi-dashboard-shared/session-ui-path.js";
6
9
  import type { ApiResponse } from "@blackbelt-technology/pi-dashboard-shared/types.js";
7
10
  import type { FastifyInstance } from "fastify";
8
11
  import { evaluateContainment } from "../access/containment-gate.js";
9
- import { canDiscloseAccessPosture } from "../auth/localhost-guard.js";
10
12
  import { readFileVerifiedUtf8, VerifiedReadRefused } from "../access/verified-read.js";
13
+ import { canDiscloseAccessPosture } from "../auth/localhost-guard.js";
11
14
  import { canAccessSession, gateHttpSession, sessionPrincipalOf } from "../identity/session-access.js";
12
15
  import type { EventStore } from "../persistence/memory-event-store.js";
13
16
  import type { SessionManager } from "../session/memory-session-manager.js";
@@ -21,6 +24,7 @@ import { findSessionCustomEntry, findSessionToolCallPayload } from "../session/s
21
24
  import type { SessionLoadWorkerPool } from "../session/session-load-worker-pool.js";
22
25
  import { originOf } from "../session/session-origin.js";
23
26
  import type { NetworkGuard } from "./route-deps.js";
27
+ import { resolveRequestUiBase } from "./ui-link-base.js";
24
28
 
25
29
  /**
26
30
  * Cumulative answers of the tool-result route that distinguished a still-running
@@ -32,6 +36,9 @@ export interface ToolResultStats {
32
36
  gone: number;
33
37
  }
34
38
 
39
+ const headerString = (v: string | string[] | undefined): string | undefined =>
40
+ Array.isArray(v) ? v[0] : v;
41
+
35
42
  export function registerSessionRoutes(
36
43
  fastify: FastifyInstance,
37
44
  deps: {
@@ -63,6 +70,14 @@ export function registerSessionRoutes(
63
70
  * SAME value so transcript- and store-sourced payloads match.
64
71
  * See change: fix-session-diff-durable-source. */
65
72
  maxStringSize?: number;
73
+ /** Inputs for `uiUrl` / `diffUrl` (D1). Read per request so tunnel / config
74
+ * changes are seen live. Absent (unit tests) → localhost fallback on `port` 8000.
75
+ * See change: add-session-ui-deep-links-for-agents. */
76
+ uiLinks?: {
77
+ configuredOrigins: () => string[];
78
+ isAdmitted: (hostHeader: string | undefined) => boolean;
79
+ port: () => number;
80
+ };
66
81
  },
67
82
  ) {
68
83
  const {
@@ -104,9 +119,41 @@ export function registerSessionRoutes(
104
119
  sizeOf: sessionDiffResultSize,
105
120
  });
106
121
 
107
- fastify.get("/api/sessions", async (request) => {
122
+ // `?id=` (single string): case-insensitive exact id, or a prefix of >= 8
123
+ // characters — the same floor as the client's `resolveSessionRouteId`.
124
+ // Applied after `filterOwned`. See change: add-session-ui-deep-links-for-agents.
125
+ fastify.get<{ Querystring: { id?: string | string[] } }>("/api/sessions", async (request, reply) => {
126
+ const rawId = request.query.id;
127
+ if (rawId !== undefined && typeof rawId !== "string") {
128
+ reply.code(400);
129
+ return { success: false, error: "id must be a single string" } satisfies ApiResponse;
130
+ }
131
+ const idQuery = rawId?.toLowerCase();
108
132
  // §8.1/§8.2: per-item owner filter — never disclose the full registry.
109
- return { success: true, data: filterOwned(request, sessionManager.listAll()) } satisfies ApiResponse;
133
+ let owned = filterOwned(request, sessionManager.listAll());
134
+ if (idQuery !== undefined) {
135
+ owned = owned.filter((s) => {
136
+ const id = s.id.toLowerCase();
137
+ return id === idQuery || (idQuery.length >= 8 && id.startsWith(idQuery));
138
+ });
139
+ }
140
+ // The links depend on the request's Host / X-Forwarded-Host: never cacheable.
141
+ reply.header("Cache-Control", "no-store");
142
+ const links = deps.uiLinks;
143
+ const base = resolveRequestUiBase({
144
+ host: headerString(request.headers.host),
145
+ forwardedHost: headerString(request.headers["x-forwarded-host"]),
146
+ protocol: request.protocol,
147
+ configuredOrigins: links?.configuredOrigins() ?? [],
148
+ isAdmitted: links?.isAdmitted ?? (() => false),
149
+ port: links?.port() ?? 8000,
150
+ });
151
+ const data: SessionListItem[] = owned.map((s) => ({
152
+ ...s,
153
+ uiUrl: base + sessionUiPath(s.id),
154
+ diffUrl: base + sessionUiPath(s.id, "diff"),
155
+ }));
156
+ return { success: true, data } satisfies ApiResponse;
110
157
  });
111
158
 
112
159
  // On-demand listing of archived sessions, served from the in-memory index
@@ -501,7 +548,7 @@ export function registerSessionRoutes(
501
548
  disclosure: canDiscloseAccessPosture(request),
502
549
  session: sessionId,
503
550
  });
504
- if (!sessionDecision.allowed) {
551
+ if (!containmentAllows(sessionDecision, absPath)) {
505
552
  reply.code(403);
506
553
  return { success: false, error: "path outside session directory", ...sessionDecision.remedy } as ApiResponse;
507
554
  }
@@ -14,11 +14,12 @@ import type { ServerToBrowserMessage } from "@blackbelt-technology/pi-dashboard-
14
14
  import type { BridgeLoadSource, PluginStatus } from "@blackbelt-technology/pi-dashboard-shared/dashboard-plugin/plugin-status.js";
15
15
  import { parseLaunchSource } from "@blackbelt-technology/pi-dashboard-shared/dashboard-starter.js";
16
16
  import { ELECTRON_RESTART_EXIT_CODE, restartsViaElectron } from "@blackbelt-technology/pi-dashboard-shared/electron-restart.js";
17
- import { whichSync } from "@blackbelt-technology/pi-dashboard-shared/platform/binary-lookup.js";
17
+ import { LOCAL_PROOF_REQUIRED } from "@blackbelt-technology/pi-dashboard-shared/local-proof-signal.js";
18
+ import { ToolResolver, whichSync } from "@blackbelt-technology/pi-dashboard-shared/platform/binary-lookup.js";
18
19
  import { getGitSourceReadout } from "@blackbelt-technology/pi-dashboard-shared/platform/git-source.js";
19
20
  import { resolveNativeTsLoader } from "@blackbelt-technology/pi-dashboard-shared/platform/ts-loader-select.mjs";
20
21
  import { classifyBridgeSource } from "@blackbelt-technology/pi-dashboard-shared/plugin-bridge-register.js";
21
- import { RESTART_QUIESCE_MS } from "@blackbelt-technology/pi-dashboard-shared/recovery-timing.js";
22
+ import { RESTART_QUIESCE_MS, SHUTDOWN_QUIESCE_MS } from "@blackbelt-technology/pi-dashboard-shared/recovery-timing.js";
22
23
  import type { NetworkInterface, PiMirrorResult, ReservedNameResult } from "@blackbelt-technology/pi-dashboard-shared/rest-api.js";
23
24
  import type { ApiResponse } from "@blackbelt-technology/pi-dashboard-shared/types.js";
24
25
  import type { FastifyInstance } from "fastify";
@@ -29,7 +30,9 @@ import {
29
30
  safeComputeBindReachability,
30
31
  sameReachability,
31
32
  } from "../auth/bind-reachability-service.js";
32
- import { canDiscloseAccessPosture, localhostGuard, loopbackCoveringEntries } from "../auth/localhost-guard.js";
33
+ import type { CspReportsSnapshot } from "../auth/csp-report-store.js";
34
+ import type { LocalTrustContext } from "../auth/local-proof.js";
35
+ import { canDiscloseAccessPosture, localhostGuard, loopbackCoveringEntries, needsLocalProof } from "../auth/localhost-guard.js";
33
36
  import { networkOnlySnapshot } from "../auth/network-trust-telemetry.js";
34
37
  import { getRegistryError } from "../auth/provider-auth-registry.js";
35
38
  import { effectiveTrustMode } from "../auth/trust-mode.js";
@@ -38,6 +41,7 @@ import type { DirectoryService } from "../directory-service.js";
38
41
  import {
39
42
  type ClientBuildSnapshot,
40
43
  readClientBuildSnapshot,
44
+ readServedDeclaration,
41
45
  runtimePluginRegistryHash,
42
46
  } from "../lib/client-dist.js";
43
47
  import { bootParentPid, computeBootParentAlive, readLivePpid } from "../lifecycle/boot-parent-liveness.js";
@@ -66,14 +70,14 @@ import { mirrorDefaultsToPi } from "../pi-agent-settings.js";
66
70
  import { EMPTY_KEEPER_LOG_STATS, type KeeperLogStats } from "../rpc-keeper/keeper-manager.js";
67
71
  import type { ServerConfig } from "../server.js";
68
72
  import { serverHeapTelemetry } from "../server-heap-telemetry.js";
69
- import { projectAcmeConfigured } from "../tls/sources/acme/config-projection.js";
70
- import { touchesTlsOrPorts, validateTlsConfigWrite } from "../tls/tls-config-validation.js";
71
- import type { TlsListener } from "../tls/tls-listener.js";
72
73
  import type { SessionManager } from "../session/memory-session-manager.js";
73
74
  import { heapFallbackStatus } from "../spawn-process/heap-args.js";
74
75
  import { spawnRestart } from "../spawn-process/restart-helper.js";
75
76
  import { readSpawnFailures } from "../spawn-process/spawn-failure-log.js";
76
77
  import { systemOpenCapability } from "../system-open-capability.js";
78
+ import { projectAcmeConfigured } from "../tls/sources/acme/config-projection.js";
79
+ import { touchesTlsOrPorts, validateTlsConfigWrite } from "../tls/tls-config-validation.js";
80
+ import type { TlsListener } from "../tls/tls-listener.js";
77
81
  import { connectedProviderIds, connectGateway, createTunnel, deleteTunnel, disconnectResolvedProviders, ensureReservedName, gatewayProviderStatus, getProviderReadiness, getTunnelStatus, getTunnelUrl, getZrokLastError, releaseShare } from "../tunnel/tunnel.js";
78
82
  import { acceptTargetFor, blockEvents } from "../tunnel/tunnel-block-events.js";
79
83
  import { collectEndpoints, liveReadinessEndpoints } from "../tunnel/tunnel-endpoints.js";
@@ -81,6 +85,7 @@ import { runEnrollStep } from "../tunnel/tunnel-enroll.js";
81
85
  import { startTunnelWatchdog, stopTunnelWatchdog } from "../tunnel/tunnel-watchdog.js";
82
86
  import { reserveNameAsync } from "../tunnel-providers/zrok.js";
83
87
  import { buildNetworkInterfaceList } from "./network-interfaces.js";
88
+ import type { PiTrustLiveCounters } from "./pi-trust-query-routes.js";
84
89
 
85
90
  /** Heartbeat poll-cost counters summed on /api/health. See change: optimize-polling-hot-paths. */
86
91
  const POLL_COST_KEYS = [
@@ -166,6 +171,23 @@ function saveConfigAndMirror(partial: Record<string, any>) {
166
171
  return runOnConfigSaveChain(run);
167
172
  }
168
173
 
174
+ /**
175
+ * `/api/health` is unauthenticated and tunnel-reachable, so its `plugins[]` stays path- and
176
+ * hash-free: local-detected rows (they name a session cwd's packages), `shadowed` (carries
177
+ * `packageDir`) and `client.sha256` are dropped; `source`, `restartRequired`, `hostApi`,
178
+ * `client.delivery` / `client.refusedReason` and `serveApp` pass through. The guarded
179
+ * `GET /api/plugins` and `plugins_changed` (authenticated WS) carry the full rows.
180
+ * See change: decouple-plugins-from-core (task 5.10, design D15).
181
+ */
182
+ export function toHealthPlugins(statuses: readonly PluginStatus[]): PluginStatus[] {
183
+ return statuses
184
+ .filter((s) => s.source !== "local-detected")
185
+ .map((s) => {
186
+ const { shadowed: _shadowed, client, ...rest } = s;
187
+ return client ? { ...rest, client: { delivery: client.delivery, ...(client.refusedReason ? { refusedReason: client.refusedReason } : {}) } } : rest;
188
+ });
189
+ }
190
+
169
191
  /**
170
192
  * Enrich each plugin status with `bridgeLoadedFrom` by classifying the
171
193
  * plugin's resolved bridge path against the live pi settings.json.
@@ -211,10 +233,19 @@ export function registerSystemRoutes(
211
233
  metaPersistence: MetaPersistence;
212
234
  config: ServerConfig;
213
235
  networkGuard: NetworkGuard;
236
+ /** Strict-proof context: `/api/health` adds `localProof: "required"` for a bare-loopback caller that lacks proof. See change: close-container-loopback-impersonation (D3). */
237
+ localTrust?: LocalTrustContext;
214
238
  version?: string;
215
239
  directoryService?: DirectoryService;
216
240
  /** Called after a `PUT /api/config` that touched `vault`, so delivery switches apply live. See change: add-credential-vault. */
217
241
  onVaultConfigChanged?: () => void;
242
+ /**
243
+ * Called after a `PUT /api/config` that touched `tls`, BEFORE the listener reconcile: withdraw values from, and
244
+ * close, TLS-admitted bridges when Accept bridges or the listener turned off. See change: prove-vault-bridge-tls (D2).
245
+ */
246
+ onTlsBridgeSwitchChanged?: () => void;
247
+ /** True while a first-plaintext-exposure registry write has not persisted; reported on `/api/health`. */
248
+ exposureWritePending?: () => boolean;
218
249
  /** Optional TLS listener: status in `/api/health.tls`, endpoints, reconcile after a `tls` config write. See change: add-tailscale-cert-tls. */
219
250
  tls?: Pick<TlsListener, "status" | "tlsListenerUrls" | "reconcile">;
220
251
  piGateway?: PiGateway;
@@ -249,6 +280,12 @@ export function registerSystemRoutes(
249
280
  // `accessGrants`, failure-isolated like every other telemetry read.
250
281
  // See change: add-access-grant-dialog (task 9.3).
251
282
  readAccessGrants?: () => AccessGrantHealth;
283
+ // Live pi-trust query counters (`piTrustMirror.live`), same disclosure gate as
284
+ // `accessGrants`. See change: mirror-dashboard-trust-live-remote (D6).
285
+ readPiTrustLive?: () => PiTrustLiveCounters;
286
+ // Persisted baseline CSP report counters (`cspReports`), same disclosure gate as `accessGrants`;
287
+ // counts only. See change: harden-cors-and-csp-reporting (D8).
288
+ readCspReports?: () => CspReportsSnapshot;
252
289
  // Live trusted-network list (top-level ∪ auth.bypassHosts) for the additive
253
290
  // `trustPosture` health field. Falls back to the boot list when unwired.
254
291
  // See change: fix-trusted-network-tunnel-bypass (D3).
@@ -292,14 +329,16 @@ export function registerSystemRoutes(
292
329
  clientBuild?: ClientBuildSnapshot;
293
330
  },
294
331
  ) {
295
- const { sessionManager, preferencesStore, metaPersistence, config, networkGuard, version, directoryService, piGateway, browserGateway, hydrationMetrics, readEventLoopDelay, eventLoopSpikes, eventStore, toolResultStats, embedLifecycle, keeperLogStats, clientDir, readAccessGrants, readTrustedNetworks, readPushErrors } = deps;
332
+ const { sessionManager, preferencesStore, metaPersistence, config, networkGuard, version, directoryService, piGateway, browserGateway, hydrationMetrics, readEventLoopDelay, eventLoopSpikes, eventStore, toolResultStats, embedLifecycle, keeperLogStats, clientDir, readAccessGrants, readPiTrustLive, readCspReports, readTrustedNetworks, readPushErrors } = deps;
296
333
 
297
334
  // Served-artifact coherence snapshot (design D4): a startup snapshot, never a
298
335
  // per-request filesystem read (P1).
336
+ // The served declaration decides which plugins the server hashes (design D11): read once with the snapshot.
337
+ const servedDeclaration = readServedDeclaration(clientDir ?? null);
299
338
  const clientBuild =
300
339
  deps.clientBuild ??
301
340
  readClientBuildSnapshot(clientDir ?? null, (policy) =>
302
- runtimePluginRegistryHash(policy === "excluded"),
341
+ runtimePluginRegistryHash(policy === "excluded", servedDeclaration),
303
342
  );
304
343
 
305
344
  // Hoisted for the same reason as `clientBuild`: `runtimePluginRegistryHash`
@@ -312,13 +351,12 @@ export function registerSystemRoutes(
312
351
  // Fixture clients are part of a production build only under the opt-in
313
352
  // PI_DASHBOARD_FIXTURE_PLUGINS gate (docker test harness) — the same rule
314
353
  // the vite plugin applied. See change: expose-plugin-credential-and-oauth-seams (D8).
315
- const bundleHash = runtimePluginRegistryHash(!config.dev && !fixturePluginsEnabled());
354
+ const bundleHash = runtimePluginRegistryHash(!config.dev && !fixturePluginsEnabled(), servedDeclaration);
316
355
 
317
356
  // Quiesce windows for the bridge `server_restarting` broadcast. See change
318
357
  // `fix-restart-bridge-auto-start-race`. Bridges that receive this message
319
358
  // suppress only the spawn step in `server-auto-start.ts` for `quiesceMs`;
320
359
  // discovery + reconnection still run.
321
- const SHUTDOWN_QUIESCE_MS = 60000;
322
360
  const announceRestart = (
323
361
  reason: "restart" | "shutdown",
324
362
  quiesceMs: number,
@@ -467,13 +505,17 @@ export function registerSystemRoutes(
467
505
  }
468
506
  const configModule = await import("@blackbelt-technology/pi-dashboard-shared/config.js");
469
507
  const cfg = configModule.loadConfig();
508
+ const tlsEndpoints = deps.tls?.tlsListenerUrls() ?? [];
470
509
  const endpoints = collectEndpoints({
471
510
  providerEndpoints,
472
511
  publicBaseUrls: configModule.resolvePublicBaseUrls(cfg),
473
512
  port: config.port,
474
- tlsEndpoints: deps.tls?.tlsListenerUrls() ?? [],
513
+ tlsEndpoints,
475
514
  });
476
- return { success: true, data: { endpoints } } satisfies ApiResponse;
515
+ // `tlsEndpoints` names the certificate-backed listener URLs on their own, so the token dialog can point at
516
+ // the native HTTPS address (a tunnel endpoint of the same shape is not a bridge target).
517
+ // See change: prove-vault-bridge-tls (D8).
518
+ return { success: true, data: { endpoints, tlsEndpoints } } satisfies ApiResponse;
477
519
  },
478
520
  );
479
521
 
@@ -639,6 +681,9 @@ export function registerSystemRoutes(
639
681
  // work is scheduled, never awaited here. A reconcile failure is reported in TLS
640
682
  // status; the config stays as written. See change: add-tailscale-cert-tls (D7).
641
683
  if (partial.tls !== undefined) {
684
+ // BEFORE the reconcile: closing the listener waits for upgraded (bridge) sockets, which `closeAllConnections`
685
+ // does not reach, so withdraw values and close TLS-admitted bridges first. See change: prove-vault-bridge-tls (D2).
686
+ deps.onTlsBridgeSwitchChanged?.();
642
687
  try {
643
688
  await deps.tls?.reconcile();
644
689
  } catch (err) {
@@ -1138,6 +1183,17 @@ export function registerSystemRoutes(
1138
1183
  if (canDiscloseAccessPosture(request)) {
1139
1184
  try { accessGrants = readAccessGrants?.() ?? null; } catch { /* keep null */ }
1140
1185
  }
1186
+ // Live pi-trust query counters: same disclosure gate as `accessGrants`.
1187
+ let piTrustMirror: { live: PiTrustLiveCounters } | null = null;
1188
+ if (readPiTrustLive && canDiscloseAccessPosture(request)) {
1189
+ try { piTrustMirror = { live: readPiTrustLive() }; } catch { /* keep null */ }
1190
+ }
1191
+ // Baseline CSP report counters: counts only, same disclosure gate as `accessGrants`. Omitted
1192
+ // (absent, not null) for any other caller or when the read throws. See change: harden-cors-and-csp-reporting (D8).
1193
+ let cspReports: CspReportsSnapshot | null = null;
1194
+ if (readCspReports && canDiscloseAccessPosture(request)) {
1195
+ try { cspReports = readCspReports(); } catch { /* omit */ }
1196
+ }
1141
1197
  // Inert-entry flag: a loopback entry in trustedNetworks/bypassHosts never
1142
1198
  // admits tunnel traffic. Same disclosure gate as `accessGrants`.
1143
1199
  // See change: fix-trusted-network-tunnel-bypass (D3).
@@ -1191,6 +1247,12 @@ export function registerSystemRoutes(
1191
1247
  // Access-grant prompting counters (additive; null when unwired or on a
1192
1248
  // throwing read). See change: add-access-grant-dialog (task 9.3).
1193
1249
  accessGrants,
1250
+ piTrustMirror,
1251
+ ...(cspReports ? { cspReports } : {}),
1252
+ // A bare-loopback caller the strict default refuses for want of proof is told so (the
1253
+ // remedy is `pi-dashboard open`). Absent for every other caller. See change:
1254
+ // close-container-loopback-impersonation (D3).
1255
+ ...(needsLocalProof(request, deps.localTrust) ? { localProof: LOCAL_PROOF_REQUIRED } : {}),
1194
1256
  ...(tlsStatus ? { tls: tlsStatus } : {}),
1195
1257
  // Loopback-trusted-entry posture (additive; null unless disclosable).
1196
1258
  // See change: fix-trusted-network-tunnel-bypass (D3).
@@ -1299,7 +1361,7 @@ export function registerSystemRoutes(
1299
1361
  // server log so it is discoverable live, not only post-mortem.
1300
1362
  // See change: bound-session-heap-and-gc-telemetry (D3a).
1301
1363
  sessionHeapFallback: heapFallbackStatus(),
1302
- plugins: enrichWithBridgeSource(getPluginStatusStore().listAll()),
1364
+ plugins: toHealthPlugins(enrichWithBridgeSource(getPluginStatusStore().listAll())),
1303
1365
  bundleHash,
1304
1366
  // Served-artifact coherence (design D4). Additive; `bundleHash` above
1305
1367
  // keeps its shape and meaning. No filesystem path is exposed.
@@ -1307,8 +1369,12 @@ export function registerSystemRoutes(
1307
1369
  clientBuild,
1308
1370
  proxy: getModelProxyStatus(),
1309
1371
  // Windows-only: active git/sh source readout for Settings + Diagnostics.
1310
- // null on macOS/Linux. See change: embed-git-bash-on-windows.
1311
- gitSource: getGitSourceReadout(whichSync),
1372
+ // null on macOS/Linux. `shellPath` is the bash.exe pi would resolve over the
1373
+ // same env a real spawn gets (buildSpawnEnv). See change:
1374
+ // embed-git-bash-on-windows, fix-windows-bundled-bash-exe.
1375
+ gitSource: getGitSourceReadout(whichSync, {
1376
+ spawnEnv: () => new ToolResolver({ processExecPath: process.execPath }).buildSpawnEnv(process.env),
1377
+ }),
1312
1378
  // Event-loop delay (ms) over the window since the last /api/health read.
1313
1379
  // Correlates hydration spikes with real main-loop lag. Additive field.
1314
1380
  // See change: instrument-session-hydration-timing.
@@ -1327,6 +1393,9 @@ export function registerSystemRoutes(
1327
1393
  // Pi runtime divergence, under two distinct labels (see readPiDivergence).
1328
1394
  // See change: select-pi-runtime-install (design D5).
1329
1395
  piRuntime: readPiDivergence(),
1396
+ // A first plaintext-exposure write has not persisted: the hub refuses all remote vault delivery while true.
1397
+ // See change: prove-vault-bridge-tls (D4).
1398
+ pairing: { exposureWritePending: deps.exposureWritePending?.() === true },
1330
1399
  // Per-hop dropped-frame counters (observability for silently-dropped
1331
1400
  // WS frames). `serverToBrowser` = frames the fanout skipped under
1332
1401
  // back-pressure, split transcript vs blocking; `bridgeToServer` = the max
@@ -0,0 +1,88 @@
1
+ /**
2
+ * Pure resolver for the absolute origin used in `GET /api/sessions` `uiUrl` /
3
+ * `diffUrl`: the origin the caller actually used, never a reflected raw header.
4
+ *
5
+ * 1. Configured match — the first of (first `X-Forwarded-Host` value, `Host`)
6
+ * whose normalized hostname equals a configured origin's hostname selects
7
+ * that origin (scheme + port from the configured entry).
8
+ * 2. Admitted direct host — `Host` passes `isAdmitted` (checked even when the
9
+ * host gate runs in `report` mode): `<protocol>://<normalized host>[:port]`.
10
+ * 3. Otherwise `<protocol>://localhost:<port>` — deliberately NOT
11
+ * `resolveRedirectBase`, which would hand the tunnel origin to an unadmitted
12
+ * caller in report mode.
13
+ *
14
+ * `X-Forwarded-Host` can only SELECT a configured origin; it never mints one.
15
+ * See change: add-session-ui-deep-links-for-agents (D1).
16
+ */
17
+ import { hostnameFromUrl, parseHostname } from "@blackbelt-technology/pi-dashboard-shared/host-admission.js";
18
+
19
+ export interface UiBaseInput {
20
+ /** Raw `Host` header. */
21
+ host: string | undefined;
22
+ /** Raw `X-Forwarded-Host` header (only its first comma-separated value is read). */
23
+ forwardedHost: string | undefined;
24
+ /** `request.protocol` (accurate for direct connections; `trustProxy` is off). */
25
+ protocol: string;
26
+ /** Public bases, every live tunnel origin and `auth.redirectBaseUrl`, in precedence order. */
27
+ configuredOrigins: string[];
28
+ /** `isHostAdmitted` bound to the server's current options. */
29
+ isAdmitted: (hostHeader: string | undefined) => boolean;
30
+ /** The server's listening port. */
31
+ port: number;
32
+ }
33
+
34
+ const stripSlashes = (s: string): string => s.replace(/\/+$/, "");
35
+
36
+ /**
37
+ * Trailing `:digits` of a raw Host, only when 1–65535. An UNBRACKETED IPv6
38
+ * literal has no port (its last group is not one), so only a name/IPv4 host or
39
+ * a bracketed `[v6]:port` yields a port.
40
+ */
41
+ function validPort(hostHeader: string): string | null {
42
+ const value = hostHeader.trim();
43
+ const bracketed = value.startsWith("[");
44
+ const portStart = bracketed ? value.indexOf("]") + 1 : value.indexOf(":");
45
+ if (portStart <= 0) return null; // no port separator (or a malformed bracket)
46
+ if (!bracketed && value.indexOf(":", portStart + 1) !== -1) return null; // unbracketed IPv6
47
+ const m = /^:(\d{1,5})$/.exec(value.slice(portStart));
48
+ if (!m) return null;
49
+ const n = Number(m[1]);
50
+ return n >= 1 && n <= 65535 ? String(n) : null;
51
+ }
52
+
53
+ /** Configured origin whose hostname equals the first matching candidate (candidate order, then origin order). */
54
+ function matchConfiguredOrigin(candidates: string[], origins: string[]): string | null {
55
+ for (const candidate of candidates) {
56
+ for (const origin of origins) {
57
+ if (hostnameFromUrl(origin) !== candidate) continue;
58
+ try {
59
+ return stripSlashes(new URL(origin).origin);
60
+ } catch {
61
+ // unparseable entry: skip, never throw
62
+ }
63
+ }
64
+ }
65
+ return null;
66
+ }
67
+
68
+ /** `<protocol>://<normalized host>[:port]` for an admitted `Host`, else null. */
69
+ function admittedDirectBase(input: UiBaseInput): string | null {
70
+ if (input.host === undefined || !input.isAdmitted(input.host)) return null;
71
+ const hostname = parseHostname(input.host);
72
+ if (!hostname) return null;
73
+ const bracketed = hostname.includes(":") ? `[${hostname}]` : hostname;
74
+ const port = validPort(input.host);
75
+ return `${input.protocol}://${bracketed}${port ? `:${port}` : ""}`;
76
+ }
77
+
78
+ export function resolveRequestUiBase(input: UiBaseInput): string {
79
+ const firstForwarded = input.forwardedHost?.split(",")[0];
80
+ const candidates = [parseHostname(firstForwarded), parseHostname(input.host)].filter(
81
+ (h): h is string => h !== null,
82
+ );
83
+ return (
84
+ matchConfiguredOrigin(candidates, input.configuredOrigins) ??
85
+ admittedDirectBase(input) ??
86
+ `${input.protocol}://localhost:${input.port}`
87
+ );
88
+ }
@@ -19,6 +19,7 @@ import { pipeline } from "node:stream/promises";
19
19
  import { normalizeEnvPathKey } from "@blackbelt-technology/pi-dashboard-shared/platform/env-path-key.js";
20
20
  import { execFileAsync } from "@blackbelt-technology/pi-dashboard-shared/platform/exec.js";
21
21
  import { prependManagedNodeToPath } from "@blackbelt-technology/pi-dashboard-shared/platform/managed-node-path.js";
22
+ import { assertSafeArchiveListing } from "@blackbelt-technology/pi-dashboard-shared/runtime-overlay/archive-safety.mjs";
22
23
  import { getDefaultRegistry } from "@blackbelt-technology/pi-dashboard-shared/tool-registry/index.js";
23
24
  import type { RuntimeLock, StagerDeps } from "./runtime-stager.js";
24
25
  import { RUNTIME_GITHUB_REPO, RUNTIME_SERVER_PACKAGE, type RuntimeReleaseFeeds } from "./runtime-update-checker.js";
@@ -49,19 +50,11 @@ async function npm(args: string[], cwd: string, timeoutMs = NPM_TIMEOUT_MS): Pro
49
50
  /** List members; refuse any that are absolute, climb out (`..`), or are links — before extracting. */
50
51
  async function safeMembers(tgz: string): Promise<string[]> {
51
52
  const { stdout } = await execFileAsync("tar", ["-tzf", tgz], { timeout: NPM_TIMEOUT_MS, maxBuffer: MAX_BUFFER });
52
- const names = String(stdout).split(/\r?\n/).filter(Boolean);
53
- for (const name of names) {
54
- if (path.isAbsolute(name) || /^[a-zA-Z]:/.test(name) || name.startsWith("\\") || name.split(/[\\/]/).includes("..")) {
55
- throw new Error(`unsafe_archive member ${JSON.stringify(name)}`);
56
- }
57
- }
58
53
  // Links could point out of the staging dir and a later member write through
59
54
  // them. A runtime tree has no links (npm ci output, plugins copied), so refuse
60
55
  // all. `tar -tv` (bsdtar and GNU) starts each line with the entry type.
61
56
  const { stdout: verbose } = await execFileAsync("tar", ["-tvzf", tgz], { timeout: NPM_TIMEOUT_MS, maxBuffer: MAX_BUFFER });
62
- const link = String(verbose).split(/\r?\n/).find((line) => /^[lh]/.test(line));
63
- if (link) throw new Error(`unsafe_archive link member ${JSON.stringify(link.trim())}`);
64
- return names;
57
+ return assertSafeArchiveListing(String(stdout), String(verbose));
65
58
  }
66
59
 
67
60
  async function tarExtract(tgz: string, destDir: string, members: string[] = []): Promise<void> {