@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
@@ -0,0 +1,246 @@
1
+ /**
2
+ * One-shot rotation of secrets that may already have been read through the
3
+ * `~/.pi` file anchor by a bare-loopback caller (the local IPC token and the
4
+ * auth HMAC secret). Runs once per HOME at server start, before anything reads
5
+ * either value.
6
+ *
7
+ * - Exclusive `local/rotation.lock`, claimed with a hard link (atomic, fails
8
+ * with EEXIST when held). Stale after 30 s or when the holder pid is dead;
9
+ * the wait is capped at 35 s.
10
+ * - `local/rotation-epoch` below `REQUIRED_ROTATION_EPOCH` → write a new token
11
+ * (0600, atomic), replace `auth.secret` via `writeConfigFileSecure`, and only
12
+ * then write the epoch. The epoch is last, so any failure retries the whole
13
+ * rotation on the next start (a second token rotation is harmless).
14
+ * - Failure is closed: callers exit 1 before listening (`RotationError`).
15
+ *
16
+ * `close-loopback-legacy-window` reuses this lock and raises the epoch to 2.
17
+ * See change: close-container-loopback-impersonation (D11).
18
+ */
19
+ import crypto from "node:crypto";
20
+ import fs from "node:fs";
21
+ import os from "node:os";
22
+ import path from "node:path";
23
+ import { writeConfigFileSecure } from "@blackbelt-technology/pi-dashboard-shared/config.js";
24
+ import { getDashboardConfigDir } from "@blackbelt-technology/pi-dashboard-shared/dashboard-paths.js";
25
+ import { isProcessAlive } from "@blackbelt-technology/pi-dashboard-shared/platform/process.js";
26
+
27
+ /** Bump (never reuse) when another one-time rotation becomes necessary. */
28
+ export const REQUIRED_ROTATION_EPOCH = 1;
29
+ const ROTATION_LOCK_STALE_MS = 30_000;
30
+ export const ROTATION_LOCK_WAIT_CAP_MS = 35_000;
31
+ const POLL_MS = 100;
32
+ const TOKEN_BYTES = 32;
33
+
34
+ /** The failed step is named so the single log line tells the operator what to look at. */
35
+ export class RotationError extends Error {
36
+ readonly step: "lock" | "token" | "secret" | "epoch";
37
+ readonly paths: { lock: string; epoch: string };
38
+
39
+ constructor(step: "lock" | "token" | "secret" | "epoch", message: string, paths: { lock: string; epoch: string }) {
40
+ super(message);
41
+ this.name = "RotationError";
42
+ this.step = step;
43
+ this.paths = paths;
44
+ }
45
+
46
+ /** One line: step, cause, lock and epoch paths. */
47
+ describe(): string {
48
+ return `[rotation] secret rotation failed at step=${this.step}: ${this.message} (lock=${this.paths.lock} epoch=${this.paths.epoch}); exiting before listen`;
49
+ }
50
+ }
51
+
52
+ export interface RotationDeps {
53
+ /** `~/.pi/dashboard/local` */
54
+ localDir?: string;
55
+ /** `~/.pi/dashboard/config.json` */
56
+ configFile?: string;
57
+ now?: () => number;
58
+ sleep?: (ms: number) => Promise<void>;
59
+ isPidAlive?: (pid: number) => boolean;
60
+ /** Replaces `writeConfigFileSecure` (fault injection). */
61
+ writeConfig?: (file: string, text: string) => void;
62
+ }
63
+
64
+ export interface RotationResult {
65
+ rotated: boolean;
66
+ /** The replacement `auth.secret`, when one existed to replace. */
67
+ newSecret?: string;
68
+ }
69
+
70
+ function atomicWrite(file: string, text: string): void {
71
+ const tmp = `${file}.tmp.${process.pid}.${crypto.randomUUID()}`;
72
+ try {
73
+ fs.writeFileSync(tmp, text, { mode: 0o600 });
74
+ try {
75
+ fs.chmodSync(tmp, 0o600);
76
+ } catch {
77
+ /* best-effort (Windows) */
78
+ }
79
+ fs.renameSync(tmp, file);
80
+ } catch (err) {
81
+ try {
82
+ fs.unlinkSync(tmp);
83
+ } catch {
84
+ /* already gone */
85
+ }
86
+ throw err;
87
+ }
88
+ }
89
+
90
+ function readEpoch(file: string): number {
91
+ try {
92
+ const n = Number.parseInt(fs.readFileSync(file, "utf-8").trim(), 10);
93
+ return Number.isFinite(n) ? n : 0;
94
+ } catch {
95
+ return 0;
96
+ }
97
+ }
98
+
99
+ interface LockBody {
100
+ pid: number;
101
+ at: number;
102
+ }
103
+
104
+ function readLock(lock: string): LockBody | null {
105
+ try {
106
+ const body = JSON.parse(fs.readFileSync(lock, "utf-8")) as Partial<LockBody>;
107
+ if (typeof body.pid === "number" && typeof body.at === "number") return { pid: body.pid, at: body.at };
108
+ } catch {
109
+ /* unreadable / half-written: judged by mtime below */
110
+ }
111
+ return null;
112
+ }
113
+
114
+ /** Try once. `true` when this process now holds the lock. */
115
+ function tryClaim(lock: string, now: () => number, isPidAlive: (pid: number) => boolean, stalePath: () => string): boolean {
116
+ const mine = `${lock}.${process.pid}.${crypto.randomUUID()}`;
117
+ fs.writeFileSync(mine, JSON.stringify({ pid: process.pid, at: now() } satisfies LockBody), { mode: 0o600 });
118
+ try {
119
+ for (let attempt = 0; attempt < 2; attempt++) {
120
+ try {
121
+ fs.linkSync(mine, lock); // atomic; EEXIST when held
122
+ return true;
123
+ } catch (err) {
124
+ if ((err as NodeJS.ErrnoException).code !== "EEXIST") throw err;
125
+ }
126
+ const held = readLock(lock);
127
+ let stale: boolean;
128
+ if (held) {
129
+ stale = now() - held.at > ROTATION_LOCK_STALE_MS || !isPidAlive(held.pid);
130
+ } else {
131
+ // Half-written or foreign content: fall back to the file's age.
132
+ try {
133
+ stale = now() - fs.statSync(lock).mtimeMs > ROTATION_LOCK_STALE_MS;
134
+ } catch {
135
+ stale = true; // vanished between link and stat → retry the link
136
+ }
137
+ }
138
+ if (!stale) return false;
139
+ // Move (not unlink) the stale lock aside: rename is atomic, so exactly one
140
+ // contender removes it and a fresh lock claimed since is not unlinked by name.
141
+ try {
142
+ fs.renameSync(lock, stalePath());
143
+ } catch {
144
+ /* someone else cleared it first */
145
+ }
146
+ }
147
+ return false;
148
+ } finally {
149
+ try {
150
+ fs.unlinkSync(mine);
151
+ } catch {
152
+ /* already gone */
153
+ }
154
+ }
155
+ }
156
+
157
+ /**
158
+ * Rotate the local token and `auth.secret` once per HOME. Idempotent: a second
159
+ * call (or a second process) finds the epoch and returns `{ rotated: false }`.
160
+ * Throws `RotationError` on any failure; the epoch is then still unwritten.
161
+ */
162
+ export async function rotateSecretsOnce(deps: RotationDeps = {}): Promise<RotationResult> {
163
+ const dashDir = getDashboardConfigDir();
164
+ const localDir = deps.localDir ?? path.join(dashDir, "local");
165
+ const configFile = deps.configFile ?? path.join(os.homedir(), ".pi", "dashboard", "config.json");
166
+ const now = deps.now ?? Date.now;
167
+ const sleep = deps.sleep ?? ((ms: number) => new Promise<void>((r) => setTimeout(r, ms)));
168
+ const isPidAlive = deps.isPidAlive ?? ((pid: number) => isProcessAlive(pid, { epermAlive: true }));
169
+ const writeConfig = deps.writeConfig ?? writeConfigFileSecure;
170
+
171
+ const lockPath = path.join(localDir, "rotation.lock");
172
+ const epochPath = path.join(localDir, "rotation-epoch");
173
+ const tokenPath = path.join(localDir, "token");
174
+ const paths = { lock: lockPath, epoch: epochPath };
175
+ const fail = (step: RotationError["step"], err: unknown): never => {
176
+ throw new RotationError(step, err instanceof Error ? err.message : String(err), paths);
177
+ };
178
+
179
+ // Cheap path: already rotated, no lock needed.
180
+ if (readEpoch(epochPath) >= REQUIRED_ROTATION_EPOCH) return { rotated: false };
181
+
182
+ try {
183
+ fs.mkdirSync(localDir, { recursive: true, mode: 0o700 });
184
+ try {
185
+ fs.chmodSync(localDir, 0o700);
186
+ } catch {
187
+ /* best-effort (Windows) */
188
+ }
189
+ } catch (err) {
190
+ return fail("lock", err);
191
+ }
192
+
193
+ const started = now();
194
+ let claimed = false;
195
+ const stalePath = () => `${lockPath}.stale.${process.pid}.${crypto.randomUUID()}`;
196
+ while (!claimed) {
197
+ try {
198
+ claimed = tryClaim(lockPath, now, isPidAlive, stalePath);
199
+ } catch (err) {
200
+ return fail("lock", err);
201
+ }
202
+ if (claimed) break;
203
+ if (now() - started >= ROTATION_LOCK_WAIT_CAP_MS) {
204
+ return fail("lock", new Error(`rotation.lock still held after ${ROTATION_LOCK_WAIT_CAP_MS / 1000}s`));
205
+ }
206
+ await sleep(POLL_MS);
207
+ }
208
+
209
+ try {
210
+ // Another process may have finished while we waited.
211
+ if (readEpoch(epochPath) >= REQUIRED_ROTATION_EPOCH) return { rotated: false };
212
+
213
+ try {
214
+ atomicWrite(tokenPath, crypto.randomBytes(TOKEN_BYTES).toString("base64url"));
215
+ } catch (err) {
216
+ return fail("token", err);
217
+ }
218
+
219
+ let newSecret: string | undefined;
220
+ try {
221
+ if (fs.existsSync(configFile)) {
222
+ const parsed = JSON.parse(fs.readFileSync(configFile, "utf-8")) as { auth?: { secret?: unknown } } | null;
223
+ if (parsed && typeof parsed === "object" && parsed.auth && typeof parsed.auth.secret === "string" && parsed.auth.secret) {
224
+ newSecret = crypto.randomBytes(32).toString("hex"); // 32 bytes, as `ensureAuthSecret` (harden-auth-credentials B17)
225
+ parsed.auth.secret = newSecret;
226
+ writeConfig(configFile, `${JSON.stringify(parsed, null, 2)}\n`);
227
+ }
228
+ }
229
+ } catch (err) {
230
+ return fail("secret", err);
231
+ }
232
+
233
+ try {
234
+ atomicWrite(epochPath, `${REQUIRED_ROTATION_EPOCH}\n`);
235
+ } catch (err) {
236
+ return fail("epoch", err);
237
+ }
238
+ return { rotated: true, ...(newSecret ? { newSecret } : {}) };
239
+ } finally {
240
+ try {
241
+ fs.unlinkSync(lockPath);
242
+ } catch {
243
+ /* already gone */
244
+ }
245
+ }
246
+ }
@@ -0,0 +1,56 @@
1
+ /**
2
+ * One per-request "is this origin secure?" predicate for every cookie the
3
+ * dashboard sets with a `Secure` attribute: the OAuth state cookie, the
4
+ * `pi_dash_token` session cookie and the `pi_dash_device` cookie.
5
+ *
6
+ * `isSecureOrigin(request, baseIsHttps)` is true when ANY of:
7
+ * 1. the socket itself is TLS;
8
+ * 2. the resolved redirect base is https (`resolveRedirectBase`) — passed in as
9
+ * `baseIsHttps` so this module stays a leaf with no `auth.ts` import;
10
+ * 3. the SOCKET peer is loopback AND the request `Host` equals (host AND port,
11
+ * compared with `canonicalOrigin`) an **https** entry of `liveTunnelOrigins()`.
12
+ * An `http:` tunnel origin never qualifies.
13
+ *
14
+ * It keys on the socket peer, never a forwarding header: Fastify runs with
15
+ * `trustProxy` OFF on purpose, and header-injecting tunnels (zrok, cloudflared)
16
+ * still arrive from a loopback socket. A forged `Host` can only make a cookie
17
+ * STRICTER (`Secure`), never weaker. Any malformed `Host` or tunnel list yields
18
+ * `false` — the predicate never throws.
19
+ *
20
+ * See change: harden-auth-credentials (D3, B16r).
21
+ */
22
+ import type { TLSSocket } from "node:tls";
23
+ import type { FastifyRequest } from "fastify";
24
+ import { liveTunnelOrigins } from "../tunnel/tunnel.js";
25
+ import { canonicalOrigin } from "./cors-origin.js";
26
+ import { isLoopbackRange } from "./loopback.js";
27
+
28
+ /** A `Host` is only host[:port]: letters, digits, `.`, `-`, IPv6 `[]:`. Positive allowlist so `a@b`, `a/x`, `a#`… never parse into a bare host. */
29
+ const HOST_CHARS = /^[A-Za-z0-9.\-[\]:]+$/;
30
+
31
+ function hostIsLiveHttpsTunnel(request: FastifyRequest): boolean {
32
+ try {
33
+ const peer = request.raw.socket?.remoteAddress;
34
+ if (!peer || !isLoopbackRange(peer)) return false;
35
+ const host = request.headers.host;
36
+ if (typeof host !== "string" || !HOST_CHARS.test(host)) return false;
37
+ const requestOrigin = canonicalOrigin(`https://${host}`);
38
+ if (!requestOrigin) return false;
39
+ const origins = liveTunnelOrigins();
40
+ if (!Array.isArray(origins)) return false;
41
+ return origins.some((raw) => {
42
+ if (typeof raw !== "string") return false;
43
+ const origin = canonicalOrigin(raw);
44
+ return origin?.startsWith("https://") === true && origin === requestOrigin;
45
+ });
46
+ } catch {
47
+ // A throwing tunnel module / odd socket means "no live tunnel", never a 500.
48
+ return false;
49
+ }
50
+ }
51
+
52
+ export function isSecureOrigin(request: FastifyRequest, baseIsHttps: boolean): boolean {
53
+ if ((request.raw.socket as TLSSocket | undefined)?.encrypted) return true;
54
+ if (baseIsHttps) return true;
55
+ return hostIsLiveHttpsTunnel(request);
56
+ }
@@ -3,20 +3,36 @@
3
3
  * binding handed to `createServerPluginContext`. The mount itself (validation,
4
4
  * registry, request handling) lives in the runtime package (`mountApp`).
5
5
  *
6
- * A plugin is TRUSTED when its package DIRECTORY name is in
7
- * `packages/server/package.json#piDashboard.bundledPlugins`, or its manifest id is
8
- * in config `auth.capabilityRoutePlugins`. `manifest.priority` is a render-order
6
+ * A plugin is TRUSTED when it is BUNDLED, or its manifest id is in config `auth.trustedPlugins` (the
7
+ * single operator trust list, any entry for the id) or in the legacy `auth.capabilityRoutePlugins`
8
+ * (read, never written by the dashboard). BUNDLED = discovery `source` ∈ {workspace, bundled, installed},
9
+ * `realpath(packageDir)` a direct child of `realpath(<repo>/packages)`, `realpath(resources/plugins)`
10
+ * or `realpath(~/.pi/dashboard/plugins)`, and its (real) DIRECTORY name in
11
+ * `packages/server/package.json#piDashboard.bundledPlugins`. A `pi-package` / `local-detected`
12
+ * copy never counts, so a spoofed basename under `~/.pi/agent/npm/node_modules` is refused
13
+ * (design D12, R17). `manifest.priority` is a render-order
9
14
  * knob and never trust. An untrusted call mounts nothing and warns once, so an
10
15
  * untrusted plugin cannot squat a trusted app's id.
11
16
  *
12
17
  * API guardrail against accidents, not a boundary against a malicious in-process plugin.
13
18
  *
14
- * See change: add-plugin-capability-routes (D2, D5).
19
+ * See change: add-plugin-capability-routes (D2, D5); decouple-plugins-from-core (task 6.6, D12).
15
20
  */
21
+ import fs from "node:fs";
16
22
  import { createRequire } from "node:module";
17
23
  import path from "node:path";
18
- import { mountApp, type ServeAppOptions } from "@blackbelt-technology/dashboard-plugin-runtime/server";
24
+ import {
25
+ findBundledPluginsDir,
26
+ findInstalledPluginsDir,
27
+ findMonorepoRoot,
28
+ getPluginStatusStore,
29
+ mountApp,
30
+ type ServeAppOptions,
31
+ } from "@blackbelt-technology/dashboard-plugin-runtime/server";
32
+ import { loadConfig } from "@blackbelt-technology/pi-dashboard-shared/config.js";
33
+ import type { PluginDiscoverySource } from "@blackbelt-technology/pi-dashboard-shared/dashboard-plugin/plugin-status.js";
19
34
  import type { FastifyInstance } from "fastify";
35
+ import { readTrustedPlugins } from "./plugin-trust-store.js";
20
36
 
21
37
  const nodeRequire = createRequire(import.meta.url);
22
38
 
@@ -38,43 +54,96 @@ export function readBundledPluginDirs(): ReadonlySet<string> {
38
54
  }
39
55
 
40
56
  export interface ServeAppTrustInput {
41
- /** Absolute path of the plugin package directory (its basename is the bundled-list key). */
57
+ /** Absolute path of the plugin package directory (its real basename is the bundled-list key). */
42
58
  packageDir: string;
43
59
  /** Manifest id (the `auth.capabilityRoutePlugins` key). */
44
60
  manifestId: string;
61
+ /** Discovery source of the winning copy. Absent → never bundled (fail closed). */
62
+ source?: PluginDiscoverySource;
45
63
  }
46
64
 
47
- /** Pure trust decision: bundled by directory name, OR named in `auth.capabilityRoutePlugins`. */
65
+ const BUNDLED_SOURCES: ReadonlySet<PluginDiscoverySource> = new Set(["workspace", "bundled", "installed"]);
66
+
67
+ function realpathOrNull(p: string): string | null {
68
+ try {
69
+ return fs.realpathSync(p);
70
+ } catch {
71
+ return null;
72
+ }
73
+ }
74
+
75
+ /** Real roots a bundled plugin may live directly under: `<repo>/packages`, `resources/plugins`, `~/.pi/dashboard/plugins`. */
76
+ function readBundledPluginRoots(): string[] {
77
+ const monorepo = findMonorepoRoot();
78
+ const candidates = [monorepo ? path.join(monorepo, "packages") : null, findBundledPluginsDir(), findInstalledPluginsDir()];
79
+ return candidates.flatMap((c) => {
80
+ const real = c ? realpathOrNull(c) : null;
81
+ return real ? [real] : [];
82
+ });
83
+ }
84
+
85
+ /**
86
+ * Pure trust decision: bundled (path-contained), OR listed in `auth.trustedPlugins` (`trustedIds`),
87
+ * OR named in the legacy `auth.capabilityRoutePlugins` (`configuredIds`).
88
+ */
48
89
  export function isServeAppTrusted(
49
90
  plugin: ServeAppTrustInput,
50
- lists: { bundledDirs: ReadonlySet<string>; configuredIds: readonly string[] },
91
+ lists: {
92
+ bundledDirs: ReadonlySet<string>;
93
+ configuredIds: readonly string[];
94
+ /** Ids with an `auth.trustedPlugins` entry (any entry: the list is the one operator trust list). */
95
+ trustedIds?: readonly string[];
96
+ bundledRoots?: readonly string[];
97
+ },
51
98
  ): boolean {
52
- return lists.bundledDirs.has(path.basename(plugin.packageDir)) || lists.configuredIds.includes(plugin.manifestId);
99
+ if (lists.configuredIds.includes(plugin.manifestId)) return true;
100
+ if (lists.trustedIds?.includes(plugin.manifestId)) return true;
101
+ if (!plugin.source || !BUNDLED_SOURCES.has(plugin.source)) return false;
102
+ const real = realpathOrNull(plugin.packageDir);
103
+ if (!real || !lists.bundledDirs.has(path.basename(real))) return false;
104
+ const roots = lists.bundledRoots ?? readBundledPluginRoots();
105
+ const parent = path.dirname(real);
106
+ return roots.some((root) => parent === root);
107
+ }
108
+
109
+ /** Live ids of `auth.trustedPlugins`. */
110
+ function readTrustedIds(): readonly string[] {
111
+ return readTrustedPlugins().map((e) => e.id);
53
112
  }
54
113
 
55
114
  export interface HostServeAppDeps {
56
115
  fastify: FastifyInstance;
57
116
  plugin: ServeAppTrustInput;
58
- /** Live read of `auth.capabilityRoutePlugins` (read when the plugin activates). */
117
+ /** Live read of the legacy `auth.capabilityRoutePlugins` (read when the plugin activates). */
59
118
  readConfiguredIds: () => readonly string[];
119
+ /** Live read of `auth.trustedPlugins` ids; defaults to the config. */
120
+ readTrustedIds?: () => readonly string[];
121
+ /** Records the mount outcome; defaults to `PluginStatus.serveApp` in the status store. */
122
+ recordOutcome?: (pluginId: string, state: "mounted" | "refused") => void;
60
123
  /** Overridable for tests; defaults to the server package's bundled list. */
61
124
  bundledDirs?: ReadonlySet<string>;
125
+ /** Overridable for tests; real roots a bundled plugin must sit directly under. */
126
+ bundledRoots?: readonly string[];
62
127
  }
63
128
 
64
129
  /** The `deps.serveApp` binding for one plugin: trust-gate, then mount. */
65
130
  export function createHostServeApp(deps: HostServeAppDeps): (opts: ServeAppOptions, env: { dataDir: string }) => void {
66
131
  const { plugin } = deps;
132
+ const record = deps.recordOutcome ?? ((id, state) => getPluginStatusStore().recordServeApp(id, state));
67
133
  let warned = false;
68
134
  return (opts, env) => {
69
135
  const trusted = isServeAppTrusted(plugin, {
70
136
  bundledDirs: deps.bundledDirs ?? readBundledPluginDirs(),
71
137
  configuredIds: deps.readConfiguredIds(),
138
+ trustedIds: (deps.readTrustedIds ?? readTrustedIds)(),
139
+ bundledRoots: deps.bundledRoots,
72
140
  });
73
141
  if (!trusted) {
142
+ record(plugin.manifestId, "refused");
74
143
  if (!warned) {
75
144
  warned = true;
76
145
  console.warn(
77
- `[serveApp] plugin '${plugin.manifestId}' is not trusted to mount an app (bundled plugin or auth.capabilityRoutePlugins); ignoring`,
146
+ `[serveApp] plugin '${plugin.manifestId}' is not trusted to mount an app (bundled plugin, auth.trustedPlugins or auth.capabilityRoutePlugins); ignoring`,
78
147
  );
79
148
  }
80
149
  return;
@@ -93,5 +162,36 @@ export function createHostServeApp(deps: HostServeAppDeps): (opts: ServeAppOptio
93
162
  },
94
163
  opts,
95
164
  );
165
+ record(plugin.manifestId, "mounted");
96
166
  };
97
167
  }
168
+
169
+ /**
170
+ * Whether a trust change flips a plugin's `serveApp` outcome: the mount is decided at activation, so a
171
+ * refused app that is trusted now (grant), or a mounted one that is no longer trusted (revoke), needs a
172
+ * restart. Pure.
173
+ */
174
+ export function serveAppRestartNeeded(recorded: "mounted" | "refused" | undefined, trustedNow: boolean): boolean {
175
+ return (recorded === "refused" && trustedNow) || (recorded === "mounted" && !trustedNow);
176
+ }
177
+
178
+ /**
179
+ * After a trust grant/revoke: compare the plugin's CURRENT `serveApp` trust with the outcome recorded at
180
+ * activation and set `restartRequired` on its status row when they differ (spec "Trust freshness differs
181
+ * per surface"). Returns whether the row was flagged; the caller broadcasts `plugins_changed`. A plugin
182
+ * that never called `serveApp` (no recorded outcome) is untouched.
183
+ */
184
+ export function noteServeAppTrustChange(plugin: ServeAppTrustInput): boolean {
185
+ const store = getPluginStatusStore();
186
+ const stored = store.getStoredStatus(plugin.manifestId);
187
+ const recorded = store.getStatus(plugin.manifestId)?.serveApp;
188
+ if (!stored || stored.restartRequired) return false;
189
+ const trustedNow = isServeAppTrusted(plugin, {
190
+ bundledDirs: readBundledPluginDirs(),
191
+ configuredIds: loadConfig().auth?.capabilityRoutePlugins ?? [],
192
+ trustedIds: readTrustedIds(),
193
+ });
194
+ if (!serveAppRestartNeeded(recorded, trustedNow)) return false;
195
+ store.setStatus({ ...stored, restartRequired: true });
196
+ return true;
197
+ }
@@ -18,6 +18,7 @@
18
18
  */
19
19
  import crypto from "node:crypto";
20
20
  import type { Principal } from "@blackbelt-technology/pi-dashboard-shared/identity.js";
21
+ import { isProvenTls } from "./proven-tls.js";
21
22
 
22
23
  /** Core WS route scopes — the only scopes a ticket may ever be bound to. */
23
24
  const CORE_WS_ROUTE_SCOPES = ["browser", "terminal", "live", "bridge"] as const;
@@ -74,11 +75,28 @@ interface TicketEntry {
74
75
  */
75
76
  principalExpiresAt?: number;
76
77
  expiresAt: number;
78
+ /** The minting request was on the hub's own TLS socket with no forwarding header (`bridge` scope). */
79
+ provenTls?: boolean;
80
+ /** How a `bridge` ticket was minted: with a device bearer, or by a genuinely-local bearer-less caller. */
81
+ mintedBy?: "device" | "local";
82
+ }
83
+
84
+ /** Facts the minting request proves, recorded on the ticket. See change: prove-vault-bridge-tls (D3). */
85
+ export interface TicketMintMeta {
86
+ provenTls: boolean;
87
+ mintedBy: "device" | "local";
77
88
  }
78
89
 
79
90
  /** Outcome of a single-use consumption attempt, with the cause named. */
80
91
  export type TicketConsumption =
81
- | { ok: true; deviceId?: string; principal?: Principal; principalExpiresAt?: number }
92
+ | {
93
+ ok: true;
94
+ deviceId?: string;
95
+ principal?: Principal;
96
+ principalExpiresAt?: number;
97
+ provenTls?: boolean;
98
+ mintedBy?: "device" | "local";
99
+ }
82
100
  | { ok: false; reason: "missing" | "unknown" | "expired" | "wrong-scope" };
83
101
 
84
102
  /**
@@ -158,6 +176,7 @@ export class WsTicketStore {
158
176
  scope: CoreWsRouteScope,
159
177
  deviceId?: string,
160
178
  identity?: { principal: Principal; principalExpiresAt?: number },
179
+ meta?: TicketMintMeta,
161
180
  ): string {
162
181
  // Lazy sweep on each mint clears abandoned (minted-but-unconsumed) tickets
163
182
  // so the map can't grow unbounded without a background timer.
@@ -169,6 +188,7 @@ export class WsTicketStore {
169
188
  principal: identity?.principal,
170
189
  principalExpiresAt: identity?.principalExpiresAt,
171
190
  expiresAt: this.now() + TICKET_TTL_MS,
191
+ ...(meta ? { provenTls: meta.provenTls, mintedBy: meta.mintedBy } : {}),
172
192
  });
173
193
  return ticket;
174
194
  }
@@ -204,6 +224,8 @@ export class WsTicketStore {
204
224
  deviceId: entry.deviceId,
205
225
  principal: entry.principal,
206
226
  principalExpiresAt: entry.principalExpiresAt,
227
+ provenTls: entry.provenTls,
228
+ mintedBy: entry.mintedBy,
207
229
  };
208
230
  }
209
231
 
@@ -215,3 +237,19 @@ export class WsTicketStore {
215
237
  }
216
238
  }
217
239
  }
240
+
241
+ /**
242
+ * Mint a `bridge` ticket recording what the MINTING request proves: whether it arrived on the hub's own
243
+ * TLS socket with no forwarding header, and whether a device bearer or a genuinely-local caller minted it.
244
+ * See change: prove-vault-bridge-tls (D3).
245
+ */
246
+ export function mintBridgeTicket(
247
+ store: WsTicketStore,
248
+ deviceId: string | undefined,
249
+ req: Parameters<typeof isProvenTls>[0],
250
+ ): string {
251
+ return store.mint("bridge", deviceId, undefined, {
252
+ provenTls: isProvenTls(req),
253
+ mintedBy: deviceId ? "device" : "local",
254
+ });
255
+ }
@@ -3,7 +3,7 @@
3
3
  * other gate logs (bridge-scope 400, auth 401, no-auth 403).
4
4
  *
5
5
  * Line: `[ws-upgrade] rejected status=<n> scope=<s> peer=<addr>
6
- * fwd=<comma-names|none> ticket=<present|absent>[ suppressed=<n>]`.
6
+ * fwd=<comma-names|none> ticket=<present|absent>[ reason=<token>][ suppressed=<n>]`.
7
7
  * Header VALUES, cookies and ticket strings are never read into the line.
8
8
  *
9
9
  * At most one line per `status|scope|peer` key per window; the first line
@@ -21,6 +21,8 @@ export interface WsUpgradeRejection {
21
21
  remoteAddress: string | undefined;
22
22
  headers: Record<string, unknown> | undefined;
23
23
  ticketPresent: boolean;
24
+ /** Machine reason when the rejection has one (e.g. `local_proof_required`); a fixed token, never caller input. */
25
+ reason?: string;
24
26
  }
25
27
 
26
28
  export interface WsUpgradeRejectLoggerOptions {
@@ -73,6 +75,7 @@ export function createWsUpgradeRejectLogger(opts: WsUpgradeRejectLoggerOptions =
73
75
  emit(
74
76
  `[ws-upgrade] rejected status=${r.status} scope=${r.scope} peer=${peer}` +
75
77
  ` fwd=${fwd.length > 0 ? fwd.join(",") : "none"} ticket=${r.ticketPresent ? "present" : "absent"}` +
78
+ (r.reason ? ` reason=${r.reason}` : "") +
76
79
  (suppressed > 0 ? ` suppressed=${suppressed}` : ""),
77
80
  );
78
81
  },
@@ -9,6 +9,7 @@ import { normalizePath } from "@blackbelt-technology/pi-dashboard-shared/platfor
9
9
  import { isGroupByMode } from "@blackbelt-technology/pi-dashboard-shared/session-group-by.js";
10
10
  import { getPiTrustMirror } from "../access/pi-trust-mirror-service.js";
11
11
  import { safeRealpathSync } from "../resolve-path.js";
12
+ import { gateRemoteFolder } from "./folder-gate.js";
12
13
  import type { BrowserHandlerContext } from "./handler-context.js";
13
14
 
14
15
  /**
@@ -25,6 +26,14 @@ function canonicalizePath(input: string): string {
25
26
  export function handlePinDirectory(
26
27
  msg: Extract<BrowserToServerMessage, { type: "pin_directory" }>,
27
28
  ctx: BrowserHandlerContext,
29
+ ): void {
30
+ // A remote socket may only pin inside the shared roots. See change: harden-server-capability-bounds (D1b).
31
+ gateRemoteFolder(ctx, canonicalizePath(msg.path), "pin_directory", () => pinDirectoryNow(msg, ctx));
32
+ }
33
+
34
+ function pinDirectoryNow(
35
+ msg: Extract<BrowserToServerMessage, { type: "pin_directory" }>,
36
+ ctx: BrowserHandlerContext,
28
37
  ): void {
29
38
  const { preferencesStore } = ctx;
30
39
  if (!preferencesStore) return;
@@ -349,6 +358,13 @@ export function handleSetLaneCollapsed(
349
358
  export function handleAddFolderToWorkspace(
350
359
  msg: Extract<BrowserToServerMessage, { type: "add_folder_to_workspace" }>,
351
360
  ctx: BrowserHandlerContext,
361
+ ): void {
362
+ gateRemoteFolder(ctx, canonicalizePath(msg.path), "add_folder_to_workspace", () => addFolderToWorkspaceNow(msg, ctx));
363
+ }
364
+
365
+ function addFolderToWorkspaceNow(
366
+ msg: Extract<BrowserToServerMessage, { type: "add_folder_to_workspace" }>,
367
+ ctx: BrowserHandlerContext,
352
368
  ): void {
353
369
  const store = ctx.preferencesStore;
354
370
  if (!store) return;
@@ -412,6 +428,13 @@ export function handleReorderWorkspaceFolders(
412
428
  export function handleMoveFolderToWorkspace(
413
429
  msg: Extract<BrowserToServerMessage, { type: "move_folder_to_workspace" }>,
414
430
  ctx: BrowserHandlerContext,
431
+ ): void {
432
+ gateRemoteFolder(ctx, canonicalizePath(msg.path), "move_folder_to_workspace", () => moveFolderToWorkspaceNow(msg, ctx));
433
+ }
434
+
435
+ function moveFolderToWorkspaceNow(
436
+ msg: Extract<BrowserToServerMessage, { type: "move_folder_to_workspace" }>,
437
+ ctx: BrowserHandlerContext,
415
438
  ): void {
416
439
  const { preferencesStore } = ctx;
417
440
  if (!preferencesStore) return;