@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,330 @@
1
+ /**
2
+ * `POST /api/pi-trust/query` — the live trust query a bridge sends at pi's
3
+ * `project_trust` when its snapshot does not cover the cwd.
4
+ *
5
+ * Order (design D1): authenticate (before any trust state is read) → per-requester
6
+ * rate limit → body cap + validation → server switches and deny rules → cover
7
+ * lookup → proof → YOLO liveness re-check.
8
+ *
9
+ * - Admission: a genuinely local requester (loopback, no forwarding headers, a
10
+ * VERIFIED endpoint-bound local-credential proof — the raw legacy token and a
11
+ * login cookie do not suffice) or a paired device at `operate` (tier enforced
12
+ * by the global `route-tier-gate` through `ROUTE_TIERS`).
13
+ * - Local answer: the covering folder + the identity recorded when the entry was
14
+ * created. Remote (device) answer: `{covered, salt, digest}` only — a salted
15
+ * digest of pi's trust-requiring resources, run under a global semaphore of 4
16
+ * (1 per device). Anything that cannot be bound answers `{covered:false}`.
17
+ * - Limits: 20 queries / 10 s per device, 200 / 10 s for the local user; one log
18
+ * line per window. Counters feed `/api/health` `piTrustMirror.live`.
19
+ *
20
+ * No new secret and no new credential type. Nothing here writes pi's trust store.
21
+ *
22
+ * See change: mirror-dashboard-trust-live-remote (D1, D3–D6).
23
+ */
24
+ import os from "node:os";
25
+ import { effectiveLiveQueryTimeoutMs, type PiTrustMirrorConfig } from "@blackbelt-technology/pi-dashboard-shared/config.js";
26
+ import { isLoopbackHost } from "@blackbelt-technology/pi-dashboard-shared/loopback-host.js";
27
+ import {
28
+ PI_TRUST_QUERY_MAX_BODY_BYTES,
29
+ PI_TRUST_QUERY_PATH,
30
+ type PiTrustLiveAnswer,
31
+ validatePiTrustQueryBody,
32
+ } from "@blackbelt-technology/pi-dashboard-shared/pi-trust-live-query.js";
33
+ import { isMirrorDenied, type MirrorDenyRules, mirrorDenyRules } from "@blackbelt-technology/pi-dashboard-shared/pi-trust-mirror.js";
34
+ import { coverSnapshot, safePiTrustKey } from "@blackbelt-technology/pi-dashboard-shared/pi-trust-mirror-snapshot.js";
35
+ import type { PiTrustSnapshot } from "@blackbelt-technology/pi-dashboard-shared/pi-trust-mirror-types.js";
36
+ import {
37
+ newTrustSalt,
38
+ trustResourceDigest,
39
+ trustResourceManifest,
40
+ } from "@blackbelt-technology/pi-dashboard-shared/pi-trust-resource-digest.js";
41
+ import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
42
+ import type { LiveEntry, PiTrustLiveProvider } from "../access/pi-trust-live.js";
43
+ import { credentialVerdict } from "../auth/local-credential.js";
44
+ import { hasProxyForwardingHeaders } from "../auth/localhost-guard.js";
45
+
46
+ export interface PiTrustLiveCounters {
47
+ covered: number;
48
+ notCovered: number;
49
+ refused: number;
50
+ rateLimited: number;
51
+ budgetMissed: number;
52
+ }
53
+
54
+ export interface PiTrustQueryDeps {
55
+ getConfig: () => PiTrustMirrorConfig;
56
+ /** Live (server-lifetime) entries, when the provider exists. */
57
+ live: () => PiTrustLiveProvider | undefined;
58
+ /** The durable snapshot as written (recorded identities), or null. */
59
+ readSnapshot: () => PiTrustSnapshot | null;
60
+ home?: string;
61
+ denyRules?: () => MirrorDenyRules;
62
+ /** Test seams. */
63
+ manifest?: typeof trustResourceManifest;
64
+ nowMs?: () => number;
65
+ log?: (line: string) => void;
66
+ /** Hook-hash probe for durable worktree-init entries (default: reads `.pi/settings.json`). */
67
+ hookHash?: (configRoot: string) => string | null;
68
+ }
69
+
70
+ const WINDOW_MS = 10_000;
71
+ const LOCAL_QUERIES_PER_WINDOW = 200;
72
+ const DEVICE_QUERIES_PER_WINDOW = 20;
73
+ const GLOBAL_PROOF_PERMITS = 4;
74
+ const DEVICE_PROOF_PERMITS = 1;
75
+ const MAX_TRACKED_REQUESTERS = 1000;
76
+
77
+ /** Strip control characters (incl. ESC / newlines) and cap the length of anything logged. */
78
+ function sanitizeForLog(value: unknown, max = 200): string {
79
+ return String(value)
80
+ .replace(/[\u0000-\u001f\u007f-\u009f]/g, "?")
81
+ .slice(0, max);
82
+ }
83
+
84
+ type Requester = { kind: "local" } | { kind: "device"; id: string };
85
+
86
+ interface Started {
87
+ requester: Requester;
88
+ startedAt: number;
89
+ }
90
+
91
+ const STARTED = Symbol("pi-trust-query-started");
92
+
93
+ /** Fixed-window counter per requester key; reports only the first refusal of each window. */
94
+ class WindowLimiter {
95
+ private readonly windows = new Map<string, { start: number; count: number; logged: boolean }>();
96
+
97
+ allow(key: string, limit: number, now: number): { ok: true } | { ok: false; firstInWindow: boolean } {
98
+ let w = this.windows.get(key);
99
+ if (!w || now - w.start >= WINDOW_MS) {
100
+ if (this.windows.size >= MAX_TRACKED_REQUESTERS) this.prune(now);
101
+ w = { start: now, count: 0, logged: false };
102
+ this.windows.set(key, w);
103
+ }
104
+ if (w.count < limit) {
105
+ w.count += 1;
106
+ return { ok: true };
107
+ }
108
+ const firstInWindow = !w.logged;
109
+ w.logged = true;
110
+ return { ok: false, firstInWindow };
111
+ }
112
+
113
+ private prune(now: number): void {
114
+ for (const [k, w] of this.windows) if (now - w.start >= WINDOW_MS) this.windows.delete(k);
115
+ }
116
+ }
117
+
118
+ /** Global + per-device permits for remote proof computation. */
119
+ class ProofPermits {
120
+ private total = 0;
121
+ private readonly perDevice = new Map<string, number>();
122
+
123
+ tryAcquire(device: string): boolean {
124
+ if (this.total >= GLOBAL_PROOF_PERMITS) return false;
125
+ if ((this.perDevice.get(device) ?? 0) >= DEVICE_PROOF_PERMITS) return false;
126
+ this.total += 1;
127
+ this.perDevice.set(device, (this.perDevice.get(device) ?? 0) + 1);
128
+ return true;
129
+ }
130
+
131
+ release(device: string): void {
132
+ this.total = Math.max(0, this.total - 1);
133
+ const n = (this.perDevice.get(device) ?? 1) - 1;
134
+ if (n <= 0) this.perDevice.delete(device);
135
+ else this.perDevice.set(device, n);
136
+ }
137
+ }
138
+
139
+ /** A covering entry, durable or live, with the identity a LOCAL answer carries. */
140
+ interface Cover {
141
+ key: string;
142
+ sourceKind: PiTrustLiveAnswerSource;
143
+ dev: string;
144
+ ino: string;
145
+ birthtimeMs?: number;
146
+ live?: LiveEntry;
147
+ }
148
+ type PiTrustLiveAnswerSource = Extract<PiTrustLiveAnswer, { sourceKind: string }>["sourceKind"];
149
+
150
+ function classify(request: FastifyRequest): Requester | null {
151
+ const headers = request.headers as Record<string, unknown>;
152
+ // Genuinely local: loopback peer, no forwarding header, and a fully VERIFIED proof
153
+ // (MAC, endpoint + method + path binding, freshness, replay cache). The raw legacy
154
+ // token (`kind: "legacy"`) is deliberately not enough here.
155
+ if (
156
+ credentialVerdict(headers).kind === "proof" &&
157
+ isLoopbackHost(request.ip ?? "") &&
158
+ !hasProxyForwardingHeaders(headers)
159
+ ) {
160
+ return { kind: "local" };
161
+ }
162
+ const via = (request as unknown as { authVia?: string }).authVia;
163
+ if (via === "device") {
164
+ const id = (request as unknown as { principalDeviceId?: string }).principalDeviceId;
165
+ return { kind: "device", id: typeof id === "string" && id ? id : "device" };
166
+ }
167
+ return null;
168
+ }
169
+
170
+ export function registerPiTrustQueryRoutes(
171
+ fastify: FastifyInstance,
172
+ deps: PiTrustQueryDeps,
173
+ ): { counters: () => PiTrustLiveCounters } {
174
+ const home = deps.home ?? os.homedir();
175
+ const nowMs = deps.nowMs ?? (() => Date.now());
176
+ const log = deps.log ?? ((line: string) => console.warn(line));
177
+ const manifestOf = deps.manifest ?? trustResourceManifest;
178
+ const counters: PiTrustLiveCounters = { covered: 0, notCovered: 0, refused: 0, rateLimited: 0, budgetMissed: 0 };
179
+ const limiter = new WindowLimiter();
180
+ const permits = new ProofPermits();
181
+
182
+ /** Authenticate first, then rate-limit — all before the body is parsed or any trust state is read. */
183
+ async function admit(request: FastifyRequest, reply: FastifyReply): Promise<void> {
184
+ const who = classify(request);
185
+ if (!who) {
186
+ counters.refused += 1;
187
+ reply.code(401).send({ success: false, error: "unauthorized" });
188
+ return;
189
+ }
190
+ const limit = who.kind === "local" ? LOCAL_QUERIES_PER_WINDOW : DEVICE_QUERIES_PER_WINDOW;
191
+ const key = who.kind === "local" ? "local" : `device:${who.id}`;
192
+ const verdict = limiter.allow(key, limit, nowMs());
193
+ if (!verdict.ok) {
194
+ if (verdict.firstInWindow) {
195
+ log(
196
+ `[pi-trust-query] rate limited requester=${sanitizeForLog(key)} limit=${limit}/${WINDOW_MS / 1000}s ` +
197
+ `(further refusals in this window are not logged)`,
198
+ );
199
+ }
200
+ counters.rateLimited += 1;
201
+ reply.code(429).send({ success: false, error: "rate_limited" });
202
+ return;
203
+ }
204
+ (request as unknown as Record<symbol, Started>)[STARTED] = { requester: who, startedAt: nowMs() };
205
+ }
206
+
207
+ /** The nearest counted entry covering `key`, durable or live (live wins only when nearer). */
208
+ function findCover(key: string): Cover | null {
209
+ let best: Cover | null = null;
210
+ const snapshotCover = coverSnapshot(deps.readSnapshot(), key, deps.hookHash ? { currentHookHash: deps.hookHash } : {});
211
+ if (snapshotCover.covered) {
212
+ const e = snapshotCover.entry;
213
+ best = {
214
+ key: e.key,
215
+ sourceKind: e.sourceKind,
216
+ dev: e.dev,
217
+ ino: e.ino,
218
+ ...(e.birthtimeMs !== undefined ? { birthtimeMs: e.birthtimeMs } : {}),
219
+ };
220
+ }
221
+ const live = deps.live()?.covering(key);
222
+ if (live && (!best || live.key.length > best.key.length)) {
223
+ best = {
224
+ key: live.key,
225
+ sourceKind: live.sourceKind,
226
+ dev: live.identity.dev,
227
+ ino: live.identity.ino,
228
+ ...(live.identity.birthtimeMs !== undefined ? { birthtimeMs: live.identity.birthtimeMs } : {}),
229
+ live,
230
+ };
231
+ }
232
+ return best;
233
+ }
234
+
235
+ /** Body → the server's own canonical key, or a 400 / an immediate "not covered". */
236
+ function canonicalKey(body: unknown): { key: string } | { status: number; error: string } | { notCovered: true } {
237
+ const checked = validatePiTrustQueryBody(body);
238
+ if (!checked.ok) return { status: checked.status, error: checked.error };
239
+ let key: string | null;
240
+ try {
241
+ key = safePiTrustKey(checked.cwd, home);
242
+ } catch {
243
+ key = null;
244
+ }
245
+ if (key === null) return { status: 400, error: "cwd malformed" };
246
+ // A symlink or `..` confusion: the bridge's key must be OUR key for that path.
247
+ return key === checked.cwd ? { key } : { notCovered: true };
248
+ }
249
+
250
+ /** The server's own switches and deny rules: may this folder be answered at all? */
251
+ function mayAnswer(key: string): boolean {
252
+ const cfg = deps.getConfig();
253
+ if (!cfg.enabled || !cfg.liveQuery) return false;
254
+ const deny = deps.denyRules ? deps.denyRules() : mirrorDenyRules({ homedir: home });
255
+ return !isMirrorDenied(key, deny);
256
+ }
257
+
258
+ /** The entry may have ended since the lookup (YOLO expiry / end): never answer from a dead one. */
259
+ const stillLive = (cover: Cover): boolean => !cover.live || deps.live()?.isStillLive(cover.live) === true;
260
+
261
+ function localAnswer(cover: Cover): PiTrustLiveAnswer {
262
+ if (!stillLive(cover)) return { covered: false };
263
+ return {
264
+ covered: true,
265
+ key: cover.key,
266
+ sourceKind: cover.sourceKind,
267
+ dev: cover.dev,
268
+ ino: cover.ino,
269
+ ...(cover.birthtimeMs !== undefined ? { birthtimeMs: cover.birthtimeMs } : {}),
270
+ };
271
+ }
272
+
273
+ /** Remote: salted digest of pi's trust-requiring resources, under permits. `null` = permits exhausted. */
274
+ async function remoteAnswer(deviceId: string, key: string, cover: Cover): Promise<PiTrustLiveAnswer | null> {
275
+ if (!permits.tryAcquire(deviceId)) {
276
+ const rl = limiter.allow(`permit:${deviceId}`, 0, nowMs());
277
+ if (!rl.ok && rl.firstInWindow) {
278
+ log(`[pi-trust-query] proof permits exhausted requester=${sanitizeForLog(deviceId)} cwd=${sanitizeForLog(key)}`);
279
+ }
280
+ return null;
281
+ }
282
+ let manifest: string | null;
283
+ try {
284
+ manifest = await manifestOf(key, { home });
285
+ } finally {
286
+ permits.release(deviceId);
287
+ }
288
+ if (manifest === null || !stillLive(cover)) return { covered: false };
289
+ const salt = newTrustSalt();
290
+ return { covered: true, salt, digest: trustResourceDigest(salt, key, manifest) };
291
+ }
292
+
293
+ type Outcome = { answer: PiTrustLiveAnswer } | { status: number; error: string };
294
+
295
+ async function evaluate(requester: Requester, body: unknown): Promise<Outcome> {
296
+ const notCovered: Outcome = { answer: { covered: false } };
297
+ const canonical = canonicalKey(body);
298
+ if ("status" in canonical) return canonical;
299
+ if ("notCovered" in canonical || !mayAnswer(canonical.key)) return notCovered;
300
+ const cover = findCover(canonical.key);
301
+ if (!cover) return notCovered;
302
+ if (requester.kind === "local") return { answer: localAnswer(cover) };
303
+ const answer = await remoteAnswer(requester.id, canonical.key, cover);
304
+ return answer ? { answer } : { status: 429, error: "rate_limited" };
305
+ }
306
+
307
+ fastify.post(
308
+ PI_TRUST_QUERY_PATH,
309
+ { bodyLimit: PI_TRUST_QUERY_MAX_BODY_BYTES, onRequest: admit },
310
+ async (request, reply): Promise<PiTrustLiveAnswer | { success: false; error: string }> => {
311
+ const started = (request as unknown as Record<symbol, Started | undefined>)[STARTED];
312
+ const requester: Requester = started?.requester ?? { kind: "local" };
313
+ const startedAt = started?.startedAt ?? nowMs();
314
+
315
+ const outcome = await evaluate(requester, request.body);
316
+ if ("status" in outcome) {
317
+ if (outcome.status === 429) counters.rateLimited += 1;
318
+ reply.code(outcome.status);
319
+ return { success: false, error: outcome.error };
320
+ }
321
+ if (outcome.answer.covered) counters.covered += 1;
322
+ else counters.notCovered += 1;
323
+ const budget = effectiveLiveQueryTimeoutMs(deps.getConfig(), requester.kind === "device");
324
+ if (nowMs() - startedAt > budget) counters.budgetMissed += 1;
325
+ return outcome.answer;
326
+ },
327
+ );
328
+
329
+ return { counters: () => ({ ...counters }) };
330
+ }
@@ -133,6 +133,29 @@ function broadcastToggleUpdates(
133
133
  }
134
134
  }
135
135
 
136
+ /**
137
+ * Re-enabling a discovered plugin whose server entry never loaded needs a restart: a refresh
138
+ * loads NEW ids only (design D14, R20). Flag a row that was disabled at boot so the Plugins tab shows the hint and the
139
+ * runtime client stays refused. Returns the ids it flagged (so a rollback can unflag them).
140
+ */
141
+ function flagNeverLoadedReenables(flips: Array<{ id: string; enabled: boolean }>): string[] {
142
+ const store = getPluginStatusStore();
143
+ const flagged: string[] = [];
144
+ for (const flip of flips) {
145
+ if (!flip.enabled) continue;
146
+ const row = store.getStoredStatus(flip.id);
147
+ if (!row || row.loaded || row.enabled || row.source === "local-detected" || row.restartRequired) continue;
148
+ store.setStatus({ ...row, restartRequired: true });
149
+ flagged.push(flip.id);
150
+ }
151
+ return flagged;
152
+ }
153
+
154
+ /** One `plugins_changed` with the current status snapshot (after the per-id config updates). */
155
+ function broadcastPluginsChanged(broadcast: (msg: ServerToBrowserMessage) => void): void {
156
+ broadcast({ type: "plugins_changed", plugins: getPluginStatusStore().listAll() });
157
+ }
158
+
136
159
  /**
137
160
  * Live teardown of WS routes on disable (spec add-browser-relay /
138
161
  * plugin-ws-route: sockets close 1001, later upgrades 404) — without a restart.
@@ -202,8 +225,10 @@ export function setPluginsEnabled(
202
225
 
203
226
  const { nextPlugins, mergedPerId } = applyToggleFlips(existingPlugins, flips);
204
227
  writeRawConfig({ ...existing, plugins: nextPlugins });
228
+ const flagged = flagNeverLoadedReenables(flips);
205
229
  broadcastToggleUpdates(broadcast, mergedPerId, repoRoot);
206
230
  teardownDisabledWsRoutes(enabled, flips);
231
+ broadcastPluginsChanged(broadcast);
207
232
 
208
233
  const rollback = () => {
209
234
  const current = readRawConfig();
@@ -219,7 +244,16 @@ export function setPluginsEnabled(
219
244
  }
220
245
  }
221
246
  writeRawConfig({ ...current, plugins: restored });
247
+ const store = getPluginStatusStore();
248
+ for (const flaggedId of flagged) {
249
+ const row = store.getStoredStatus(flaggedId);
250
+ if (row) {
251
+ const { restartRequired: _drop, ...rest } = row;
252
+ store.setStatus(rest);
253
+ }
254
+ }
222
255
  broadcastToggleUpdates(broadcast, restoredBlocks, repoRoot);
256
+ broadcastPluginsChanged(broadcast);
223
257
  };
224
258
  return { ok: true, flips, impact, rollback };
225
259
  }
@@ -292,6 +326,31 @@ export function registerPluginActivationRoutes(
292
326
  };
293
327
  });
294
328
 
329
+ // Rows with no discovered plugin behind them: a plugin whose server entry is still loaded
330
+ // although its package disappeared (`restartRequired`), and local-detected plugins. One row per
331
+ // id; any other id absent from discovery is not returned. See change: decouple-plugins-from-core (5.10).
332
+ const discoveredIds = new Set(plugins.map((p) => p.manifest.id));
333
+ for (const status of all) {
334
+ if (discoveredIds.has(status.id)) continue;
335
+ if (!(status.source === "local-detected" || (status.loaded && status.restartRequired))) continue;
336
+ rows.push({
337
+ id: status.id,
338
+ // No discovered package behind the row: "" = unknown (the client's documented sentinel).
339
+ packageDir: "",
340
+ displayName: status.displayName,
341
+ priority: 1000,
342
+ firstParty: false,
343
+ hasServer: status.loaded,
344
+ hasBridge: false,
345
+ hasClient: false,
346
+ claims: [],
347
+ requires: null,
348
+ dependsOn: status.dependsOn ?? [],
349
+ dependents: Array.from(transitiveDependents(graph, status.id)).sort(),
350
+ status,
351
+ });
352
+ }
353
+
295
354
  return reply.status(200).send({ success: true, plugins: rows });
296
355
  },
297
356
  );
@@ -0,0 +1,149 @@
1
+ /**
2
+ * Runtime plugin client routes:
3
+ *
4
+ * GET /api/plugins/runtime-clients — admitted runtime clients only (`observe`).
5
+ * POST /api/plugins/:id/trust — `{sha256}` pins the client bundle, `{server:true}` grants
6
+ * pi-package server-entry trust (`operate` AND genuinely local).
7
+ * DELETE /api/plugins/:id/trust — removes the whole trust entry (`operate`).
8
+ *
9
+ * Every trust write goes through the dedicated trust writer inside `withSettingsWriteLock`, logs id,
10
+ * action and the 12-hex hash prefix (never the full hash), then yields ONE `plugins_changed`.
11
+ *
12
+ * See change: decouple-plugins-from-core (tasks 6.11, 6.12, 6.20; design D12).
13
+ */
14
+ import {
15
+ buildRuntimeClientListing,
16
+ type DiscoveredPlugin,
17
+ type DiscoveryOptions,
18
+ discoverPlugins,
19
+ getPluginStatusStore,
20
+ } from "@blackbelt-technology/dashboard-plugin-runtime/server";
21
+ import type { ServerToBrowserMessage } from "@blackbelt-technology/pi-dashboard-shared/browser-protocol.js";
22
+ import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
23
+ import type { LocalTrustContext } from "../auth/local-proof.js";
24
+ import { isLocallyTrusted } from "../auth/localhost-guard.js";
25
+ import { grantClientTrust, grantServerTrust, revokeTrust, TRUST_WRITE_LOCK_KEY } from "../auth/plugin-trust-store.js";
26
+ import { noteServeAppTrustChange } from "../auth/serve-app-host.js";
27
+ import { withSettingsWriteLock } from "../pi/settings-write-lock.js";
28
+ import { type AdmissionLog, getRuntimeClientRegistry, hashPrefix, logRuntimeAdmissions } from "../plugin-runtime-clients.js";
29
+ import type { NetworkGuard } from "./route-deps.js";
30
+
31
+ export interface PluginRuntimeClientRoutesDeps {
32
+ networkGuard: NetworkGuard;
33
+ broadcast: (msg: ServerToBrowserMessage) => void;
34
+ /** Genuinely-local proof context (strict mode); omitted → plain loopback-without-forwarding. */
35
+ localTrust?: LocalTrustContext;
36
+ /** `refreshPluginDiscovery()`: loads a newly trusted pi-package server entry and ends in ONE `plugins_changed`. */
37
+ refreshDiscovery?: () => Promise<void>;
38
+ /** Fastify runs with `logger:false`, so the server passes console-backed sinks. */
39
+ log?: AdmissionLog;
40
+ repoRoot?: string;
41
+ /** Discovery options matching the boot load (tests inject a pi-package agent dir). */
42
+ discovery?: DiscoveryOptions;
43
+ }
44
+
45
+ interface TrustBody {
46
+ sha256?: unknown;
47
+ server?: unknown;
48
+ }
49
+
50
+ const SHA256 = /^[0-9a-f]{64}$/;
51
+
52
+ function findPlugin(id: string, repoRoot?: string, discovery?: DiscoveryOptions): DiscoveredPlugin | undefined {
53
+ return discoverPlugins(repoRoot, [], discovery).find((p) => p.manifest.id === id);
54
+ }
55
+
56
+ /** `{sha256}` XOR `{server:true}`; anything else is a 400. */
57
+ function parseTrustBody(body: TrustBody | undefined): { kind: "client"; sha256: string } | { kind: "server" } | { error: string } {
58
+ const hasSha = body?.sha256 !== undefined;
59
+ const hasServer = body?.server !== undefined;
60
+ if (hasSha === hasServer) return { error: "body must carry exactly one of sha256 or server:true" };
61
+ if (hasServer) return body?.server === true ? { kind: "server" } : { error: "server must be true" };
62
+ return typeof body?.sha256 === "string" && SHA256.test(body.sha256) ? { kind: "client", sha256: body.sha256 } : { error: "sha256 must be 64 hex characters" };
63
+ }
64
+
65
+ export function registerPluginRuntimeClientRoutes(fastify: FastifyInstance, deps: PluginRuntimeClientRoutesDeps): void {
66
+ const { networkGuard, broadcast, repoRoot, discovery } = deps;
67
+ const log: AdmissionLog = deps.log ?? { info: (m) => console.log(m) };
68
+
69
+ /** After a trust write: serve-app restart flag, then ONE `plugins_changed` (the refresh owns it for a server grant). */
70
+ async function afterTrustChange(plugin: DiscoveredPlugin | undefined, refresh: boolean): Promise<void> {
71
+ if (plugin) noteServeAppTrustChange({ packageDir: plugin.packageDir, manifestId: plugin.manifest.id, source: plugin.source });
72
+ if (refresh && deps.refreshDiscovery) {
73
+ await deps.refreshDiscovery();
74
+ } else {
75
+ broadcast({ type: "plugins_changed", plugins: getPluginStatusStore().listAll() });
76
+ }
77
+ logRuntimeAdmissions(log, "trust");
78
+ }
79
+
80
+ // GET /api/plugins/runtime-clients — admitted runtime plugins only.
81
+ fastify.get("/api/plugins/runtime-clients", { preHandler: networkGuard }, async (_request, reply) => {
82
+ const admitted = getRuntimeClientRegistry()?.getAdmittedRuntimePlugins() ?? [];
83
+ return reply.status(200).send({ success: true, plugins: buildRuntimeClientListing(admitted) });
84
+ });
85
+
86
+ /** `{server:true}`: record pi-package server trust, then refresh discovery (loads the entry additively). */
87
+ async function grantServer(plugin: DiscoveredPlugin, reply: FastifyReply): Promise<FastifyReply> {
88
+ const id = plugin.manifest.id;
89
+ if (plugin.source !== "pi-package" || !plugin.serverEntryPath) {
90
+ return reply.status(400).send({ success: false, error: "server trust applies to a pi-package plugin with a server entry" });
91
+ }
92
+ const { after } = await withSettingsWriteLock(TRUST_WRITE_LOCK_KEY, async () => grantServerTrust(id));
93
+ log.info(`[plugin-trust] id=${id} action=grant-server sha=${hashPrefix(after.find((e) => e.id === id)?.clientSha256)}`);
94
+ await afterTrustChange(plugin, true);
95
+ return reply.status(200).send({ success: true, entry: after.find((e) => e.id === id) });
96
+ }
97
+
98
+ /** `{sha256}`: pin the client bundle, only when the hash is the CURRENT one (decided against a full rehash). */
99
+ async function grantClient(plugin: DiscoveredPlugin, sha256: string, reply: FastifyReply): Promise<FastifyReply> {
100
+ const id = plugin.manifest.id;
101
+ const registry = getRuntimeClientRegistry();
102
+ registry?.clearContentHashCache(); // the pin is never decided against a stale stat cache (design D12, R2)
103
+ const outcome = await withSettingsWriteLock(TRUST_WRITE_LOCK_KEY, async () => {
104
+ const current = registry?.currentContentHash(id);
105
+ if (!current) return { status: 400 as const };
106
+ if (current !== sha256) return { status: 409 as const };
107
+ return { status: 200 as const, after: grantClientTrust(id, sha256).after };
108
+ });
109
+ if (outcome.status === 400) return reply.status(400).send({ success: false, error: "plugin has no client bundle to trust" });
110
+ if (outcome.status === 409) {
111
+ return reply.status(409).send({ success: false, error: "stale_hash", message: "The bundle changed since the hash was displayed; reload and review it again." });
112
+ }
113
+ log.info(`[plugin-trust] id=${id} action=grant-client sha=${hashPrefix(sha256)}`);
114
+ await afterTrustChange(plugin, false);
115
+ return reply.status(200).send({ success: true, entry: outcome.after.find((e) => e.id === id) });
116
+ }
117
+
118
+ // POST /api/plugins/:id/trust
119
+ fastify.post<{ Params: { id: string }; Body: TrustBody }>(
120
+ "/api/plugins/:id/trust",
121
+ { preHandler: networkGuard },
122
+ async (request: FastifyRequest<{ Params: { id: string }; Body: TrustBody }>, reply: FastifyReply) => {
123
+ // Trusting code is a host-owner decision: a remote operate bearer may revoke but never grant.
124
+ if (!isLocallyTrusted({ ip: request.ip, headers: request.headers as Record<string, unknown> }, deps.localTrust)) {
125
+ return reply.status(403).send({ success: false, error: "local_only", message: "Plugin trust can only be granted from the machine running the dashboard." });
126
+ }
127
+ const { id } = request.params;
128
+ const parsed = parseTrustBody(request.body);
129
+ if ("error" in parsed) return reply.status(400).send({ success: false, error: parsed.error });
130
+ const plugin = findPlugin(id, repoRoot, discovery);
131
+ if (!plugin) return reply.status(404).send({ success: false, error: `Plugin "${id}" not found` });
132
+ return parsed.kind === "server" ? grantServer(plugin, reply) : grantClient(plugin, parsed.sha256, reply);
133
+ },
134
+ );
135
+
136
+ // DELETE /api/plugins/:id/trust — drops the whole entry (client pin and server grant).
137
+ fastify.delete<{ Params: { id: string } }>("/api/plugins/:id/trust", { preHandler: networkGuard }, async (request, reply) => {
138
+ const { id } = request.params;
139
+ const { before } = await withSettingsWriteLock(TRUST_WRITE_LOCK_KEY, async () => revokeTrust(id));
140
+ const removed = before.find((e) => e.id === id);
141
+ log.info(`[plugin-trust] id=${id} action=revoke sha=${hashPrefix(removed?.clientSha256)}`);
142
+ // A server entry that is already running keeps running until a restart: say so on its row.
143
+ const store = getPluginStatusStore();
144
+ const row = store.getStoredStatus(id);
145
+ if (removed?.server && row?.loaded) store.setStatus({ ...row, restartRequired: true });
146
+ await afterTrustChange(findPlugin(id, repoRoot, discovery), false);
147
+ return reply.status(200).send({ success: true, removed: Boolean(removed), restartRequired: Boolean(removed?.server && row?.loaded) });
148
+ });
149
+ }
@@ -13,6 +13,7 @@
13
13
 
14
14
  import type { CatalogueReadyResponse, LegacyProviderIdsResponse } from "@blackbelt-technology/pi-dashboard-shared/rest-api.js";
15
15
  import type { FastifyInstance } from "fastify";
16
+ import { auditLine, auditPrefix, auditRequestFields } from "../auth/audit-log.js";
16
17
  import { beginFlow, isPluginFlow } from "../auth/begin-flow.js";
17
18
  import {
18
19
  abortAllFlows,
@@ -157,9 +158,13 @@ export function registerProviderAuthRoutes(
157
158
  const out = readRadiusMcpStatus(radiusMcpDeps());
158
159
  return reply.code(out.status).send(out.body);
159
160
  });
160
- fastify.post("/api/provider-auth/radius/mcp", async (_request, reply) => {
161
+ fastify.post("/api/provider-auth/radius/mcp", async (request, reply) => {
161
162
  await registryReady;
162
163
  const out = await configureRadiusMcp(radiusMcpDeps());
164
+ // Audit a configured outcome only (D2); `written` is a boolean, never request data.
165
+ if (out.status === 200) {
166
+ auditLine("provider-auth", "radius_mcp", { written: out.body.written === true, ...auditRequestFields(request) });
167
+ }
163
168
  return reply.code(out.status).send(out.body);
164
169
  });
165
170
 
@@ -235,6 +240,7 @@ export function registerProviderAuthRoutes(
235
240
  // polling, so the message travels in this response.
236
241
  return reply.code(500).send({ error: result.message });
237
242
  }
243
+ auditLine("provider-auth", "oauth_start", { provider: auditPrefix(provider, 64), ...auditRequestFields(request) });
238
244
  return toFlowStatus(result.flow);
239
245
  },
240
246
  );
@@ -262,6 +268,8 @@ export function registerProviderAuthRoutes(
262
268
  return reply.code(409).send({ error: "No input pending for this flow" });
263
269
  }
264
270
  resolve(typeof request.body?.value === "string" ? request.body.value : "");
271
+ // The value may be an auth code: only the flow id prefix is audited (D2).
272
+ auditLine("provider-auth", "flow_input", { flow: auditPrefix(request.params.flowId), ...auditRequestFields(request) });
265
273
  return reply.code(202).send({ ok: true });
266
274
  },
267
275
  );
@@ -290,6 +298,7 @@ export function registerProviderAuthRoutes(
290
298
  const authJsonKey = resolveAuthJsonKey(provider);
291
299
  const credential: ApiKeyCredential = { type: "api_key", key };
292
300
  await writeCredential(authJsonKey, credential);
301
+ auditLine("provider-auth", "key_set", { provider: auditPrefix(authJsonKey, 64), ...auditRequestFields(request) });
293
302
  notifyBridges();
294
303
  return { ok: true };
295
304
  } catch (err: any) {
@@ -328,7 +337,11 @@ export function registerProviderAuthRoutes(
328
337
  // api-key row (X2).
329
338
  const isOAuthRow = oauthIdSet().has(rawId);
330
339
  const authJsonKey = resolveAuthJsonKey(rawId);
331
- await removeCredential(authJsonKey, isOAuthRow ? "oauth" : "api_key");
340
+ // Audit a real removal only (DELETE stays idempotent for an absent provider); `onRemoved` runs inside
341
+ // the storage lock, so two concurrent DELETEs log exactly one `removed`.
342
+ let removed = false;
343
+ await removeCredential(authJsonKey, isOAuthRow ? "oauth" : "api_key", { onRemoved: () => { removed = true; } });
344
+ if (removed) auditLine("provider-auth", "removed", { provider: auditPrefix(authJsonKey, 64), ...auditRequestFields(request) });
332
345
  } catch (err: any) {
333
346
  if (err instanceof CredentialTypeConflictError) {
334
347
  return reply.code(409).send({