@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
@@ -20,18 +20,24 @@ import crypto from "node:crypto";
20
20
  import type { Principal } from "@blackbelt-technology/pi-dashboard-shared/identity.js";
21
21
  import type { Tier } from "@blackbelt-technology/pi-dashboard-shared/tiers.js";
22
22
  import type { TokenPayload } from "../auth/auth.js";
23
+ import { isLocallyTrusted } from "../auth/localhost-guard.js";
24
+ import { CAPABILITY_SEGMENT, redactCapability } from "./capability-redact.js";
23
25
 
24
26
  // Lifetime note: a capability's life is bounded by its own idle/absolute limits and
25
27
  // by revocation (target removed, device revoked, logout / passkey revoke, restart).
26
28
  // It is deliberately independent of the minting session JWT's natural `exp`.
27
29
  export const CAPABILITY_IDLE_MS = 30 * 60_000;
28
30
  export const CAPABILITY_MAX_MS = 12 * 60 * 60_000;
31
+ /** Static-target tokens live shorter: 10 min idle / 2 h absolute. See change: improve-canvas-html-and-url-ux (D3). */
32
+ export const STATIC_CAPABILITY_IDLE_MS = 10 * 60_000;
33
+ export const STATIC_CAPABILITY_MAX_MS = 2 * 60 * 60_000;
34
+ /** Allow-once origins kept per viewer, and viewers kept (oldest viewer dropped first). */
35
+ const MAX_ALLOW_ONCE_PER_VIEWER = 32;
36
+ const MAX_ALLOW_ONCE_VIEWERS = 256;
29
37
  /** Hard cap on live tokens (oldest dropped): a loop minting tokens cannot grow memory. */
30
38
  const MAX_TOKENS = 1024;
31
39
  /** Live tokens per minting principal: one caller's mint loop evicts only ITS OWN oldest tokens. */
32
40
  const MAX_TOKENS_PER_PRINCIPAL = 64;
33
- /** `/~c/<token>` anywhere in a path or `Referer`. Tokens are base64url. */
34
- const CAPABILITY_SEGMENT = /\/~c\/[A-Za-z0-9_-]+/g;
35
41
  const TOKEN_SHAPE = /^[A-Za-z0-9_-]{22,}$/;
36
42
 
37
43
  /** Who minted a capability — the identity and tier an accepted request carries. */
@@ -54,11 +60,71 @@ export interface CapabilityPrincipal {
54
60
  identityExpiresAt?: number;
55
61
  }
56
62
 
63
+ /** Egress policy a token carries. Fail-closed default: `restricted`, scripts off. */
64
+ export interface LivePolicy {
65
+ egress: "open" | "restricted";
66
+ scripts: boolean;
67
+ }
68
+
69
+ /** Whether the target is a loopback port target or a static document root. */
70
+ export type LiveTargetKind = "port" | "static";
71
+
72
+ /** Dashboard exposure when a token was minted. */
73
+ export type LiveExposure = "local-only" | "exposed";
74
+
75
+ /** Opaque id for a client-generated viewer instance (carries allow-once sets across re-mints). */
76
+ const VIEWER_ID_SHAPE = /^[A-Za-z0-9_-]{8,64}$/;
77
+ export const isViewerId = (v: unknown): v is string => typeof v === "string" && VIEWER_ID_SHAPE.test(v);
78
+
57
79
  interface Entry {
58
80
  targetId: string;
59
81
  principal: CapabilityPrincipal;
60
82
  mintedAt: number;
61
83
  lastUsedAt: number;
84
+ /** Non-secret handle distinct from the token (touch / egress / allow-once address tokens by it). */
85
+ tokenId: string;
86
+ kind: LiveTargetKind;
87
+ policy: LivePolicy;
88
+ viewerId?: string;
89
+ /** Identity of the minting principal ({@link principalKeyOf}); egress/touch/allow-once check it. */
90
+ minterKey: string;
91
+ /** Exposure at mint time (a restricted scripted token minted `local-only` dies on the flip to `exposed`). */
92
+ mintExposure: LiveExposure;
93
+ /** Minted by a genuinely local caller: valid only from genuinely local requests. */
94
+ localBound: boolean;
95
+ idleMs: number;
96
+ maxMs: number;
97
+ }
98
+
99
+ /** What the capability hook / proxy learn about a validated token. Never contains the secret. */
100
+ export interface LiveCapabilityGrant {
101
+ targetId: string;
102
+ tokenId: string;
103
+ kind: LiveTargetKind;
104
+ policy: LivePolicy;
105
+ viewerId?: string;
106
+ minterKey: string;
107
+ principal: CapabilityPrincipal;
108
+ }
109
+
110
+ export interface MintOptions {
111
+ kind?: LiveTargetKind;
112
+ policy?: Partial<LivePolicy>;
113
+ viewerId?: string;
114
+ exposure?: LiveExposure;
115
+ /**
116
+ * The minting request was genuinely local (loopback peer, no forwarding header) and the
117
+ * minter held no revocable credential: the token then works only from genuinely local
118
+ * requests. Decided by the mint route from the request — never inferred from the principal
119
+ * kind, which is also `local` for an identity principal reaching the dashboard remotely.
120
+ */
121
+ localBound?: boolean;
122
+ }
123
+
124
+ /** Request-boundary facts the store cannot know itself. */
125
+ export interface ValidateContext {
126
+ /** Is the request genuinely local (loopback peer, no forwarding header)? */
127
+ genuinelyLocal: boolean;
62
128
  }
63
129
 
64
130
  export interface LiveCapabilityStoreOptions {
@@ -73,6 +139,9 @@ export interface LiveCapabilityStoreOptions {
73
139
  const principalKey = (p: CapabilityPrincipal): string =>
74
140
  p.deviceId ? `device:${p.deviceId}` : p.sessionKey ? `session:${p.sessionKey}` : p.kind;
75
141
 
142
+ /** Stable identity of a minting principal; the egress / touch / allow-once routes compare it. */
143
+ export const principalKeyOf = principalKey;
144
+
76
145
  const hash = (token: string): string => crypto.createHash("sha256").update(token).digest("hex");
77
146
 
78
147
  /** sha256 of a session cookie value, for {@link CapabilityPrincipal.sessionKey}. */
@@ -82,6 +151,8 @@ export function sessionKeyOf(cookieValue: string): string {
82
151
 
83
152
  export class LiveCapabilityStore {
84
153
  private readonly entries = new Map<string, Entry>();
154
+ /** viewerId → allow-once origins (insertion-ordered, bounded). */
155
+ private readonly allowOnce = new Map<string, Set<string>>();
85
156
  private readonly now: () => number;
86
157
  private readonly isPrincipalLive: (p: CapabilityPrincipal) => boolean;
87
158
  private readonly isTargetLive: (id: string) => boolean;
@@ -92,12 +163,42 @@ export class LiveCapabilityStore {
92
163
  this.isTargetLive = opts.isTargetLive ?? (() => true);
93
164
  }
94
165
 
95
- /** Mint a token for `targetId`. Only its hash is kept. */
96
- mint(targetId: string, principal: CapabilityPrincipal): { token: string; expiresAt: number } {
166
+ /**
167
+ * Mint a token for `targetId`. Only its hash is kept. The policy is fail-closed
168
+ * (`restricted`, scripts off) unless the caller states otherwise; static targets
169
+ * get the shorter 10 min / 2 h lifetime.
170
+ */
171
+ mint(
172
+ targetId: string,
173
+ principal: CapabilityPrincipal,
174
+ opts: MintOptions = {},
175
+ ): { token: string; tokenId: string; expiresAt: number; policy: LivePolicy } {
97
176
  const now = this.now();
98
177
  this.sweep(now);
99
178
  const token = crypto.randomBytes(32).toString("base64url");
100
- this.entries.set(hash(token), { targetId, principal, mintedAt: now, lastUsedAt: now });
179
+ const tokenId = crypto.randomBytes(16).toString("base64url");
180
+ const kind: LiveTargetKind = opts.kind === "static" ? "static" : "port";
181
+ const policy: LivePolicy = {
182
+ egress: opts.policy?.egress === "open" ? "open" : "restricted",
183
+ scripts: opts.policy?.scripts === true,
184
+ };
185
+ const idleMs = kind === "static" ? STATIC_CAPABILITY_IDLE_MS : CAPABILITY_IDLE_MS;
186
+ const maxMs = kind === "static" ? STATIC_CAPABILITY_MAX_MS : CAPABILITY_MAX_MS;
187
+ this.entries.set(hash(token), {
188
+ targetId,
189
+ principal,
190
+ mintedAt: now,
191
+ lastUsedAt: now,
192
+ tokenId,
193
+ kind,
194
+ policy,
195
+ ...(isViewerId(opts.viewerId) ? { viewerId: opts.viewerId } : {}),
196
+ minterKey: principalKey(principal),
197
+ mintExposure: opts.exposure ?? "exposed",
198
+ localBound: opts.localBound === true,
199
+ idleMs,
200
+ maxMs,
201
+ });
101
202
  // Evict within the minting principal first, so a mint loop cannot push out
102
203
  // another user's active preview tokens.
103
204
  const who = principalKey(principal);
@@ -111,21 +212,30 @@ export class LiveCapabilityStore {
111
212
  if (oldest === undefined) break;
112
213
  this.entries.delete(oldest);
113
214
  }
114
- return { token, expiresAt: now + CAPABILITY_MAX_MS };
215
+ return { token, tokenId, expiresAt: now + maxMs, policy };
115
216
  }
116
217
 
117
218
  /**
118
219
  * Validate `token` for `targetId`. A hit extends the idle expiry. A missing,
119
220
  * unknown, wrong-target, expired or no-longer-live token returns `null` — the
120
221
  * caller cannot tell which.
222
+ *
223
+ * `ctx` carries request-boundary facts: a token minted by a genuinely local
224
+ * caller is refused when `ctx.genuinelyLocal` is false. Every request-facing
225
+ * caller (HTTP hook, WS upgrade) MUST pass it; only store-level unit tests omit it.
121
226
  */
122
- validate(targetId: string, token: string): CapabilityPrincipal | null {
227
+ validate(targetId: string, token: string, ctx?: ValidateContext): CapabilityPrincipal | null {
228
+ return this.validateGrant(targetId, token, ctx)?.principal ?? null;
229
+ }
230
+
231
+ /** {@link validate}, returning everything the proxy needs to apply the token's policy. */
232
+ validateGrant(targetId: string, token: string, ctx?: ValidateContext): LiveCapabilityGrant | null {
123
233
  if (!TOKEN_SHAPE.test(token)) return null;
124
234
  const key = hash(token);
125
235
  const entry = this.entries.get(key);
126
236
  if (!entry || entry.targetId !== targetId) return null;
127
237
  const now = this.now();
128
- if (now - entry.lastUsedAt >= CAPABILITY_IDLE_MS || now - entry.mintedAt >= CAPABILITY_MAX_MS) {
238
+ if (now - entry.lastUsedAt >= entry.idleMs || now - entry.mintedAt >= entry.maxMs) {
129
239
  this.entries.delete(key);
130
240
  return null;
131
241
  }
@@ -133,8 +243,87 @@ export class LiveCapabilityStore {
133
243
  this.entries.delete(key);
134
244
  return null;
135
245
  }
246
+ // Bound to the local machine: a leaked local token is useless from anywhere else.
247
+ // Refused, not deleted — the genuine local holder keeps a working token.
248
+ if (entry.localBound && ctx && !ctx.genuinelyLocal) return null;
136
249
  entry.lastUsedAt = now;
137
- return entry.principal;
250
+ return grantOf(entry);
251
+ }
252
+
253
+ /** The live token behind a non-secret `tokenId`, or `null` (expired / unknown). Does not extend idle. */
254
+ findByTokenId(tokenId: string): LiveCapabilityGrant | null {
255
+ const now = this.now();
256
+ for (const [key, e] of this.entries) {
257
+ if (e.tokenId !== tokenId) continue;
258
+ if (now - e.lastUsedAt >= e.idleMs || now - e.mintedAt >= e.maxMs) {
259
+ this.entries.delete(key);
260
+ return null;
261
+ }
262
+ return grantOf(e);
263
+ }
264
+ return null;
265
+ }
266
+
267
+ /**
268
+ * Extend a token's idle expiry (keepalive) without a request through its path.
269
+ * Only the minting principal may: `minterKey` must equal the entry's. Never
270
+ * extends past the absolute lifetime. Returns whether a live token was touched.
271
+ */
272
+ touch(tokenId: string, minterKey: string): boolean {
273
+ const now = this.now();
274
+ for (const [key, e] of this.entries) {
275
+ if (e.tokenId !== tokenId) continue;
276
+ if (e.minterKey !== minterKey) return false;
277
+ if (now - e.lastUsedAt >= e.idleMs || now - e.mintedAt >= e.maxMs) {
278
+ this.entries.delete(key);
279
+ return false;
280
+ }
281
+ if (!this.isTargetLive(e.targetId) || !this.isPrincipalLive(e.principal)) {
282
+ this.entries.delete(key);
283
+ return false;
284
+ }
285
+ e.lastUsedAt = now;
286
+ return true;
287
+ }
288
+ return false;
289
+ }
290
+
291
+ /** Remember an allow-once origin for a viewer (bounded: 32 origins, 256 viewers). */
292
+ addAllowOnce(viewerId: string, origin: string): void {
293
+ if (!isViewerId(viewerId)) return;
294
+ let set = this.allowOnce.get(viewerId);
295
+ if (set) this.allowOnce.delete(viewerId); // re-insert: most recently used last
296
+ else set = new Set<string>();
297
+ set.delete(origin);
298
+ set.add(origin);
299
+ while (set.size > MAX_ALLOW_ONCE_PER_VIEWER) {
300
+ const oldest = set.values().next().value;
301
+ if (oldest === undefined) break;
302
+ set.delete(oldest);
303
+ }
304
+ this.allowOnce.set(viewerId, set);
305
+ while (this.allowOnce.size > MAX_ALLOW_ONCE_VIEWERS) {
306
+ const oldest = this.allowOnce.keys().next().value;
307
+ if (oldest === undefined) break;
308
+ this.allowOnce.delete(oldest);
309
+ }
310
+ }
311
+
312
+ /** The viewer's allow-once origins (a copy; empty when none). */
313
+ getAllowOnce(viewerId: string | undefined): string[] {
314
+ return viewerId ? [...(this.allowOnce.get(viewerId) ?? [])] : [];
315
+ }
316
+
317
+ /** Revoke every token whose record matches `pred`. Returns how many died. Never exposes a token. */
318
+ revokeWhere(pred: (e: Readonly<{ kind: LiveTargetKind; policy: LivePolicy; mintExposure: LiveExposure; targetId: string }>) => boolean): number {
319
+ let n = 0;
320
+ for (const [key, e] of this.entries) {
321
+ if (pred(e)) {
322
+ this.entries.delete(key);
323
+ n++;
324
+ }
325
+ }
326
+ return n;
138
327
  }
139
328
 
140
329
  revokeByTarget(targetId: string): void {
@@ -161,11 +350,21 @@ export class LiveCapabilityStore {
161
350
 
162
351
  private sweep(now: number): void {
163
352
  for (const [key, e] of this.entries) {
164
- if (now - e.lastUsedAt >= CAPABILITY_IDLE_MS || now - e.mintedAt >= CAPABILITY_MAX_MS) this.entries.delete(key);
353
+ if (now - e.lastUsedAt >= e.idleMs || now - e.mintedAt >= e.maxMs) this.entries.delete(key);
165
354
  }
166
355
  }
167
356
  }
168
357
 
358
+ const grantOf = (e: Entry): LiveCapabilityGrant => ({
359
+ targetId: e.targetId,
360
+ tokenId: e.tokenId,
361
+ kind: e.kind,
362
+ policy: { ...e.policy },
363
+ ...(e.viewerId ? { viewerId: e.viewerId } : {}),
364
+ minterKey: e.minterKey,
365
+ principal: e.principal,
366
+ });
367
+
169
368
  /** A parsed capability URL. `rest` starts with `/` (or is `/`); `prefix` is `/live/<id>/~c/<token>`. */
170
369
  export interface CapabilityPath {
171
370
  targetId: string;
@@ -204,10 +403,7 @@ export function parseCapabilityPath(url: string | undefined): CapabilityPath | n
204
403
  return { targetId, token, prefix, rest: rest.startsWith("/") ? rest : `/${rest}` };
205
404
  }
206
405
 
207
- /** Replace any `/~c/<token>` in a log field / path with a redaction marker. */
208
- export function redactCapability(text: string): string {
209
- return text.replace(CAPABILITY_SEGMENT, "/~c/<redacted>");
210
- }
406
+ export { redactCapability };
211
407
 
212
408
  /** Remove any `/~c/<token>` segment (forwarded `Referer`). */
213
409
  export function stripCapabilitySegment(text: string): string {
@@ -223,6 +419,8 @@ interface CapabilityRequestState {
223
419
  principal?: Principal | null;
224
420
  principalExpiresAt?: number | null;
225
421
  liveCapabilityPrefix?: string;
422
+ /** Set with the prefix: the validated token's policy and ids (never the secret). */
423
+ liveCapability?: LiveCapabilityGrant;
226
424
  }
227
425
 
228
426
  /**
@@ -234,12 +432,20 @@ interface CapabilityRequestState {
234
432
  * token from none.
235
433
  */
236
434
  export function createLiveCapabilityHook(store: LiveCapabilityStore) {
237
- return async function liveCapabilityHook(request: { url: string }): Promise<void> {
435
+ return async function liveCapabilityHook(request: {
436
+ url: string;
437
+ ip?: string;
438
+ headers?: Record<string, unknown>;
439
+ }): Promise<void> {
238
440
  if (!request.url.startsWith("/live/")) return;
239
441
  const cap = parseCapabilityPath(request.url);
240
442
  if (!cap) return;
241
- const principal = store.validate(cap.targetId, cap.token);
242
- if (!principal) return;
443
+ // A token minted by a genuinely local caller works only from genuinely local requests.
444
+ const grant = store.validateGrant(cap.targetId, cap.token, {
445
+ genuinelyLocal: isLocallyTrusted({ ip: request.ip ?? "", headers: request.headers ?? {} }),
446
+ });
447
+ if (!grant) return;
448
+ const principal = grant.principal;
243
449
  const r = request as unknown as CapabilityRequestState;
244
450
  r.isAuthenticated = true;
245
451
  r.authVia = "live-capability";
@@ -250,5 +456,6 @@ export function createLiveCapabilityHook(store: LiveCapabilityStore) {
250
456
  r.principalExpiresAt = principal.identityExpiresAt ?? null;
251
457
  }
252
458
  r.liveCapabilityPrefix = cap.prefix;
459
+ r.liveCapability = grant;
253
460
  };
254
461
  }
@@ -0,0 +1,63 @@
1
+ /**
2
+ * The reserved `/__pi/csp-report` endpoint under a capability prefix: the sink the
3
+ * restricted-preview CSP's `report-uri` / `report-to` point at.
4
+ *
5
+ * Capability-required (the proxy only dispatches a VALID capability here), `POST`
6
+ * only, both report media types, 64 KiB (413 above), rate limited per token (429,
7
+ * see `live-egress.ts`). Only `blocked-uri` is read, and the result is a `runtime`
8
+ * entry the page itself could have forged — never project-grantable. Nothing from
9
+ * the body (it carries the capability in `document-uri`) is logged.
10
+ *
11
+ * See change: improve-canvas-html-and-url-ux (design D6, task 2.8).
12
+ */
13
+ import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
14
+ import type { LiveCapabilityGrant } from "./live-capability.js";
15
+ import { CSP_REPORT_SUBPATH } from "./live-csp.js";
16
+ import { CSP_REPORT_MAX_BYTES, type PreviewEgress } from "./live-egress.js";
17
+ import { type LiveLogSink, liveLog } from "./live-log.js";
18
+
19
+ const REPORT_TYPES = ["application/csp-report", "application/reports+json"] as const;
20
+
21
+ /** Parse the two report media types as JSON (an unparseable body becomes `null`, never a throw). Idempotent. */
22
+ export function registerCspReportParsers(fastify: FastifyInstance): void {
23
+ for (const type of REPORT_TYPES) {
24
+ if (fastify.hasContentTypeParser(type)) continue;
25
+ fastify.addContentTypeParser(type, { parseAs: "buffer", bodyLimit: CSP_REPORT_MAX_BYTES }, (_req, body, done) => {
26
+ try {
27
+ done(null, JSON.parse((body as Buffer).toString("utf8")));
28
+ } catch {
29
+ done(null, null);
30
+ }
31
+ });
32
+ }
33
+ }
34
+
35
+ const notFound = (reply: FastifyReply) => reply.code(404).send({ error: "live-server target not found" });
36
+
37
+ export interface CspReportHandlerDeps {
38
+ egress: PreviewEgress;
39
+ /** The dashboard's own origin as this request reached it (reports of it are not egress). */
40
+ ownOriginsOf?: (request: FastifyRequest) => readonly string[];
41
+ log?: LiveLogSink;
42
+ }
43
+
44
+ /** The proxy's `reservedHandler`: serves `/__pi/csp-report`, answers 404 for the rest of `/__pi/*`. */
45
+ export function createReservedHandler(deps: CspReportHandlerDeps) {
46
+ return (request: FastifyRequest, reply: FastifyReply, ctx: { grant: LiveCapabilityGrant; subPath: string }) => {
47
+ const q = ctx.subPath.search(/[?#]/);
48
+ const pathname = q >= 0 ? ctx.subPath.slice(0, q) : ctx.subPath;
49
+ if (pathname !== CSP_REPORT_SUBPATH) return notFound(reply);
50
+ if (request.method !== "POST") return reply.code(405).header("allow", "POST").send({ error: "method not allowed" });
51
+ const declared = Number(request.headers["content-length"]);
52
+ if (Number.isFinite(declared) && declared > CSP_REPORT_MAX_BYTES) {
53
+ liveLog(deps.log, "csp-report refused", { reason: "too-large", tokenId: ctx.grant.tokenId });
54
+ return reply.code(413).send({ error: "report too large" });
55
+ }
56
+ const outcome = deps.egress.report(ctx.grant, request.body, deps.ownOriginsOf?.(request));
57
+ if (outcome === "rate-limited") {
58
+ liveLog(deps.log, "csp-report refused", { reason: "rate-limited", tokenId: ctx.grant.tokenId });
59
+ return reply.code(429).send({ error: "too many reports" });
60
+ }
61
+ return reply.code(204).send();
62
+ };
63
+ }
@@ -0,0 +1,93 @@
1
+ /**
2
+ * Content-Security-Policy builder for every capability response under
3
+ * `/live/<id>/~c/<token>/` (port AND static targets).
4
+ *
5
+ * Pure: the policy comes from the token (never from a request path, query or
6
+ * header), the prefix origin from the already host-admitted `Host`. The frame
7
+ * is sandboxed (opaque origin); this header makes the same isolation hold when
8
+ * the capability URL is opened directly. Restricted mode confines every fetch
9
+ * directive to the capability prefix plus the granted egress origins `<G>`;
10
+ * it never contains `'self'` (that would be the dashboard origin).
11
+ *
12
+ * See change: improve-canvas-html-and-url-ux (design D3, D4).
13
+ */
14
+ import type { LivePolicy } from "./live-capability.js";
15
+
16
+ export interface LiveCspInput {
17
+ policy: LivePolicy;
18
+ /** Validated `Host` header value (host[:port]). */
19
+ host: string;
20
+ /** `http` or `https` — the scheme the dashboard is reached on. */
21
+ scheme: "http" | "https";
22
+ /** `/live/<id>/~c/<token>` (no trailing slash). */
23
+ prefix: string;
24
+ /** Granted egress origins `<G>`: project grants ∪ the viewer's allow-once set. */
25
+ granted?: readonly string[];
26
+ }
27
+
28
+ export interface LiveCspResult {
29
+ /** `Content-Security-Policy` header value. */
30
+ csp: string;
31
+ /** `Reporting-Endpoints` header value, restricted mode only. */
32
+ reportingEndpoints?: string;
33
+ }
34
+
35
+ /** A canonical https origin: no path/space/`;`/`,` can ride into the header. */
36
+ const SAFE_ORIGIN = /^https:\/\/[a-z0-9.-]+(?::\d{1,5})?$/;
37
+ /** A `Host` header value we are willing to embed in a header. */
38
+ const SAFE_HOST = /^(?:[a-z0-9.-]+|\[[0-9a-f:.]+\])(?::\d{1,5})?$/i;
39
+
40
+ /** The report endpoint, relative to the capability prefix. */
41
+ export const CSP_REPORT_SUBPATH = "/__pi/csp-report";
42
+
43
+ function sandboxDirective(policy: LivePolicy): string {
44
+ if (!policy.scripts) return "sandbox";
45
+ return policy.egress === "open"
46
+ ? "sandbox allow-scripts allow-forms allow-popups allow-downloads"
47
+ : "sandbox allow-scripts allow-forms";
48
+ }
49
+
50
+ /**
51
+ * Build the CSP for one capability response. Returns `null` when `host` is not a
52
+ * plain host[:port] (fail closed — the caller answers 404 rather than emit a
53
+ * header it cannot trust).
54
+ */
55
+ export function buildLiveCsp(input: LiveCspInput): LiveCspResult | null {
56
+ const { policy, host, scheme, prefix } = input;
57
+ if (!SAFE_HOST.test(host)) return null;
58
+ const sandbox = sandboxDirective(policy);
59
+
60
+ if (policy.egress === "open") {
61
+ return { csp: `${sandbox}; object-src 'none'; frame-ancestors 'self'` };
62
+ }
63
+
64
+ const wsScheme = scheme === "https" ? "wss" : "ws";
65
+ const p = `${scheme}://${host}${prefix}/`;
66
+ const pws = `${wsScheme}://${host}${prefix}/`;
67
+ const g = [...new Set(input.granted ?? [])].filter((o) => SAFE_ORIGIN.test(o));
68
+ const gStr = g.length > 0 ? ` ${g.join(" ")}` : "";
69
+ const scriptKw = policy.scripts ? "'unsafe-inline' 'unsafe-eval'" : "'unsafe-inline'";
70
+ const s = `${p} ${scriptKw}${gStr}`;
71
+ const styleS = `${p} 'unsafe-inline'${gStr}`;
72
+ const reportPath = `${prefix}${CSP_REPORT_SUBPATH}`;
73
+ const directives = [
74
+ sandbox,
75
+ "default-src 'none'",
76
+ `script-src ${s}`,
77
+ `style-src ${styleS}`,
78
+ `img-src ${p} data: blob:${gStr}`,
79
+ `font-src ${p} data:${gStr}`,
80
+ `media-src ${p} blob:${gStr}`,
81
+ `connect-src ${p} ${pws}${gStr}`,
82
+ "form-action 'none'",
83
+ "base-uri 'none'",
84
+ "frame-src 'none'",
85
+ "object-src 'none'",
86
+ "frame-ancestors 'self'",
87
+ `worker-src ${p} blob:`,
88
+ "manifest-src 'none'",
89
+ `report-uri ${reportPath}`,
90
+ "report-to csp",
91
+ ];
92
+ return { csp: directives.join("; "), reportingEndpoints: `csp="${reportPath}"` };
93
+ }