@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
@@ -1,36 +1,137 @@
1
1
  /**
2
- * Allowed-root confinement for the directory-browse endpoints
2
+ * Shared-root confinement for the directory-browse endpoints
3
3
  * (`/api/browse`, `/api/browse/flags`, `/api/browse/mkdir`).
4
4
  *
5
- * These routes carry only `networkGuard`, so before this module
5
+ * Applied ONLY to requests that are not genuinely local (tunnel, LAN, relayed
6
+ * loopback): those carry `networkGuard` alone, so before this module
6
7
  * `/api/browse?path=/` enumerated the whole filesystem and
7
- * `/api/browse/mkdir` created a directory anywhere — over a tunnel that is a
8
- * filesystem-enumeration + write primitive outside the containment model.
8
+ * `/api/browse/mkdir` created a directory anywhere. A local caller keeps the
9
+ * unrestricted picker (it already has a shell).
9
10
  *
10
- * The allowed set is `$HOME` plus the pinned directories. Both sides are
11
- * compared on REAL paths (`safeRealpath`), so a symlink inside an allowed root
12
- * that points out of it is refused rather than followed.
11
+ * The allowed set is every place the dashboard already "shares": `$HOME`,
12
+ * pinned directories, session cwds, workspace folders, worktree-init trust
13
+ * roots and project-scope access-grant subjects. Both sides are compared on
14
+ * REAL paths, so a symlink inside a root pointing out of it is refused.
13
15
  *
14
- * See change: harden-server-capability-bounds (B8).
16
+ * See change: harden-server-capability-bounds (B8, D1, D2).
15
17
  */
18
+ import fs from "node:fs/promises";
16
19
  import os from "node:os";
17
20
  import path from "node:path";
21
+ import {
22
+ type ForbiddenSubjectsEnv,
23
+ forbiddenGrantSubjects,
24
+ } from "@blackbelt-technology/pi-dashboard-shared/forbidden-subjects.js";
18
25
  import { safeRealpath, within } from "./path-containment.js";
19
26
 
20
27
  /** Stable client-facing message for a refused browse/mkdir path. */
21
28
  export const BROWSE_OUTSIDE_ROOTS_ERROR = "path outside allowed roots";
22
29
 
23
- /** Real paths of `$HOME` and every pinned directory, deduplicated. */
30
+ /**
31
+ * Where roots come from. Each source is a lazy reader so one that throws (store
32
+ * read error) contributes no roots for that request instead of failing it open.
33
+ */
34
+ export interface BrowseRootSources {
35
+ pinned(): readonly string[];
36
+ sessionCwds(): readonly string[];
37
+ workspaceFolders(): readonly string[];
38
+ worktreeRoots(): readonly string[];
39
+ /** Project-scope access-grant subjects (session-scope grants are transient: excluded). */
40
+ projectGrants(): readonly string[];
41
+ }
42
+
43
+ /**
44
+ * The resolved allowed set for ONE request. `sensitive` (`~/.ssh`, `~/.pi`) is
45
+ * computed once here: `forbiddenGrantSubjects` does ~18 sync realpaths, which
46
+ * must not be repeated per candidate root or per checked path.
47
+ */
48
+ export interface BrowseRoots {
49
+ roots: string[];
50
+ sensitive: string[];
51
+ }
52
+
53
+ const warnedSources = new Set<string>();
54
+ function warnOnce(source: string, err: unknown): void {
55
+ if (warnedSources.has(source)) return;
56
+ warnedSources.add(source);
57
+ console.warn(`[browse-roots] source "${source}" failed; contributing no roots:`, err instanceof Error ? err.message : err);
58
+ }
59
+
60
+ /**
61
+ * The allowed set: real paths of `$HOME` and every shared root, deduplicated. Candidates from the
62
+ * non-home sources that are ungrantable (`/`, `$HOME` itself, system roots, any
63
+ * ancestor of those or of `~/.ssh` / `~/.pi`) are dropped, so a remote pin of
64
+ * `/` can never become a root. `$HOME` is the one explicit exception.
65
+ */
24
66
  export async function resolveBrowseRoots(
25
- pinnedDirs: readonly string[],
26
- home: string = os.homedir(),
27
- ): Promise<string[]> {
28
- const real = await Promise.all([home, ...pinnedDirs].map((d) => safeRealpath(path.resolve(d))));
29
- return [...new Set(real)];
67
+ sources: BrowseRootSources,
68
+ env?: ForbiddenSubjectsEnv,
69
+ ): Promise<BrowseRoots> {
70
+ const home = env?.homedir ?? os.homedir();
71
+ const sets = forbiddenGrantSubjects(env);
72
+ const roots = new Set<string>([await safeRealpath(path.resolve(home))]);
73
+
74
+ const named: Array<[string, () => readonly string[]]> = [
75
+ ["pinned", sources.pinned],
76
+ ["sessionCwds", sources.sessionCwds],
77
+ ["workspaceFolders", sources.workspaceFolders],
78
+ ["worktreeRoots", sources.worktreeRoots],
79
+ ["projectGrants", sources.projectGrants],
80
+ ];
81
+ // `forbidden` = every subject a root may neither BE nor CONTAIN (`/`, `$HOME`, system roots,
82
+ // `~/.ssh`, `~/.pi`). Evaluated here on the already-real path against the sets built once above:
83
+ // `isUngrantableSubject` would re-canonicalise (sync realpath) per candidate, ~2 sync fs calls per
84
+ // root on every request. Same rule: a root is dropped when it IS a whole-subject, is at/under a
85
+ // sensitive dir, or is an ancestor of any forbidden subject.
86
+ const forbidden = [...sets.whole, ...sets.sensitive];
87
+ const ungrantable = (real: string): boolean =>
88
+ forbidden.some((f) => within(f, real)) || // real equals or contains a forbidden subject
89
+ sets.sensitive.some((f) => within(real, f)); // real is at/under a sensitive dir
90
+
91
+ const candidates: string[] = [];
92
+ for (const [name, read] of named) {
93
+ try {
94
+ candidates.push(...read());
95
+ } catch (err) {
96
+ warnOnce(name, err);
97
+ }
98
+ }
99
+ // Strict realpath (deleted / EACCES -> dropped), in parallel: one slow volume must not serialise the rest.
100
+ const resolved = await Promise.all(
101
+ candidates.map((dir) => fs.realpath(path.resolve(dir)).catch(() => null)),
102
+ );
103
+ for (const real of resolved) if (real !== null && !ungrantable(real)) roots.add(real);
104
+ return { roots: [...roots], sensitive: sets.sensitive };
30
105
  }
31
106
 
32
- /** True when `target` (symlinks resolved) sits at or under one of `roots` (already real paths). */
33
- export async function isWithinBrowseRoots(target: string, roots: readonly string[]): Promise<boolean> {
107
+ /**
108
+ * True when `target` (symlinks resolved) sits at or under one of `roots` (real
109
+ * paths) and is not inside a sensitive subtree (`~/.ssh`, `~/.pi`) — those stay
110
+ * refused even though `$HOME` is a root.
111
+ */
112
+ export async function isWithinBrowseRoots(target: string, allowed: BrowseRoots): Promise<boolean> {
34
113
  const real = await safeRealpath(path.resolve(target));
35
- return roots.some((root) => within(real, root));
114
+ if (allowed.sensitive.some((s) => within(real, s))) return false;
115
+ return allowed.roots.some((root) => within(real, root));
116
+ }
117
+
118
+ /**
119
+ * The root sources, built once from the stores the server already owns and shared
120
+ * by the browse routes and the remote pin/workspace gate, so "what is shared" has
121
+ * ONE definition. `worktreeRoots` / `projectGrants` are readers only server.ts can
122
+ * supply (project-scope grants only; session-scope grants are transient).
123
+ */
124
+ export function buildBrowseRootSources(deps: {
125
+ preferencesStore: { getPinnedDirectories(): string[]; getWorkspaces(): Array<{ folders: string[] }> };
126
+ sessionManager: { listAll(): Array<{ cwd: string }> };
127
+ worktreeRoots?: () => readonly string[];
128
+ projectGrants?: () => readonly string[];
129
+ }): BrowseRootSources {
130
+ return {
131
+ pinned: () => deps.preferencesStore.getPinnedDirectories(),
132
+ sessionCwds: () => deps.sessionManager.listAll().map((s) => s.cwd),
133
+ workspaceFolders: () => deps.preferencesStore.getWorkspaces().flatMap((w) => w.folders),
134
+ worktreeRoots: deps.worktreeRoots ?? (() => []),
135
+ projectGrants: deps.projectGrants ?? (() => []),
136
+ };
36
137
  }
@@ -20,14 +20,13 @@ import path from "node:path";
20
20
  import { createRequire } from "node:module";
21
21
  import { fileURLToPath } from "node:url";
22
22
  import {
23
+ type BuildDeclaration,
23
24
  type FixturePolicy,
24
- bundleRootsFor,
25
25
  discoverPlugins,
26
26
  findMonorepoRoot,
27
27
  isUsableDeclaration,
28
- pluginRegistryHash,
29
28
  readBuildDeclaration,
30
- selectClientRegistryPlugins,
29
+ serverRegistryHash,
31
30
  } from "@blackbelt-technology/dashboard-plugin-runtime/server";
32
31
 
33
32
  /** Four-state coherence of the served artifact against the runtime plugin set. */
@@ -83,24 +82,27 @@ export function resolveStaticClientDir(opts: ResolveStaticClientOptions = {}): s
83
82
  * diverge (spec: *Comparison uses the same basis as the staleness hash*).
84
83
  *
85
84
  * `isProd` maps the fixture policy: `"excluded"` is a production selection,
86
- * `"included"` a dev one.
85
+ * `"included"` a dev one. `declaration` is the served build's declaration: with
86
+ * `bundledPluginIds` the set follows it (`serverRegistryHash`: build copies of the declared ids,
87
+ * else the declaration's own hash; runtime-only plugins never count); without it the
88
+ * pre-change selection applies (`bundleRootsFor` where a monorepo root resolves — a root-less host
89
+ * counts every discovered client plugin, the same mismatch that existed before). `bundleRoots` is
90
+ * deliberately omitted when no monorepo marker is discoverable: an EMPTY allowlist would exclude
91
+ * every plugin. See change: decouple-plugins-from-core (task 6.2, design D11).
87
92
  */
88
- export function runtimePluginRegistryHash(isProd: boolean): string {
89
- const root = findMonorepoRoot();
90
- // `bundleRoots` is deliberately omitted when no monorepo marker is
91
- // discoverable: an allowlist needs a known root, and an EMPTY list would
92
- // exclude every plugin (a guaranteed mismatch on any installed host). On such
93
- // hosts a user-installed client plugin is therefore still counted at runtime
94
- // but absent from a published build — the same mismatch that existed before
95
- // this change, and the plugin contributes no client UI anyway (proposal.md —
96
- // known gap). On repository/bundled layouts every hash producer resolves the
97
- // same root.
98
- return pluginRegistryHash(
99
- selectClientRegistryPlugins(discoverPlugins(), {
100
- isProd,
101
- ...(root ? { bundleRoots: bundleRootsFor(root) } : {}),
102
- }),
103
- );
93
+ export function runtimePluginRegistryHash(isProd: boolean, declaration?: BuildDeclaration): string {
94
+ return serverRegistryHash(discoverPlugins(undefined, [], { bundledPluginIds: declaration?.bundledPluginIds }), {
95
+ isProd,
96
+ declaration,
97
+ monorepoRoot: findMonorepoRoot(),
98
+ });
99
+ }
100
+
101
+ /** The served build's validated declaration, or `undefined` (no served build / unreadable / schema mismatch). */
102
+ export function readServedDeclaration(clientDir: string | null): BuildDeclaration | undefined {
103
+ if (!clientDir) return undefined;
104
+ const read = readBuildDeclaration(clientDir);
105
+ return isUsableDeclaration(read) ? read.declaration : undefined;
104
106
  }
105
107
 
106
108
  /**
@@ -156,7 +158,20 @@ export function clientBuildDiagnostic(snapshot: ClientBuildSnapshot): string {
156
158
  * hash. Convenience wrapper for the server bootstrap.
157
159
  */
158
160
  export function clientBuildSnapshotFor(clientDir: string | null): ClientBuildSnapshot {
161
+ const declaration = readServedDeclaration(clientDir);
159
162
  return readClientBuildSnapshot(clientDir, (policy) =>
160
- runtimePluginRegistryHash(policy === "excluded"),
163
+ runtimePluginRegistryHash(policy === "excluded", declaration),
161
164
  );
162
165
  }
166
+
167
+ /**
168
+ * Ids the served build declares bundled (`pi-dashboard-build.json#bundledPluginIds`), from the VALIDATED
169
+ * declaration (a usable schema-1 file; sorted, deduped). `undefined` = undeclared (no served build,
170
+ * unreadable / malformed / schema-mismatched file, or the field is absent / not a string array) —
171
+ * discovery then falls back to plain source priority. Handed to the loader via
172
+ * `setDeclaredBundledPluginIds` before any server-side discovery call, and re-read by
173
+ * `refreshPluginDiscovery()`. See change: decouple-plugins-from-core (tasks 5.4, 6.2, design D11/D15).
174
+ */
175
+ export function readServedBundledPluginIds(clientDir: string | null): readonly string[] | undefined {
176
+ return readServedDeclaration(clientDir)?.bundledPluginIds;
177
+ }
@@ -0,0 +1,230 @@
1
+ /**
2
+ * Dashboard secrets out of reach of the path-taking routes.
3
+ *
4
+ * `~/.pi/dashboard/` holds the local IPC token (`local/token`), the server
5
+ * identity key and `config.json` (which carries the auth HMAC secret). The file
6
+ * routes anchor on `[cwd, ~/.pi]`, and a session cwd of `$HOME` contains them
7
+ * too, so any running session used to let a bare-loopback caller read them.
8
+ *
9
+ * Two tiers, decided on REAL paths (symlinks resolved on both sides):
10
+ * - **always** — `<dir>/local/**` and `<dir>/identity.key`: refused for every
11
+ * caller in every mode. This tier is the recorded exception to
12
+ * rollback-by-flag (`requireLocalProof: false` does not reopen it).
13
+ * - **gated** — the rest of `<dir>`: refused unless the caller is locally
14
+ * trusted NOW (proof, or the strict default is off) or holds a login
15
+ * session. A caller that passes then falls through to the ordinary anchors.
16
+ *
17
+ * The caller is supplied per request through an `AsyncLocalStorage` set by one
18
+ * `onRequest` hook, so every containment decision made while serving that
19
+ * request sees it without each site threading a request through. With no caller
20
+ * in scope (internal, non-HTTP code) only the always-refused tier applies.
21
+ *
22
+ * `handleIsAlwaysRefused` closes the check-then-open race: after opening, the
23
+ * handle's (dev, ino) is compared with each always-refused file, so a symlink
24
+ * swapped in between the path check and the open is still caught. The
25
+ * trust-gated tier keeps only the pre-open check (its residual race is
26
+ * documented in the design).
27
+ *
28
+ * Deliberately NOT built on `access/verified-read.ts`: that is grant-only and
29
+ * `lstat`-based, and would regress in-scope symlink reads.
30
+ *
31
+ * See change: close-container-loopback-impersonation (D8).
32
+ */
33
+ import { AsyncLocalStorage } from "node:async_hooks";
34
+ import { realpathSync } from "node:fs";
35
+ import fs from "node:fs/promises";
36
+ import os from "node:os";
37
+ import path from "node:path";
38
+ import { getDashboardConfigDir } from "@blackbelt-technology/pi-dashboard-shared/dashboard-paths.js";
39
+
40
+ type DashboardStateTier = "always" | "gated";
41
+
42
+ /** What the guard needs to know about the caller of the current request. */
43
+ export interface StateCaller {
44
+ /** May the trust-gated tier be read? (locally trusted now, or a login session) */
45
+ gatedAdmitted(): boolean;
46
+ /** Is this a bare-loopback caller that only lacks local proof? (never raises an operator prompt) */
47
+ unproven(): boolean;
48
+ }
49
+
50
+ const callers = new AsyncLocalStorage<StateCaller>();
51
+
52
+ /** Run `fn` with `caller` in scope for every containment decision it (transitively) makes. */
53
+ export function runWithStateCaller<T>(caller: StateCaller, fn: () => T): T {
54
+ return callers.run(caller, fn);
55
+ }
56
+
57
+ /** The caller of the request being served, if any. */
58
+ export function currentStateCaller(): StateCaller | undefined {
59
+ return callers.getStore();
60
+ }
61
+
62
+ /** Resolve symlinks; for a path that does not exist, resolve the nearest existing ancestor and re-append the tail. */
63
+ async function realpathLoose(p: string): Promise<string> {
64
+ try {
65
+ return await fs.realpath(p);
66
+ } catch {
67
+ const parent = path.dirname(p);
68
+ if (parent === p) return p;
69
+ return path.join(await realpathLoose(parent), path.basename(p));
70
+ }
71
+ }
72
+
73
+ // Compared case-insensitively everywhere: macOS/Windows volumes are case-insensitive (`Local/Token` IS the token),
74
+ // and on a case-sensitive volume the only cost is refusing a differently-cased name inside the dashboard dir.
75
+ const norm = (s: string): string => s.toLowerCase();
76
+
77
+ let cachedFor = "";
78
+ let cachedReal = "";
79
+ async function realDashboardDir(): Promise<string> {
80
+ // Recomputed when HOME changes (tests reassign it; `os.homedir()` follows it).
81
+ const key = `${os.homedir()}`;
82
+ if (cachedFor !== key) {
83
+ cachedReal = await realpathLoose(getDashboardConfigDir());
84
+ cachedFor = key;
85
+ }
86
+ return cachedReal;
87
+ }
88
+
89
+ /** The tier of a path that is ALREADY a real path, relative to the real dashboard dir; `null` outside it. */
90
+ function tierWithin(realDir: string, realTarget: string): DashboardStateTier | null {
91
+ const rel = path.relative(norm(realDir), norm(realTarget));
92
+ if (rel === "") return "gated";
93
+ if (rel === ".." || rel.startsWith(`..${path.sep}`) || path.isAbsolute(rel)) return null;
94
+ const first = rel.split(path.sep)[0];
95
+ if (first === "local" || rel === "identity.key") return "always";
96
+ return "gated";
97
+ }
98
+
99
+ /**
100
+ * Is `target` (any spelling: relative symlinks, `~` already expanded) inside the
101
+ * dashboard state dir, and which tier? Realpath-based, so a symlink INTO the dir
102
+ * and a `$HOME` symlink are both seen through.
103
+ */
104
+ export async function isDashboardStatePath(target: string): Promise<DashboardStateTier | null> {
105
+ const [realDir, realTarget] = await Promise.all([realDashboardDir(), realpathLoose(path.resolve(target))]);
106
+ return tierWithin(realDir, realTarget);
107
+ }
108
+
109
+ /**
110
+ * Must the current caller be refused this path? Always-refused tier: every caller.
111
+ * Trust-gated tier: unless the request's caller is admitted (no caller in scope ⇒ internal ⇒ admitted).
112
+ */
113
+ export async function dashboardStateRefuses(target: string): Promise<boolean> {
114
+ const tier = await isDashboardStatePath(target);
115
+ if (tier === null) return false;
116
+ if (tier === "always") return true;
117
+ const caller = currentStateCaller();
118
+ return caller ? !caller.gatedAdmitted() : false;
119
+ }
120
+
121
+ /** Is the current request's caller a bare-loopback one that merely lacks proof? */
122
+ export function currentCallerUnproven(): boolean {
123
+ return currentStateCaller()?.unproven() === true;
124
+ }
125
+
126
+ async function alwaysRefusedFiles(realDir: string): Promise<string[]> {
127
+ const out: string[] = [path.join(realDir, "identity.key")];
128
+ const walk = async (dir: string, depth: number): Promise<void> => {
129
+ let entries: import("node:fs").Dirent[];
130
+ try {
131
+ entries = await fs.readdir(dir, { withFileTypes: true });
132
+ } catch {
133
+ return;
134
+ }
135
+ for (const e of entries) {
136
+ const full = path.join(dir, e.name);
137
+ if (e.isDirectory()) {
138
+ if (depth < 3) await walk(full, depth + 1);
139
+ } else {
140
+ out.push(full);
141
+ }
142
+ }
143
+ };
144
+ await walk(path.join(realDir, "local"), 0);
145
+ return out;
146
+ }
147
+
148
+ /**
149
+ * After OPENING a path, is the handle one of the always-refused files? Compares
150
+ * (dev, ino) of the handle with each always-refused file, so a symlink or hard
151
+ * link swapped in after the path check is caught. Fails closed on a stat error
152
+ * of the HANDLE; a vanished always-refused file simply cannot match.
153
+ */
154
+ export async function handleIsAlwaysRefused(handle: { stat(): Promise<{ dev: number | bigint; ino: number | bigint }> }): Promise<boolean> {
155
+ const hs = await handle.stat();
156
+ const realDir = await realDashboardDir();
157
+ for (const file of await alwaysRefusedFiles(realDir)) {
158
+ try {
159
+ const st = await fs.stat(file);
160
+ if (st.ino === hs.ino && st.dev === hs.dev) return true;
161
+ } catch {
162
+ /* absent: cannot be the opened file */
163
+ }
164
+ }
165
+ return false;
166
+ }
167
+
168
+ let cachedSyncFor = "";
169
+ let cachedSyncReal = "";
170
+ /**
171
+ * Synchronous "is this directory the dashboard state dir itself?" for the one sync walker (the JS grep
172
+ * fallback), so it never enters the dir. Cheap: only a directory whose BASE NAME matches the state dir's
173
+ * is resolved. Compared on real paths, like {@link isDashboardStatePath}.
174
+ */
175
+ export function isDashboardStateDirSync(dir: string): boolean {
176
+ const configured = getDashboardConfigDir();
177
+ if (norm(path.basename(dir)) !== norm(path.basename(configured))) return false;
178
+ const key = `${os.homedir()}`;
179
+ if (cachedSyncFor !== key) {
180
+ try {
181
+ cachedSyncReal = realpathSync(configured);
182
+ } catch {
183
+ cachedSyncReal = path.resolve(configured);
184
+ }
185
+ cachedSyncFor = key;
186
+ }
187
+ try {
188
+ return norm(realpathSync(dir)) === norm(cachedSyncReal);
189
+ } catch {
190
+ return false;
191
+ }
192
+ }
193
+
194
+ /** Thrown when an OPENED handle turned out to be one of the always-refused files. */
195
+ export class DashboardStateRefused extends Error {
196
+ constructor() {
197
+ super("refused: dashboard state file");
198
+ this.name = "DashboardStateRefused";
199
+ }
200
+ }
201
+
202
+ /**
203
+ * `fs.open` + the post-open handle check. A refused handle is closed at once and
204
+ * nothing is read from it.
205
+ */
206
+ export async function openStateChecked(
207
+ p: string,
208
+ flags: string | number = "r",
209
+ ): Promise<import("node:fs/promises").FileHandle> {
210
+ const fh = await fs.open(p, flags);
211
+ try {
212
+ if (await handleIsAlwaysRefused(fh)) throw new DashboardStateRefused();
213
+ } catch (err) {
214
+ await fh.close().catch(() => undefined);
215
+ throw err;
216
+ }
217
+ return fh;
218
+ }
219
+
220
+ /** `fs.readFile` through {@link openStateChecked}: the bytes come from the checked handle. */
221
+ export async function readFileStateChecked(p: string): Promise<Buffer>;
222
+ export async function readFileStateChecked(p: string, encoding: BufferEncoding): Promise<string>;
223
+ export async function readFileStateChecked(p: string, encoding?: BufferEncoding): Promise<Buffer | string> {
224
+ const fh = await openStateChecked(p, "r");
225
+ try {
226
+ return encoding ? await fh.readFile(encoding) : await fh.readFile();
227
+ } finally {
228
+ await fh.close().catch(() => undefined);
229
+ }
230
+ }
@@ -4,9 +4,11 @@
4
4
  *
5
5
  * See OpenSpec change: diagram-rendering (design D3, D4, D5).
6
6
  */
7
+
7
8
  import { createHash } from "node:crypto";
8
9
  import zlib from "node:zlib";
9
- import { resolveKrokiEndpoint, type KrokiConfig } from "@blackbelt-technology/pi-dashboard-shared/config.js";
10
+ import { type KrokiConfig, resolveKrokiEndpoint } from "@blackbelt-technology/pi-dashboard-shared/config.js";
11
+ import { DIAGRAM_SVG_PROFILE } from "@blackbelt-technology/pi-dashboard-shared/sanitize-profiles.js";
10
12
  import { createSemaphore } from "@blackbelt-technology/pi-dashboard-shared/semaphore.js";
11
13
  import { loadPurify } from "./purify.js";
12
14
 
@@ -31,11 +33,7 @@ const MAX_DIAGRAM_RESPONSE_BYTES = 5 * 1024 * 1024; // 5 MB response cap
31
33
 
32
34
  async function sanitizeSvg(svg: string): Promise<string> {
33
35
  const purify = await loadPurify();
34
- return purify.sanitize(svg, {
35
- USE_PROFILES: { svg: true, svgFilters: true },
36
- FORBID_TAGS: ["foreignObject", "script", "style"],
37
- FORBID_ATTR: ["onclick", "onload", "onerror", "onmouseover", "onmouseout"],
38
- });
36
+ return purify.sanitize(svg, DIAGRAM_SVG_PROFILE);
39
37
  }
40
38
 
41
39
  // ── In-memory LRU cache ─────────────────────────────────────────────────────
@@ -9,8 +9,10 @@
9
9
  * NEVER fetches remote URLs — the browser does, inside the opaque-origin iframe.
10
10
  * See change: add-eml-preview.
11
11
  */
12
+
12
13
  import type { Stats } from "node:fs";
13
14
  import fs from "node:fs/promises";
15
+ import { EML_PROFILE } from "@blackbelt-technology/pi-dashboard-shared/sanitize-profiles.js";
14
16
  import { type ParsedMail, simpleParser } from "mailparser";
15
17
  import { loadPurify } from "./purify.js";
16
18
 
@@ -184,14 +186,7 @@ export async function sanitizeBody(
184
186
  ): Promise<{ html: string; hasRemote: boolean }> {
185
187
  if (!rawHtml) return { html: "", hasRemote: false };
186
188
  const DOMPurify = await loadPurify();
187
- const bodyEl = DOMPurify.sanitize(rawHtml, {
188
- RETURN_DOM: true,
189
- WHOLE_DOCUMENT: false,
190
- // FORCE_BODY keeps a leading `<style>` from being hoisted to <head> + dropped.
191
- FORCE_BODY: true,
192
- ADD_TAGS: ["style"],
193
- ADD_ATTR: ["target"],
194
- }) as unknown as DomEl;
189
+ const bodyEl = DOMPurify.sanitize(rawHtml, { ...EML_PROFILE, RETURN_DOM: true }) as unknown as DomEl;
195
190
 
196
191
  let hasRemote = false;
197
192
  const elements: DomEl[] = [bodyEl, ...Array.from(bodyEl.querySelectorAll("*"))];
@@ -0,0 +1,145 @@
1
+ /**
2
+ * Cwd admission for the file-family routes (change: core-file-cwd-admission, D1/D2/D3/D4): one
3
+ * function every file gate helper, inline route, editor-pane save, grep route and live-preview gate
4
+ * calls, so the shared guard's contract (503 on undecidable, `cwd_unknown` on refusal, canonical
5
+ * anchor) cannot drift between sites.
6
+ *
7
+ * The branch on `admissionAllows(admission, raw)` is right here so static analysis keeps the
8
+ * modelled path-injection barrier. Callers use the returned GUARDED `cwd` (the unmodified request
9
+ * string `admissionAllows` accepted) and release the token when done.
10
+ */
11
+ import path from "node:path";
12
+ import { admissionAllows, releaseAdmission } from "@blackbelt-technology/pi-dashboard-shared/cwd-guard.js";
13
+ import type { FastifyReply } from "fastify";
14
+ import {
15
+ admitRouteCwd,
16
+ CWD_ADMISSION_UNAVAILABLE_BODY,
17
+ type RouteAdmissionDeps,
18
+ sendAdmissionUnavailable,
19
+ } from "./route-admission.js";
20
+
21
+ /**
22
+ * Additive wire fields of a cwd-admission failure (core-file-cwd-admission D3/D4):
23
+ * `code` is `"cwd_unknown"` (refused) or `"cwd-admission-unavailable"` (503, with
24
+ * `message` + `retryAfterMs`). Absent on every other failure.
25
+ */
26
+ export interface GateWire {
27
+ code: string;
28
+ message?: string;
29
+ retryAfterMs?: number;
30
+ }
31
+
32
+ /** The minimal shape of a cwd-admission failure; assignable to the file routes' `GateFailure`. */
33
+ export interface CwdFailure {
34
+ code: number;
35
+ error: string;
36
+ wire: GateWire;
37
+ }
38
+
39
+ /** The shared 503 of an undecidable cwd admission as a gate failure (D3). */
40
+ export const CWD_UNAVAILABLE_FAILURE: CwdFailure = {
41
+ code: 503,
42
+ error: CWD_ADMISSION_UNAVAILABLE_BODY.error,
43
+ wire: {
44
+ code: CWD_ADMISSION_UNAVAILABLE_BODY.code,
45
+ message: CWD_ADMISSION_UNAVAILABLE_BODY.message,
46
+ retryAfterMs: CWD_ADMISSION_UNAVAILABLE_BODY.retryAfterMs,
47
+ },
48
+ };
49
+
50
+ /** A cwd refusal: the route's own pre-change `error` string plus the additive `code: "cwd_unknown"` (D4). */
51
+ function cwdRefusal(error: string): CwdFailure {
52
+ return { code: 403, error, wire: { code: "cwd_unknown" } };
53
+ }
54
+
55
+ /**
56
+ * Outcome of {@link admitFileCwd}. `cwd` is the GUARDED request value (the unmodified string
57
+ * `admissionAllows` accepted); `canonCwd` is its canonical form. `release()` ends the
58
+ * admission token: callers run it when done (helpers in a `finally`, inline routes via
59
+ * `reply.raw` close).
60
+ */
61
+ export type FileCwdAdmission =
62
+ | { ok: true; cwd: string; canonCwd: string; release: () => void }
63
+ | { ok: false; failure: CwdFailure };
64
+
65
+ /**
66
+ * Release an admission when the response closes (success, error, throw or disconnect). The client may
67
+ * have gone while admission ran (`close` already fired): then release at once.
68
+ */
69
+ export function releaseOnClose(reply: FastifyReply, release: () => void): void {
70
+ reply.raw.once("close", release);
71
+ if (reply.raw.destroyed) release();
72
+ }
73
+
74
+ /**
75
+ * Admit a request `cwd` through the shared guard for the file-family routes (change:
76
+ * core-file-cwd-admission, D1). The branch on `admissionAllows(admission, raw)` is right here so
77
+ * the modelled path-injection barrier survives; every file gate helper and inline route calls
78
+ * this one function. A non-string or non-absolute value is refused BEFORE admission (it can never
79
+ * select a global scope or reach `admitCwd`). Indeterminate → the shared 503 failure.
80
+ * With `reply`, the token is released when the response closes.
81
+ */
82
+ export async function admitFileCwd(
83
+ raw: unknown,
84
+ routeAdmission: RouteAdmissionDeps,
85
+ opts: { error?: string; reply?: FastifyReply } = {},
86
+ ): Promise<FileCwdAdmission> {
87
+ const error = opts.error ?? "unknown session path";
88
+ if (typeof raw !== "string" || !path.isAbsolute(raw)) return { ok: false, failure: cwdRefusal(error) };
89
+ const admission = await admitRouteCwd(raw, routeAdmission);
90
+ if (admission.kind === "indeterminate") return { ok: false, failure: CWD_UNAVAILABLE_FAILURE };
91
+ if (admission.kind !== "admit" || !admissionAllows(admission, raw)) {
92
+ return { ok: false, failure: cwdRefusal(error) };
93
+ }
94
+ const token = admission.token;
95
+ const release = (): void => releaseAdmission(token);
96
+ if (opts.reply) releaseOnClose(opts.reply, release);
97
+ return { ok: true, cwd: raw, canonCwd: token.canonCwd, release };
98
+ }
99
+
100
+ /**
101
+ * Containment anchors for an admitted cwd (D2): the request spelling first (relative paths
102
+ * resolve against it), then the canonical cwd when it differs. Layer ② roots are the same for
103
+ * both, so nothing outside the admitted directory is added.
104
+ */
105
+ export function cwdAnchors(a: { cwd: string; canonCwd: string }): string[] {
106
+ return a.canonCwd === a.cwd ? [a.cwd] : [a.cwd, a.canonCwd];
107
+ }
108
+
109
+ /** The `cwd_unknown` refusal body of the package, canvas-types, resources and groups routes (D4). */
110
+ export const CWD_NOT_ALLOWED_BODY = {
111
+ success: false,
112
+ code: "cwd_unknown",
113
+ error: "cwd not allowed",
114
+ reason: "cwd is not a known session or pinned directory.",
115
+ hint: "Pin this directory to allow it, or open a session rooted in it.",
116
+ } as const;
117
+
118
+ /** Reply with the shared 503 (undecidable) or the 403 {@link CWD_NOT_ALLOWED_BODY} (refused). */
119
+ export function sendCwdFailure(
120
+ reply: FastifyReply,
121
+ failure: CwdFailure,
122
+ ): typeof CWD_NOT_ALLOWED_BODY | typeof CWD_ADMISSION_UNAVAILABLE_BODY {
123
+ if (failure.code === 503) return sendAdmissionUnavailable(reply);
124
+ reply.code(403);
125
+ return CWD_NOT_ALLOWED_BODY;
126
+ }
127
+
128
+ /** Outcome of {@link admitOptionalCwd}: `cwd` is the guarded value, or `undefined` when the request sent none. */
129
+ export type OptionalCwdAdmission = { ok: true; cwd: string | undefined } | { ok: false; failure: CwdFailure };
130
+
131
+ /**
132
+ * Admit a `cwd` that the route treats as optional (package, canvas-types, resources routes). Absent
133
+ * (`undefined`, `null`, `""`) keeps the route's server-chosen fallback and hands the sink `undefined`,
134
+ * never the request value; any other value must be an admitted absolute cwd. The token is released
135
+ * when the response closes. See change: core-file-cwd-admission (D1).
136
+ */
137
+ export async function admitOptionalCwd(
138
+ raw: unknown,
139
+ routeAdmission: RouteAdmissionDeps,
140
+ reply: FastifyReply,
141
+ ): Promise<OptionalCwdAdmission> {
142
+ if (raw === undefined || raw === null || raw === "") return { ok: true, cwd: undefined };
143
+ const admitted = await admitFileCwd(raw, routeAdmission, { error: "cwd not allowed", reply });
144
+ return admitted.ok ? { ok: true, cwd: admitted.cwd } : { ok: false, failure: admitted.failure };
145
+ }