@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,138 @@
1
+ /**
2
+ * Bounds on what the dashboard server (or anything holding a bridge socket)
3
+ * can make this bridge do per unit time:
4
+ *
5
+ * - concurrent shell commands per session (`!`, `!!`, exec slash templates);
6
+ * - the rate of turn-starting inbound commands per bridge process (token bucket).
7
+ *
8
+ * The bash bound limits concurrent EXECUTIONS the bridge awaits (backpressure);
9
+ * it is not a sandbox — `cmd &` returns at once. Anyone who can send `!` can already exec.
10
+ *
11
+ * Both are env-configurable; an invalid value falls back to the default and is
12
+ * logged exactly once per variable per limiter (one limiter per bridge process,
13
+ * so never per message). `0` is NOT "unlimited" — it is invalid.
14
+ *
15
+ * The bucket is keyed by an object the CALLER chooses: the bridge passes its
16
+ * process-global state, so neither a WebSocket reconnect nor a `/reload` (new
17
+ * manager, same process) refills it, while two keys are independent. Buckets
18
+ * are weakly held: a retired key leaks nothing.
19
+ *
20
+ * No module-level mutable state — the bridge holds the single instance in its
21
+ * process-global `BridgeState`, so `/reload` keeps the allowance.
22
+ *
23
+ * See change: harden-bridge-inbound-and-discovery (D17).
24
+ */
25
+
26
+ /** Concurrent bash commands in flight per session. */
27
+ export const DEFAULT_MAX_BASH = 4;
28
+ /** Prompt bucket: burst capacity. */
29
+ export const DEFAULT_PROMPT_BURST = 30;
30
+ /** Prompt bucket: tokens refilled per second. */
31
+ export const DEFAULT_PROMPT_REFILL_PER_SEC = 10;
32
+
33
+ const MAX_BASH_ENV = "PI_DASHBOARD_BRIDGE_MAX_BASH";
34
+ const PROMPT_RATE_ENV = "PI_DASHBOARD_BRIDGE_PROMPT_RATE";
35
+
36
+ const POSITIVE_INT = /^[1-9]\d*$/;
37
+ const RATE = /^([1-9]\d*)\/([1-9]\d*)$/;
38
+
39
+ export interface InboundLimitsOptions {
40
+ env?: NodeJS.ProcessEnv;
41
+ /** Clock in ms; fractional ok. Defaults to `Date.now`. */
42
+ now?: () => number;
43
+ /** Sink for the once-per-variable "invalid value" line. Defaults to `console.warn`. */
44
+ log?: (line: string) => void;
45
+ }
46
+
47
+ export interface InboundLimits {
48
+ readonly maxBash: number;
49
+ readonly promptBurst: number;
50
+ readonly promptRefillPerSec: number;
51
+ /**
52
+ * Take one slot for a shell command in `sessionId`. Returns the release
53
+ * function (idempotent), or `undefined` when the session is at its limit.
54
+ */
55
+ tryAcquireBash(sessionId: string): (() => void) | undefined;
56
+ /** Spend one token of `key`'s bucket. `false` = refused. */
57
+ takePrompt(key: object): boolean;
58
+ /** In-flight shell commands for a session (tests / diagnostics). */
59
+ bashInFlight(sessionId: string): number;
60
+ }
61
+
62
+ function parseMaxBash(raw: string | undefined, warn: (name: string, detail: string) => void): number {
63
+ if (raw === undefined) return DEFAULT_MAX_BASH;
64
+ if (POSITIVE_INT.test(raw)) return Number(raw);
65
+ warn(MAX_BASH_ENV, `expected a positive integer, got ${JSON.stringify(raw)}; using ${DEFAULT_MAX_BASH}`);
66
+ return DEFAULT_MAX_BASH;
67
+ }
68
+
69
+ function parsePromptRate(
70
+ raw: string | undefined,
71
+ warn: (name: string, detail: string) => void,
72
+ ): { burst: number; refill: number } {
73
+ const fallback = { burst: DEFAULT_PROMPT_BURST, refill: DEFAULT_PROMPT_REFILL_PER_SEC };
74
+ if (raw === undefined) return fallback;
75
+ const m = RATE.exec(raw);
76
+ if (m) return { burst: Number(m[1]), refill: Number(m[2]) };
77
+ warn(
78
+ PROMPT_RATE_ENV,
79
+ `expected "<burst>/<refillPerSec>" (positive integers), got ${JSON.stringify(raw)}; using ${DEFAULT_PROMPT_BURST}/${DEFAULT_PROMPT_REFILL_PER_SEC}`,
80
+ );
81
+ return fallback;
82
+ }
83
+
84
+ export function createInboundLimits(opts: InboundLimitsOptions = {}): InboundLimits {
85
+ const env = opts.env ?? process.env;
86
+ const now = opts.now ?? Date.now;
87
+ const log = opts.log ?? ((line: string) => console.warn(line));
88
+ const warned = new Set<string>();
89
+ const warn = (name: string, detail: string): void => {
90
+ if (warned.has(name)) return;
91
+ warned.add(name);
92
+ log(`[dashboard] ${name}: ${detail}`);
93
+ };
94
+
95
+ const maxBash = parseMaxBash(env[MAX_BASH_ENV], warn);
96
+ const rate = parsePromptRate(env[PROMPT_RATE_ENV], warn);
97
+
98
+ const bash = new Map<string, number>();
99
+ const buckets = new WeakMap<object, { tokens: number; at: number }>();
100
+
101
+ return {
102
+ maxBash,
103
+ promptBurst: rate.burst,
104
+ promptRefillPerSec: rate.refill,
105
+
106
+ tryAcquireBash(sessionId) {
107
+ const n = bash.get(sessionId) ?? 0;
108
+ if (n >= maxBash) return undefined;
109
+ bash.set(sessionId, n + 1);
110
+ let released = false;
111
+ return () => {
112
+ if (released) return;
113
+ released = true;
114
+ const cur = (bash.get(sessionId) ?? 1) - 1;
115
+ if (cur <= 0) bash.delete(sessionId);
116
+ else bash.set(sessionId, cur);
117
+ };
118
+ },
119
+
120
+ takePrompt(key) {
121
+ const t = now();
122
+ let b = buckets.get(key);
123
+ if (!b) {
124
+ b = { tokens: rate.burst, at: t };
125
+ buckets.set(key, b);
126
+ } else {
127
+ const elapsed = Math.max(0, t - b.at);
128
+ b.tokens = Math.min(rate.burst, b.tokens + (elapsed * rate.refill) / 1000);
129
+ b.at = t;
130
+ }
131
+ if (b.tokens < 1) return false;
132
+ b.tokens -= 1;
133
+ return true;
134
+ },
135
+
136
+ bashInFlight: (sessionId) => bash.get(sessionId) ?? 0,
137
+ };
138
+ }
@@ -21,11 +21,13 @@
21
21
  * unix socket it is redundant, and to a remote endpoint it would be a leak — the
22
22
  * remote path authenticates with a ticket and a pinned identity instead.
23
23
  *
24
- * See change: add-pi-gateway-transport-identity (D6); loopback-credential-proof (D1, D6, D7).
24
+ * See change: add-pi-gateway-transport-identity (D6); loopback-credential-proof (D1, D6, D7);
25
+ * harden-bridge-inbound-and-discovery (D19).
25
26
  */
26
27
  import fs from "node:fs";
27
28
  import net from "node:net";
28
29
  import path from "node:path";
30
+ import tls from "node:tls";
29
31
  import { getDashboardConfigDir } from "@blackbelt-technology/pi-dashboard-shared/dashboard-paths.js";
30
32
  import {
31
33
  BRIDGE_PURPOSE,
@@ -41,6 +43,40 @@ import type { DialPlan } from "./connection.js";
41
43
 
42
44
  const CONNECT_TIMEOUT_MS = 10_000;
43
45
 
46
+ /**
47
+ * Explicit opt-out of the loopback server counter-proof, for a same-host server
48
+ * older than 0.10.0 (which cannot answer one). Exactly `"1"` — `0`, `true`, the
49
+ * empty string and every other value do NOT opt out. Deliberately not
50
+ * `PI_DASHBOARD_REQUIRE_SERVER_PROOF`: that marker is overwritten by the spawner
51
+ * and any non-empty value (`"0"` included) enforces.
52
+ */
53
+ export const ALLOW_UNPROVEN_LOCAL_SERVER_ENV = "PI_DASHBOARD_ALLOW_UNPROVEN_LOCAL_SERVER";
54
+
55
+ /** `ws.WebSocket`-style cause names as logged (`server_proof_missing`), from the internal `server-proof-missing`. */
56
+ export function proofFailureLogCause(cause: string): string {
57
+ return cause.replace(/-/g, "_");
58
+ }
59
+
60
+ /**
61
+ * Must THIS dial be verified with a server counter-proof?
62
+ *
63
+ * - `ws+unix:` → never (filesystem permissions are the credential);
64
+ * - token held → always, unless the explicit opt-out is set (independent of the spawn marker);
65
+ * - no token → only a marked dial, which then fails closed (there is nothing to verify against).
66
+ *
67
+ * The caller has already established the dial is loopback.
68
+ */
69
+ export function requiresServerProof(input: {
70
+ endpoint: string;
71
+ tokenHeld: boolean;
72
+ optOut: boolean;
73
+ marker: string | undefined;
74
+ }): boolean {
75
+ if (input.endpoint.startsWith("ws+unix:")) return false;
76
+ if (input.tokenHeld) return !input.optOut;
77
+ return markerEnforces(input.marker, input.endpoint);
78
+ }
79
+
44
80
  /** Read this HOME's local token, or `undefined` when there is none to present. */
45
81
  export function readLocalToken(env?: { homedir?: string }): string | undefined {
46
82
  try {
@@ -109,6 +145,26 @@ function defaultConnect(host: string, port: number): Promise<net.Socket> {
109
145
  });
110
146
  }
111
147
 
148
+ /** Open a TLS connection ourselves (loopback `wss:`), certificate verification left at Node's default. */
149
+ function defaultConnectTls(host: string, port: number): Promise<net.Socket> {
150
+ return new Promise((resolve, reject) => {
151
+ const socket = tls.connect({ host, port, servername: net.isIP(host) ? undefined : host });
152
+ const timer = setTimeout(() => {
153
+ socket.destroy();
154
+ reject(new Error(`TLS connect to ${host}:${port} timed out`));
155
+ }, CONNECT_TIMEOUT_MS);
156
+ socket.once("secureConnect", () => {
157
+ clearTimeout(timer);
158
+ socket.removeAllListeners("error");
159
+ resolve(socket);
160
+ });
161
+ socket.once("error", (err) => {
162
+ clearTimeout(timer);
163
+ reject(err);
164
+ });
165
+ });
166
+ }
167
+
112
168
  export interface LocalCredentialPlanDeps {
113
169
  /** HOME override for the token location. */
114
170
  env?: { homedir?: string };
@@ -116,6 +172,12 @@ export interface LocalCredentialPlanDeps {
116
172
  marker?: string | undefined;
117
173
  /** Injectable TCP connector (default `net.connect`). */
118
174
  connect?: (host: string, port: number) => Promise<net.Socket>;
175
+ /** Injectable TLS connector for a loopback `wss:` dial (default `tls.connect`). */
176
+ connectTls?: (host: string, port: number) => Promise<net.Socket>;
177
+ /** Opt-out value; defaults to `process.env.PI_DASHBOARD_ALLOW_UNPROVEN_LOCAL_SERVER`. */
178
+ allowUnproven?: string | undefined;
179
+ /** Sink for the "proof skipped" line (default `console.log`). */
180
+ log?: (line: string) => void;
119
181
  /** Injectable clock / nonce for tests. */
120
182
  now?: () => number;
121
183
  nonce?: () => string;
@@ -123,7 +185,7 @@ export interface LocalCredentialPlanDeps {
123
185
 
124
186
  /**
125
187
  * The dial plan for `endpoint`, or `undefined` when it gets no local credential
126
- * (unix socket, remote endpoint, TLS, or no token and no marker). Fresh on every
188
+ * (unix socket, remote endpoint, or no token and no marker). Fresh on every
127
189
  * call: each dial carries its own timestamp and nonce.
128
190
  */
129
191
  export async function localCredentialPlan(
@@ -136,15 +198,24 @@ export async function localCredentialPlan(
136
198
  // the spawner uses to mark an endpoint, so a marked `127.0.0.5` dial still gets a
137
199
  // proof and server verification (`isRemoteEndpoint` only knows 127.0.0.1).
138
200
  if (!target || !(target.host === "localhost" || isLoopbackLiteral(target.host))) return undefined;
139
- // `createConnection` hands `ws` a plain socket, so only a cleartext dial qualifies.
140
- if (new URL(endpoint).protocol !== "ws:") return undefined;
201
+ // `ws:` is dialled over a plain socket we open ourselves, `wss:` over a TLS socket:
202
+ // either way the proof binds to the address actually reached. Anything else has no plan.
203
+ const protocol = new URL(endpoint).protocol;
204
+ if (protocol !== "ws:" && protocol !== "wss:") return undefined;
141
205
 
142
206
  const marker = "marker" in deps ? deps.marker : process.env[REQUIRE_SERVER_PROOF_ENV];
143
- const enforce = markerEnforces(marker, endpoint);
144
207
  const token = readLocalToken(deps.env);
208
+ const optOut = ("allowUnproven" in deps ? deps.allowUnproven : process.env[ALLOW_UNPROVEN_LOCAL_SERVER_ENV]) === "1";
209
+ const enforce = requiresServerProof({ endpoint, tokenHeld: token !== undefined, optOut, marker });
145
210
  if (!token && !enforce) return undefined;
211
+ if (token && optOut) {
212
+ (deps.log ?? ((line: string) => console.log(line)))(
213
+ `[dashboard] ${ALLOW_UNPROVEN_LOCAL_SERVER_ENV}=1: skipping server counter-proof for ${endpoint}`,
214
+ );
215
+ }
146
216
 
147
- const socket = await (deps.connect ?? defaultConnect)(target.host, target.port);
217
+ const connect = protocol === "wss:" ? (deps.connectTls ?? defaultConnectTls) : (deps.connect ?? defaultConnect);
218
+ const socket = await connect(target.host, target.port);
148
219
  let binding: string;
149
220
  try {
150
221
  if (!socket.remoteAddress || socket.remotePort === undefined) throw new Error("socket has no remote address");
@@ -112,3 +112,72 @@ export async function refreshAfterCredentialsReload(
112
112
  ? reportRefresh(registry?.refresh?.({ providers: touched }), `credentials reload refresh (${touched.join(", ")})`)
113
113
  : reportRefresh(registry?.refresh?.({ allowNetwork: false }), "credentials reload refresh (full, local)");
114
114
  }
115
+
116
+ /**
117
+ * Bound on the providers.json re-apply `list_models` runs before its local
118
+ * refresh. When hit, discovery continues in the background on `reloadChain`.
119
+ * See change: list-models-auto-resync (design D1).
120
+ */
121
+ export const PROVIDERS_RESYNC_TIMEOUT_MS = 5_000;
122
+
123
+ /**
124
+ * Resync the in-process registry from global config before `list_models`
125
+ * reads it: (1) bounded, signal-aware `reloadProviders` re-apply; (2) skip if
126
+ * aborted; (3) local `refresh({allowNetwork:false})` bounded by
127
+ * `REFRESH_TIMEOUT_MS`. The signal is never passed into `refresh` — aborting a
128
+ * shared full refresh would supersede a concurrent `request_models` pass; the
129
+ * caller stops waiting by racing the signal instead. Never rejects.
130
+ * See change: list-models-auto-resync (design D1).
131
+ */
132
+ export async function resyncForListModels(
133
+ registry: { refresh?: (opts: object) => Promise<ModelsRefreshResultLike | undefined> },
134
+ opts: { reloadProviders?: () => Promise<unknown>; signal?: AbortSignal } = {},
135
+ ): Promise<ModelsRefreshResultLike | undefined> {
136
+ const { reloadProviders, signal } = opts;
137
+ if (reloadProviders) {
138
+ let timer: ReturnType<typeof setTimeout> | undefined;
139
+ let onAbort: (() => void) | undefined;
140
+ try {
141
+ const pending = Promise.resolve().then(reloadProviders);
142
+ pending.catch(() => {});
143
+ const TIMED_OUT = Symbol("resync-timeout");
144
+ const outcome = await Promise.race([
145
+ pending,
146
+ new Promise<typeof TIMED_OUT>((resolve) => {
147
+ timer = setTimeout(() => resolve(TIMED_OUT), PROVIDERS_RESYNC_TIMEOUT_MS);
148
+ }),
149
+ new Promise<void>((resolve) => {
150
+ if (!signal) return;
151
+ onAbort = () => resolve();
152
+ if (signal.aborted) resolve();
153
+ else signal.addEventListener("abort", onAbort, { once: true });
154
+ }),
155
+ ]);
156
+ if (outcome === TIMED_OUT) {
157
+ console.warn(`[dashboard] list_models providers re-sync timed out after ${PROVIDERS_RESYNC_TIMEOUT_MS}ms — continuing`);
158
+ }
159
+ } catch (err) {
160
+ console.warn("[dashboard] list_models providers re-sync failed:", errText(err));
161
+ } finally {
162
+ if (timer) clearTimeout(timer);
163
+ if (onAbort) signal?.removeEventListener("abort", onAbort);
164
+ }
165
+ }
166
+ if (signal?.aborted) return undefined;
167
+ let pending: Promise<ModelsRefreshResultLike | undefined> | undefined;
168
+ try {
169
+ pending = registry.refresh?.({ allowNetwork: false });
170
+ } catch (err) {
171
+ console.warn("[dashboard] list_models refresh threw:", errText(err));
172
+ return undefined;
173
+ }
174
+ return reportRefresh(pending, "list_models refresh");
175
+ }
176
+
177
+ /** Map a refresh result to `{provider,message}[]`; `[]` when aborted or absent. */
178
+ export function toRefreshErrors(
179
+ result: ModelsRefreshResultLike | undefined,
180
+ ): { provider: string; message: string }[] {
181
+ if (!result || result.aborted || !result.errors) return [];
182
+ return [...result.errors].map(([provider, err]) => ({ provider, message: errText(err) }));
183
+ }
@@ -0,0 +1,44 @@
1
+ /**
2
+ * "Is this endpoint one the operator pinned?" — the gate in front of the
3
+ * paired-device bearer.
4
+ *
5
+ * Pinned means canonical `host:port` EQUALITY with the configured endpoint or
6
+ * with a pin-store entry's `lastEndpoint`. Canonical = lowercase host, no
7
+ * trailing dot, bracketed-IPv6-insensitive, scheme-default port applied.
8
+ *
9
+ * Deliberately NOT `resolvePinForEndpoint`: that falls back to "the sole pin"
10
+ * for ANY endpoint, so one stored pin would make every discovered host look
11
+ * pinned and hand it the bearer. A discovery-only host is unpinned.
12
+ *
13
+ * See change: harden-bridge-inbound-and-discovery (D19).
14
+ */
15
+ import { normalizeHostKey } from "@blackbelt-technology/pi-dashboard-shared/host-port.js";
16
+ import type { ServerPinStore } from "./server-pin-store.js";
17
+
18
+ const DEFAULT_PORTS: Record<string, number> = { "ws:": 80, "wss:": 443, "http:": 80, "https:": 443 };
19
+
20
+ /** Canonical `host:port` key for an endpoint (`ws://h:9`, `h:9`, `[::1]:9`), or `undefined` if unparseable. */
21
+ export function canonicalEndpointKey(endpoint: string): string | undefined {
22
+ const raw = endpoint.trim();
23
+ if (!raw) return undefined;
24
+ try {
25
+ const u = new URL(/^[a-z][a-z0-9+.-]*:\/\//i.test(raw) ? raw : `ws://${raw}`);
26
+ const port = u.port ? Number(u.port) : DEFAULT_PORTS[u.protocol];
27
+ if (port === undefined) return undefined;
28
+ const host = normalizeHostKey(u.hostname);
29
+ if (!host) return undefined;
30
+ return `${host.includes(":") ? `[${host}]` : host}:${port}`;
31
+ } catch {
32
+ return undefined;
33
+ }
34
+ }
35
+
36
+ export function isPinnedEndpoint(
37
+ endpoint: string,
38
+ known: { configured: ReadonlyArray<string | undefined>; pins: ServerPinStore },
39
+ ): boolean {
40
+ const key = canonicalEndpointKey(endpoint);
41
+ if (!key) return false;
42
+ const candidates = [...known.configured, ...known.pins.servers.map((s) => s.lastEndpoint)];
43
+ return candidates.some((c) => c !== undefined && canonicalEndpointKey(c) === key);
44
+ }
@@ -0,0 +1,143 @@
1
+ /**
2
+ * The bridge's side of the live trust query: how it asks, and which bridges are
3
+ * "remote".
4
+ *
5
+ * One authenticated one-shot `POST /api/pi-trust/query` (the gateway WebSocket is
6
+ * not open at the first `project_trust`). Credential, by bridge kind:
7
+ * - local: a freshly minted, endpoint-bound `X-Pi-Local-Proof` (never the raw token);
8
+ * - remote: `Authorization: Bearer <PI_DASHBOARD_TOKEN>`, the same paired-device
9
+ * bearer a remote bridge already uses to mint its gateway ticket.
10
+ * Redirects are never followed. The caller owns the deadline: it passes an
11
+ * `AbortSignal` that also covers the response body.
12
+ *
13
+ * Pure transport — it maps nothing to trust. `project-trust.ts` maps the outcome.
14
+ *
15
+ * See change: mirror-dashboard-trust-live-remote (D1, D2), fix-remote-bridge-ticket-origin (D2, D4).
16
+ */
17
+ import { loadConfig } from "@blackbelt-technology/pi-dashboard-shared/config.js";
18
+ import { httpProofHeaders, localDialHost } from "@blackbelt-technology/pi-dashboard-shared/local-credential-proof.js";
19
+ import { isLoopbackEndpoint } from "@blackbelt-technology/pi-dashboard-shared/loopback-host.js";
20
+ import { PI_TRUST_QUERY_PATH } from "@blackbelt-technology/pi-dashboard-shared/pi-trust-live-query.js";
21
+ import { readDeviceToken } from "./bridge-ticket-client.js";
22
+ import { checkTlsCall } from "./bridge-tls-checks.js";
23
+ import { readLocalToken } from "./local-token-header.js";
24
+ import { resolveDashboardHttpOrigin } from "./dashboard-http-origin.js";
25
+
26
+ /** What the transport saw. Mapping to reason codes is the decision's job. */
27
+ export type LiveQueryResult =
28
+ | { kind: "response"; status: number; body: unknown }
29
+ /** No TCP connection (refused, DNS, reset, …). */
30
+ | { kind: "unreachable" }
31
+ /** Anything else that went wrong before a usable response (redirect, protocol error). */
32
+ | { kind: "error" };
33
+
34
+ export type LiveQueryFn = (req: { cwdKey: string; remote: boolean; signal: AbortSignal }) => Promise<LiveQueryResult>;
35
+
36
+ /**
37
+ * A remote bridge: its resolved dashboard endpoint is not loopback (`localhost`
38
+ * counts as loopback) and a paired-device token is present — the same predicate
39
+ * under which `prepareRemoteUpgrade` mints a gateway ticket.
40
+ */
41
+ export function isRemoteBridge(endpoint: string, env: NodeJS.ProcessEnv = process.env): boolean {
42
+ return !isLoopbackEndpoint(endpoint) && readDeviceToken(env) !== undefined;
43
+ }
44
+
45
+ export interface HttpLiveQueryDeps {
46
+ /** The bridge's resolved dashboard (gateway) endpoint, read per call (it can be re-targeted). */
47
+ endpoint: () => string;
48
+ /** HTTP port of a discovered local instance (rendezvous), when known. */
49
+ httpPort?: () => number | undefined;
50
+ fetchImpl?: typeof fetch;
51
+ env?: NodeJS.ProcessEnv;
52
+ }
53
+
54
+ const CONNECTION_CODES = new Set([
55
+ "ECONNREFUSED",
56
+ "ECONNRESET",
57
+ "ENOTFOUND",
58
+ "EHOSTUNREACH",
59
+ "ENETUNREACH",
60
+ "ETIMEDOUT",
61
+ "EAI_AGAIN",
62
+ "UND_ERR_CONNECT_TIMEOUT",
63
+ "UND_ERR_SOCKET",
64
+ ]);
65
+
66
+ function failureKind(err: unknown): "unreachable" | "error" {
67
+ const cause = (err as { cause?: { code?: unknown; message?: unknown } } | null)?.cause;
68
+ const code = typeof cause?.code === "string" ? cause.code : undefined;
69
+ if (code && CONNECTION_CODES.has(code)) return "unreachable";
70
+ // An AggregateError (Happy Eyeballs, several addresses) carries the codes one level down.
71
+ const nested = (cause as { errors?: unknown[] } | undefined)?.errors;
72
+ if (Array.isArray(nested) && nested.some((e) => CONNECTION_CODES.has((e as { code?: string })?.code ?? ""))) return "unreachable";
73
+ return "error";
74
+ }
75
+
76
+ type Prepared = { url: string; headers: Record<string, string> } | { early: LiveQueryResult };
77
+
78
+ /** URL + credential for this bridge kind, or an answer that needs no round trip. */
79
+ function prepareRequest(deps: HttpLiveQueryDeps, remote: boolean, loggedCauses: Set<string>): Prepared {
80
+ const headers: Record<string, string> = { "content-type": "application/json" };
81
+ if (remote) {
82
+ const endpoint = deps.endpoint();
83
+ const origin = resolveDashboardHttpOrigin(endpoint, deps.env ?? process.env);
84
+ if (!origin.ok) {
85
+ // Fails silently otherwise: say why, once per distinct cause.
86
+ if (!loggedCauses.has(origin.cause)) {
87
+ loggedCauses.add(origin.cause);
88
+ console.error(`[dashboard] live trust query ${origin.cause}: ${origin.reason}`);
89
+ }
90
+ return { early: { kind: "error" } };
91
+ }
92
+ const token = readDeviceToken(deps.env);
93
+ if (!token) return { early: { kind: "error" } };
94
+ // `tls-only-token` / `tls-verify-disabled`: no bearer leaves, once per cause.
95
+ // See change: prove-vault-bridge-tls (D7, D9).
96
+ const refusal = checkTlsCall({ origin: origin.origin, token, env: deps.env ?? process.env });
97
+ if (refusal) {
98
+ if (!loggedCauses.has(refusal.cause)) {
99
+ loggedCauses.add(refusal.cause);
100
+ console.error(`[dashboard] live trust query ${refusal.cause}: ${refusal.reason}`);
101
+ }
102
+ return { early: { kind: "error" } };
103
+ }
104
+ headers.authorization = `Bearer ${token}`;
105
+ return { url: `${origin.origin}${PI_TRUST_QUERY_PATH}`, headers };
106
+ }
107
+ const cfg = loadConfig();
108
+ const url = `http://${localDialHost(cfg.bindHost)}:${deps.httpPort?.() ?? cfg.port}${PI_TRUST_QUERY_PATH}`;
109
+ const token = readLocalToken();
110
+ // No local token ⇒ nothing to prove with; the server would refuse. Say so without a round trip.
111
+ if (!token) return { early: { kind: "response", status: 401, body: undefined } };
112
+ Object.assign(headers, httpProofHeaders(token, url, "POST"));
113
+ return { url, headers };
114
+ }
115
+
116
+ /** The real transport. Never throws. */
117
+ export function createHttpLiveQuery(deps: HttpLiveQueryDeps): LiveQueryFn {
118
+ const doFetch = deps.fetchImpl ?? fetch;
119
+ const loggedCauses = new Set<string>();
120
+ return async ({ cwdKey, remote, signal }) => {
121
+ try {
122
+ const prepared = prepareRequest(deps, remote, loggedCauses);
123
+ if ("early" in prepared) return prepared.early;
124
+ const res = await doFetch(prepared.url, {
125
+ method: "POST",
126
+ headers: prepared.headers,
127
+ body: JSON.stringify({ cwd: cwdKey }),
128
+ redirect: "error",
129
+ signal,
130
+ });
131
+ let body: unknown;
132
+ try {
133
+ body = res.status === 200 ? await res.json() : undefined;
134
+ } catch {
135
+ body = undefined;
136
+ }
137
+ return { kind: "response", status: res.status, body };
138
+ } catch (err) {
139
+ if (signal.aborted) return { kind: "error" };
140
+ return { kind: failureKind(err) };
141
+ }
142
+ };
143
+ }