@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
@@ -8,13 +8,21 @@ import fs from "node:fs/promises";
8
8
  import { createRequire } from "node:module";
9
9
  import os from "node:os";
10
10
  import path from "node:path";
11
+ import type { CwdHoldDecision } from "@blackbelt-technology/dashboard-plugin-runtime/server";
11
12
  import { loadConfig } from "@blackbelt-technology/pi-dashboard-shared/config.js";
13
+ import { containmentAllows } from "@blackbelt-technology/pi-dashboard-shared/containment-guard.js";
14
+ import {
15
+ admissionAllows,
16
+ issueHeldAdmission,
17
+ releaseAdmission,
18
+ } from "@blackbelt-technology/pi-dashboard-shared/cwd-guard.js";
12
19
  import { DIGEST_CEILING_BYTES, fileKind } from "@blackbelt-technology/pi-dashboard-shared/file-kind.js";
13
20
  import { repairAsciiDoc } from "@blackbelt-technology/pi-dashboard-shared/markup-repair/asciidoc.js";
14
21
  import { realpathAsync } from "@blackbelt-technology/pi-dashboard-shared/platform/git.js";
22
+ import { ASCIIDOC_PROFILE, keepColWidthStyleOnly } from "@blackbelt-technology/pi-dashboard-shared/sanitize-profiles.js";
15
23
  import type { ApiResponse } from "@blackbelt-technology/pi-dashboard-shared/types.js";
16
24
  import type { FastifyInstance } from "fastify";
17
- import { type DenialRemedy, evaluateContainment } from "../access/containment-gate.js";
25
+ import { type DenialRemedy, decidePassive, evaluateContainment } from "../access/containment-gate.js";
18
26
  import { resolveCwdVerdict } from "../access/cwd-verdict.js";
19
27
  import { type HoldTarget, holdDenial } from "../access/denial-hold.js";
20
28
  import {
@@ -24,7 +32,8 @@ import {
24
32
  readFileVerifiedUtf8,
25
33
  VerifiedReadRefused,
26
34
  } from "../access/verified-read.js";
27
- import { canDiscloseAccessPosture } from "../auth/localhost-guard.js";
35
+ import type { LocalTrustContext } from "../auth/local-proof.js";
36
+ import { canDiscloseAccessPosture, isLocallyTrusted } from "../auth/localhost-guard.js";
28
37
  import {
29
38
  CreateProjectError,
30
39
  type CreateProjectReason,
@@ -34,12 +43,21 @@ import {
34
43
  listDirectories,
35
44
  parseFlagsQuery,
36
45
  } from "../browse.js";
37
- import { BROWSE_OUTSIDE_ROOTS_ERROR, isWithinBrowseRoots, resolveBrowseRoots } from "../lib/browse-roots.js";
38
46
  import { isImageUnderArtifactRoot } from "../lib/artifact-roots.js";
47
+ import {
48
+ BROWSE_OUTSIDE_ROOTS_ERROR,
49
+ type BrowseRootSources,
50
+ type BrowseRoots,
51
+ buildBrowseRootSources,
52
+ isWithinBrowseRoots,
53
+ resolveBrowseRoots,
54
+ } from "../lib/browse-roots.js";
55
+ import { DashboardStateRefused, openStateChecked, readFileStateChecked } from "../lib/dashboard-state-guard.js";
39
56
  import { decodeFileUri } from "../lib/decode-file-uri.js";
40
57
  import { renderDiagram } from "../lib/diagram-render.js";
41
58
  import { createDigestGate, type DigestGate, type DigestLane } from "../lib/digest-gate.js";
42
59
  import { EML_SIZE_CAP, loadParsedEml, toParseResult } from "../lib/eml.js";
60
+ import { admitFileCwd, CWD_UNAVAILABLE_FAILURE, cwdAnchors, type GateWire, releaseOnClose } from "../lib/file-cwd-admission.js";
43
61
  import { enumerateMdCandidates } from "../lib/md-candidates.js";
44
62
  import { extToContentType } from "../lib/mime-types.js";
45
63
  import {
@@ -54,24 +72,31 @@ import {
54
72
  renderPptx,
55
73
  resolveRowLimit,
56
74
  } from "../lib/office-preview.js";
57
- import { isAllowed, safeRealpath } from "../lib/path-containment.js";
75
+ import { safeRealpath } from "../lib/path-containment.js";
58
76
  import { loadPurify } from "../lib/purify.js";
77
+ import { admitRouteCwd, listKnownFolderCwds, type RouteAdmissionDeps } from "../lib/route-admission.js";
59
78
 
60
79
  /**
61
80
  * A gate failure. `error` is byte-identical to what the site returned before
62
81
  * this change; `reason`/`hint`/`subject`/`denialId` are ADDITIVE (design D7) so
63
82
  * the denial can name its remedy and bind a later grant to this refusal (D15).
64
83
  * `{ code, error }` stays INTERNAL — callers convert via `denialBody`.
84
+ * `code` is the HTTP status; the wire `code` string lives in `wire`.
65
85
  */
66
- type GateFailure = { code: number; error: string } & Partial<DenialRemedy>;
86
+ export type GateFailure = { code: number; error: string; wire?: GateWire } & Partial<DenialRemedy>;
67
87
 
68
88
  /**
69
89
  * The single conversion from a gate failure to the wire body. Every containment
70
90
  * caller uses this so the additive fields cannot drift between sites, and so
71
91
  * pre-existing fields stay byte-identical (task 3.2).
72
92
  */
73
- function denialBody(gate: GateFailure): ApiResponse {
93
+ export function denialBody(gate: GateFailure): ApiResponse {
74
94
  const body: Record<string, unknown> = { success: false, error: gate.error };
95
+ if (gate.wire !== undefined) {
96
+ body.code = gate.wire.code;
97
+ if (gate.wire.message !== undefined) body.message = gate.wire.message;
98
+ if (gate.wire.retryAfterMs !== undefined) body.retryAfterMs = gate.wire.retryAfterMs;
99
+ }
75
100
  if (gate.reason !== undefined) body.reason = gate.reason;
76
101
  if (gate.hint !== undefined) body.hint = gate.hint;
77
102
  if (gate.subject !== undefined) body.subject = gate.subject;
@@ -82,6 +107,17 @@ function denialBody(gate: GateFailure): ApiResponse {
82
107
  return body as unknown as ApiResponse;
83
108
  }
84
109
 
110
+ /**
111
+ * Reply with a gate failure: the status, `Retry-After: 1` on a 503 (an undecidable
112
+ * cwd admission), and the `denialBody`. Every caller of the file gate helpers uses
113
+ * this so the 503 contract cannot drift between sites. See change: core-file-cwd-admission (D3).
114
+ */
115
+ export function sendGateFailure(reply: import("fastify").FastifyReply, gate: GateFailure): ApiResponse {
116
+ reply.code(gate.code);
117
+ if (gate.code === 503) reply.header("Retry-After", "1");
118
+ return denialBody(gate);
119
+ }
120
+
85
121
  import { serializeWrite } from "../lib/file-write-lock.js";
86
122
  import { resolveFileMention } from "../lib/resolve-file-mention.js";
87
123
  import { isWritableMdTarget } from "../lib/writable-md-target.js";
@@ -97,6 +133,23 @@ import {
97
133
  import { type FileHandlerDeps, registerFileWriteBinaryRoute } from "./file-write-binary-routes.js";
98
134
  import type { NetworkGuard } from "./route-deps.js";
99
135
 
136
+ /** Per-response sandbox for scriptable raw responses. See change: harden-raw-svg-responses. */
137
+ export const RAW_SANDBOX_CSP =
138
+ "sandbox; default-src 'none'; style-src 'unsafe-inline'; img-src data:; font-src data:; frame-ancestors 'self'";
139
+
140
+ const SCRIPTABLE_MEDIA_TYPES = new Set([
141
+ "text/html",
142
+ "image/svg+xml",
143
+ "application/xhtml+xml",
144
+ "application/xml",
145
+ "text/xml",
146
+ ]);
147
+
148
+ /** True when a browser would execute script from this `Content-Type` (params/case ignored). */
149
+ export function isScriptableMediaType(contentType: string): boolean {
150
+ return SCRIPTABLE_MEDIA_TYPES.has(contentType.split(";")[0].trim().toLowerCase());
151
+ }
152
+
100
153
  // Per-target write serialization. The optimistic mtime check + atomic rename
101
154
  // must run as one critical section per file, else two concurrent writes can
102
155
  // both read the same mtime, both pass, and the later rename clobbers the earlier
@@ -138,23 +191,32 @@ async function hashHandle(fh: import("node:fs/promises").FileHandle, signal: Abo
138
191
  }
139
192
 
140
193
  // Resolve + scope-validate a markdown target shared by the write + md-read
141
- // endpoints. Directory scope (cwd present) requires a known session; global
142
- // scope requires an absolute path. Returns the resolved abs path, or {code,error}
143
- // to map to a reply. Authorization (`isWritableMdTarget`) is applied by callers.
144
- // See change: directory-settings-page-and-scoped-md-editing.
145
- function resolveScopedMdPath(
146
- cwd: string | undefined,
194
+ // endpoints. Directory scope (cwd present) requires an admitted cwd (shared
195
+ // guard: session, pinned, workspace folder or a worktree / main checkout of a
196
+ // known repository); global scope (cwd absent: undefined, null or "") requires
197
+ // an absolute path. Any other cwd value that is not an absolute string is
198
+ // REFUSED — it never selects the global scope. Returns the resolved abs path
199
+ // plus the guarded `cwd` (undefined in global scope: the no-cwd branch hands the
200
+ // sinks a constant, never the request value), or a GateFailure. Authorization
201
+ // (`isWritableMdTarget`) is applied by callers.
202
+ // See change: directory-settings-page-and-scoped-md-editing, core-file-cwd-admission.
203
+ async function resolveScopedMdPath(
204
+ rawCwd: unknown,
147
205
  rawPath: string,
148
- sessionManager: SessionManager,
149
- ): { resolved: string } | { code: number; error: string } {
150
- if (cwd && !sessionManager.listAll().some((s) => s.cwd === cwd)) {
151
- return { code: 403, error: "unknown session path" };
152
- }
206
+ routeAdmission: RouteAdmissionDeps,
207
+ ): Promise<{ resolved: string; cwd: string | undefined } | GateFailure> {
153
208
  const decoded = decodeFileUri(rawPath);
154
- if (!cwd && !path.isAbsolute(decoded)) {
155
- return { code: 400, error: "global scope requires an absolute path" };
209
+ if (rawCwd === undefined || rawCwd === null || rawCwd === "") {
210
+ if (!path.isAbsolute(decoded)) return { code: 400, error: "global scope requires an absolute path" };
211
+ return { resolved: path.resolve(decoded), cwd: undefined };
212
+ }
213
+ const admitted = await admitFileCwd(rawCwd, routeAdmission);
214
+ if (!admitted.ok) return admitted.failure;
215
+ try {
216
+ return { resolved: path.resolve(admitted.cwd, decoded), cwd: admitted.cwd };
217
+ } finally {
218
+ admitted.release();
156
219
  }
157
- return { resolved: cwd ? path.resolve(cwd, decoded) : path.resolve(decoded) };
158
220
  }
159
221
 
160
222
  /** Discriminated outcome of an atomic markdown write. */
@@ -163,25 +225,24 @@ type MdWriteOutcome =
163
225
  | { code: 404 | 409 | 413 | 500; error: string };
164
226
 
165
227
  /** Parsed + authorized write request, or a {code,error} reply mapping. */
166
- type MdWritePrep = { resolved: string; content: string; mtime: number } | { code: number; error: string };
228
+ type MdWritePrep = { resolved: string; content: string; mtime: number } | GateFailure;
167
229
 
168
230
  // Parse, scope-validate, and authorize a `POST /api/file/write` body. Keeps the
169
231
  // route handler trivial. Authorization is the `isWritableMdTarget` security
170
232
  // boundary. See change: directory-settings-page-and-scoped-md-editing.
171
233
  async function prepareMdWrite(
172
234
  body: { cwd?: unknown; path?: unknown; content?: unknown; mtime?: unknown },
173
- sessionManager: SessionManager,
235
+ routeAdmission: RouteAdmissionDeps,
174
236
  ): Promise<MdWritePrep> {
175
- const cwd = typeof body.cwd === "string" && body.cwd ? body.cwd : undefined;
176
237
  const rawPath = typeof body.path === "string" ? body.path : "";
177
238
  const content = typeof body.content === "string" ? body.content : undefined;
178
239
  const mtime = typeof body.mtime === "number" ? body.mtime : undefined;
179
240
  if (!rawPath || content === undefined || mtime === undefined) {
180
241
  return { code: 400, error: "path, content and mtime are required" };
181
242
  }
182
- const target = resolveScopedMdPath(cwd, rawPath, sessionManager);
243
+ const target = await resolveScopedMdPath(body.cwd, rawPath, routeAdmission);
183
244
  if ("code" in target) return target;
184
- if (!(await isWritableMdTarget(target.resolved, { cwd }))) {
245
+ if (!(await isWritableMdTarget(target.resolved, { cwd: target.cwd }))) {
185
246
  return { code: 403, error: "target is not a writable markdown file in scope" };
186
247
  }
187
248
  return { resolved: target.resolved, content, mtime };
@@ -291,17 +352,8 @@ function convertAdocCapturingWarnings(source: string): { html: string; warnings:
291
352
  // asciidoctor `safe:"secure"` still passes raw HTML through (`+++…+++`,
292
353
  // `pass:[…]`), so the converted HTML is sanitized with DOMPurify before it is
293
354
  // returned. `style` survives only as asciidoctor's own `<col style="width: N%;">`
294
- // column widths. A module-scope hook function so `removeHook` matches by
295
- // identity. See change: sanitize-untrusted-rendered-content.
296
- const COL_WIDTH_STYLE_RE = /^\s*width:\s*[\d.]+%?;?\s*$/;
297
- function keepColWidthStyleOnly(
298
- node: { nodeName: string },
299
- data: { attrName: string; attrValue: string; keepAttr: boolean },
300
- ): void {
301
- if (data.attrName !== "style") return;
302
- const tag = node.nodeName.toLowerCase();
303
- if ((tag !== "col" && tag !== "colgroup") || !COL_WIDTH_STYLE_RE.test(data.attrValue)) data.keepAttr = false;
304
- }
355
+ // column widths (`keepColWidthStyleOnly`, shared with the client policy in
356
+ // sanitize-profiles.ts). See change: sanitize-untrusted-rendered-content.
305
357
 
306
358
  async function sanitizeAdocHtml(html: string): Promise<string> {
307
359
  const purify = await loadPurify();
@@ -312,10 +364,7 @@ async function sanitizeAdocHtml(html: string): Promise<string> {
312
364
  // no `await`, so it cannot interleave with another sanitize call.
313
365
  purify.addHook("uponSanitizeAttribute", keepColWidthStyleOnly);
314
366
  try {
315
- return purify.sanitize(html, {
316
- USE_PROFILES: { html: true },
317
- FORBID_TAGS: ["style", "form", "input", "button", "textarea", "select"],
318
- });
367
+ return purify.sanitize(html, ASCIIDOC_PROFILE);
319
368
  } finally {
320
369
  purify.removeHook("uponSanitizeAttribute", keepColWidthStyleOnly);
321
370
  }
@@ -325,24 +374,33 @@ async function sanitizeAdocHtml(html: string): Promise<string> {
325
374
  // `/api/file/raw` (known session + `isAllowed` against the cwd anchor), factored
326
375
  // so both new routes CALL it rather than re-implementing the containment logic
327
376
  // (design D5). Returns the resolved abs path or a {code,error} reply mapping.
328
- async function gateFilePath(
377
+ export async function gateFilePath(
329
378
  cwd: string | undefined,
330
379
  relPath: string | undefined,
331
- sessionManager: SessionManager,
332
- /** `disclosure`: the caller may see `promptOutcome` (`canDiscloseAccessPosture`). */
333
- opts: { allowGrant?: boolean; disclosure?: boolean } = {},
380
+ routeAdmission: RouteAdmissionDeps,
381
+ /**
382
+ * `disclosure`: the caller may see `promptOutcome` (`canDiscloseAccessPosture`).
383
+ * `quiet`: record no denial and raise no prompt (a per-request re-check on a static preview).
384
+ */
385
+ opts: { allowGrant?: boolean; disclosure?: boolean; quiet?: boolean } = {},
334
386
  ): Promise<{ resolved: string; viaGrant: boolean } | GateFailure> {
335
387
  if (!cwd || !relPath) return { code: 400, error: "cwd and path parameters required" };
336
- if (!sessionManager.listAll().some((s) => s.cwd === cwd)) {
337
- return { code: 403, error: "unknown session path" };
388
+ const admitted = await admitFileCwd(cwd, routeAdmission);
389
+ if (!admitted.ok) return admitted.failure;
390
+ let resolved: string;
391
+ let decision: Awaited<ReturnType<typeof evaluateContainment>>;
392
+ try {
393
+ resolved = path.resolve(admitted.cwd, relPath);
394
+ decision = await evaluateContainment(resolved, cwdAnchors(admitted), {
395
+ site: "file-routes:gateFilePath",
396
+ allowGrant: opts.allowGrant,
397
+ disclosure: opts.disclosure,
398
+ ...(opts.quiet ? { quiet: true } : {}),
399
+ });
400
+ } finally {
401
+ admitted.release();
338
402
  }
339
- const resolved = path.resolve(cwd, relPath);
340
- const decision = await evaluateContainment(resolved, [cwd], {
341
- site: "file-routes:gateFilePath",
342
- allowGrant: opts.allowGrant,
343
- disclosure: opts.disclosure,
344
- });
345
- if (!decision.allowed) {
403
+ if (!containmentAllows(decision, resolved)) {
346
404
  return { code: 403, error: "path outside working directory", ...decision.remedy };
347
405
  }
348
406
  // `viaGrant` MUST be propagated: `assertRegularFile` and the handle-verified
@@ -366,7 +424,7 @@ async function gateReadPath(
366
424
  cwd: string | undefined,
367
425
  rawPath: string | undefined,
368
426
  req: {
369
- sessionManager: SessionManager;
427
+ routeAdmission: RouteAdmissionDeps;
370
428
  request: import("fastify").FastifyRequest;
371
429
  reply: import("fastify").FastifyReply;
372
430
  quiet?: boolean;
@@ -374,22 +432,27 @@ async function gateReadPath(
374
432
  ): Promise<{ resolved: string; viaGrant: boolean; relPath: string } | GateFailure> {
375
433
  const relPath = rawPath ? decodeFileUri(rawPath) : rawPath;
376
434
  if (!cwd || !relPath) return { code: 400, error: "cwd and path parameters required" };
377
- if (!req.sessionManager.listAll().some((s) => s.cwd === cwd)) {
378
- return { code: 403, error: "unknown session path" };
435
+ const admitted = await admitFileCwd(cwd, req.routeAdmission);
436
+ if (!admitted.ok) return admitted.failure;
437
+ let resolved: string;
438
+ let readDecision: Awaited<ReturnType<typeof evaluateContainment>>;
439
+ try {
440
+ resolved = path.resolve(admitted.cwd, relPath);
441
+ // Anchors include the fixed `~/.pi` allowlist so a resolved `~/.pi/…`
442
+ // mention (from `/api/file/resolve-mention`) previews without a 403 (D7).
443
+ readDecision = await evaluateContainment(resolved, [...cwdAnchors(admitted), homePiAnchor()], {
444
+ site: "file-routes:read",
445
+ ...(req.quiet ? { quiet: true } : { hold: { request: req.request, reply: req.reply } }),
446
+ disclosure: canDiscloseAccessPosture(req.request),
447
+ session: admitted.cwd,
448
+ // Polymorphic: this route serves files AND directories, so the remedy
449
+ // must name whichever the target is (task 4.5 round 2, B1).
450
+ subjectKind: "auto",
451
+ });
452
+ } finally {
453
+ admitted.release();
379
454
  }
380
- const resolved = path.resolve(cwd, relPath);
381
- // Anchors include the fixed `~/.pi` allowlist so a resolved `~/.pi/…`
382
- // mention (from `/api/file/resolve-mention`) previews without a 403 (D7).
383
- const readDecision = await evaluateContainment(resolved, [cwd, homePiAnchor()], {
384
- site: "file-routes:read",
385
- ...(req.quiet ? { quiet: true } : { hold: { request: req.request, reply: req.reply } }),
386
- disclosure: canDiscloseAccessPosture(req.request),
387
- session: cwd,
388
- // Polymorphic: this route serves files AND directories, so the remedy
389
- // must name whichever the target is (task 4.5 round 2, B1).
390
- subjectKind: "auto",
391
- });
392
- if (!readDecision.allowed) {
455
+ if (!containmentAllows(readDecision, resolved)) {
393
456
  return { code: 403, error: "path outside working directory", ...readDecision.remedy };
394
457
  }
395
458
  return { resolved, viaGrant: readDecision.viaGrant, relPath };
@@ -430,10 +493,29 @@ export function registerFileRoutes(
430
493
  // Plugin file-handler registry/validator seams for `POST /api/file/write-binary`
431
494
  // (change: add-editor-pane-file-handlers). Absent → every handler save is refused (403).
432
495
  fileHandlers?: FileHandlerDeps;
496
+ // Browse confinement (change: harden-server-capability-bounds, D1/D2).
497
+ // `localTrust`: strict-mode context for `isLocallyTrusted`. `browseRootSources`:
498
+ // the two root sources only server.ts can read (worktree-init trust roots and
499
+ // project-scope access grants); pinned dirs, session cwds and workspace
500
+ // folders come from `preferencesStore` / `sessionManager`.
501
+ localTrust?: LocalTrustContext;
502
+ browseRootSources?: Pick<BrowseRootSources, "worktreeRoots" | "projectGrants">;
503
+ /** `browse.confineRemote` (default true). `false` = a remote caller browses like a local one. */
504
+ browseConfineRemote?: boolean;
505
+ /**
506
+ * Shared cwd admission (change: core-file-cwd-admission, D1): `knownCwds` is the live known-folder
507
+ * set (sessions ∪ pins ∪ workspace folders), `admitOptions` the host logger + test seams. Absent →
508
+ * the known set of this registrar's own `sessionManager` + `preferencesStore`.
509
+ */
510
+ routeAdmission?: RouteAdmissionDeps;
433
511
  },
434
512
  ) {
435
513
  const { sessionManager, preferencesStore, networkGuard } = deps;
436
- registerFileWriteBinaryRoute(fastify, { sessionManager, networkGuard, fileHandlers: deps.fileHandlers });
514
+ const routeAdmission: RouteAdmissionDeps = {
515
+ ...deps.routeAdmission,
516
+ knownCwds: deps.routeAdmission?.knownCwds ?? (() => listKnownFolderCwds({ sessionManager, preferencesStore })),
517
+ };
518
+ registerFileWriteBinaryRoute(fastify, { sessionManager, networkGuard, fileHandlers: deps.fileHandlers, routeAdmission });
437
519
  const systemOpenCapable = deps.systemOpen?.capable ?? systemOpenCapability;
438
520
  const systemOpenRun = deps.systemOpen?.run ?? runOpener;
439
521
  const systemOpenPlatform = deps.systemOpen?.platform ?? process.platform;
@@ -460,12 +542,20 @@ export function registerFileRoutes(
460
542
  if (!cwd || !relPath) return { code: 400, error: "cwd and path parameters required" };
461
543
  const ext = path.extname(relPath).toLowerCase();
462
544
  if (!allowedExts.includes(ext)) return { code: 400, error: "renderer not supported for extension" };
463
- if (!sessionManager.listAll().some((s) => s.cwd === cwd)) {
464
- return { code: 403, error: "unknown session path" };
545
+ const admitted = await admitFileCwd(cwd, routeAdmission);
546
+ if (!admitted.ok) return admitted.failure;
547
+ let resolved: string;
548
+ let decision: Awaited<ReturnType<typeof evaluateContainment>>;
549
+ try {
550
+ resolved = path.resolve(admitted.cwd, relPath);
551
+ decision = await evaluateContainment(resolved, cwdAnchors(admitted), {
552
+ site: "file-routes:gateOfficeFile",
553
+ disclosure,
554
+ });
555
+ } finally {
556
+ admitted.release();
465
557
  }
466
- const resolved = path.resolve(cwd, relPath);
467
- const decision = await evaluateContainment(resolved, [cwd], { site: "file-routes:gateOfficeFile", disclosure });
468
- if (!decision.allowed) {
558
+ if (!containmentAllows(decision, resolved)) {
469
559
  return { code: 403, error: "path outside working directory", ...decision.remedy };
470
560
  }
471
561
  let stat: import("node:fs").Stats;
@@ -493,9 +583,28 @@ export function registerFileRoutes(
493
583
  return { resolved, ext, stat, viaGrant: decision.viaGrant };
494
584
  }
495
585
 
496
- // Allowed browse roots: `$HOME` + current pinned dirs, recomputed per request
497
- // so a pin/unpin takes effect immediately. See change: harden-server-capability-bounds.
498
- const browseRoots = () => resolveBrowseRoots(preferencesStore.getPinnedDirectories());
586
+ // Browse confinement applies ONLY to requests that are not genuinely local
587
+ // (tunnel, LAN, relayed loopback). Returns the shared-root set to enforce, or
588
+ // `null` for a local request (unrestricted picker). Roots are recomputed per
589
+ // request so a pin / unpin / grant applies immediately.
590
+ // See change: harden-server-capability-bounds (D1, D2).
591
+ const browseRootSources = buildBrowseRootSources({
592
+ preferencesStore,
593
+ sessionManager,
594
+ worktreeRoots: deps.browseRootSources?.worktreeRoots,
595
+ projectGrants: deps.browseRootSources?.projectGrants,
596
+ });
597
+ async function confinedRoots(request: { ip: string; headers: Record<string, unknown> }): Promise<BrowseRoots | null> {
598
+ if (deps.browseConfineRemote === false) return null;
599
+ if (isLocallyTrusted({ ip: request.ip, headers: request.headers }, deps.localTrust)) return null;
600
+ return resolveBrowseRoots(browseRootSources);
601
+ }
602
+ const refuseOutsideRoots = (reply: { code(n: number): unknown }, route: string, requested: string) => {
603
+ // JSON.stringify: the path is caller-controlled, so a newline must not forge a log line.
604
+ console.warn(`[browse] refused ${route}: ${JSON.stringify(requested)} is outside the shared roots`);
605
+ reply.code(403);
606
+ return { success: false, error: BROWSE_OUTSIDE_ROOTS_ERROR } satisfies ApiResponse;
607
+ };
499
608
 
500
609
  // Directory browse endpoint.
501
610
  // `detect=1` opts into eager `.git` / `.pi` classification on every entry
@@ -507,13 +616,10 @@ export function registerFileRoutes(
507
616
  "/api/browse",
508
617
  { preHandler: networkGuard },
509
618
  async (request, reply) => {
510
- // Confined to `$HOME` + pinned dirs (B8). No path → home, always allowed.
511
- // See change: harden-server-capability-bounds.
512
- const roots = await browseRoots();
619
+ const roots = await confinedRoots(request);
513
620
  const requested = request.query.path || undefined;
514
- if (requested && !(await isWithinBrowseRoots(requested, roots))) {
515
- reply.code(403);
516
- return { success: false, error: BROWSE_OUTSIDE_ROOTS_ERROR } satisfies ApiResponse;
621
+ if (roots && requested && !(await isWithinBrowseRoots(requested, roots))) {
622
+ return refuseOutsideRoots(reply, "GET /api/browse", requested);
517
623
  }
518
624
  try {
519
625
  const result = await listDirectories(
@@ -521,9 +627,10 @@ export function registerFileRoutes(
521
627
  request.query.q || undefined,
522
628
  { detect: request.query.detect === "1" },
523
629
  );
524
- // Never offer a `..` row that leads to a refused directory.
525
- if (result.parent && !(await isWithinBrowseRoots(result.parent, roots))) {
526
- result.parent = null;
630
+ if (roots) {
631
+ result.confined = true;
632
+ // Never offer a `..` row that leads to a refused directory.
633
+ if (result.parent && !(await isWithinBrowseRoots(result.parent, roots))) result.parent = null;
527
634
  }
528
635
  return { success: true, data: result } satisfies ApiResponse;
529
636
  } catch {
@@ -547,11 +654,10 @@ export function registerFileRoutes(
547
654
  reply.code(400);
548
655
  return { success: false, error: parsed.error } satisfies ApiResponse;
549
656
  }
550
- const roots = await browseRoots();
551
- for (const p of parsed.paths) {
552
- if (!(await isWithinBrowseRoots(p, roots))) {
553
- reply.code(403);
554
- return { success: false, error: BROWSE_OUTSIDE_ROOTS_ERROR } satisfies ApiResponse;
657
+ const roots = await confinedRoots(request);
658
+ if (roots) {
659
+ for (const p of parsed.paths) {
660
+ if (!(await isWithinBrowseRoots(p, roots))) return refuseOutsideRoots(reply, "GET /api/browse/flags", p);
555
661
  }
556
662
  }
557
663
  const flags = await classifyPaths(parsed.paths);
@@ -567,10 +673,10 @@ export function registerFileRoutes(
567
673
  const body = request.body ?? {};
568
674
  const parent = typeof body.parent === "string" ? body.parent : "";
569
675
  const name = typeof body.name === "string" ? body.name : "";
570
- // mkdir only inside `$HOME` + pinned dirs (B8). Checked before any fs write.
571
- if (parent && !(await isWithinBrowseRoots(parent, await browseRoots()))) {
572
- reply.code(403);
573
- return { success: false, error: BROWSE_OUTSIDE_ROOTS_ERROR } satisfies ApiResponse;
676
+ // A remote caller may create only inside the shared roots; checked before any fs write.
677
+ const roots = await confinedRoots(request);
678
+ if (roots && parent && !(await isWithinBrowseRoots(parent, roots))) {
679
+ return refuseOutsideRoots(reply, "POST /api/browse/mkdir", parent);
574
680
  }
575
681
  try {
576
682
  const newPath = await createDirectory(parent, name);
@@ -620,10 +726,9 @@ export function registerFileRoutes(
620
726
  "/api/file",
621
727
  { preHandler: networkGuard },
622
728
  async (request, reply) => {
623
- const gate = await gateReadPath(request.query.cwd, request.query.path, { sessionManager, request, reply });
729
+ const gate = await gateReadPath(request.query.cwd, request.query.path, { routeAdmission, request, reply });
624
730
  if ("code" in gate) {
625
- reply.code(gate.code);
626
- return denialBody(gate);
731
+ return sendGateFailure(reply, gate);
627
732
  }
628
733
  const { resolved } = gate;
629
734
 
@@ -649,7 +754,7 @@ export function registerFileRoutes(
649
754
  // a FIFO in the gap. Layer ①/② reads keep the pre-existing open.
650
755
  const fh = gate.viaGrant
651
756
  ? await openVerifiedRegularFile(resolved)
652
- : await fs.open(resolved, "r");
757
+ : await openStateChecked(resolved, "r");
653
758
  let kindResult;
654
759
  let content: string | undefined;
655
760
  try {
@@ -684,9 +789,10 @@ export function registerFileRoutes(
684
789
  },
685
790
  } satisfies ApiResponse;
686
791
  } catch (err) {
687
- if (err instanceof VerifiedReadRefused) {
792
+ if (err instanceof VerifiedReadRefused || err instanceof DashboardStateRefused) {
688
793
  // A granted path whose file is not a regular file, or was swapped
689
- // between the check and the open. Refused in the site's existing
794
+ // between the check and the open (or a swap onto a dashboard secret).
795
+ // Refused in the site's existing
690
796
  // containment shape — deliberately no new user-facing string.
691
797
  reply.code(403);
692
798
  return { success: false, error: "path outside working directory" } satisfies ApiResponse;
@@ -710,15 +816,14 @@ export function registerFileRoutes(
710
816
  { preHandler: networkGuard },
711
817
  async (request, reply) => {
712
818
  const gate = await gateReadPath(request.query.cwd, request.query.path, {
713
- sessionManager,
819
+ routeAdmission,
714
820
  request,
715
821
  reply,
716
822
  quiet: true,
717
823
  });
718
824
  reply.header("Cache-Control", "no-store");
719
825
  if ("code" in gate) {
720
- reply.code(gate.code);
721
- return denialBody(gate);
826
+ return sendGateFailure(reply, gate);
722
827
  }
723
828
  const lane: DigestLane = request.query.purpose === "baseline" ? "baseline" : "verify";
724
829
  const ac = new AbortController();
@@ -804,14 +909,13 @@ export function registerFileRoutes(
804
909
  // `allowGrant: false` — a read grant must NOT authorize launching a local
805
910
  // application or revealing in the file manager. Those are a different
806
911
  // capability from reading, so the two spawn routes keep the pre-change
807
- // `isAllowed`-only decision (task 4.5 review gate, blocking #2).
808
- const gate = await gateFilePath(cwd, rawPath, sessionManager, {
912
+ // layers ①/② only decision (task 4.5 review gate, blocking #2).
913
+ const gate = await gateFilePath(cwd, rawPath, routeAdmission, {
809
914
  allowGrant: false,
810
915
  disclosure: canDiscloseAccessPosture(request),
811
916
  });
812
917
  if ("code" in gate) {
813
- reply.code(gate.code);
814
- return denialBody(gate);
918
+ return sendGateFailure(reply, gate);
815
919
  }
816
920
  const { cmd, args } = build(systemOpenPlatform, gate.resolved);
817
921
  systemOpenRun(cmd, args);
@@ -848,22 +952,20 @@ export function registerFileRoutes(
848
952
  return { success: false, error: "cwd and path parameters required" } satisfies ApiResponse;
849
953
  }
850
954
 
851
- if (!sessionManager.listAll().some((s) => s.cwd === cwd)) {
852
- reply.code(403);
853
- return { success: false, error: "unknown session path" } satisfies ApiResponse;
854
- }
955
+ const admitted = await admitFileCwd(cwd, routeAdmission, { reply });
956
+ if (!admitted.ok) return sendGateFailure(reply, admitted.failure);
855
957
 
856
- const resolved = path.resolve(cwd, relPath);
857
- const treeDecision = await evaluateContainment(resolved, [cwd], {
958
+ const resolved = path.resolve(admitted.cwd, relPath);
959
+ const treeDecision = await evaluateContainment(resolved, cwdAnchors(admitted), {
858
960
  site: "file-routes:tree",
859
961
  hold: { request, reply },
860
962
  disclosure: canDiscloseAccessPosture(request),
861
- session: cwd,
963
+ session: admitted.cwd,
862
964
  // Directory-only site: the remedy must name THIS directory, not its
863
965
  // parent (task 4.5 review).
864
966
  subjectKind: "directory",
865
967
  });
866
- if (!treeDecision.allowed) {
968
+ if (!containmentAllows(treeDecision, resolved)) {
867
969
  reply.code(403);
868
970
  return { success: false, error: "path outside working directory", ...treeDecision.remedy } as unknown as ApiResponse;
869
971
  }
@@ -918,10 +1020,9 @@ export function registerFileRoutes(
918
1020
  // the handler still refuses content above the 256 MiB ceiling.
919
1021
  { preHandler: networkGuard, bodyLimit: 600 * 1024 * 1024 },
920
1022
  async (request, reply) => {
921
- const prep = await prepareMdWrite(request.body ?? {}, sessionManager);
1023
+ const prep = await prepareMdWrite(request.body ?? {}, routeAdmission);
922
1024
  if ("code" in prep) {
923
- reply.code(prep.code);
924
- return { success: false, error: prep.error } satisfies ApiResponse;
1025
+ return sendGateFailure(reply, prep);
925
1026
  }
926
1027
  // Critical section: stat → mtime check → write → rename runs serialized per
927
1028
  // target so the optimistic check is atomic w.r.t. a concurrent write.
@@ -952,15 +1053,16 @@ export function registerFileRoutes(
952
1053
  "/api/file/md-candidates",
953
1054
  { preHandler: networkGuard },
954
1055
  async (request, reply) => {
955
- const cwd = request.query.cwd || undefined;
956
- if (cwd) {
957
- const allSessions = sessionManager.listAll();
958
- if (!allSessions.some((s) => s.cwd === cwd)) {
959
- reply.code(403);
960
- return { success: false, error: "unknown session path" } satisfies ApiResponse;
961
- }
962
- }
963
- const candidates = await enumerateMdCandidates({ cwd });
1056
+ // Absent (undefined / "") → global scope with a constant `{}`; any other value must be an
1057
+ // admitted absolute cwd. See change: core-file-cwd-admission (D1).
1058
+ const rawCwd: unknown = request.query.cwd;
1059
+ if (rawCwd === undefined || rawCwd === "") {
1060
+ const globalCandidates = await enumerateMdCandidates({});
1061
+ return { success: true, data: { candidates: globalCandidates } } satisfies ApiResponse;
1062
+ }
1063
+ const admitted = await admitFileCwd(rawCwd, routeAdmission, { reply });
1064
+ if (!admitted.ok) return sendGateFailure(reply, admitted.failure);
1065
+ const candidates = await enumerateMdCandidates({ cwd: admitted.cwd });
964
1066
  return { success: true, data: { candidates } } satisfies ApiResponse;
965
1067
  },
966
1068
  );
@@ -976,19 +1078,17 @@ export function registerFileRoutes(
976
1078
  "/api/file/md-read",
977
1079
  { preHandler: networkGuard },
978
1080
  async (request, reply) => {
979
- const cwd = request.query.cwd || undefined;
980
1081
  const rawPath = request.query.path;
981
1082
  if (!rawPath) {
982
1083
  reply.code(400);
983
1084
  return { success: false, error: "path parameter required" } satisfies ApiResponse;
984
1085
  }
985
- const target = resolveScopedMdPath(cwd, rawPath, sessionManager);
1086
+ const target = await resolveScopedMdPath(request.query.cwd, rawPath, routeAdmission);
986
1087
  if ("code" in target) {
987
- reply.code(target.code);
988
- return { success: false, error: target.error } satisfies ApiResponse;
1088
+ return sendGateFailure(reply, target);
989
1089
  }
990
1090
  const resolved = target.resolved;
991
- if (!(await isWritableMdTarget(resolved, { cwd }))) {
1091
+ if (!(await isWritableMdTarget(resolved, { cwd: target.cwd }))) {
992
1092
  reply.code(403);
993
1093
  return { success: false, error: "target is not a readable markdown file in scope" } satisfies ApiResponse;
994
1094
  }
@@ -1024,21 +1124,12 @@ export function registerFileRoutes(
1024
1124
  reply.code(400);
1025
1125
  return { success: false, error: "cwd and path parameters required" } satisfies ApiResponse;
1026
1126
  }
1027
- const allSessions = sessionManager.listAll();
1028
- const knownCwds = new Set(allSessions.map((s) => s.cwd));
1029
- for (const dir of preferencesStore.getPinnedDirectories()) knownCwds.add(dir);
1030
- // The unknown-cwd denial may ask the operator (add-access-grant-dialog,
1031
- // task 6.2). An allow verdict authorises a RE-RUN of this same guard, never
1032
- // a skip: `allow-always` pinned the directory, so the live pinned set must
1033
- // now contain it; `allow-once` admits exactly the named directory, for this
1034
- // request only. Every other outcome returns the unchanged denial below.
1035
- const cwdAdmitted =
1036
- knownCwds.has(cwd) ||
1037
- (await unknownCwdVerdictAdmits(cwd, { request, reply }, () => [
1038
- ...sessionManager.listAll().map((s) => s.cwd),
1039
- ...preferencesStore.getPinnedDirectories(),
1040
- ]));
1041
- if (!cwdAdmitted) {
1127
+ // Admission (change: core-file-cwd-admission, D5). An absolute cwd is admitted through the
1128
+ // shared guard; a refusal may ask the operator (add-access-grant-dialog, task 6.2). An allow
1129
+ // verdict authorises a RE-RUN of the guard, never a skip: `allow-always` pinned the
1130
+ // directory so the live known set now contains it; `allow-once` admits exactly the named
1131
+ // directory, for this request only. An undecidable admission answers 503 and never prompts.
1132
+ const existsRefusal = (): ApiResponse => {
1042
1133
  reply.code(403);
1043
1134
  // Additive remedy fields beside the unchanged `"unknown cwd"` string
1044
1135
  // (design D7/D18); the known-cwd set already includes pinned
@@ -1048,10 +1139,24 @@ export function registerFileRoutes(
1048
1139
  // add-access-grants-and-review.
1049
1140
  return {
1050
1141
  success: false,
1142
+ code: "cwd_unknown",
1051
1143
  error: "unknown cwd",
1052
1144
  reason: "cwd is not a known session or pinned directory.",
1053
1145
  hint: "Pin this directory to allow it, or open a session rooted in it.",
1054
1146
  } as unknown as ApiResponse;
1147
+ };
1148
+ if (typeof cwd !== "string" || !path.isAbsolute(cwd)) return existsRefusal();
1149
+ let admitted = await admitFileCwd(cwd, routeAdmission, { error: "unknown cwd", reply });
1150
+ if (!admitted.ok && admitted.failure.code === 503) return sendGateFailure(reply, admitted.failure);
1151
+ if (!admitted.ok) {
1152
+ const decision = await unknownCwdVerdict(cwd, { request, reply }, routeAdmission);
1153
+ if (decision.kind === "indeterminate") return sendGateFailure(reply, CWD_UNAVAILABLE_FAILURE);
1154
+ const held = issueHeldAdmission(decision, cwd);
1155
+ if (held.kind !== "admit" || !admissionAllows(held, cwd)) return existsRefusal();
1156
+ const token = held.token;
1157
+ const release = (): void => releaseAdmission(token);
1158
+ releaseOnClose(reply, release);
1159
+ admitted = { ok: true, cwd, canonCwd: token.canonCwd, release };
1055
1160
  }
1056
1161
  // Anti-traversal: probePath MUST be inside cwd (or a pinned dir / repo
1057
1162
  // git root). Pinned-dir anchor is exists-only; not folded onto read/raw/render.
@@ -1064,16 +1169,16 @@ export function registerFileRoutes(
1064
1169
  return { success: false, error: "path outside cwd" } satisfies ApiResponse;
1065
1170
  }
1066
1171
  const resolved = path.resolve(probePath);
1067
- const anchors = [cwd, ...preferencesStore.getPinnedDirectories()];
1172
+ const anchors = [...cwdAnchors(admitted), ...preferencesStore.getPinnedDirectories()];
1068
1173
  const existsDecision = await evaluateContainment(resolved, anchors, {
1069
1174
  site: "file-routes:exists",
1070
1175
  hold: { request, reply },
1071
1176
  disclosure: canDiscloseAccessPosture(request),
1072
- session: cwd,
1177
+ session: admitted.cwd,
1073
1178
  // `fs.access` accepts files AND directories — polymorphic, see above.
1074
1179
  subjectKind: "auto",
1075
1180
  });
1076
- if (!existsDecision.allowed) {
1181
+ if (!containmentAllows(existsDecision, resolved)) {
1077
1182
  reply.code(403);
1078
1183
  return { success: false, error: "path outside cwd", ...existsDecision.remedy } as unknown as ApiResponse;
1079
1184
  }
@@ -1107,11 +1212,9 @@ export function registerFileRoutes(
1107
1212
  reply.code(400);
1108
1213
  return { success: false, error: "cwd and mention are required" } satisfies ApiResponse;
1109
1214
  }
1110
- if (!sessionManager.listAll().some((s) => s.cwd === cwd)) {
1111
- reply.code(403);
1112
- return { success: false, error: "unknown session path" } satisfies ApiResponse;
1113
- }
1114
- const result = await resolveFileMention(mention, { cwd });
1215
+ const admitted = await admitFileCwd(cwd, routeAdmission, { reply });
1216
+ if (!admitted.ok) return sendGateFailure(reply, admitted.failure);
1217
+ const result = await resolveFileMention(mention, { cwd: admitted.cwd, canonCwd: admitted.canonCwd });
1115
1218
  return {
1116
1219
  success: true,
1117
1220
  data: result ? { resolved: result.resolved, kind: result.kind } : { resolved: null },
@@ -1146,13 +1249,11 @@ export function registerFileRoutes(
1146
1249
  return { success: false, error: "cwd and path parameters required" } satisfies ApiResponse;
1147
1250
  }
1148
1251
 
1149
- const allSessions = sessionManager.listAll();
1150
- if (!allSessions.some((s) => s.cwd === cwd)) {
1151
- reply.code(403);
1152
- return { success: false, error: "unknown session path" } satisfies ApiResponse;
1153
- }
1252
+ const admitted = await admitFileCwd(cwd, routeAdmission, { reply });
1253
+ if (!admitted.ok) return sendGateFailure(reply, admitted.failure);
1254
+ const rawAnchors = [...cwdAnchors(admitted), homePiAnchor()];
1154
1255
 
1155
- const resolved = path.resolve(cwd, relPath);
1256
+ const resolved = path.resolve(admitted.cwd, relPath);
1156
1257
  // Layers ①/② (cwd + git common root) serve any type. Layer ③ — artifact
1157
1258
  // roots — is image-only and real-path contained; it covers agent
1158
1259
  // screenshots that live outside every cwd and git root.
@@ -1163,15 +1264,15 @@ export function registerFileRoutes(
1163
1264
  // True only when the GRANT layer admitted this read — layers ①/② and the
1164
1265
  // artifact root do NOT get handle verification (task 2.8 scope).
1165
1266
  let viaGrant = false;
1166
- if (!(await isAllowed(resolved, { anchors: [cwd, homePiAnchor()] }))) {
1267
+ if (!containmentAllows(await decidePassive(resolved, rawAnchors, { allowGrant: false }), resolved)) {
1167
1268
  if (!(await isImageUnderArtifactRoot(resolved))) {
1168
- const rawDecision = await evaluateContainment(resolved, [cwd, homePiAnchor()], {
1269
+ const rawDecision = await evaluateContainment(resolved, rawAnchors, {
1169
1270
  site: "file-routes:raw",
1170
1271
  hold: { request, reply },
1171
1272
  disclosure: canDiscloseAccessPosture(request),
1172
- session: cwd,
1273
+ session: admitted.cwd,
1173
1274
  });
1174
- if (!rawDecision.allowed) {
1275
+ if (!containmentAllows(rawDecision, resolved)) {
1175
1276
  reply.code(403);
1176
1277
  return { success: false, error: "path outside working directory", ...rawDecision.remedy } as unknown as ApiResponse;
1177
1278
  }
@@ -1199,6 +1300,15 @@ export function registerFileRoutes(
1199
1300
 
1200
1301
  reply.header("Content-Type", contentType);
1201
1302
  reply.header("Content-Disposition", "inline");
1303
+ // Scriptable media types (SVG/HTML/XML) opened directly would run with the
1304
+ // dashboard origin. Enforce an opaque-origin sandbox in EVERY dashboard CSP
1305
+ // mode, on 200/206/416 and every admission path. The baseline CSP hook
1306
+ // only adds a header that is absent, so this is never overwritten.
1307
+ // See change: harden-raw-svg-responses.
1308
+ if (isScriptableMediaType(contentType)) {
1309
+ reply.header("Content-Security-Policy", RAW_SANDBOX_CSP);
1310
+ reply.header("X-Content-Type-Options", "nosniff");
1311
+ }
1202
1312
  reply.header("Cache-Control", "private, max-age=60");
1203
1313
  reply.header("Accept-Ranges", "bytes");
1204
1314
 
@@ -1266,19 +1376,31 @@ export function registerFileRoutes(
1266
1376
  }
1267
1377
  }
1268
1378
 
1379
+ // Non-grant reads open here so the handle can be checked against the always-refused dashboard
1380
+ // files before a single byte is streamed (the path check and the open are two syscalls).
1381
+ let rawHandle: Awaited<ReturnType<typeof openStateChecked>> | undefined;
1382
+ if (!grantedHandle) {
1383
+ try {
1384
+ rawHandle = await openStateChecked(resolved, "r");
1385
+ } catch (err) {
1386
+ reply.code(err instanceof DashboardStateRefused ? 403 : 404);
1387
+ return {
1388
+ success: false,
1389
+ error: err instanceof DashboardStateRefused ? "path outside working directory" : "not found",
1390
+ } satisfies ApiResponse;
1391
+ }
1392
+ }
1393
+ const servedHandle = grantedHandle ?? rawHandle!;
1394
+
1269
1395
  if (range) {
1270
1396
  reply.code(206);
1271
1397
  reply.header("Content-Range", `bytes ${range.start}-${range.end}/${size}`);
1272
1398
  reply.header("Content-Length", String(range.end - range.start + 1));
1273
- return reply.send(
1274
- grantedHandle
1275
- ? grantedHandle.createReadStream({ start: range.start, end: range.end })
1276
- : createReadStream(resolved, { start: range.start, end: range.end }),
1277
- );
1399
+ return reply.send(servedHandle.createReadStream({ start: range.start, end: range.end }));
1278
1400
  }
1279
1401
 
1280
1402
  reply.header("Content-Length", String(size));
1281
- return reply.send(grantedHandle ? grantedHandle.createReadStream() : createReadStream(resolved));
1403
+ return reply.send(servedHandle.createReadStream());
1282
1404
  },
1283
1405
  );
1284
1406
 
@@ -1323,8 +1445,7 @@ export function registerFileRoutes(
1323
1445
  canDiscloseAccessPosture(request),
1324
1446
  );
1325
1447
  if ("code" in gate) {
1326
- reply.code(gate.code);
1327
- return denialBody(gate);
1448
+ return sendGateFailure(reply, gate);
1328
1449
  }
1329
1450
  const result = await renderPptx(
1330
1451
  gate.resolved,
@@ -1348,8 +1469,7 @@ export function registerFileRoutes(
1348
1469
  canDiscloseAccessPosture(request),
1349
1470
  );
1350
1471
  if ("code" in gate) {
1351
- reply.code(gate.code);
1352
- return denialBody(gate);
1472
+ return sendGateFailure(reply, gate);
1353
1473
  }
1354
1474
  const result = await renderDocx(
1355
1475
  gate.resolved,
@@ -1365,20 +1485,17 @@ export function registerFileRoutes(
1365
1485
  return { success: true, data } satisfies ApiResponse;
1366
1486
  }
1367
1487
 
1368
- const allSessions = sessionManager.listAll();
1369
- if (!allSessions.some((s) => s.cwd === cwd)) {
1370
- reply.code(403);
1371
- return { success: false, error: "unknown session path" } satisfies ApiResponse;
1372
- }
1488
+ const admitted = await admitFileCwd(cwd, routeAdmission, { reply });
1489
+ if (!admitted.ok) return sendGateFailure(reply, admitted.failure);
1373
1490
 
1374
- const resolved = path.resolve(cwd, relPath);
1375
- const renderDecision = await evaluateContainment(resolved, [cwd, homePiAnchor()], {
1491
+ const resolved = path.resolve(admitted.cwd, relPath);
1492
+ const renderDecision = await evaluateContainment(resolved, [...cwdAnchors(admitted), homePiAnchor()], {
1376
1493
  site: "file-routes:render",
1377
1494
  hold: { request, reply },
1378
1495
  disclosure: canDiscloseAccessPosture(request),
1379
- session: cwd,
1496
+ session: admitted.cwd,
1380
1497
  });
1381
- if (!renderDecision.allowed) {
1498
+ if (!containmentAllows(renderDecision, resolved)) {
1382
1499
  reply.code(403);
1383
1500
  return { success: false, error: "path outside working directory", ...renderDecision.remedy } as unknown as ApiResponse;
1384
1501
  }
@@ -1409,7 +1526,7 @@ export function registerFileRoutes(
1409
1526
  }
1410
1527
  } else {
1411
1528
  try {
1412
- source = await fs.readFile(resolved, "utf-8");
1529
+ source = await readFileStateChecked(resolved, "utf-8");
1413
1530
  } catch {
1414
1531
  reply.code(404);
1415
1532
  return { success: false, error: "not found" } satisfies ApiResponse;
@@ -1454,8 +1571,7 @@ export function registerFileRoutes(
1454
1571
  canDiscloseAccessPosture(request),
1455
1572
  );
1456
1573
  if ("code" in gate) {
1457
- reply.code(gate.code);
1458
- return denialBody(gate);
1574
+ return sendGateFailure(reply, gate);
1459
1575
  }
1460
1576
  const out = pdfCachePath(gate.resolved, gate.stat.mtimeMs, gate.stat.size);
1461
1577
  try {
@@ -1496,8 +1612,7 @@ export function registerFileRoutes(
1496
1612
  canDiscloseAccessPosture(request),
1497
1613
  );
1498
1614
  if ("code" in gate) {
1499
- reply.code(gate.code);
1500
- return denialBody(gate);
1615
+ return sendGateFailure(reply, gate);
1501
1616
  }
1502
1617
  let buffer: Buffer;
1503
1618
  if (gate.viaGrant) {
@@ -1515,7 +1630,7 @@ export function registerFileRoutes(
1515
1630
  }
1516
1631
  } else {
1517
1632
  try {
1518
- buffer = await fs.readFile(gate.resolved);
1633
+ buffer = await readFileStateChecked(gate.resolved);
1519
1634
  } catch {
1520
1635
  reply.code(404);
1521
1636
  return { success: false, error: "not found" } satisfies ApiResponse;
@@ -1543,12 +1658,11 @@ export function registerFileRoutes(
1543
1658
  "/api/file/eml",
1544
1659
  { preHandler: networkGuard },
1545
1660
  async (request, reply) => {
1546
- const gate = await gateFilePath(request.query.cwd, request.query.path, sessionManager, {
1661
+ const gate = await gateFilePath(request.query.cwd, request.query.path, routeAdmission, {
1547
1662
  disclosure: canDiscloseAccessPosture(request),
1548
1663
  });
1549
1664
  if ("code" in gate) {
1550
- reply.code(gate.code);
1551
- return denialBody(gate);
1665
+ return sendGateFailure(reply, gate);
1552
1666
  }
1553
1667
  const ext = path.extname(request.query.path ?? "").toLowerCase();
1554
1668
  if (ext !== ".eml") {
@@ -1602,12 +1716,11 @@ export function registerFileRoutes(
1602
1716
  "/api/file/eml-attachment",
1603
1717
  { preHandler: networkGuard },
1604
1718
  async (request, reply) => {
1605
- const gate = await gateFilePath(request.query.cwd, request.query.path, sessionManager, {
1719
+ const gate = await gateFilePath(request.query.cwd, request.query.path, routeAdmission, {
1606
1720
  disclosure: canDiscloseAccessPosture(request),
1607
1721
  });
1608
1722
  if ("code" in gate) {
1609
- reply.code(gate.code);
1610
- return denialBody(gate);
1723
+ return sendGateFailure(reply, gate);
1611
1724
  }
1612
1725
  if (path.extname(request.query.path ?? "").toLowerCase() !== ".eml") {
1613
1726
  reply.code(400);
@@ -1700,24 +1813,31 @@ export function registerFileRoutes(
1700
1813
  }
1701
1814
 
1702
1815
  /**
1703
- * Ask about an unknown-cwd denial and re-run the known-cwd guard on an allow
1704
- * verdict (add-access-grant-dialog, task 6.2). Resolves `false` for anything but
1705
- * an explicit allow that the re-run confirms. The re-run is the shared
1706
- * `resolveCwdVerdict` (canonical compare against sessions ∪ pins, allow-once
1707
- * real-path re-resolution) — the same rules plugin holds use.
1708
- * See change: harden-plugin-cwd-admission.
1816
+ * Ask about an unknown-cwd denial and re-run the shared guard on an allow verdict
1817
+ * (add-access-grant-dialog, task 6.2). Returns the post-verdict decision: `admit` only for an
1818
+ * explicit allow that the re-run confirms, `indeterminate` when the re-run cannot decide, else
1819
+ * `refuse`. The re-run is the shared `resolveCwdVerdict` (canonical compare against the known
1820
+ * set, allow-once real-path re-resolution, `rerunAlways` through `admitRouteCwd`) — the same
1821
+ * rules plugin holds use. See change: harden-plugin-cwd-admission, core-file-cwd-admission (D5).
1709
1822
  */
1710
- async function unknownCwdVerdictAdmits(
1823
+ async function unknownCwdVerdict(
1711
1824
  cwd: string,
1712
1825
  target: HoldTarget,
1713
- known: () => string[],
1714
- ): Promise<boolean> {
1826
+ routeAdmission: RouteAdmissionDeps,
1827
+ ): Promise<CwdHoldDecision> {
1715
1828
  // The subject is the REAL path, so an allow-once can later be compared strictly against
1716
1829
  // what the path means at release time. A cwd that does not resolve is never asked about:
1717
1830
  // the post-verdict re-run refuses it whatever the operator answers (and a pin for a
1718
1831
  // directory that is not there is meaningless) — the same rule the plugin seam applies.
1719
1832
  const real = await realpathAsync(path.resolve(cwd));
1720
- if (real.kind !== "ok") return false;
1833
+ if (real.kind !== "ok") return { kind: "refuse" };
1721
1834
  const resolution = await holdDenial({ plane: "cwd", rawSubject: real.path, origin: "file-routes:exists" }, target);
1722
- return (await resolveCwdVerdict(cwd, resolution, { known })).kind === "admit";
1835
+ return resolveCwdVerdict(cwd, resolution, {
1836
+ known: routeAdmission.knownCwds ?? (() => []),
1837
+ rerunAlways: async (canon) => {
1838
+ const admission = await admitRouteCwd(canon, routeAdmission);
1839
+ if (admission.kind === "admit") releaseAdmission(admission.token);
1840
+ return admission.kind;
1841
+ },
1842
+ });
1723
1843
  }