@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,244 @@
1
+ /**
2
+ * Live dashboard-trust entries: trust whose lifetime is the running server.
3
+ *
4
+ * Sources (all in memory, never persisted, never in the snapshot):
5
+ * - session-scoped worktree-init trust ("until the dashboard restarts");
6
+ * - session-scoped access grants on project roots;
7
+ * - each root of a live YOLO session (operator: until expiry/end; env: for the
8
+ * server process; unscoped never).
9
+ *
10
+ * Every entry records the folder's identity (dev + ino [+ birth time]) the first
11
+ * time the provider sees it — `reconcile()` runs synchronously inside the action
12
+ * that created it — so a deleted-and-re-created folder never inherits trust. A
13
+ * folder that cannot be stat'ed at creation gets no identity and never counts.
14
+ * Per-entry "also trust in pi" choices for live entries are held here, in memory,
15
+ * and end with the entry.
16
+ *
17
+ * Entries then pass the SAME switch / choice / deny / hook / project-root rules as
18
+ * durable ones (`filterMirrorEntries`). The provider answers: how many count
19
+ * (`reconcile`), which cover a cwd (`covering`), and whether a YOLO entry is still
20
+ * live (`isStillLive`, re-checked after a proof is built).
21
+ *
22
+ * See change: mirror-dashboard-trust-live-remote (D3).
23
+ */
24
+ import os from "node:os";
25
+ import type { PiTrustMirrorConfig } from "@blackbelt-technology/pi-dashboard-shared/config.js";
26
+ import {
27
+ type FolderIdentity,
28
+ filterMirrorEntries,
29
+ findCoveringEntry,
30
+ type MirrorCandidate,
31
+ type MirrorDenyRules,
32
+ type MirrorIgnored,
33
+ mirrorDenyRules,
34
+ statFolderIdentity,
35
+ } from "@blackbelt-technology/pi-dashboard-shared/pi-trust-mirror.js";
36
+ import { currentHookHash, safePiTrustKey } from "@blackbelt-technology/pi-dashboard-shared/pi-trust-mirror-snapshot.js";
37
+ import type { MirrorSourceKind } from "@blackbelt-technology/pi-dashboard-shared/pi-trust-mirror-types.js";
38
+ import { hasProjectRootMarker } from "@blackbelt-technology/pi-dashboard-shared/project-root.js";
39
+ import type { YoloSession } from "./yolo-session.js";
40
+
41
+ type LiveSourceKind = Extract<MirrorSourceKind, "worktreeInit" | "accessGrants" | "yolo">;
42
+
43
+ export type LiveLifetime =
44
+ | { kind: "restart" }
45
+ | { kind: "yolo-until"; until: number }
46
+ | { kind: "yolo-process" };
47
+
48
+ /** Human lifetime phrase for server-side views ("until dashboard restarts", …). */
49
+ export function liveLifetimeText(l: LiveLifetime): string {
50
+ if (l.kind === "restart") return "until dashboard restarts";
51
+ if (l.kind === "yolo-process") return "YOLO while the server runs";
52
+ return `YOLO until ${new Date(l.until).toISOString()}`;
53
+ }
54
+
55
+ export interface LiveEntry {
56
+ sourceKind: LiveSourceKind;
57
+ /** pi trust-store key form (canonical absolute path). */
58
+ key: string;
59
+ /** Identity recorded when the entry was created. */
60
+ identity: FolderIdentity;
61
+ lifetime: LiveLifetime;
62
+ }
63
+
64
+ export interface LiveProviderDeps {
65
+ getConfig: () => PiTrustMirrorConfig;
66
+ /** In-memory session worktree-init trust (`path.resolve` keys). */
67
+ listSessionTrust: () => Array<{ repoRoot: string; hash: string }>;
68
+ /** In-memory session access grants. */
69
+ listSessionGrants: () => Array<{ subject: string }>;
70
+ /** Lazy: YOLO is constructed after the mirror service. */
71
+ getYolo: () => { status(): YoloSession | null } | undefined;
72
+ home?: string;
73
+ now?: () => number;
74
+ hookHash?: (configRoot: string) => string | null;
75
+ denyRules?: () => MirrorDenyRules;
76
+ /** Test seam: identity probe (default `statFolderIdentity`). */
77
+ stat?: (key: string) => FolderIdentity | null;
78
+ }
79
+
80
+ interface LiveEnumeration {
81
+ counted: LiveEntry[];
82
+ ignored: MirrorIgnored[];
83
+ /** Every live candidate (counted + ignored), with its lifetime, for the Access page. */
84
+ candidates: Array<{ candidate: MirrorCandidate; lifetime: LiveLifetime; confers: boolean }>;
85
+ }
86
+
87
+ export interface PiTrustLiveProvider {
88
+ /** Record identities of new entries, drop those that ended, return how many count. */
89
+ reconcile(): number;
90
+ enumerate(): LiveEnumeration;
91
+ /** The nearest counted live entry whose folder is the cwd key or an ancestor. */
92
+ covering(cwdKey: string): LiveEntry | null;
93
+ /** False once a YOLO entry's session ended or expired (always true for the other sources). */
94
+ isStillLive(entry: LiveEntry): boolean;
95
+ /** Hold (or clear with `null`) one live entry's choice in memory. */
96
+ setChoice(kind: LiveSourceKind, folder: string, choice: boolean | null): void;
97
+ }
98
+
99
+ const idKey = (kind: string, key: string): string => `${kind}\u0000${key}`;
100
+
101
+ interface RawCandidate {
102
+ candidate: MirrorCandidate;
103
+ lifetime: LiveLifetime;
104
+ }
105
+
106
+ type Unchoiced = { candidate: Omit<MirrorCandidate, "choice">; lifetime: LiveLifetime };
107
+ type KeyOf = (folder: string) => string | null;
108
+
109
+ function sessionTrustCandidates(deps: LiveProviderDeps, keyOf: KeyOf, hookHash: (root: string) => string | null): Unchoiced[] {
110
+ const out: Unchoiced[] = [];
111
+ for (const { repoRoot, hash } of deps.listSessionTrust()) {
112
+ const key = keyOf(repoRoot);
113
+ if (!key) continue;
114
+ const current = hookHash(repoRoot);
115
+ const hookState = current === null ? "unreadable" : current === hash ? "current" : "changed";
116
+ out.push({
117
+ candidate: { sourceKind: "worktreeInit", key, hookState, meta: { configRoot: repoRoot, hookHash: hash } },
118
+ lifetime: { kind: "restart" },
119
+ });
120
+ }
121
+ return out;
122
+ }
123
+
124
+ function sessionGrantCandidates(deps: LiveProviderDeps, keyOf: KeyOf): Unchoiced[] {
125
+ const out: Unchoiced[] = [];
126
+ for (const { subject } of deps.listSessionGrants()) {
127
+ const key = keyOf(subject);
128
+ if (key) {
129
+ out.push({ candidate: { sourceKind: "accessGrants", key, projectRoot: hasProjectRootMarker(key) }, lifetime: { kind: "restart" } });
130
+ }
131
+ }
132
+ return out;
133
+ }
134
+
135
+ function yoloCandidates(deps: LiveProviderDeps, keyOf: KeyOf): Unchoiced[] {
136
+ const session = deps.getYolo()?.status() ?? null;
137
+ if (!session || session.unscoped) return [];
138
+ const lifetime: LiveLifetime =
139
+ session.expiresAt === null ? { kind: "yolo-process" } : { kind: "yolo-until", until: session.expiresAt };
140
+ const out: Unchoiced[] = [];
141
+ for (const root of session.roots) {
142
+ const key = keyOf(root.path);
143
+ if (key) out.push({ candidate: { sourceKind: "yolo", key }, lifetime });
144
+ }
145
+ return out;
146
+ }
147
+
148
+ /** Counted candidates that hold a recorded identity become entries; the rest are ignored `identity-mismatch`. */
149
+ function toEntries(
150
+ counted: readonly MirrorCandidate[],
151
+ identities: ReadonlyMap<string, FolderIdentity | null>,
152
+ lifetimes: ReadonlyMap<string, LiveLifetime>,
153
+ ): { entries: LiveEntry[]; noIdentity: MirrorIgnored[] } {
154
+ const entries: LiveEntry[] = [];
155
+ const noIdentity: MirrorIgnored[] = [];
156
+ for (const c of counted) {
157
+ const k = idKey(c.sourceKind, c.key);
158
+ const identity = identities.get(k);
159
+ if (!identity) {
160
+ noIdentity.push({ entry: c, reason: "identity-mismatch" });
161
+ continue;
162
+ }
163
+ entries.push({ sourceKind: c.sourceKind as LiveSourceKind, key: c.key, identity, lifetime: lifetimes.get(k) as LiveLifetime });
164
+ }
165
+ return { entries, noIdentity };
166
+ }
167
+
168
+ export function createPiTrustLiveProvider(deps: LiveProviderDeps): PiTrustLiveProvider {
169
+ const home = deps.home ?? os.homedir();
170
+ const now = deps.now ?? Date.now;
171
+ const hookHash = deps.hookHash ?? currentHookHash;
172
+ const stat = deps.stat ?? statFolderIdentity;
173
+ /** `null` = could not be stat'ed at creation: never counts. */
174
+ const identities = new Map<string, FolderIdentity | null>();
175
+ const choices = new Map<string, boolean>();
176
+
177
+ const keyOf: KeyOf = (folder) => safePiTrustKey(folder, home);
178
+
179
+ function raw(): RawCandidate[] {
180
+ const all = [...sessionTrustCandidates(deps, keyOf, hookHash), ...sessionGrantCandidates(deps, keyOf), ...yoloCandidates(deps, keyOf)];
181
+ return all.map(({ candidate, lifetime }) => ({
182
+ candidate: { ...candidate, choice: choices.get(idKey(candidate.sourceKind, candidate.key)) },
183
+ lifetime,
184
+ }));
185
+ }
186
+
187
+ /** Stat new keys now (creation time), forget keys that ended, drop their choices. */
188
+ function sync(candidates: RawCandidate[]): void {
189
+ const present = new Set(candidates.map((c) => idKey(c.candidate.sourceKind, c.candidate.key)));
190
+ for (const { candidate } of candidates) {
191
+ const k = idKey(candidate.sourceKind, candidate.key);
192
+ if (!identities.has(k)) identities.set(k, stat(candidate.key));
193
+ }
194
+ for (const k of [...identities.keys()]) {
195
+ if (!present.has(k)) {
196
+ identities.delete(k);
197
+ choices.delete(k);
198
+ }
199
+ }
200
+ }
201
+
202
+ function enumerate(): LiveEnumeration {
203
+ const candidates = raw();
204
+ sync(candidates);
205
+ const lifetimes = new Map(candidates.map((c) => [idKey(c.candidate.sourceKind, c.candidate.key), c.lifetime]));
206
+ const filtered = filterMirrorEntries(candidates.map((c) => c.candidate), { sources: deps.getConfig().sources }, {
207
+ choicesReadable: true,
208
+ deny: deps.denyRules ? deps.denyRules() : mirrorDenyRules({ homedir: home }),
209
+ home,
210
+ });
211
+ const { entries, noIdentity } = toEntries(filtered.counted, identities, lifetimes);
212
+ const countedKeys = new Set(entries.map((e) => idKey(e.sourceKind, e.key)));
213
+ return {
214
+ counted: entries,
215
+ ignored: [...filtered.ignored, ...noIdentity],
216
+ candidates: candidates.map((c) => ({
217
+ candidate: c.candidate,
218
+ lifetime: c.lifetime,
219
+ confers: countedKeys.has(idKey(c.candidate.sourceKind, c.candidate.key)),
220
+ })),
221
+ };
222
+ }
223
+
224
+ function yoloStillLive(entry: LiveEntry): boolean {
225
+ if (!deps.getConfig().sources.yolo) return false;
226
+ const session = deps.getYolo()?.status() ?? null;
227
+ if (!session || session.unscoped) return false;
228
+ if (session.expiresAt !== null && now() >= session.expiresAt) return false;
229
+ return session.roots.some((r) => keyOf(r.path) === entry.key);
230
+ }
231
+
232
+ return {
233
+ reconcile: () => enumerate().counted.length,
234
+ enumerate,
235
+ covering: (cwdKey) => findCoveringEntry(enumerate().counted, cwdKey),
236
+ isStillLive: (entry) => entry.sourceKind !== "yolo" || yoloStillLive(entry),
237
+ setChoice(kind, folder, choice) {
238
+ const key = keyOf(folder);
239
+ if (!key) return;
240
+ if (choice === null) choices.delete(idKey(kind, key));
241
+ else choices.set(idKey(kind, key), choice);
242
+ },
243
+ };
244
+ }
@@ -45,6 +45,8 @@ import type {
45
45
  PiTrustSnapshot,
46
46
  PiTrustSnapshotEntry,
47
47
  } from "@blackbelt-technology/pi-dashboard-shared/pi-trust-mirror-types.js";
48
+ import { hasProjectRootMarker } from "@blackbelt-technology/pi-dashboard-shared/project-root.js";
49
+ import type { PiTrustLiveProvider } from "./pi-trust-live.js";
48
50
 
49
51
  /** Above this many counted entries every snapshot rewrite logs a warning. */
50
52
  export const SNAPSHOT_WARN_ENTRIES = 5000;
@@ -71,6 +73,12 @@ export interface PiTrustMirrorServiceDeps {
71
73
  canWrite?: () => boolean;
72
74
  /** Test seam: deny rules (default `mirrorDenyRules({ homedir: home })`). */
73
75
  denyRules?: () => MirrorDenyRules;
76
+ /**
77
+ * Live (server-lifetime) entries: counted into the snapshot's `liveCount` only —
78
+ * their paths and identities never reach disk. Absent → `liveCount` stays 0.
79
+ * See change: mirror-dashboard-trust-live-remote.
80
+ */
81
+ live?: PiTrustLiveProvider;
74
82
  }
75
83
 
76
84
  interface CountedMirrorEntry {
@@ -107,6 +115,14 @@ export interface PiTrustMirrorService {
107
115
  refresh(): void;
108
116
  /** The snapshot as currently on disk, or null. */
109
117
  readSnapshot(): PiTrustSnapshot | null;
118
+ /** The live-entry provider, when one was configured. */
119
+ readonly live: PiTrustLiveProvider | undefined;
120
+ /**
121
+ * A live source changed (session trust/grant, YOLO): recompute the live count and,
122
+ * when it changed, rewrite the snapshot SYNCHRONOUSLY — before the changing action
123
+ * reports success. A failed rewrite is logged and never fails the action.
124
+ */
125
+ noteLiveChanged(): void;
110
126
  }
111
127
 
112
128
  const choiceKey = (kind: MirrorSourceKind, key: string): string => `${kind}\u0000${key}`;
@@ -174,19 +190,11 @@ function buildCandidates(
174
190
  }
175
191
  for (const { subject } of deps.listPersistedGrants()) {
176
192
  const key = keyOf(subject);
177
- if (key) push({ sourceKind: "accessGrants", key, projectRoot: isProjectRootDir(key) });
193
+ if (key) push({ sourceKind: "accessGrants", key, projectRoot: hasProjectRootMarker(key) });
178
194
  }
179
195
  return out;
180
196
  }
181
197
 
182
- function isProjectRootDir(dir: string): boolean {
183
- try {
184
- return fs.existsSync(path.join(dir, ".git")) || fs.existsSync(path.join(dir, ".pi"));
185
- } catch {
186
- return false;
187
- }
188
- }
189
-
190
198
  function defaultWriteAtomic(file: string, content: string, mode: number): void {
191
199
  fs.mkdirSync(path.dirname(file), { recursive: true });
192
200
  const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
@@ -212,6 +220,7 @@ export function createPiTrustMirrorService(deps: PiTrustMirrorServiceDeps): PiTr
212
220
  const warn = deps.warn ?? ((m: string) => console.warn(`[pi-trust-mirror] ${m}`));
213
221
  const installed: Partial<Record<MirrorSourceKind, boolean>> = { workflow: false, ...deps.installed };
214
222
  let lastGeneration = 0;
223
+ let lastLiveCount = 0;
215
224
 
216
225
  const keyOf = (folder: string): string | null => {
217
226
  try {
@@ -265,18 +274,30 @@ export function createPiTrustMirrorService(deps: PiTrustMirrorServiceDeps): PiTr
265
274
  return { counted, ignored, candidates, choicesReadable: readable, sourcesNotInstalled };
266
275
  }
267
276
 
268
- function rewriteSnapshot(opts?: { exclude?: Array<{ sourceKind: MirrorSourceKind; key: string }> }): number {
277
+ function countLive(): number {
278
+ try {
279
+ return deps.live?.reconcile() ?? 0;
280
+ } catch (err) {
281
+ warn(`live count failed: ${(err as Error)?.message}`);
282
+ return lastLiveCount;
283
+ }
284
+ }
285
+
286
+ function rewriteSnapshot(opts?: { exclude?: Array<{ sourceKind: MirrorSourceKind; key: string }>; liveCount?: number }): number {
269
287
  if (deps.canWrite && !deps.canWrite()) throw new Error("pi-trust-mirror: this server does not hold the home lock");
270
288
  const evaluation = evaluate(opts);
289
+ const liveCount = opts?.liveCount ?? countLive();
271
290
  const onDisk = readPiTrustMirrorSnapshot(snapshotFile);
272
291
  const generation = Math.max(lastGeneration, onDisk?.generation ?? 0) + 1;
273
292
  const snapshot: PiTrustSnapshot = {
274
293
  version: 1,
275
294
  generation,
276
295
  entries: evaluation.counted.map((c) => c.snapshotEntry),
296
+ liveCount,
277
297
  };
278
298
  writeAtomic(snapshotFile, `${JSON.stringify(snapshot)}\n`, 0o600);
279
299
  lastGeneration = generation;
300
+ lastLiveCount = liveCount;
280
301
  if (snapshot.entries.length > SNAPSHOT_WARN_ENTRIES) {
281
302
  warn(`snapshot holds ${snapshot.entries.length} entries (> ${SNAPSHOT_WARN_ENTRIES}); consider unpinning unused folders`);
282
303
  }
@@ -324,7 +345,19 @@ export function createPiTrustMirrorService(deps: PiTrustMirrorServiceDeps): PiTr
324
345
  return choices[choiceKey(kind, key)];
325
346
  },
326
347
  rewriteSnapshot,
327
- rebuildAtBoot: () => rewriteSnapshot(),
348
+ // Boot writes `liveCount` 0 whatever a crashed predecessor left behind; live
349
+ // entries that appear afterwards (env YOLO) raise it through `noteLiveChanged`.
350
+ rebuildAtBoot: () => rewriteSnapshot({ liveCount: 0 }),
351
+ live: deps.live,
352
+ noteLiveChanged() {
353
+ if (!deps.live) return;
354
+ if (countLive() === lastLiveCount) return;
355
+ try {
356
+ rewriteSnapshot();
357
+ } catch (err) {
358
+ warn(`snapshot live-count rewrite failed: ${(err as Error)?.message}`);
359
+ }
360
+ },
328
361
  setChoice,
329
362
  grant(kind, folder, choice, writeSource) {
330
363
  const key = keyOf(folder);
@@ -1,5 +1,5 @@
1
1
  /**
2
- * The four access planes this change registers (design D5; tasks 5.2-5.4).
2
+ * The access planes (design D5; tasks 5.2-5.4; plus `preview-egress`, see the end of the file).
3
3
  *
4
4
  * Exactly the planes `add-access-grants-and-review` made grantable, each
5
5
  * delegating `grant` to THAT change's store, so there is nothing new to revoke
@@ -16,16 +16,22 @@
16
16
  *
17
17
  * See change: add-access-grant-dialog.
18
18
  */
19
+ import dns from "node:dns";
19
20
  import { isIP } from "node:net";
20
21
  import path from "node:path";
21
22
  import type {
22
23
  DeferredGrantPromptCopy,
23
24
  HeldGrantPromptCopy,
24
25
  } from "@blackbelt-technology/pi-dashboard-shared/browser-protocol.js";
26
+ import {
27
+ canonicalHttpsOrigin,
28
+ isUngrantableEgressOrigin,
29
+ } from "@blackbelt-technology/pi-dashboard-shared/preview-egress.js";
25
30
  import { normalizeGrantSubject } from "./access-grants.js";
26
31
  import type { DeferredAccessPlane, HeldAccessPlane } from "./access-plane.js";
27
32
  import { isUngrantableSubject } from "./forbidden-subjects.js";
28
33
  import { grantNamedPathSubject } from "./named-grant.js";
34
+ import { addPreviewEgressGrant } from "./preview-egress-store.js";
29
35
 
30
36
  /** Store writers the planes delegate to. */
31
37
  export interface PlaneDeps {
@@ -201,3 +207,102 @@ export function createCorsPlane(deps: Pick<PlaneDeps, "readRawCors" | "writeConf
201
207
  },
202
208
  };
203
209
  }
210
+
211
+ /** Grant-time DNS budget (design D7). */
212
+ const EGRESS_DNS_TIMEOUT_MS = 3000;
213
+ /** The dialog text when a name cannot be resolved in time (decision C3). */
214
+ const EGRESS_UNVERIFIABLE_MESSAGE = "Could not verify this origin; try again";
215
+
216
+ /** Resolve a host to its addresses; throws on failure. Injectable so tests need no network. */
217
+ type EgressResolver = (host: string) => Promise<readonly string[]>;
218
+
219
+ const defaultEgressResolver: EgressResolver = async (host) =>
220
+ (await dns.promises.lookup(host, { all: true, verbatim: true })).map((a) => a.address);
221
+
222
+ /** Does this resolved address fall in loopback / private / link-local / shared / ULA space? */
223
+ function isPrivateAddress(address: string): boolean {
224
+ const literal = isIP(address) === 6 ? `https://[${address}]` : `https://${address}`;
225
+ return isIP(address) === 0 || isUngrantableEgressOrigin(literal);
226
+ }
227
+
228
+ /**
229
+ * Resolve `origin`'s host within the 3 s budget and classify. `"ok"` = every
230
+ * address public; `"private"` = at least one is not; `"unverifiable"` = it failed,
231
+ * timed out or resolved to nothing.
232
+ */
233
+ async function verifyEgressHost(
234
+ origin: string,
235
+ resolve: EgressResolver,
236
+ timeoutMs: number,
237
+ ): Promise<"ok" | "private" | "unverifiable"> {
238
+ const host = new URL(origin).hostname;
239
+ // A public IP literal passed `subjectOf` (private ones are ungrantable there): nothing to resolve.
240
+ if (isIP(host.replace(/^\[|\]$/g, "")) !== 0) return "ok";
241
+ let timer: ReturnType<typeof setTimeout> | undefined;
242
+ try {
243
+ const addresses = await Promise.race([
244
+ resolve(host),
245
+ new Promise<never>((_, reject) => {
246
+ timer = setTimeout(() => reject(new Error("dns timeout")), timeoutMs);
247
+ }),
248
+ ]);
249
+ if (addresses.length === 0) return "unverifiable";
250
+ return addresses.some(isPrivateAddress) ? "private" : "ok";
251
+ } catch {
252
+ return "unverifiable";
253
+ } finally {
254
+ if (timer) clearTimeout(timer);
255
+ }
256
+ }
257
+
258
+ export interface PreviewEgressPlaneDeps {
259
+ /** The dashboard's own origins (tunnels, public base URLs, …): ungrantable. */
260
+ ownOrigins?: () => readonly string[];
261
+ resolve?: EgressResolver;
262
+ dnsTimeoutMs?: number;
263
+ /** Persist the grant (default: the locked `preview-egress.json` store). */
264
+ addGrant?: (project: string, origin: string) => Promise<unknown>;
265
+ }
266
+
267
+ /**
268
+ * Preview egress: an external https origin a restricted live preview may load, granted
269
+ * per PROJECT. Deferred (the preview's own request is never held) and never YOLO-eligible.
270
+ * The subject is the canonical https origin; an ungrantable one (private / loopback /
271
+ * own / single-label / …) is not promptable. The project key rides in the request's
272
+ * `origin` (the audit origin of the denial). `grant` re-checks ungrantability, resolves
273
+ * the host (3 s) and refuses a private or unverifiable one before writing.
274
+ *
275
+ * See change: improve-canvas-html-and-url-ux (design D7).
276
+ */
277
+ export function createPreviewEgressPlane(deps: PreviewEgressPlaneDeps = {}): DeferredAccessPlane {
278
+ const store = "preview-egress.json";
279
+ const own = () => deps.ownOrigins?.() ?? [];
280
+ const resolve = deps.resolve ?? defaultEgressResolver;
281
+ const addGrant = deps.addGrant ?? addPreviewEgressGrant;
282
+ const subjectOf = (raw: string): string | null => {
283
+ const canon = raw ? canonicalHttpsOrigin(raw) : null;
284
+ return canon && !isUngrantableEgressOrigin(canon, own()) ? canon : null;
285
+ };
286
+ return {
287
+ id: "preview-egress",
288
+ mode: "deferred",
289
+ store,
290
+ subjectOf,
291
+ keyOf: identity,
292
+ describe: () => deferredCopy(store),
293
+ async grant(req) {
294
+ if (req.subject !== req.deniedSubject) return { ok: false, reason: "unnamed" };
295
+ if (subjectOf(req.subject) !== req.subject) return { ok: false, reason: "forbidden" };
296
+ if (!path.isAbsolute(req.origin)) return { ok: false, reason: "invalid-subject" };
297
+ const verdict = await verifyEgressHost(req.subject, resolve, deps.dnsTimeoutMs ?? EGRESS_DNS_TIMEOUT_MS);
298
+ if (verdict === "private") return { ok: false, reason: "forbidden" };
299
+ if (verdict === "unverifiable") return { ok: false, reason: "unverifiable", error: EGRESS_UNVERIFIABLE_MESSAGE };
300
+ try {
301
+ await addGrant(req.origin, req.subject);
302
+ } catch (err) {
303
+ return { ok: false, reason: "write-failed", error: String((err as Error)?.message ?? err) };
304
+ }
305
+ return { ok: true, store };
306
+ },
307
+ };
308
+ }
@@ -0,0 +1,153 @@
1
+ /**
2
+ * Project egress grants for restricted live previews:
3
+ * `~/.pi/dashboard/preview-egress.json` → `{ [projectKey]: string[] }` (canonical
4
+ * https origins). Its own file under `auth/locked-json-file.ts`, NOT `config.json`,
5
+ * so a grant can never race `writeConfigPartial`, and never a repository file.
6
+ *
7
+ * - Reads are side-effect free and cheap (stat-validated cache): a missing or
8
+ * malformed file reads as empty and is never rewritten by a read, so a grant or
9
+ * revoke applies to the NEXT CSP build without a restart.
10
+ * - Writes take the file lock around one synchronous read-modify-write; a corrupt
11
+ * file is byte-copied aside by the checked read and the write refuses when that
12
+ * backup could not be made.
13
+ * - `PI_PREVIEW_EGRESS_STORE` overrides the path (tests).
14
+ *
15
+ * See change: improve-canvas-html-and-url-ux (design D7).
16
+ */
17
+ import fs from "node:fs";
18
+ import os from "node:os";
19
+ import path from "node:path";
20
+ import { canonicalHttpsOrigin } from "@blackbelt-technology/pi-dashboard-shared/preview-egress.js";
21
+ import {
22
+ corruptUnbackedRefusal,
23
+ readJsonChecked,
24
+ tryReadJson,
25
+ withLockedJsonFile,
26
+ writeJsonAtomic,
27
+ } from "../auth/locked-json-file.js";
28
+
29
+ const LOG_TAG = "preview-egress";
30
+ /** Bounds: grants per project, projects overall (a hand-edited file cannot inflate the CSP). */
31
+ const MAX_ORIGINS_PER_PROJECT = 64;
32
+ const MAX_PROJECTS = 256;
33
+
34
+ export interface PreviewEgressRow {
35
+ project: string;
36
+ origin: string;
37
+ }
38
+
39
+ /** Where the store lives (read at call time so a test can redirect it). */
40
+ export function previewEgressStorePath(): string {
41
+ return process.env.PI_PREVIEW_EGRESS_STORE || path.join(os.homedir(), ".pi", "dashboard", "preview-egress.json");
42
+ }
43
+
44
+ /** Keep only canonical https origins, de-duplicated, bounded. */
45
+ function cleanOrigins(value: unknown): string[] {
46
+ if (!Array.isArray(value)) return [];
47
+ const out = new Set<string>();
48
+ for (const v of value) {
49
+ if (typeof v !== "string") continue;
50
+ const canon = canonicalHttpsOrigin(v);
51
+ if (canon === v) out.add(canon);
52
+ if (out.size >= MAX_ORIGINS_PER_PROJECT) break;
53
+ }
54
+ return [...out];
55
+ }
56
+
57
+ function cleanDoc(doc: Record<string, unknown>): Record<string, string[]> {
58
+ const out: Record<string, string[]> = {};
59
+ let n = 0;
60
+ for (const [project, origins] of Object.entries(doc)) {
61
+ if (!path.isAbsolute(project)) continue;
62
+ const list = cleanOrigins(origins);
63
+ if (list.length === 0) continue;
64
+ out[project] = list;
65
+ if (++n >= MAX_PROJECTS) break;
66
+ }
67
+ return out;
68
+ }
69
+
70
+ let cache: { file: string; mtimeMs: number; size: number; ino: number; doc: Record<string, string[]> } | null = null;
71
+
72
+ /** Forget the stat cache (tests / after an in-process write). */
73
+ export function resetPreviewEgressCache(): void {
74
+ cache = null;
75
+ }
76
+
77
+ /** Every project's grants. Never throws, never creates or rewrites the file. */
78
+ export function readPreviewEgressGrants(): Record<string, string[]> {
79
+ const file = previewEgressStorePath();
80
+ let st: fs.Stats;
81
+ try {
82
+ st = fs.statSync(file);
83
+ } catch {
84
+ cache = null;
85
+ return {};
86
+ }
87
+ if (cache && cache.file === file && cache.mtimeMs === st.mtimeMs && cache.size === st.size && cache.ino === st.ino) return cache.doc;
88
+ let doc: Record<string, string[]> = {};
89
+ try {
90
+ const read = tryReadJson(file);
91
+ if (read.ok) doc = cleanDoc(read.data as Record<string, unknown>);
92
+ } catch {
93
+ doc = {};
94
+ }
95
+ cache = { file, mtimeMs: st.mtimeMs, size: st.size, ino: st.ino, doc };
96
+ return doc;
97
+ }
98
+
99
+ /** The origins granted for one project (a copy). */
100
+ export function projectEgressGrants(projectKey: string): string[] {
101
+ return [...(readPreviewEgressGrants()[projectKey] ?? [])];
102
+ }
103
+
104
+ /** Flat list for the Access surface, project-then-origin ordered. */
105
+ export function listPreviewEgressRows(): PreviewEgressRow[] {
106
+ const rows: PreviewEgressRow[] = [];
107
+ for (const [project, origins] of Object.entries(readPreviewEgressGrants())) {
108
+ for (const origin of origins) rows.push({ project, origin });
109
+ }
110
+ return rows.sort((a, b) => (a.project === b.project ? a.origin.localeCompare(b.origin) : a.project.localeCompare(b.project)));
111
+ }
112
+
113
+ /** Locked read-modify-write; `mutate` returns the new list for `project` (or `null` for "no change"). */
114
+ async function update(
115
+ project: string,
116
+ mutate: (current: string[]) => string[] | null,
117
+ ): Promise<{ changed: boolean }> {
118
+ const file = previewEgressStorePath();
119
+ const result = await withLockedJsonFile(
120
+ file,
121
+ () => {
122
+ const read = readJsonChecked(file, LOG_TAG);
123
+ if (read.corrupt && !read.quarantined) throw corruptUnbackedRefusal(file);
124
+ const doc = cleanDoc(read.data as Record<string, unknown>);
125
+ const next = mutate(doc[project] ?? []);
126
+ if (next === null) return { changed: false };
127
+ if (next.length === 0) delete doc[project];
128
+ else doc[project] = next;
129
+ writeJsonAtomic(file, doc);
130
+ return { changed: true };
131
+ },
132
+ { logTag: LOG_TAG, createIfMissing: false },
133
+ );
134
+ resetPreviewEgressCache();
135
+ return result;
136
+ }
137
+
138
+ /** Grant `origin` (canonical https) for `project` (an absolute project key). Idempotent. */
139
+ export async function addPreviewEgressGrant(project: string, origin: string): Promise<{ changed: boolean }> {
140
+ if (!path.isAbsolute(project) || canonicalHttpsOrigin(origin) !== origin) {
141
+ throw new Error("invalid preview-egress grant");
142
+ }
143
+ return update(project, (current) => {
144
+ if (current.includes(origin)) return null;
145
+ if (current.length >= MAX_ORIGINS_PER_PROJECT) throw new Error("too many preview-egress grants for this project");
146
+ return [...current, origin];
147
+ });
148
+ }
149
+
150
+ /** Revoke one grant. Resolves `changed:false` when it was not present. */
151
+ export async function revokePreviewEgressGrant(project: string, origin: string): Promise<{ changed: boolean }> {
152
+ return update(project, (current) => (current.includes(origin) ? current.filter((o) => o !== origin) : null));
153
+ }
@@ -99,6 +99,11 @@ export function releasePromptChannel(socketId: string): void {
99
99
  channels.delete(socketId);
100
100
  }
101
101
 
102
+ /** Whether `socketId` still holds a live capability (provisioning: the gateway's per-socket check). */
103
+ export function hasPromptChannel(socketId: string): boolean {
104
+ return channels.has(socketId);
105
+ }
106
+
102
107
  /** Live capability count (diagnostics and tests only). */
103
108
  export function promptChannelCount(): number {
104
109
  return channels.size;