@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
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blackbelt-technology/pi-agent-dashboard",
3
- "version": "0.10.0",
3
+ "version": "0.11.0",
4
4
  "description": "Web dashboard for monitoring and interacting with pi agent sessions",
5
5
  "repository": {
6
6
  "type": "git",
@@ -98,13 +98,15 @@
98
98
  "site:build": "npm --prefix site run build",
99
99
  "site:preview": "npm --prefix site run preview",
100
100
  "screenshots": "npm --prefix site run shots",
101
- "pretest:e2e": "node -e \"process.env.PW_CHANNEL||require('child_process').execSync('playwright install chromium',{stdio:'inherit'})\"",
101
+ "pretest:e2e": "node -e \"require('child_process').execSync(process.env.PW_CHANNEL?'playwright install firefox webkit':'playwright install chromium firefox webkit',{stdio:'inherit'})\"",
102
102
  "test:e2e": "playwright test",
103
- "pretest:e2e:ui": "node -e \"process.env.PW_CHANNEL||require('child_process').execSync('playwright install chromium',{stdio:'inherit'})\"",
103
+ "pretest:e2e:ui": "node -e \"require('child_process').execSync(process.env.PW_CHANNEL?'playwright install firefox webkit':'playwright install chromium firefox webkit',{stdio:'inherit'})\"",
104
104
  "test:e2e:ui": "playwright test --ui",
105
+ "pretest:e2e:chrome": "playwright install firefox webkit",
105
106
  "test:e2e:chrome": "PW_CHANNEL=chrome playwright test",
106
107
  "test:e2e:reconnect": "PI_E2E_INDEPENDENT_SESSION=1 playwright test faux-ask",
107
108
  "test:e2e:identity": "playwright test --config playwright.identity.config.ts",
109
+ "test:e2e:dist-only": "playwright test --config playwright.dist-only.config.ts",
108
110
  "test:e2e:identity-matrix": "playwright test --config playwright.identity-matrix.config.ts",
109
111
  "pretest:e2e:team": "npm run build:app --workspace=@blackbelt-technology/pi-dashboard-team-plugin",
110
112
  "test:e2e:team": "playwright test --config playwright.team.config.ts",
@@ -115,15 +117,18 @@
115
117
  "knip:ratchet": "node scripts/knip-ratchet.mjs",
116
118
  "codeql": "node scripts/codeql-local.mjs",
117
119
  "z-layer:lint": "node scripts/z-layer-lint.mjs",
118
- "knip:config": "node scripts/knip-config.mjs"
120
+ "knip:config": "node scripts/knip-config.mjs",
121
+ "check:plugin-boundary": "node scripts/check-plugin-boundary.mjs",
122
+ "check:advisory-triage": "node scripts/check-advisory-triage.mjs --xlsx",
123
+ "build:canary": "node scripts/build-runtime-canary.mjs"
119
124
  },
120
125
  "engines": {
121
126
  "node": ">=22.19.0 <27"
122
127
  },
123
128
  "dependencies": {
124
- "@blackbelt-technology/pi-dashboard-extension": "^0.10.0",
125
- "@blackbelt-technology/pi-dashboard-server": "^0.10.0",
126
- "@blackbelt-technology/pi-dashboard-web": "^0.10.0"
129
+ "@blackbelt-technology/pi-dashboard-extension": "^0.11.0",
130
+ "@blackbelt-technology/pi-dashboard-server": "^0.11.0",
131
+ "@blackbelt-technology/pi-dashboard-web": "^0.11.0"
127
132
  },
128
133
  "optionalDependencies": {
129
134
  "appdmg": "^0.6.6"
@@ -131,8 +136,8 @@
131
136
  "devDependencies": {
132
137
  "@axe-core/playwright": "^4.10.0",
133
138
  "@biomejs/biome": "2.5.11",
134
- "@blackbelt-technology/pi-dashboard-bus-client": "^0.10.0",
135
- "@blackbelt-technology/pi-dashboard-shared": "^0.10.0",
139
+ "@blackbelt-technology/pi-dashboard-bus-client": "^0.11.0",
140
+ "@blackbelt-technology/pi-dashboard-shared": "^0.11.0",
136
141
  "@earendil-works/pi-ai": "^1.3.0",
137
142
  "@playwright/test": "1.62.1",
138
143
  "@types/node": "^26.4.0",
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blackbelt-technology/pi-dashboard-extension",
3
- "version": "0.10.0",
3
+ "version": "0.11.0",
4
4
  "description": "Pi bridge extension for pi-dashboard",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -20,6 +20,7 @@
20
20
  ".pi/skills/pi-dashboard",
21
21
  ".pi/skills/browser",
22
22
  ".pi/skills/project-init",
23
+ ".pi/skills/project-access",
23
24
  ".pi/skills/doctor"
24
25
  ],
25
26
  "tools": [
@@ -39,6 +40,7 @@
39
40
  ".pi/skills/pi-dashboard/",
40
41
  ".pi/skills/browser/",
41
42
  ".pi/skills/project-init/",
43
+ ".pi/skills/project-access/",
42
44
  ".pi/skills/doctor/",
43
45
  "agents/",
44
46
  "!**/AGENTS.md",
@@ -48,8 +50,8 @@
48
50
  "!**/*.test.tsx"
49
51
  ],
50
52
  "dependencies": {
51
- "@blackbelt-technology/pi-dashboard-bus-client": "^0.10.0",
52
- "@blackbelt-technology/pi-dashboard-shared": "^0.10.0",
53
+ "@blackbelt-technology/pi-dashboard-bus-client": "^0.11.0",
54
+ "@blackbelt-technology/pi-dashboard-shared": "^0.11.0",
53
55
  "@fission-ai/openspec": "1.14.3",
54
56
  "minimatch": "^10.0.0",
55
57
  "ws": "^8.18.0"
@@ -20,10 +20,62 @@ import { handleUiManagement } from "../ui-modules.js";
20
20
  import type { BridgeInstance } from "./instance.js";
21
21
 
22
22
  /** Handle one inbound server message. Called by the connection's `onMessage` (wrapped in `safe`). */
23
+ /**
24
+ * Name of the turn-starting inbound command carried by `msg`, or `undefined`.
25
+ * Every entry here spends one token of the per-PROCESS prompt bucket;
26
+ * the list is exhaustive for commands that can start a turn or fan out into
27
+ * one (D17). Keep in step with the `Inbound command bounds` spec.
28
+ */
29
+ export function turnStartingCommand(msg: { type?: unknown; action?: unknown }): string | undefined {
30
+ switch (msg.type) {
31
+ case "send_prompt":
32
+ case "retry_session":
33
+ case "git_commit_draft":
34
+ case "plugin_emit_event":
35
+ case "promote_followup_entry":
36
+ return msg.type;
37
+ case "flow_management":
38
+ return msg.action === "run" ? "flow_management" : undefined;
39
+ default:
40
+ return undefined;
41
+ }
42
+ }
43
+
44
+ /** Refuse an over-rate command visibly: route a `command_feedback` error to the sender. */
45
+ function refuseOverRate(inst: BridgeInstance, command: string): void {
46
+ const { promptBurst, promptRefillPerSec } = inst.inboundLimits;
47
+ const message = `${command} refused: inbound command rate limit reached (burst ${promptBurst}, refill ${promptRefillPerSec}/s) — retry shortly`;
48
+ // A refused send_prompt must settle its optimistic bubble first, exactly like
49
+ // the other non-turn refusals in command-handler.
50
+ if (command === "send_prompt") {
51
+ inst.connection.send({ type: "prompt_received", sessionId: inst.sessionId, fresh: false } as never);
52
+ }
53
+ inst.connection.send({
54
+ type: "event_forward",
55
+ sessionId: inst.sessionId,
56
+ event: {
57
+ eventType: "command_feedback",
58
+ timestamp: Date.now(),
59
+ data: { command, status: "error", message },
60
+ },
61
+ } as never);
62
+ }
63
+
23
64
  export async function handleInboundMessage(inst: BridgeInstance, data: unknown): Promise<void> {
24
65
  const pi = inst.pi;
25
66
  if (!inst.isActive()) return; // Stale listener guard
26
67
  const msg = data as ServerToExtensionMessage;
68
+ // Prompt-rate bound (B21): ONE bucket per bridge PROCESS across every
69
+ // turn-starting command, spent before the command does any work. Keyed by the
70
+ // process-global `shared` state, not the `ConnectionManager`: `/reload` builds a
71
+ // new manager, so a connection key would hand the server a fresh allowance by
72
+ // sending `/reload` itself.
73
+ // See change: harden-bridge-inbound-and-discovery (D17).
74
+ const gated = turnStartingCommand(msg as { type?: unknown; action?: unknown });
75
+ if (gated && !inst.inboundLimits.takePrompt(inst.shared)) {
76
+ refuseOverRate(inst, gated);
77
+ return;
78
+ }
27
79
  // D12: the dashboard asking for a slice of THIS session's transcript.
28
80
  // Guarded before any filesystem touch — a request naming a path, or
29
81
  // another session, never reaches the reader. See change:
@@ -80,9 +132,11 @@ export async function handleInboundMessage(inst: BridgeInstance, data: unknown):
80
132
  if ((msg as any).type === "server_restarting") {
81
133
  const reason = (msg as any).reason;
82
134
  const quiesceMs = (msg as any).quiesceMs;
83
- if (typeof quiesceMs === "number" && quiesceMs > 0) {
84
- inst.connection.pauseAutoStart(quiesceMs);
85
- console.log(`[dashboard] server announced restart (reason=${reason} quiesceMs=${quiesceMs})`);
135
+ // `pauseAutoStart` normalizes + bounds (invalid -> 0 = ignored).
136
+ // See change: harden-bridge-inbound-and-discovery (D17).
137
+ const applied = inst.connection.pauseAutoStart(quiesceMs);
138
+ if (applied > 0) {
139
+ console.log(`[dashboard] server announced restart (reason=${reason} quiesceMs=${applied})`);
86
140
  }
87
141
  return;
88
142
  }
@@ -29,6 +29,7 @@ import type { EmptyActionableGuard } from "../empty-actionable-guard.js";
29
29
  import type { resolveEndpoint } from "../endpoint-resolution.js";
30
30
  import type { createFollowupBuffer } from "../followup-buffer.js";
31
31
  import type { GitTracker } from "../git-tracker.js";
32
+ import type { InboundLimits } from "../inbound-limits.js";
32
33
  import type { ReadFileOutcome } from "../markdown-image-inliner.js";
33
34
  import type { createMcpDashboardRegistrar } from "../mcp-token-delivery.js";
34
35
  import type { MessageUpdateCoalescer } from "../message-update-coalescer.js";
@@ -36,7 +37,6 @@ import type { createPathGate } from "../path-gate/index.js";
36
37
  import type { Suppression } from "../path-gate/suppression.js";
37
38
  import type { PluginForwardRegistry } from "../plugin-event-forward-registry.js";
38
39
  import type { createPluginRequestClient } from "../plugin-request-client.js";
39
- import type { VaultDelivery } from "../vault-delivery.js";
40
40
  import type { PrStatusScheduler } from "../pr-status.js";
41
41
  import type { PromptBus } from "../prompt-bus.js";
42
42
  import type { RetryTracker } from "../retry-tracker.js";
@@ -46,6 +46,7 @@ import type { SubagentTickThrottle } from "../subagent-tick-throttle.js";
46
46
  import type { createTransportDiagnostics } from "../transport-diagnostics.js";
47
47
  import type { UiModulesBridgeCtx } from "../ui-modules.js";
48
48
  import type { UsageDrain } from "../usage-drain.js";
49
+ import type { VaultDelivery } from "../vault-delivery.js";
49
50
 
50
51
  export interface BridgeState {
51
52
  cleanup?: () => void;
@@ -61,6 +62,8 @@ export interface BridgeState {
61
62
  pi?: ExtensionAPI;
62
63
  /** All connection instances from any bridge incarnation (for cleanup) */
63
64
  connections?: ConnectionManager[];
65
+ /** Process-wide inbound limiter (see `BridgeInstance.inboundLimits`). */
66
+ inboundLimits?: InboundLimits;
64
67
  /** All interval timers from any bridge incarnation (for cleanup) */
65
68
  timers?: ReturnType<typeof setInterval>[];
66
69
  /**
@@ -189,6 +192,12 @@ export interface BridgeInstance {
189
192
  vaultDelivery: VaultDelivery;
190
193
  connection: ConnectionManager;
191
194
  commandHandler: ReturnType<typeof createCommandHandler>;
195
+ /**
196
+ * Process-wide inbound bounds (bash concurrency + per-connection prompt
197
+ * bucket); the single instance lives in `shared.inboundLimits` so `/reload`
198
+ * keeps the allowance. See change: harden-bridge-inbound-and-discovery (D17).
199
+ */
200
+ inboundLimits: InboundLimits;
192
201
  syncBc: () => BridgeContext;
193
202
  applyBc: (bc: BridgeContext) => void;
194
203
  /** `liveTailOpen`: keep in-flight tail calls open. See change: fix-replay-fabricates-orphan-end-for-live-calls. */
@@ -6,6 +6,7 @@
6
6
  */
7
7
 
8
8
  import { loadConfig, resolveDashboardPorts } from "@blackbelt-technology/pi-dashboard-shared/config.js";
9
+ import { formatHostPort } from "@blackbelt-technology/pi-dashboard-shared/host-port.js";
9
10
  import { discoverDashboard } from "@blackbelt-technology/pi-dashboard-shared/mdns-discovery.js";
10
11
  import { isDashboardRunning } from "@blackbelt-technology/pi-dashboard-shared/server-identity.js";
11
12
  import { Loader } from "@earendil-works/pi-tui";
@@ -22,22 +23,24 @@ import { bridgeExtensionIdentity } from "../extension-identity.js";
22
23
  import { registerFlowEventListeners } from "../flow-event-wiring.js";
23
24
  import { createGitPollState, runGitPollTick } from "../git-poll.js";
24
25
  import { flipHasUI } from "../hasui-flip.js";
25
- import { healthUrlForInstance, probeEndpointReachability, verifyInstanceIdentity } from "../instance-verification.js";
26
+ import { healthUrlForInstance, verifyInstanceIdentity } from "../instance-verification.js";
26
27
  import { sendPiVersionIfChanged as _sendPiVersionIfChanged } from "../model-tracker.js";
27
28
  import { provisionOpenspecCli } from "../openspec-cli-shim.js";
28
29
  import { pollCost } from "../poll-cost.js";
29
30
  import { collectMetrics, startMetricsMonitor, stopMetricsMonitor } from "../process-metrics.js";
30
31
  import { createProcessScanScheduler } from "../process-scan-scheduler.js";
31
32
  import { scanChildProcessesAsync } from "../process-scanner.js";
32
- import { decideBridgeProjectTrust, readEventCwd } from "../project-trust.js";
33
+ import { decideBridgeProjectTrust, type ProjectTrustDeps, readEventCwd } from "../project-trust.js";
34
+ import { createHttpLiveQuery, isRemoteBridge } from "../project-trust-live.js";
33
35
  import { PromptBus } from "../prompt-bus.js";
34
- import { buildProviderCatalogue, toModelInfo } from "../provider-register.js";
36
+ import { buildProviderCatalogue, reloadProviders, toModelInfo } from "../provider-register.js";
35
37
  import { gateRemoteRegistration, isRemoteEndpoint } from "../remote-registration-gate.js";
36
38
  import { registerRoleModelTools } from "../role-model-tools.js";
37
39
  import { autoStartServer } from "../server-auto-start.js";
38
40
  import { launchServer } from "../server-launcher.js";
39
41
  import { loadServerPins, notePinEndpoint, serverPinsPath } from "../server-pin-store.js";
40
- import { handleSessionChange as _handleSessionChange, consumeSpawnToken, filterByEnabledModels, isLive } from "../session-sync.js";
42
+ import { verifyDiscoveredCandidate } from "../server-proof-probe.js";
43
+ import { handleSessionChange as _handleSessionChange, branchFingerprint, consumeSpawnToken, filterByEnabledModels, isLive } from "../session-sync.js";
41
44
  import { detectSessionSource } from "../source-detector.js";
42
45
  import { consumePendingReloadOnSessionStart, releaseBridgeOwnerOnShutdown, reloadCompletedFeedback } from "../terminal-reload.js";
43
46
  import { refreshUiModules, subscribeUiInvalidate } from "../ui-modules.js";
@@ -45,7 +48,6 @@ import { runUiSafely } from "../ui-stale-guard.js";
45
48
  import { sendShutdownUsageThenUnregister, type UsageDrain } from "../usage-drain.js";
46
49
  import { detectIsGitRepo } from "../vcs-info.js";
47
50
  import { buildVisibilityRegisterFields } from "../visibility-intent.js";
48
- import { formatHostPort } from "@blackbelt-technology/pi-dashboard-shared/host-port.js";
49
51
  import type { BridgeInstance } from "./instance.js";
50
52
  import { patchUiForPromptBus } from "./ui-prompt-patch.js";
51
53
 
@@ -182,23 +184,49 @@ export function registerSessionInfoChanged(inst: BridgeInstance): void {
182
184
  } catch { /* older pi: no session_info_changed — poll fallback covers it */ }
183
185
  }
184
186
 
185
- /** `project_trust`: trust-gate decision for the dashboard-spawned project. */
186
- export function registerProjectTrust(inst: BridgeInstance): void {
187
+ /**
188
+ * `project_trust`: trust-gate decision for the dashboard-spawned project.
189
+ *
190
+ * pi awaits this handler, so it may be asynchronous: on a snapshot miss the
191
+ * decision runs a live trust query bounded by `piTrustMirror.liveQueryTimeoutMs`
192
+ * (default 300 ms local / 1000 ms remote). The body has its own try/catch and
193
+ * every path resolves to `{ trusted: "undecided" }` or a per-run yes — it never
194
+ * relies on `safe()` or pi's runner to contain a failure. A bridge replaced while
195
+ * the query was pending (reload) answers undecided. See change: mirror-dashboard-trust-live-remote.
196
+ */
197
+ export function registerProjectTrust(inst: BridgeInstance, overrides: Partial<ProjectTrustDeps> = {}): void {
187
198
  const pi = inst.pi;
188
199
  try {
189
- pi.on("project_trust" as any, inst.safe((event: any, ctx: any) => {
200
+ pi.on("project_trust" as any, inst.safe(async (event: any, ctx: any) => {
190
201
  // Return the pi trust decision. A newer bridge taking over, or any
191
202
  // non-match, defers. `remember:false` = trust for THIS run only.
192
- if (!inst.isActive()) return { trusted: "undecided" };
193
- const decision = decideBridgeProjectTrust({
194
- dashboardSpawned: inst.dashboardSpawned,
195
- isHeadless: isHeadlessRpcSession(),
196
- eventCwd: readEventCwd(event, ctx),
197
- activationCwd: inst.activationCwd,
198
- });
199
- return decision.trusted === "yes"
200
- ? { trusted: "yes", remember: false }
201
- : { trusted: "undecided" };
203
+ try {
204
+ if (!inst.isActive()) return { trusted: "undecided" };
205
+ const decision = await decideBridgeProjectTrust(
206
+ {
207
+ dashboardSpawned: inst.dashboardSpawned,
208
+ isHeadless: isHeadlessRpcSession(),
209
+ eventCwd: readEventCwd(event, ctx),
210
+ activationCwd: inst.activationCwd,
211
+ },
212
+ {
213
+ isRemoteBridge: () => isRemoteBridge(inst.dashboardUrl),
214
+ liveQuery: createHttpLiveQuery({
215
+ endpoint: () => inst.dashboardUrl,
216
+ httpPort: () => inst.rendezvous?.httpPort,
217
+ env: process.env,
218
+ }),
219
+ ...overrides,
220
+ },
221
+ );
222
+ // The instance may have been replaced while the live query was pending.
223
+ if (!inst.isActive()) return { trusted: "undecided" };
224
+ return decision.trusted === "yes"
225
+ ? { trusted: "yes", remember: false }
226
+ : { trusted: "undecided" };
227
+ } catch {
228
+ return { trusted: "undecided" };
229
+ }
202
230
  }));
203
231
  } catch { /* older pi: no project_trust event — no-op */ }
204
232
  }
@@ -320,6 +348,9 @@ export function registerSessionStart(inst: BridgeInstance): void {
320
348
  // Ctrl+P cycling). Absent on older pi / empty when unscoped → no filter.
321
349
  // See change: update-pi-core-0-83-adopt-apis.
322
350
  getScopedModels: () => (inst.cachedCtx as any)?.scopedModels,
351
+ // Resync from global config before each read.
352
+ // See change: list-models-auto-resync (design D2).
353
+ reloadProviders: () => reloadProviders(pi),
323
354
  });
324
355
 
325
356
  // Extract session file/dir early — needed for source detection and UI proxy
@@ -445,6 +476,7 @@ export function registerSessionStart(inst: BridgeInstance): void {
445
476
  const verdict = await gateRemoteRegistration({
446
477
  endpoint: inst.dashboardUrl,
447
478
  store: loadServerPins(pinsFile),
479
+ env: process.env,
448
480
  });
449
481
  // Task 10.3: the cause is distinguishable in the log, not folded into
450
482
  // a generic connection failure.
@@ -533,12 +565,11 @@ export function registerSessionStart(inst: BridgeInstance): void {
533
565
  inst.lastModel = initialModel;
534
566
  inst.lastThinkingLevel = initialThinkingLevel;
535
567
 
536
- // Include eventCount so server can skip event wipe on reconnect
537
- let eventCount: number | undefined;
538
- try {
539
- const entries = ctx.sessionManager?.getBranch?.();
540
- if (entries) eventCount = entries.length;
541
- } catch { /* ignore */ }
568
+ // Include eventCount (+ leaf id, liveTailOpen) so server can skip event wipe
569
+ // on reconnect. `liveTailOpen` is computed ONCE and shared with the replay
570
+ // below. See change: fix-large-session-resume-replay (D7).
571
+ const { eventCount, leafEntryId } = branchFingerprint(ctx.sessionManager);
572
+ const liveTailOpen = isLive(ctx, inst.shared.isAgentStreaming);
542
573
 
543
574
  // See change: fix-dashboard-source-mislabelling — sent on every
544
575
  // register so server can re-stamp source after restart. Derived from the
@@ -563,6 +594,8 @@ export function registerSessionStart(inst: BridgeInstance): void {
563
594
  sessionDir,
564
595
  firstMessage,
565
596
  eventCount,
597
+ ...(leafEntryId !== undefined ? { leafEntryId } : {}),
598
+ liveTailOpen,
566
599
  // The ONLY channel by which the server learns this session's process for a
567
600
  // non-headless spawn: `tmux new-window` returns tmux's own pid, not pi's,
568
601
  // so without this the server's record has no `pid` and shutdown has
@@ -572,6 +605,8 @@ export function registerSessionStart(inst: BridgeInstance): void {
572
605
  // fresh session, did not.
573
606
  // See change: fix-tmux-session-shutdown-leak (D6).
574
607
  pid: process.pid,
608
+ // See change: prove-vault-bridge-tls (D7).
609
+ ...(inst.connection.certValidation ? { certValidation: "enforced" as const } : {}),
575
610
  // The spawn correlation token, echoed back so the server can match THIS
576
611
  // register to the spawn that produced it. This is a fresh session's FIRST
577
612
  // register, and it omitted the token entirely: tier-1 correlation never
@@ -626,7 +661,7 @@ export function registerSessionStart(inst: BridgeInstance): void {
626
661
  // still running across a `/reload` keeps its in-flight calls open instead
627
662
  // of getting a fabricated `session_ended` end. See change:
628
663
  // fix-replay-fabricates-orphan-end-for-live-calls (D3).
629
- inst.replaySessionEntries({ liveTailOpen: isLive(ctx, inst.shared.isAgentStreaming) });
664
+ inst.replaySessionEntries({ liveTailOpen });
630
665
  inst.connection.send({ type: "replay_complete", sessionId: inst.sessionId });
631
666
  // After replay_complete: inside the replay window the server may drop
632
667
  // forwarded events without insert or broadcast (`skipReplayInsert`).
@@ -829,7 +864,11 @@ export function registerSessionStart(inst: BridgeInstance): void {
829
864
  inst.connection
830
865
  .retargetTo(candidateUrl, {
831
866
  trigger,
832
- verify: () => probeEndpointReachability({ healthUrl }),
867
+ // Reachable AND — when this bridge holds the local token — able to
868
+ // return a valid server counter-proof: a healthy answer is not an
869
+ // identity. A refusal keeps the established connection and is logged
870
+ // with its named cause. See change: harden-bridge-inbound-and-discovery (D19).
871
+ verify: () => verifyDiscoveredCandidate({ healthUrl, candidateUrl }),
833
872
  })
834
873
  .then((accepted) => {
835
874
  console.log(`[dashboard] re-target ${inst.dashboardUrl} -> ${candidateUrl}: ${accepted ? "accepted" : "refused by migration gate"}`);
@@ -16,6 +16,9 @@
16
16
  * See change: add-pi-gateway-transport-identity (D10b).
17
17
  */
18
18
 
19
+ import { TLS_ONLY_TOKEN_UNTRUSTED_CHANNEL } from "@blackbelt-technology/pi-dashboard-shared/tls-only-token.js";
20
+ import { checkTlsCall } from "./bridge-tls-checks.js";
21
+
19
22
  /** Env var carrying a paired-device bearer for the dashboard being dialled. */
20
23
  export const DEVICE_TOKEN_ENV = "PI_DASHBOARD_TOKEN";
21
24
 
@@ -23,7 +26,15 @@ type TicketMintCause =
23
26
  | "no-token"
24
27
  | "unreachable"
25
28
  | "refused"
26
- | "malformed";
29
+ /** The URL answered, but it is not the dashboard's HTTP listener (or is broken). */
30
+ | "wrong-origin"
31
+ | "malformed"
32
+ /** A `pi_tls_` token with a non-`https` origin: refused, no request. See change: prove-vault-bridge-tls (D9). */
33
+ | "tls-only-token"
34
+ /** Certificate validation is disabled in the process: refused, no request. See change: prove-vault-bridge-tls (D7). */
35
+ | "tls-verify-disabled"
36
+ /** The hub refused a `pi_tls_` bearer that reached it over a relaying (TLS-terminating) channel. */
37
+ | "tls-only-token-relayed";
27
38
 
28
39
  export type TicketMintResult =
29
40
  | { ok: true; ticket: string }
@@ -51,7 +62,11 @@ export function readDeviceToken(env: NodeJS.ProcessEnv = process.env): string |
51
62
  export async function mintBridgeTicket(input: {
52
63
  httpBase: string;
53
64
  token: string | undefined;
65
+ /** Where `httpBase` came from (`resolveDashboardHttpOrigin().source`), named in a wrong-origin reason. */
66
+ originSource?: string;
54
67
  fetchImpl?: typeof fetch;
68
+ /** Read per call for the TLS checks; defaults to `process.env`. */
69
+ env?: Record<string, string | undefined>;
55
70
  }): Promise<TicketMintResult> {
56
71
  if (!input.token) {
57
72
  return {
@@ -60,11 +75,25 @@ export async function mintBridgeTicket(input: {
60
75
  reason: `no paired-device bearer: set ${DEVICE_TOKEN_ENV} to a token from this dashboard's pairing flow`,
61
76
  };
62
77
  }
78
+ const refusal = checkTlsCall({ origin: input.httpBase, token: input.token, env: input.env ?? process.env });
79
+ if (refusal) return { ok: false, cause: refusal.cause, reason: refusal.reason };
63
80
  const doFetch = input.fetchImpl ?? fetch;
81
+ const url = `${input.httpBase}/api/ws-ticket`;
82
+ const wrongOrigin = (what: string): TicketMintResult => ({
83
+ ok: false,
84
+ cause: "wrong-origin",
85
+ reason:
86
+ `ticket mint at ${url} ${what}` +
87
+ `${input.originSource ? ` (origin from ${input.originSource})` : ""} — ` +
88
+ "if this is not the dashboard's HTTP address, set PI_DASHBOARD_HTTP_URL; if it is, check the server log",
89
+ });
64
90
  let res: Response;
65
91
  try {
66
- res = await doFetch(`${input.httpBase}/api/ws-ticket`, {
92
+ res = await doFetch(url, {
67
93
  method: "POST",
94
+ // Never follow a redirect: it would re-send the bearer to a URL the
95
+ // operator did not configure.
96
+ redirect: "error",
68
97
  headers: {
69
98
  "Content-Type": "application/json",
70
99
  Authorization: `Bearer ${input.token}`,
@@ -72,14 +101,29 @@ export async function mintBridgeTicket(input: {
72
101
  body: JSON.stringify({ scope: "bridge" }),
73
102
  });
74
103
  } catch (err) {
104
+ // `redirect: "error"` surfaces as a TypeError whose cause names the redirect.
105
+ const detail = `${(err as Error).message} ${((err as { cause?: { message?: string } }).cause?.message) ?? ""}`;
106
+ if (/redirect/i.test(detail)) return wrongOrigin("answered with a redirect");
75
107
  return { ok: false, cause: "unreachable", reason: `ticket mint failed: ${(err as Error).message}` };
76
108
  }
77
109
  if (!res.ok) {
78
- return {
79
- ok: false,
80
- cause: "refused",
81
- reason: `ticket mint refused with HTTP ${res.status} — the bearer may be unpaired or revoked`,
82
- };
110
+ if (res.status === 401 && (await isRelayedTlsOnlyRefusal(res))) {
111
+ return {
112
+ ok: false,
113
+ cause: "tls-only-token-relayed",
114
+ reason:
115
+ `ticket mint at ${url} was answered 401 ${TLS_ONLY_TOKEN_UNTRUSTED_CHANNEL}: the https origin is a TLS-terminating ` +
116
+ "tunnel or proxy, not the dashboard's own HTTPS listener — point PI_DASHBOARD_HTTP_URL at the dashboard's native HTTPS address",
117
+ };
118
+ }
119
+ if (res.status === 401 || res.status === 403) {
120
+ return {
121
+ ok: false,
122
+ cause: "refused",
123
+ reason: `ticket mint refused with HTTP ${res.status} — the bearer may be unpaired or revoked`,
124
+ };
125
+ }
126
+ return wrongOrigin(`answered HTTP ${res.status}`);
83
127
  }
84
128
  let body: unknown;
85
129
  try {
@@ -94,6 +138,16 @@ export async function mintBridgeTicket(input: {
94
138
  return { ok: true, ticket };
95
139
  }
96
140
 
141
+ /** Does a 401 body carry the hub's `tls_only_token_untrusted_channel` error? Never throws. */
142
+ async function isRelayedTlsOnlyRefusal(res: Response): Promise<boolean> {
143
+ try {
144
+ const body = (await res.json()) as { error?: unknown } | null;
145
+ return body?.error === TLS_ONLY_TOKEN_UNTRUSTED_CHANNEL;
146
+ } catch {
147
+ return false;
148
+ }
149
+ }
150
+
97
151
  /**
98
152
  * Carry the ticket on the upgrade URL. The gateway also accepts it via
99
153
  * `sec-websocket-protocol`; the query form is used because it survives the
@@ -0,0 +1,79 @@
1
+ /**
2
+ * The per-call TLS checks a REMOTE bridge runs before every credential call
3
+ * (ticket mint, identity challenge, live trust query) and dial, plus the
4
+ * `certValidation` declaration that follows from them.
5
+ *
6
+ * Order (the caller runs `bad-http-url` first, in `resolveDashboardHttpOrigin`):
7
+ * 2. `tls-only-token` — a `pi_tls_` token to a non-`https` origin
8
+ * 3. `tls-verify-disabled` — `NODE_TLS_REJECT_UNAUTHORIZED=0`, TLS only
9
+ * A refusal means: no bearer is sent and nothing is dialled. `env` is read per
10
+ * call, so a variable flipped at runtime is caught on the next reconnect.
11
+ * Plain `ws`/`http` stays untouched for plain tokens.
12
+ *
13
+ * See change: prove-vault-bridge-tls (D7, D9).
14
+ */
15
+ import { TLS_VERIFY_ENV, tlsVerifyDisabled } from "@blackbelt-technology/pi-dashboard-shared/server-pinning.js";
16
+ import { isTlsOnlyToken } from "@blackbelt-technology/pi-dashboard-shared/tls-only-token.js";
17
+ import { isRemoteEndpoint } from "./remote-registration-gate.js";
18
+
19
+ type TlsRefusalCause = "tls-only-token" | "tls-verify-disabled";
20
+
21
+ export interface TlsRefusal {
22
+ cause: TlsRefusalCause;
23
+ reason: string;
24
+ }
25
+
26
+ function protocolOf(url: string | undefined): string | undefined {
27
+ if (!url) return undefined;
28
+ try {
29
+ return new URL(url).protocol;
30
+ } catch {
31
+ return undefined;
32
+ }
33
+ }
34
+
35
+ /**
36
+ * Check one remote call.
37
+ * - `origin`: the HTTP origin the bearer would go to (absent for a pure dial check).
38
+ * - `token`: the bearer that call would carry.
39
+ * - `dialUrl`: the gateway URL dialled afterwards; a `wss:` dial is a TLS use too.
40
+ */
41
+ export function checkTlsCall(input: {
42
+ origin?: string;
43
+ token?: string;
44
+ dialUrl?: string;
45
+ env: Record<string, string | undefined>;
46
+ }): TlsRefusal | undefined {
47
+ const originProto = protocolOf(input.origin);
48
+ if (input.token !== undefined && isTlsOnlyToken(input.token) && originProto !== "https:") {
49
+ return {
50
+ cause: "tls-only-token",
51
+ reason:
52
+ `a pi_tls_ token is never sent to a non-https origin (${input.origin ?? "none"}) — ` +
53
+ "use a wss:// PI_DASHBOARD_URL, or set PI_DASHBOARD_HTTP_URL to an https:// origin",
54
+ };
55
+ }
56
+ const usesTls = originProto === "https:" || protocolOf(input.dialUrl) === "wss:";
57
+ if (usesTls && tlsVerifyDisabled(input.env)) {
58
+ return {
59
+ cause: "tls-verify-disabled",
60
+ reason:
61
+ `${TLS_VERIFY_ENV}=0 disables certificate validation, so no bearer is sent and nothing is dialled — ` +
62
+ "unset it and trust a private CA with NODE_EXTRA_CA_CERTS",
63
+ };
64
+ }
65
+ return undefined;
66
+ }
67
+
68
+ /**
69
+ * `"enforced"` when this bridge applied the TLS checks to a connection on
70
+ * `endpoint`: a remote `wss:` endpoint with validation not disabled. Plain `ws`,
71
+ * loopback and the local socket never declare it.
72
+ */
73
+ export function certValidationFor(
74
+ endpoint: string,
75
+ env: Record<string, string | undefined> = process.env,
76
+ ): "enforced" | undefined {
77
+ if (protocolOf(endpoint) !== "wss:" || !isRemoteEndpoint(endpoint)) return undefined;
78
+ return tlsVerifyDisabled(env) ? undefined : "enforced";
79
+ }