@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
@@ -8,6 +8,8 @@ import {
8
8
  } from "@blackbelt-technology/pi-dashboard-shared/plugin-bridge-register.js";
9
9
  import type { ApiResponse } from "@blackbelt-technology/pi-dashboard-shared/types.js";
10
10
  import type { FastifyInstance } from "fastify";
11
+ import { admitOptionalCwd, sendCwdFailure } from "../lib/file-cwd-admission.js";
12
+ import type { RouteAdmissionDeps } from "../lib/route-admission.js";
11
13
  import {
12
14
  attachPublishedVariants,
13
15
  enrichInstalledRows,
@@ -48,9 +50,15 @@ export function registerPackageRoutes(
48
50
  fastify: FastifyInstance,
49
51
  deps: {
50
52
  packageManagerWrapper: PackageManagerWrapper;
53
+ /**
54
+ * Shared cwd admission (change: core-file-cwd-admission): a supplied `cwd` must be admitted;
55
+ * no `cwd` keeps today's fallback. Absent → fail-closed (nothing is known).
56
+ */
57
+ routeAdmission?: RouteAdmissionDeps;
51
58
  },
52
59
  ) {
53
60
  const { packageManagerWrapper } = deps;
61
+ const routeAdmission: RouteAdmissionDeps = deps.routeAdmission ?? {};
54
62
 
55
63
  // ── Search npm packages ─────────────────────────────────────────
56
64
 
@@ -94,9 +102,11 @@ export function registerPackageRoutes(
94
102
 
95
103
  fastify.get<{ Querystring: { scope?: string; cwd?: string } }>(
96
104
  "/api/packages/installed",
97
- async (request) => {
105
+ async (request, reply) => {
98
106
  const scope = request.query.scope === "local" ? "local" : "global";
99
- const cwd = request.query.cwd;
107
+ const admitted = await admitOptionalCwd(request.query.cwd, routeAdmission, reply);
108
+ if (!admitted.ok) return sendCwdFailure(reply, admitted.failure);
109
+ const cwd = admitted.cwd;
100
110
  try {
101
111
  const packages = await packageManagerWrapper.listInstalled(scope, cwd);
102
112
  const managedPaths = scope === "global" ? readManagedPaths(fastify) : undefined;
@@ -122,12 +132,15 @@ export function registerPackageRoutes(
122
132
  fastify.post<{ Body: { source: string; scope: string; cwd?: string } }>(
123
133
  "/api/packages/install",
124
134
  async (request, reply) => {
125
- const { source, scope, cwd } = request.body ?? {};
135
+ const { source, scope } = request.body ?? {};
126
136
  if (!source) {
127
137
  reply.code(400);
128
138
  return { success: false, error: "source is required" } satisfies ApiResponse;
129
139
  }
130
140
  const effectiveScope = scope === "local" ? "local" as const : "global" as const;
141
+ const admitted = await admitOptionalCwd(request.body?.cwd, routeAdmission, reply);
142
+ if (!admitted.ok) return sendCwdFailure(reply, admitted.failure);
143
+ const cwd = admitted.cwd;
131
144
  try {
132
145
  const operationId = await packageManagerWrapper.run({
133
146
  action: "install",
@@ -152,12 +165,15 @@ export function registerPackageRoutes(
152
165
  fastify.post<{ Body: { source: string; scope: string; cwd?: string } }>(
153
166
  "/api/packages/remove",
154
167
  async (request, reply) => {
155
- const { source, scope, cwd } = request.body ?? {};
168
+ const { source, scope } = request.body ?? {};
156
169
  if (!source) {
157
170
  reply.code(400);
158
171
  return { success: false, error: "source is required" } satisfies ApiResponse;
159
172
  }
160
173
  const effectiveScope = scope === "local" ? "local" as const : "global" as const;
174
+ const admitted = await admitOptionalCwd(request.body?.cwd, routeAdmission, reply);
175
+ if (!admitted.ok) return sendCwdFailure(reply, admitted.failure);
176
+ const cwd = admitted.cwd;
161
177
  try {
162
178
  const operationId = await packageManagerWrapper.run({
163
179
  action: "remove",
@@ -182,8 +198,11 @@ export function registerPackageRoutes(
182
198
  fastify.post<{ Body: { source?: string; scope: string; cwd?: string } }>(
183
199
  "/api/packages/update",
184
200
  async (request, reply) => {
185
- const { source, scope, cwd } = request.body ?? {};
201
+ const { source, scope } = request.body ?? {};
186
202
  const effectiveScope = scope === "local" ? "local" as const : "global" as const;
203
+ const admitted = await admitOptionalCwd(request.body?.cwd, routeAdmission, reply);
204
+ if (!admitted.ok) return sendCwdFailure(reply, admitted.failure);
205
+ const cwd = admitted.cwd;
187
206
  try {
188
207
  const operationId = await packageManagerWrapper.run({
189
208
  action: "update",
@@ -216,7 +235,7 @@ export function registerPackageRoutes(
216
235
  };
217
236
  }>("/api/packages/move", async (request, reply) => {
218
237
  const body = request.body ?? {};
219
- const { entry, fromCwd, toCwd } = body;
238
+ const { entry } = body;
220
239
  const fromScope = body.fromScope === "local" ? "local" : body.fromScope === "global" ? "global" : null;
221
240
  const toScope = body.toScope === "local" ? "local" : body.toScope === "global" ? "global" : null;
222
241
 
@@ -229,6 +248,25 @@ export function registerPackageRoutes(
229
248
  return { success: false, error: "fromScope and toScope are required ('global' or 'local')" } satisfies ApiResponse;
230
249
  }
231
250
 
251
+ // A local scope needs a string cwd: the wrapper's own check, run up front so a non-string value
252
+ // answers `invalid_request` instead of reaching admission (core-file-cwd-admission D1).
253
+ for (const [scopeValue, cwdValue, label] of [
254
+ [fromScope, body.fromCwd, "fromCwd"],
255
+ [toScope, body.toCwd, "toCwd"],
256
+ ] as const) {
257
+ if (scopeValue === "local" && (typeof cwdValue !== "string" || !cwdValue)) {
258
+ reply.code(400);
259
+ return { success: false, error: `${label} required when ${label.slice(0, -3)}Scope is local`, code: "invalid_request" } as any;
260
+ }
261
+ }
262
+ // Both sides are admitted; a refusal beats an undecidable side.
263
+ const from = await admitOptionalCwd(body.fromCwd, routeAdmission, reply);
264
+ const to = await admitOptionalCwd(body.toCwd, routeAdmission, reply);
265
+ const failed = [from, to].flatMap((a) => (a.ok ? [] : [a.failure]));
266
+ if (failed.length > 0) return sendCwdFailure(reply, failed.find((f) => f.code !== 503) ?? failed[0]);
267
+ const fromCwd = from.ok ? from.cwd : undefined;
268
+ const toCwd = to.ok ? to.cwd : undefined;
269
+
232
270
  try {
233
271
  const moveId = await packageManagerWrapper.move({
234
272
  entry: entry as PackageEntry,
@@ -271,12 +309,21 @@ export function registerPackageRoutes(
271
309
  fastify.post<{ Body: { source?: string; scope?: string; cwd?: string } }>(
272
310
  "/api/packages/reset-to-npm",
273
311
  async (request, reply) => {
274
- const { source, cwd } = request.body ?? {};
312
+ const { source } = request.body ?? {};
275
313
  const scope = request.body?.scope === "local" ? "local" as const : "global" as const;
276
314
  if (!source) {
277
315
  reply.code(400);
278
316
  return { success: false, error: "source is required" } satisfies ApiResponse;
279
317
  }
318
+ // Local scope needs a string cwd (the wrapper's own check, run up front; see `move`).
319
+ const rawCwd: unknown = request.body?.cwd;
320
+ if (scope === "local" && (typeof rawCwd !== "string" || !rawCwd)) {
321
+ reply.code(400);
322
+ return { success: false, error: "cwd required when scope is local", code: "invalid_request" } as any;
323
+ }
324
+ const admitted = await admitOptionalCwd(rawCwd, routeAdmission, reply);
325
+ if (!admitted.ok) return sendCwdFailure(reply, admitted.failure);
326
+ const cwd = admitted.cwd;
280
327
  // Authoritative server-side resolution: find the installed row and
281
328
  // resolve its published variant. Never trust a client-supplied target.
282
329
  try {
@@ -320,10 +367,11 @@ export function registerPackageRoutes(
320
367
 
321
368
  fastify.post<{ Body: { cwd?: string } }>(
322
369
  "/api/packages/check-updates",
323
- async (request) => {
324
- const { cwd } = request.body ?? {};
370
+ async (request, reply) => {
371
+ const admitted = await admitOptionalCwd(request.body?.cwd, routeAdmission, reply);
372
+ if (!admitted.ok) return sendCwdFailure(reply, admitted.failure);
325
373
  try {
326
- const updates = await packageManagerWrapper.checkUpdates(cwd);
374
+ const updates = await packageManagerWrapper.checkUpdates(admitted.cwd);
327
375
  return { success: true, data: updates } satisfies ApiResponse;
328
376
  } catch (err: any) {
329
377
  return { success: false, error: err.message } satisfies ApiResponse;
@@ -15,14 +15,19 @@
15
15
  */
16
16
 
17
17
  import type { TLSSocket } from "node:tls";
18
+ import type { PairPollData } from "@blackbelt-technology/pi-dashboard-shared/rest-api.js";
18
19
  import { isTier, TIERS } from "@blackbelt-technology/pi-dashboard-shared/tiers.js";
20
+ import { TLS_ONLY_TOKEN_UNTRUSTED_CHANNEL } from "@blackbelt-technology/pi-dashboard-shared/tls-only-token.js";
19
21
  import type { ApiResponse } from "@blackbelt-technology/pi-dashboard-shared/types.js";
20
22
  import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
21
23
  import { describeApprovalRefusal } from "../auth/approval-refusal.js";
24
+ import { auditLine, auditPrefix, auditRequestFields } from "../auth/audit-log.js";
25
+ import { parseBearerHeader, ROTATE_ROUTE } from "../auth/bearer-auth.js";
22
26
  import { type HostAdmissionOptions, isHostAdmitted } from "../auth/host-admission.js";
23
27
  import type { ServerIdentity } from "../auth/identity.js";
24
28
  import { signNonce } from "../auth/identity.js";
25
29
  import { hasLocalCredential } from "../auth/local-credential.js";
30
+ import { bearerChannelOf, isProvenChannel } from "../auth/proven-tls.js";
26
31
  import { createLocalTrustContext, hasLocalProof, type LocalTrustContext } from "../auth/local-proof.js";
27
32
  import { isLocallyTrusted, type LanInterface } from "../auth/localhost-guard.js";
28
33
  import {
@@ -33,12 +38,31 @@ import {
33
38
  knockPeerInput,
34
39
  knockPeerState,
35
40
  } from "../pairing/knock-admission.js";
36
- import type { PairedDeviceRegistry, PairedDeviceView } from "../pairing/paired-devices.js";
41
+ import { BRIDGE_TOKEN_REQUIRES_HTTPS, type PairedDeviceRegistry, type PairedDeviceView } from "../pairing/paired-devices.js";
37
42
  import type { ApproveResult, PairingManager, PendingDeviceView } from "../pairing/pairing.js";
38
43
  import { SUPPORTED_PAIRING_VERSIONS } from "../pairing/pairing.js";
39
44
  import { localEndpoints } from "../tunnel/tunnel-endpoints.js";
40
45
  import type { NetworkGuard } from "./route-deps.js";
41
46
 
47
+ /**
48
+ * The `https:` origins of the reachable list, de-duplicated, in order. `wss://`
49
+ * and the `PI_E2E_SEED` loopback `http` origin that `reachableUrls()` admits for
50
+ * the QR payload are NOT routes. See change: group-servers-by-identity (D7).
51
+ */
52
+ function httpsOrigins(urls: readonly string[]): string[] {
53
+ const out: string[] = [];
54
+ for (const raw of urls) {
55
+ let url: URL;
56
+ try {
57
+ url = new URL(raw);
58
+ } catch {
59
+ continue;
60
+ }
61
+ if (url.protocol === "https:" && !out.includes(url.origin)) out.push(url.origin);
62
+ }
63
+ return out;
64
+ }
65
+
42
66
  /** Strip trailing slashes without a regex (avoids a polynomial-ReDoS shape). */
43
67
  function stripTrailingSlashes(u: string): string {
44
68
  let end = u.length;
@@ -192,6 +216,66 @@ function createApprovalGuard(deps: {
192
216
  };
193
217
  }
194
218
 
219
+ /**
220
+ * `POST /api/paired-devices/rotate` — a browser-held device bearer rotates ITSELF.
221
+ *
222
+ * Authenticated ONLY by `Authorization: Bearer`: a cookie, local proof, operator
223
+ * session or nothing is 401 `bearer_required`, and any device id in the body is
224
+ * ignored (the bearer identifies the row). Deliberately no `networkGuard`: the
225
+ * bearer is the sole credential, so no network position can stand in for it.
226
+ * The registry does the work synchronously (no await between verify and write),
227
+ * so two same-tick rotations with one bearer serialise (second → 409
228
+ * `bearer_superseded`). Success returns `{token, expiresAt}` with `no-store`.
229
+ * An EXPIRED bearer is refused earlier by the bearer hook (401 `bearer_expired`).
230
+ * See change: harden-auth-credentials (D5).
231
+ */
232
+ export function registerBearerRotateRoute(fastify: FastifyInstance, deps: { registry: PairedDeviceRegistry }): void {
233
+ const { registry } = deps;
234
+ fastify.post<{ Body: unknown }>(ROTATE_ROUTE, async (request, reply) => {
235
+ reply.header("Cache-Control", "no-store");
236
+ const presented = parseBearerHeader(request.headers.authorization);
237
+ if (!presented) {
238
+ reply.code(401);
239
+ return { success: false, error: "bearer_required", code: "bearer_required" };
240
+ }
241
+ const body = request.body;
242
+ // Only the exact string "browser" is a declaration; anything else is none (A-G11).
243
+ const declared =
244
+ body !== null && typeof body === "object" && (body as Record<string, unknown>).holder === "browser";
245
+ const result = registry.rotate(presented, declared, { channel: bearerChannelOf(request.raw) });
246
+ if (result.ok) {
247
+ auditLine("pairing", "rotated", { id: auditPrefix(result.id), ip: request.ip });
248
+ return { token: result.token, expiresAt: result.expiresAt };
249
+ }
250
+ const refuse = (status: number, code: string) => {
251
+ if (result.id !== undefined) {
252
+ auditLine("pairing", "rotate_refused", { id: auditPrefix(result.id), reason: code, ip: request.ip });
253
+ }
254
+ reply.code(status);
255
+ return { success: false, error: code, code };
256
+ };
257
+ switch (result.reason) {
258
+ case "expired":
259
+ return refuse(401, "bearer_expired");
260
+ case "superseded":
261
+ return refuse(409, "bearer_superseded");
262
+ case "holder_declaration_required":
263
+ return refuse(409, "holder_declaration_required");
264
+ case "persist_failed":
265
+ return refuse(500, "rotation_failed");
266
+ case "tls_only_untrusted_channel":
267
+ return refuse(401, TLS_ONLY_TOKEN_UNTRUSTED_CHANNEL);
268
+ case "rate_limited":
269
+ reply.header("Retry-After", String(result.retryAfterS ?? 60));
270
+ return refuse(429, "rate_limited");
271
+ default:
272
+ // Unknown / revoked / superseded-after-grace: a plain 401, byte-equal to every other route's.
273
+ reply.code(401);
274
+ return { success: false, error: "unauthorized" };
275
+ }
276
+ });
277
+ }
278
+
195
279
  export function registerPairingRoutes(
196
280
  fastify: FastifyInstance,
197
281
  deps: {
@@ -212,6 +296,8 @@ export function registerPairingRoutes(
212
296
  * list so the browser Settings flow and the CLI share one source (D8).
213
297
  */
214
298
  getReachableUrls?: () => string[];
299
+ /** Certificate-backed `https://` URLs of the native TLS listener (named in a refused bridge-token issue). */
300
+ getTlsListenerUrls?: () => string[];
215
301
  /** Bound HTTP port, used to enumerate loopback/LAN endpoints. A thunk so
216
302
  * a `port: 0` server reports the real bound port per request. */
217
303
  getPort?: () => number;
@@ -290,7 +376,7 @@ export function registerPairingRoutes(
290
376
  );
291
377
 
292
378
  // ── Device: redeem a code → pending device + confirm code (public) ─────
293
- fastify.post<{ Body: { code?: string } }>(
379
+ fastify.post<{ Body: { code?: string; holder?: unknown } }>(
294
380
  "/api/pair/redeem",
295
381
  async (request, reply): Promise<ApiResponse<{ pendingId: string; confirmCode: string }>> => {
296
382
  const code = request.body?.code;
@@ -305,6 +391,8 @@ export function registerPairingRoutes(
305
391
  host: headerString(request.headers.host),
306
392
  remoteAddress: request.ip,
307
393
  forwardedFor: headerString(request.headers["x-forwarded-for"]),
394
+ // Only the exact string "browser" is a holder declaration (the manager enforces it).
395
+ holder: request.body?.holder,
308
396
  });
309
397
  if (!result.ok) {
310
398
  reply.code(result.error === "rate_limited" ? 429 : 400);
@@ -321,7 +409,7 @@ export function registerPairingRoutes(
321
409
  // semantics), the LAN gates, the switch and the limits. Admission uses the
322
410
  // SOCKET peer address — never `request.ip` — and that same address is recorded
323
411
  // as the pending device's remote address.
324
- fastify.post<{ Body: { name?: unknown } | null }>(
412
+ fastify.post<{ Body: { name?: unknown; holder?: unknown } | null }>(
325
413
  "/api/pair/request",
326
414
  async (
327
415
  request,
@@ -367,6 +455,7 @@ export function registerPairingRoutes(
367
455
  userAgent: headerString(request.headers["user-agent"]),
368
456
  host: headerString(request.headers.host),
369
457
  remoteAddress: decision.sourceKey,
458
+ holder: request.body?.holder,
370
459
  },
371
460
  });
372
461
  return {
@@ -492,15 +581,30 @@ export function registerPairingRoutes(
492
581
  );
493
582
 
494
583
  // ── Device: poll for approval + collect the bearer token (public) ──────
495
- fastify.post<{ Body: { pendingId?: string } }>(
584
+ fastify.post<{ Body: { pendingId?: string; holder?: unknown } }>(
496
585
  "/api/pair/poll",
497
- async (request, reply): Promise<ApiResponse<{ status: string; token?: string }>> => {
586
+ async (request, reply): Promise<ApiResponse<PairPollData>> => {
498
587
  const pendingId = request.body?.pendingId;
499
588
  if (typeof pendingId !== "string") {
500
589
  reply.code(400);
501
590
  return { success: false, error: "pendingId required" };
502
591
  }
503
- const result = pairing.poll(pendingId);
592
+ const result = pairing.poll(pendingId, request.body?.holder, bearerChannelOf(request.raw));
593
+ // Route delegation (D7): the one approved answer that carries the token also
594
+ // names the server's https origins. Filtered here, not in PairingManager.poll,
595
+ // so knock and QR redemption both get it and the QR payload `urls` stay as minted.
596
+ if (result.status === "approved") {
597
+ return {
598
+ success: true,
599
+ data: {
600
+ status: "approved",
601
+ token: result.token,
602
+ // Present only for a browser-held (expiring) row; epoch ms.
603
+ ...(result.expiresAt !== undefined ? { expiresAt: result.expiresAt } : {}),
604
+ routes: httpsOrigins(pairing.reachableUrls()),
605
+ },
606
+ };
607
+ }
504
608
  return { success: true, data: result };
505
609
  },
506
610
  );
@@ -525,19 +629,25 @@ export function registerPairingRoutes(
525
629
  reply.code(404);
526
630
  return { success: false, error: "device not found" };
527
631
  }
632
+ // Audit: id prefix + actor + socket peer only — never a bearer or hash (D2).
633
+ auditLine("pairing", "revoked", { id: auditPrefix(request.params.id), ...auditRequestFields(request) });
528
634
  return { success: true };
529
635
  },
530
636
  );
531
637
 
638
+ // ── Browser device: rotate its own bearer (bearer-only credential) ────
639
+ registerBearerRotateRoute(fastify, { registry });
640
+
532
641
  // ── Dashboard: mint a device token for an MCP client (operator-only) ──
533
642
  // Deliberately NOT in PUBLIC_PAIRING_PREFIXES: this route issues durable
534
643
  // credentials and requires an operator credential, not a pairing code (D5).
535
- fastify.post<{ Body: { label?: unknown; tier?: unknown } }>(
644
+ fastify.post<{ Body: { label?: unknown; tier?: unknown; purpose?: unknown } }>(
536
645
  "/api/paired-devices",
537
646
  { preHandler: operatorGuard },
538
- async (request, reply): Promise<ApiResponse<{ device: PairedDeviceView; token: string }>> => {
647
+ async (request, reply): Promise<ApiResponse<{ device: PairedDeviceView; token: string }> & { httpsUrl?: string }> => {
539
648
  const label = request.body?.label;
540
649
  const tier = request.body?.tier;
650
+ const purpose = request.body?.purpose;
541
651
  if (typeof label !== "string") {
542
652
  reply.code(400);
543
653
  return { success: false, error: "label must be a string" };
@@ -556,10 +666,36 @@ export function registerPairingRoutes(
556
666
  error: `label must be 1..${MAX_DEVICE_LABEL_BYTES} UTF-8 bytes`,
557
667
  };
558
668
  }
669
+ // `purpose` is absent or "bridge" (D9); `bridge` forces tier `operate`, which bridge-ticket
670
+ // minting needs. Both are validated BEFORE the registry is touched, so a refusal leaves no row.
671
+ if (purpose !== undefined && purpose !== "bridge") {
672
+ reply.code(400);
673
+ return { success: false, error: 'purpose must be "bridge" when present' };
674
+ }
675
+ if (purpose === "bridge" && tier !== undefined && tier !== "operate") {
676
+ reply.code(400);
677
+ return { success: false, error: "a bridge token is always tier operate" };
678
+ }
679
+ const channel = bearerChannelOf(request.raw);
680
+ if (purpose === "bridge" && !isProvenChannel(channel)) {
681
+ // A bridge token is never handed out plain-and-exposed by accident.
682
+ const httpsUrl = deps.getTlsListenerUrls?.()[0];
683
+ reply.code(403);
684
+ return { success: false, error: BRIDGE_TOKEN_REQUIRES_HTTPS, ...(httpsUrl ? { httpsUrl } : {}) };
685
+ }
559
686
  // The plaintext token rides this ONE response and is never retrievable
560
687
  // again (D4) — same plaintext-once semantics as the pairing ceremony.
561
- // No tier → the manual source default (`observe`, D1).
562
- return { success: true, data: registry.add(trimmed, "manual", isTier(tier) ? tier : undefined) };
688
+ // No tier → the manual source default (`observe`, D1). The delivering channel decides exposure.
689
+ const minted = registry.add(trimmed, "manual", isTier(tier) ? tier : undefined, undefined, {
690
+ channel,
691
+ ...(purpose === "bridge" ? { purpose: "bridge" as const } : {}),
692
+ });
693
+ auditLine("pairing", "minted", {
694
+ id: auditPrefix(minted.device.id),
695
+ tier: minted.device.tier,
696
+ ...auditRequestFields(request),
697
+ });
698
+ return { success: true, data: minted };
563
699
  },
564
700
  );
565
701