@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
@@ -107,6 +107,8 @@ export class YoloController {
107
107
  private readonly now: () => number;
108
108
  private readonly ladder: (base: string) => Promise<string[]>;
109
109
  private readonly emit: (line: string) => void;
110
+ private changeListener: (() => void) | undefined;
111
+ private expiryTimer: ReturnType<typeof setTimeout> | undefined;
110
112
 
111
113
  constructor(deps: YoloDeps) {
112
114
  this.deps = deps;
@@ -115,10 +117,47 @@ export class YoloController {
115
117
  this.emit = deps.onLog ?? ((line) => console.error(line));
116
118
  }
117
119
 
120
+ /**
121
+ * Notified synchronously whenever the set of live roots changes: activate,
122
+ * addRoot, end, environment activation, and expiry (the unref'd timer, or a
123
+ * lazy clear in `status()`). Feeds the pi-trust live count. A listener never
124
+ * fails the action. See change: mirror-dashboard-trust-live-remote.
125
+ */
126
+ setChangeListener(fn: (() => void) | undefined): void {
127
+ this.changeListener = fn;
128
+ }
129
+
130
+ private notifyChanged(): void {
131
+ try {
132
+ this.changeListener?.();
133
+ } catch {
134
+ /* a listener never fails an activation */
135
+ }
136
+ }
137
+
138
+ /** (Re)arm the expiry timer for the current session; unref'd so it never holds the process open. */
139
+ private armExpiry(): void {
140
+ if (this.expiryTimer) clearTimeout(this.expiryTimer);
141
+ this.expiryTimer = undefined;
142
+ const s = this.session;
143
+ if (!s || s.expiresAt === null) return;
144
+ const delay = Math.max(0, s.expiresAt - this.now());
145
+ this.expiryTimer = setTimeout(() => {
146
+ this.expiryTimer = undefined;
147
+ this.status(); // clears an expired session and notifies
148
+ }, delay);
149
+ this.expiryTimer.unref?.();
150
+ }
151
+
118
152
  /** The live session, or `null`. An expired session is cleared here. */
119
153
  status(): YoloSession | null {
120
154
  const s = this.session;
121
- if (s && s.expiresAt !== null && this.now() >= s.expiresAt) this.session = null;
155
+ if (s && s.expiresAt !== null && this.now() >= s.expiresAt) {
156
+ this.session = null;
157
+ if (this.expiryTimer) clearTimeout(this.expiryTimer);
158
+ this.expiryTimer = undefined;
159
+ this.notifyChanged();
160
+ }
122
161
  return this.session;
123
162
  }
124
163
 
@@ -167,6 +206,8 @@ export class YoloController {
167
206
  const now = this.now();
168
207
  if (req.unscoped) {
169
208
  this.session = { source: "operator", activatedAt: now, expiresAt: now + req.durationMs, unscoped: true, roots: [] };
209
+ this.armExpiry();
210
+ this.notifyChanged();
170
211
  return { ok: true, session: this.session };
171
212
  }
172
213
  const root = await this.pickRoot(req.base, req.root);
@@ -178,6 +219,8 @@ export class YoloController {
178
219
  unscoped: false,
179
220
  roots: [{ path: root.path, addedAt: now }],
180
221
  };
222
+ this.armExpiry();
223
+ this.notifyChanged();
181
224
  return { ok: true, session: this.session };
182
225
  }
183
226
 
@@ -188,13 +231,20 @@ export class YoloController {
188
231
  if (live.unscoped) return { ok: true, session: live };
189
232
  const root = await this.pickRoot(req.base, req.root);
190
233
  if (!root.ok) return root;
191
- if (!live.roots.some((r) => r.path === root.path)) live.roots.push({ path: root.path, addedAt: this.now() });
234
+ if (!live.roots.some((r) => r.path === root.path)) {
235
+ live.roots.push({ path: root.path, addedAt: this.now() });
236
+ this.notifyChanged();
237
+ }
192
238
  return { ok: true, session: live, added: true };
193
239
  }
194
240
 
195
241
  /** End the session now; the next denial behaves as if it never existed. */
196
242
  end(): void {
243
+ const had = this.session !== null;
197
244
  this.session = null;
245
+ if (this.expiryTimer) clearTimeout(this.expiryTimer);
246
+ this.expiryTimer = undefined;
247
+ if (had) this.notifyChanged();
198
248
  }
199
249
 
200
250
  /**
@@ -210,6 +260,7 @@ export class YoloController {
210
260
  const now = this.now();
211
261
  if (parsed.kind === "unscoped") {
212
262
  this.session = { source: "env", activatedAt: now, expiresAt: null, unscoped: true, roots: [] };
263
+ this.notifyChanged();
213
264
  return { ok: true, session: this.session };
214
265
  }
215
266
  const roots: YoloRoot[] = [];
@@ -220,6 +271,7 @@ export class YoloController {
220
271
  if (!roots.some((r) => r.path === real)) roots.push({ path: real, addedAt: now });
221
272
  }
222
273
  this.session = { source: "env", activatedAt: now, expiresAt: null, unscoped: false, roots };
274
+ this.notifyChanged();
223
275
  return { ok: true, session: this.session };
224
276
  }
225
277
 
@@ -424,8 +424,11 @@ export function createAcpSessionAdapter(opts: AcpSessionAdapterOptions): AcpSess
424
424
  async function start(): Promise<void> {
425
425
  send(registerMessage("spawn"));
426
426
  // A fresh session has nothing to replay. The server holds every event back
427
- // (replayingSessions) after a register until `replay_complete`, or for 5 s —
428
- // without this the first turn of a new session would stay invisible.
427
+ // (replay mode) after a register until `replay_complete` (or its idle/cap
428
+ // fallback exit) — without this the first turn of a new session would stay
429
+ // invisible. Replayed events carry `replay: true` (see `reconnected`), so
430
+ // the server never treats them as live whatever its timers say.
431
+ // See change: fix-large-session-resume-replay.
429
432
  send({ type: "replay_complete", sessionId });
430
433
  startWatchdogs();
431
434
  const timedOut = new Promise<never>((_, reject) => {
@@ -461,7 +464,9 @@ export function createAcpSessionAdapter(opts: AcpSessionAdapterOptions): AcpSess
461
464
  publishModelsRaw();
462
465
  const snapshot = opts.eventLog ? (await opts.eventLog.flush(), opts.eventLog.size()) : 0;
463
466
  if (opts.eventLog) {
464
- await opts.eventLog.replay((event) => opts.send({ type: "event_forward", sessionId, event }), snapshot);
467
+ // `replay: true`: the server handles a marked event as replayed whatever
468
+ // its replay timers say. See change: fix-large-session-resume-replay (D1).
469
+ await opts.eventLog.replay((event) => opts.send({ type: "event_forward", sessionId, event, replay: true }), snapshot);
465
470
  }
466
471
  opts.send({ type: "replay_complete", sessionId });
467
472
  replaying = false;
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Agent event hub: the compact, transition-only feed behind
3
+ * `GET /api/events/stream`, for an external controller (a Claude Code session
4
+ * driving pi through the dashboard) that must REACT to a session instead of
5
+ * polling it.
6
+ *
7
+ * Inputs are the two existing fan-outs: the browser gateway's registry frames
8
+ * (`session_added` / `session_updated` / `session_removed`, tapped in its
9
+ * `broadcast`) and the question store's `onChange`. Output is one event per
10
+ * meaningful change: a status transition (deduped — a `session_updated` that
11
+ * does not change `status` emits nothing), a question opened or closed (once
12
+ * each; brief updates emit nothing), a session added or removed. Streaming
13
+ * token/tool churn never reaches subscribers.
14
+ *
15
+ * Every event is delivered with the session's last known owner so the route
16
+ * can apply the session-list visibility predicate, also after removal.
17
+ * Transport-agnostic; holds no per-subscriber state.
18
+ * See change: add-agent-event-stream.
19
+ */
20
+ import type { ServerToBrowserMessage } from "@blackbelt-technology/pi-dashboard-shared/browser-protocol.js";
21
+ import type { QuestionRow } from "@blackbelt-technology/pi-dashboard-shared/question-types.js";
22
+ import type { SessionStatus } from "@blackbelt-technology/pi-dashboard-shared/types.js";
23
+ import type { QuestionChange } from "../questions/question-store.js";
24
+
25
+ type Owner = { iss: string; sub: string };
26
+
27
+ export type AgentEvent =
28
+ | { type: "session_added"; sessionId: string; status?: SessionStatus; cwd?: string; name?: string }
29
+ | { type: "status"; sessionId: string; from?: SessionStatus; to: SessionStatus }
30
+ | { type: "session_removed"; sessionId: string }
31
+ | { type: "question_opened"; sessionId: string; questionId: string; questionType: string; preview: string; sessionLabel: string }
32
+ | { type: "question_closed"; sessionId: string; questionId: string; reason: "answered" | "removed" };
33
+
34
+ export type AgentEventType = AgentEvent["type"];
35
+
36
+ export const AGENT_EVENT_TYPES: readonly AgentEventType[] = ["session_added", "status", "session_removed", "question_opened", "question_closed"];
37
+
38
+ export type AgentEventListener = (event: AgentEvent, owner: Owner | undefined) => void;
39
+
40
+ export interface AgentEventHub {
41
+ onRegistryFrame(msg: ServerToBrowserMessage): void;
42
+ onQuestionChange(change: QuestionChange): void;
43
+ /** Currently open questions, as `question_opened` events (initial frame for a new subscriber). */
44
+ openQuestions(): Array<Extract<AgentEvent, { type: "question_opened" }>>;
45
+ ownerOf(sessionId: string): Owner | undefined;
46
+ subscribe(listener: AgentEventListener): () => void;
47
+ }
48
+
49
+ const openedOf = (row: QuestionRow): Extract<AgentEvent, { type: "question_opened" }> => ({
50
+ type: "question_opened",
51
+ sessionId: row.sessionId,
52
+ questionId: row.id,
53
+ questionType: row.type,
54
+ preview: row.preview,
55
+ sessionLabel: row.sessionLabel,
56
+ });
57
+
58
+ export function createAgentEventHub(deps: {
59
+ listQuestionRows: () => QuestionRow[];
60
+ /** Owner of a live session (fallback when no frame carried one). */
61
+ ownerOf: (sessionId: string) => Owner | undefined;
62
+ }): AgentEventHub {
63
+ const lastStatus = new Map<string, SessionStatus>();
64
+ const lastOwner = new Map<string, Owner>();
65
+ /** Questions announced as opened (dedupes a re-sent `added`). */
66
+ const openIds = new Set<string>();
67
+ /** Questions closed by a transmitted answer whose `removed` has not arrived yet. */
68
+ const hiddenIds = new Set<string>();
69
+ const listeners = new Set<AgentEventListener>();
70
+
71
+ const ownerOf = (sessionId: string): Owner | undefined => deps.ownerOf(sessionId) ?? lastOwner.get(sessionId);
72
+
73
+ function emit(event: AgentEvent): void {
74
+ const owner = ownerOf(event.sessionId);
75
+ for (const l of [...listeners]) {
76
+ try {
77
+ l(event, owner);
78
+ } catch (err) {
79
+ console.error("[agent-events] listener failed:", (err as Error).message);
80
+ }
81
+ }
82
+ }
83
+
84
+ function sessionAdded(s: Extract<ServerToBrowserMessage, { type: "session_added" }>["session"]): void {
85
+ if (s.principalOwner) lastOwner.set(s.id, s.principalOwner);
86
+ if (s.status) lastStatus.set(s.id, s.status);
87
+ emit({
88
+ type: "session_added",
89
+ sessionId: s.id,
90
+ ...(s.status ? { status: s.status } : {}),
91
+ ...(s.cwd ? { cwd: s.cwd } : {}),
92
+ ...(s.name ? { name: s.name } : {}),
93
+ });
94
+ }
95
+
96
+ function sessionUpdated(sessionId: string, raw: unknown): void {
97
+ const updates = (raw ?? {}) as { status?: unknown; principalOwner?: Owner };
98
+ if (updates.principalOwner) lastOwner.set(sessionId, updates.principalOwner);
99
+ if (typeof updates.status !== "string") return;
100
+ const to = updates.status as SessionStatus;
101
+ const from = lastStatus.get(sessionId);
102
+ if (from === to) return;
103
+ lastStatus.set(sessionId, to);
104
+ emit({ type: "status", sessionId, ...(from ? { from } : {}), to });
105
+ }
106
+
107
+ function sessionRemoved(sessionId: string): void {
108
+ emit({ type: "session_removed", sessionId });
109
+ lastStatus.delete(sessionId);
110
+ lastOwner.delete(sessionId);
111
+ }
112
+
113
+ function onRegistryFrame(msg: ServerToBrowserMessage): void {
114
+ if (msg.type === "session_added") sessionAdded(msg.session);
115
+ else if (msg.type === "session_updated") sessionUpdated(msg.sessionId, msg.updates);
116
+ else if (msg.type === "session_removed") sessionRemoved(msg.sessionId);
117
+ }
118
+
119
+ function questionAdded(change: QuestionChange): void {
120
+ if (openIds.has(change.id)) return;
121
+ const row = deps.listQuestionRows().find((r) => r.id === change.id);
122
+ if (!row) return;
123
+ openIds.add(change.id);
124
+ hiddenIds.delete(change.id);
125
+ emit(openedOf(row));
126
+ }
127
+
128
+ function questionClosed(change: QuestionChange): void {
129
+ openIds.delete(change.id);
130
+ const answered = change.kind === "hidden";
131
+ // A transmitted answer hides the question first; its later removal is the same close.
132
+ if (hiddenIds.has(change.id)) {
133
+ if (!answered) hiddenIds.delete(change.id);
134
+ return;
135
+ }
136
+ if (answered) hiddenIds.add(change.id);
137
+ // `hidden` = the answer was transmitted; a plain removal closed it unanswered.
138
+ emit({ type: "question_closed", sessionId: change.sessionId, questionId: change.id, reason: answered ? "answered" : "removed" });
139
+ }
140
+
141
+ function onQuestionChange(change: QuestionChange): void {
142
+ if (change.kind === "added") questionAdded(change);
143
+ else if (change.kind === "hidden" || change.kind === "removed") questionClosed(change);
144
+ }
145
+
146
+ return {
147
+ onRegistryFrame,
148
+ onQuestionChange,
149
+ openQuestions: () => deps.listQuestionRows().map(openedOf),
150
+ ownerOf,
151
+ subscribe(listener) {
152
+ listeners.add(listener);
153
+ return () => {
154
+ listeners.delete(listener);
155
+ };
156
+ },
157
+ };
158
+ }
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Auth audit lines — one shared, sanitising emitter for credential/pairing
3
+ * mutations (harden-auth-credentials D2).
4
+ *
5
+ * Format: `[<area>] <verb> k=v k=v`, the same shape as the existing `[pairing]`
6
+ * decision lines. Every value is sanitised (characters outside `[\w.:-]` → `_`)
7
+ * BEFORE any prefix cut, so an attacker-chosen JWT `sub`, device id or peer
8
+ * string can never inject a second record or a fake `k=v`. `ip=` is the SOCKET
9
+ * peer (`request.ip`; `trustProxy` is never enabled) — forwarding headers are
10
+ * never read. Callers pass identifiers and codes only: never a secret, token,
11
+ * hash, key or flow input value.
12
+ *
13
+ * An audit write failure is swallowed: the mutation it describes has already
14
+ * happened and must not turn into a 500.
15
+ */
16
+
17
+ import type { FastifyRequest } from "fastify";
18
+
19
+ /** Prefix length for ids / subjects (`id=d0123456`, `actor=session:alice_ex`). */
20
+ const PREFIX_LEN = 8;
21
+
22
+ /** Replace every character outside `[\w.:-]` with `_` (per code point). */
23
+ function sanitizeAuditValue(value: unknown): string {
24
+ return String(value ?? "").replace(/[^\w.:-]/gu, "_");
25
+ }
26
+
27
+ /** Sanitise FIRST, then keep the first `len` characters (default 8). */
28
+ export function auditPrefix(value: unknown, len: number = PREFIX_LEN): string {
29
+ return sanitizeAuditValue(value).slice(0, len);
30
+ }
31
+
32
+ type AuditFieldValue = string | number | boolean | undefined;
33
+
34
+ /** Pure formatter: `[area] verb k=v …` — fields with an `undefined` value are omitted. */
35
+ function formatAuditLine(area: string, verb: string, fields: Record<string, AuditFieldValue> = {}): string {
36
+ const parts = [`[${sanitizeAuditValue(area)}]`, sanitizeAuditValue(verb)];
37
+ for (const [key, value] of Object.entries(fields)) {
38
+ if (value === undefined) continue;
39
+ parts.push(`${sanitizeAuditValue(key)}=${sanitizeAuditValue(value)}`);
40
+ }
41
+ return parts.join(" ");
42
+ }
43
+
44
+ /**
45
+ * Emit one audit line via `console.log` (the Fastify logger is off). Field
46
+ * values are sanitised here; apply {@link auditPrefix} to ids first. Never throws.
47
+ */
48
+ export function auditLine(area: string, verb: string, fields: Record<string, AuditFieldValue> = {}): void {
49
+ try {
50
+ console.log(formatAuditLine(area, verb, fields));
51
+ } catch {
52
+ // Fail-open: a broken log sink must not fail the mutation (AX12).
53
+ }
54
+ }
55
+
56
+ /**
57
+ * `actor=` for a request that passed an auth hook:
58
+ * `session:<sub8>` (login session / identity principal) | `device:<id8>` | `local`.
59
+ * `local` covers the local token and a genuinely-local loopback caller — the
60
+ * only other callers an operator guard admits.
61
+ */
62
+ function auditActor(request: FastifyRequest): string {
63
+ const r = request as {
64
+ authVia?: string;
65
+ principalDeviceId?: string;
66
+ sessionPayload?: { sub?: unknown };
67
+ principal?: { sub?: unknown } | null;
68
+ };
69
+ if (r.authVia === "session" || r.authVia === "principal") {
70
+ const sub = r.authVia === "session" ? r.sessionPayload?.sub : r.principal?.sub;
71
+ return `session:${auditPrefix(sub) || "unknown"}`;
72
+ }
73
+ if (r.authVia === "device") return `device:${auditPrefix(r.principalDeviceId) || "unknown"}`;
74
+ return "local";
75
+ }
76
+
77
+ /** `{ actor, ip }` for a request-driven audit line; `ip` is the socket peer only. */
78
+ export function auditRequestFields(request: FastifyRequest): { actor: string; ip: string } {
79
+ return { actor: auditActor(request), ip: request.ip };
80
+ }
@@ -7,6 +7,7 @@ import crypto from "node:crypto";
7
7
  import { getAppMountRegistry } from "@blackbelt-technology/dashboard-plugin-runtime/server";
8
8
  import type { AuthConfig, DashboardConfig } from "@blackbelt-technology/pi-dashboard-shared/config.js";
9
9
  import type { Principal } from "@blackbelt-technology/pi-dashboard-shared/identity.js";
10
+ import { isSafeLocalPath } from "@blackbelt-technology/pi-dashboard-shared/safe-local-path.js";
10
11
  import type { Tier } from "@blackbelt-technology/pi-dashboard-shared/tiers.js";
11
12
  import cookie from "@fastify/cookie";
12
13
  import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
@@ -31,13 +32,15 @@ import {
31
32
  warnOnInvalidRedirectBase,
32
33
  } from "./auth.js";
33
34
  import { isBypassed } from "./bypass-urls.js";
35
+ import { CSP_REPORT_POLICIES, cspReportPath } from "./csp-report-paths.js";
34
36
  import { hasLocalCredential } from "./local-credential.js";
35
37
  import type { LocalTrustContext } from "./local-proof.js";
36
- import { isLocallyTrusted, isObserveApiRequest, isTrustedSource } from "./localhost-guard.js";
38
+ import { isLocallyTrusted, isObserveApiRequest, isTrustedSource, needsLocalProof } from "./localhost-guard.js";
37
39
  import { noteNetworkOnlyAdmission } from "./network-trust-telemetry.js";
38
40
  import { renderLoginPasskeySection } from "./passkey/passkey-pages.js";
39
41
  import { registerPasskeyRoutes } from "./passkey/passkey-routes.js";
40
42
  import { PASSKEY_PROVIDER, type PasskeyService } from "./passkey/passkey-service.js";
43
+ import { isSecureOrigin } from "./secure-origin.js";
41
44
  import type { CoreWsRouteScope, TicketConsumption } from "./ws-ticket.js";
42
45
 
43
46
  // Re-exported so the existing `auth-plugin.js` import surface is unchanged; the
@@ -115,20 +118,14 @@ function decodeState(state: string): { returnUrl: string; nonce: string } {
115
118
  * path. Anything else → `/`. See change: harden-trust-and-credential-boundaries (D1).
116
119
  */
117
120
  export function sanitizeReturnUrl(raw: unknown): string {
118
- if (typeof raw !== "string" || raw.length === 0) return "/";
119
- if (raw[0] !== "/" || raw[1] === "/" || raw[1] === "\\") return "/";
120
- // biome-ignore lint/suspicious/noControlCharactersInRegex: rejecting control chars is the point
121
- if (/[\u0000-\u001f\u007f]/.test(raw)) return "/";
122
- try {
123
- if (new URL(raw, "http://x.invalid").origin !== "http://x.invalid") return "/";
124
- } catch {
125
- return "/";
126
- }
127
- return raw;
121
+ return isSafeLocalPath(raw) ? raw : "/";
128
122
  }
129
123
 
130
124
  const STATE_COOKIE = "pi_dash_oauth_state";
131
125
 
126
+ /** The only sink paths that skip the OAuth gate (exact match; see the `onRequest` hook). */
127
+ const CSP_SINK_PATHS: ReadonlySet<string> = new Set(CSP_REPORT_POLICIES.map(cspReportPath));
128
+
132
129
  /** Domain-separated key for the OAuth state cookie (never the JWT key). */
133
130
  function stateKey(secret: string): Buffer {
134
131
  return crypto.createHmac("sha256", secret).update("pi-dashboard/oauth-state/v1").digest();
@@ -156,7 +153,7 @@ function readStateCookie(cookieValue: unknown, secret: string): string | null {
156
153
  /**
157
154
  * Simple login page HTML with provider links.
158
155
  */
159
- function renderLoginPage(providers: ResolvedProvider[], error?: string, returnUrl = "/", passkeySection = ""): string {
156
+ function renderLoginPage(providers: ResolvedProvider[], error?: string, returnUrl = "/", passkeySection = "", needsProof = false): string {
160
157
  const ret = encodeURIComponent(sanitizeReturnUrl(returnUrl));
161
158
  const providerLinks = providers
162
159
  .map((p) => `<a href="/auth/start/${p.key}?return=${ret}" style="display:block;margin:10px 0;padding:12px 24px;background:#2563eb;color:#fff;text-decoration:none;border-radius:6px;text-align:center;font-size:16px;">Sign in with ${p.name}</a>`)
@@ -165,6 +162,11 @@ function renderLoginPage(providers: ResolvedProvider[], error?: string, returnUr
165
162
  const errorHtml = error
166
163
  ? `<div style="color:#ef4444;margin-bottom:16px;">${escapeHtml(String(error))}</div>`
167
164
  : "";
165
+ // A bare-loopback tab the strict default refuses for want of proof: the remedy first, because
166
+ // signing in is not what this browser is missing. See change: close-container-loopback-impersonation (D3).
167
+ const proofHtml = needsProof
168
+ ? `<div style="text-align:left;margin:0 0 20px;padding:12px 14px;background:#0f172a;border:1px solid #475569;border-radius:8px;font-size:14px;line-height:1.45;">This browser has not proven it is on the same machine as the dashboard. Run <code style="background:#334155;padding:2px 6px;border-radius:4px;">pi-dashboard open</code> in a terminal on that machine (or use the desktop app) to authorize it.</div>`
169
+ : "";
168
170
 
169
171
  return `<!DOCTYPE html>
170
172
  <html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
@@ -172,7 +174,7 @@ function renderLoginPage(providers: ResolvedProvider[], error?: string, returnUr
172
174
  <style>body{font-family:system-ui,sans-serif;display:flex;align-items:center;justify-content:center;min-height:100vh;margin:0;background:#0f172a;color:#e2e8f0;}
173
175
  .card{background:#1e293b;padding:40px;border-radius:12px;max-width:400px;width:100%;text-align:center;}
174
176
  h1{margin:0 0 24px;font-size:24px;}</style>
175
- </head><body><div class="card"><h1>🔐 PI Dashboard</h1>${errorHtml}${providerLinks}${providerLinks && passkeySection ? "<hr>" : ""}${passkeySection}</div></body></html>`;
177
+ </head><body><div class="card"><h1>🔐 PI Dashboard</h1>${proofHtml}${errorHtml}${providerLinks}${providerLinks && passkeySection ? "<hr>" : ""}${passkeySection}</div></body></html>`;
176
178
  }
177
179
 
178
180
  /**
@@ -303,13 +305,13 @@ export async function registerAuthPlugin(
303
305
  if (!fastify.hasRequestDecorator?.("cookies")) await fastify.register(cookie);
304
306
 
305
307
  // Set the signed OAuth state cookie and return the nonce to embed in `state`.
306
- const issueState = (reply: FastifyReply): string => {
308
+ const issueState = (request: FastifyRequest, reply: FastifyReply): string => {
307
309
  const nonce = crypto.randomBytes(16).toString("hex");
308
310
  const { base } = resolveRedirectBase(port, authState.redirectBaseUrl);
309
311
  reply.setCookie(STATE_COOKIE, `${nonce}.${stateMac(authState.secret, nonce)}`, {
310
312
  path: "/auth/",
311
313
  httpOnly: true,
312
- secure: base.startsWith("https:"),
314
+ secure: isSecureOrigin(request, base.startsWith("https:")),
313
315
  sameSite: "lax", // the IdP callback is a cross-site top-level GET
314
316
  maxAge: 600,
315
317
  });
@@ -323,12 +325,15 @@ export async function registerAuthPlugin(
323
325
  // the resolved public origin, which is operator-stated config that no
324
326
  // request header can influence.
325
327
  // See change: config-override-oauth-redirect-base (design D14).
326
- const setSessionCookie = (reply: FastifyReply, token: string): void => {
328
+ // `Secure` = `isSecureOrigin(request, …)`: TLS socket || https base || loopback
329
+ // socket peer + Host equal to a live https tunnel origin (never a header).
330
+ // See change: harden-auth-credentials (D3).
331
+ const setSessionCookie = (request: FastifyRequest, reply: FastifyReply, token: string): void => {
327
332
  const { base: publicBase } = resolveRedirectBase(port, authState.redirectBaseUrl);
328
333
  reply.setCookie(COOKIE_NAME, token, {
329
334
  path: "/",
330
335
  httpOnly: true,
331
- secure: publicBase.startsWith("https:"),
336
+ secure: isSecureOrigin(request, publicBase.startsWith("https:")),
332
337
  sameSite: "lax",
333
338
  maxAge: 7 * 24 * 60 * 60, // 7 days in seconds
334
339
  });
@@ -347,6 +352,7 @@ export async function registerAuthPlugin(
347
352
  service: passkeys,
348
353
  issueSession: (reply, user) =>
349
354
  setSessionCookie(
355
+ reply.request,
350
356
  reply,
351
357
  signToken({ sub: user.id, name: user.name, username: user.name, provider: PASSKEY_PROVIDER, tier: user.tier }, authState.secret),
352
358
  ),
@@ -360,21 +366,24 @@ export async function registerAuthPlugin(
360
366
  const providers = Array.from(authState.providerRegistry.values());
361
367
  const error = (request.query as any)?.error;
362
368
  const passkeysOn = passkeys?.isEnabled() === true;
369
+ // A bare-loopback request the strict default refuses for want of proof must see the remedy, not be
370
+ // bounced to a provider whose sign-in would not help it. See change: close-container-loopback-impersonation (D3).
371
+ const needsProof = needsLocalProof(request as unknown as { ip: string; headers: unknown; isAuthenticated?: boolean }, localTrust);
363
372
 
364
373
  // With passkeys enabled the picker always renders: both options are offered.
365
- if (providers.length === 1 && !error && !passkeysOn) {
374
+ if (providers.length === 1 && !error && !passkeysOn && !needsProof) {
366
375
  // Auto-redirect to single provider
367
376
  const p = providers[0];
368
377
  const redirectUri = buildRedirectUri(p.key, port, authState.redirectBaseUrl);
369
378
  const returnUrl = sanitizeReturnUrl((request.query as any)?.return);
370
- const state = encodeState(returnUrl, issueState(reply));
379
+ const state = encodeState(returnUrl, issueState(request, reply));
371
380
  const url = buildAuthorizeUrl(p, redirectUri, state);
372
381
  return reply.redirect(url);
373
382
  }
374
383
 
375
384
  const returnUrl = sanitizeReturnUrl((request.query as any)?.return);
376
385
  const section = passkeysOn && passkeys ? renderLoginPasskeySection(passkeys.rpContext(), returnUrl) : "";
377
- return reply.type("text/html").send(renderLoginPage(providers, error, returnUrl, section));
386
+ return reply.type("text/html").send(renderLoginPage(providers, error, returnUrl, section, needsProof));
378
387
  });
379
388
 
380
389
  // GET /auth/start/:provider — redirect to provider's authorize URL
@@ -386,7 +395,7 @@ export async function registerAuthPlugin(
386
395
  }
387
396
  const redirectUri = buildRedirectUri(providerKey, port, authState.redirectBaseUrl);
388
397
  const returnUrl = sanitizeReturnUrl((request.query as any)?.return);
389
- const state = encodeState(returnUrl, issueState(reply));
398
+ const state = encodeState(returnUrl, issueState(request, reply));
390
399
  const url = buildAuthorizeUrl(provider, redirectUri, state);
391
400
  return reply.redirect(url);
392
401
  });
@@ -450,7 +459,7 @@ export async function registerAuthPlugin(
450
459
  );
451
460
 
452
461
  const { returnUrl } = decoded;
453
- setSessionCookie(reply, token);
462
+ setSessionCookie(request, reply, token);
454
463
 
455
464
  return reply.redirect(returnUrl);
456
465
  });
@@ -516,14 +525,24 @@ export async function registerAuthPlugin(
516
525
  // Strict observe exception: bare local may still READ observe-tier REST routes.
517
526
  if (
518
527
  localTrust?.strict() &&
519
- isLocallyTrusted({ ip: request.ip, headers: request.headers as Record<string, unknown> }) &&
520
- isObserveApiRequest(request)
521
- ) return;
528
+ isLocallyTrusted({ ip: request.ip, headers: request.headers as Record<string, unknown> })
529
+ ) {
530
+ // Recognise a signed-in session FIRST (tag only: never refuses, never clears a cookie on
531
+ // these routes), so a signed-in loopback tab is `isAuthenticated` on observe routes and is
532
+ // not shown the proof banner. See change: close-container-loopback-impersonation (D3).
533
+ tagSessionCookie(request);
534
+ if (isObserveApiRequest(request)) return;
535
+ }
522
536
  if (localToken && hasLocalCredential(request.headers)) return;
523
537
 
524
538
  // Skip auth routes
525
539
  if (request.url.startsWith("/auth/")) return;
526
540
 
541
+ // Skip the baseline CSP report sink: signed-out pages (login, passkey) must be able to report.
542
+ // Exactly `POST` on the three policy paths (query ignored) — no prefix match, nothing else widens.
543
+ // See change: harden-cors-and-csp-reporting (D8).
544
+ if (request.method === "POST" && CSP_SINK_PATHS.has(request.url.split("?", 1)[0] ?? "")) return;
545
+
527
546
  // Skip PUBLIC device-facing pairing routes (a pairing device has no
528
547
  // credential yet; these are gated by the one-time code + approval).
529
548
  if (PUBLIC_PAIRING_PREFIXES.some((p) => request.url.startsWith(p))) return;
@@ -132,14 +132,32 @@ async function resolveProvider(
132
132
 
133
133
  // ─── Auth Secret Management ─────────────────────────────────────────────────
134
134
 
135
+ /** Minimum recommended `auth.secret` length in characters (32 hex = 16 bytes of entropy at worst). */
136
+ const MIN_SECRET_LENGTH = 32;
137
+ /** Module-level once flag: the short-secret warning prints once per process. */
138
+ let shortSecretWarned = false;
139
+
135
140
  /**
136
- * Ensure the auth config has a secret. If missing, generate one and persist.
141
+ * Ensure the auth config has a secret. If missing, generate one (32 random
142
+ * bytes, 64 hex chars) and persist. An existing non-empty secret is ALWAYS
143
+ * kept byte-identical (no forced logout); one shorter than 32 characters logs a
144
+ * single startup warning recommending rotation and never prints the value.
137
145
  * Returns the secret string.
146
+ * See change: harden-auth-credentials (D1).
138
147
  */
139
148
  export function ensureAuthSecret(authConfig: AuthConfig): string {
140
- if (authConfig.secret) return authConfig.secret;
149
+ if (authConfig.secret) {
150
+ if (authConfig.secret.length < MIN_SECRET_LENGTH && !shortSecretWarned) {
151
+ shortSecretWarned = true;
152
+ console.warn(
153
+ `⚠️ auth.secret is shorter than ${MIN_SECRET_LENGTH} characters; consider rotating it ` +
154
+ "(replace it with a random 64-hex value — rotation signs out existing sessions).",
155
+ );
156
+ }
157
+ return authConfig.secret;
158
+ }
141
159
 
142
- const secret = crypto.randomBytes(16).toString("hex"); // 32-char hex
160
+ const secret = crypto.randomBytes(32).toString("hex"); // 64-char hex
143
161
  authConfig.secret = secret;
144
162
 
145
163
  // Persist back to config file
@@ -178,7 +196,9 @@ export function signToken(user: AuthUser, secret: string): string {
178
196
 
179
197
  export function verifyToken(token: string, secret: string): TokenPayload | null {
180
198
  try {
181
- const payload = jwt.verify(token, secret) as TokenPayload;
199
+ // Pin HS256: reject `none` and every other alg (algorithm confusion).
200
+ // See change: harden-auth-credentials (D1).
201
+ const payload = jwt.verify(token, secret, { algorithms: ["HS256"] }) as TokenPayload;
182
202
  // A present-but-unknown tier is never widened to `operate`: reject the
183
203
  // token outright (fail closed). See change: add-passkey-user-auth (D4).
184
204
  if (payload.tier !== undefined && !isTier(payload.tier)) return null;