@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.
- package/AGENTS.md +2 -2
- package/README.md +47 -6
- package/docs/architecture.md +1369 -63
- package/package.json +14 -9
- package/packages/extension/package.json +5 -3
- package/packages/extension/src/bridge-handlers/dispatch.ts +57 -3
- package/packages/extension/src/bridge-handlers/instance.ts +10 -1
- package/packages/extension/src/bridge-handlers/lifecycle.ts +65 -26
- package/packages/extension/src/bridge-ticket-client.ts +61 -7
- package/packages/extension/src/bridge-tls-checks.ts +79 -0
- package/packages/extension/src/bridge.ts +41 -28
- package/packages/extension/src/canvas-tool.ts +2 -0
- package/packages/extension/src/command-handler.ts +80 -6
- package/packages/extension/src/connect-target.ts +23 -0
- package/packages/extension/src/connection.ts +30 -7
- package/packages/extension/src/dashboard-http-origin.ts +88 -0
- package/packages/extension/src/dev-build.ts +11 -1
- package/packages/extension/src/git-link-builder.ts +11 -2
- package/packages/extension/src/inbound-limits.ts +138 -0
- package/packages/extension/src/local-token-header.ts +77 -6
- package/packages/extension/src/model-refresh.ts +69 -0
- package/packages/extension/src/pinned-endpoint.ts +44 -0
- package/packages/extension/src/project-trust-live.ts +143 -0
- package/packages/extension/src/project-trust.ts +159 -20
- package/packages/extension/src/provider-register.ts +59 -18
- package/packages/extension/src/remote-registration-gate.ts +21 -21
- package/packages/extension/src/remote-upgrade-preparer.ts +104 -0
- package/packages/extension/src/role-model-tools.ts +47 -6
- package/packages/extension/src/server-auto-start.ts +1 -1
- package/packages/extension/src/server-proof-probe.ts +117 -0
- package/packages/extension/src/session-sync.ts +42 -12
- package/packages/extension/src/vault-delivery.ts +11 -1
- package/packages/server/package.json +8 -8
- package/packages/server/src/access/access-grants.ts +61 -8
- package/packages/server/src/access/access-health.ts +10 -0
- package/packages/server/src/access/access-plane.ts +5 -1
- package/packages/server/src/access/containment-gate.ts +55 -17
- package/packages/server/src/access/cwd-verdict.ts +3 -3
- package/packages/server/src/access/pi-trust-live.ts +244 -0
- package/packages/server/src/access/pi-trust-mirror-service.ts +44 -11
- package/packages/server/src/access/planes.ts +106 -1
- package/packages/server/src/access/preview-egress-store.ts +153 -0
- package/packages/server/src/access/prompt-channel.ts +5 -0
- package/packages/server/src/access/provisioning-wiring.ts +113 -0
- package/packages/server/src/access/provisioning.ts +763 -0
- package/packages/server/src/access/yolo-session.ts +54 -2
- package/packages/server/src/acp-bridge/acp-session-adapter.ts +8 -3
- package/packages/server/src/agent-events/agent-event-hub.ts +158 -0
- package/packages/server/src/auth/audit-log.ts +80 -0
- package/packages/server/src/auth/auth-plugin.ts +44 -25
- package/packages/server/src/auth/auth.ts +24 -4
- package/packages/server/src/auth/bearer-auth.ts +52 -12
- package/packages/server/src/auth/cors-origin.ts +76 -29
- package/packages/server/src/auth/csp-report-paths.ts +31 -0
- package/packages/server/src/auth/csp-report-sink.ts +302 -0
- package/packages/server/src/auth/csp-report-store.ts +406 -0
- package/packages/server/src/auth/csp.ts +105 -9
- package/packages/server/src/auth/dashboard-credential-store.ts +4 -0
- package/packages/server/src/auth/dashboard-state-caller.ts +29 -0
- package/packages/server/src/auth/local-proof-refusal-log.ts +89 -0
- package/packages/server/src/auth/local-proof.ts +69 -18
- package/packages/server/src/auth/localhost-guard.ts +48 -10
- package/packages/server/src/auth/nav-intent.ts +72 -0
- package/packages/server/src/auth/passkey/passkey-assets.ts +99 -0
- package/packages/server/src/auth/passkey/passkey-pages.ts +17 -81
- package/packages/server/src/auth/passkey/passkey-routes.ts +8 -0
- package/packages/server/src/auth/pi-legacy-credentials.ts +3 -0
- package/packages/server/src/auth/plugin-server-trust.ts +29 -0
- package/packages/server/src/auth/plugin-trust-store.ts +103 -0
- package/packages/server/src/auth/proven-tls.ts +45 -0
- package/packages/server/src/auth/provider-auth-storage.ts +6 -1
- package/packages/server/src/auth/radius-mcp.ts +1 -1
- package/packages/server/src/auth/request-principal.ts +32 -0
- package/packages/server/src/auth/secret-rotation.ts +246 -0
- package/packages/server/src/auth/secure-origin.ts +56 -0
- package/packages/server/src/auth/serve-app-host.ts +111 -11
- package/packages/server/src/auth/ws-ticket.ts +39 -1
- package/packages/server/src/auth/ws-upgrade-reject-log.ts +4 -1
- package/packages/server/src/browser-handlers/directory-handler.ts +23 -0
- package/packages/server/src/browser-handlers/folder-gate.ts +55 -0
- package/packages/server/src/browser-handlers/handler-context.ts +25 -2
- package/packages/server/src/browser-handlers/session-action-handler.ts +9 -1
- package/packages/server/src/browser-handlers/subscription-handler.ts +100 -2
- package/packages/server/src/browser-handlers/terminal-handler.ts +108 -10
- package/packages/server/src/canvas/canvas-accumulator.ts +35 -7
- package/packages/server/src/cli.ts +210 -39
- package/packages/server/src/config-api.ts +23 -1
- package/packages/server/src/config-snapshot.ts +48 -1
- package/packages/server/src/directory-service.ts +160 -54
- package/packages/server/src/event-wiring.ts +143 -108
- package/packages/server/src/git-worktree/git-operations.ts +44 -10
- package/packages/server/src/git-worktree/redact-git-text.ts +124 -0
- package/packages/server/src/git-worktree/ref-arg.ts +39 -0
- package/packages/server/src/git-worktree/worktree-init-trust.ts +43 -1
- package/packages/server/src/identity/http-road-classification.ts +13 -1
- package/packages/server/src/identity/ws-message-scope.ts +1 -0
- package/packages/server/src/identity/ws-road-classification.ts +1 -0
- package/packages/server/src/known-server-moves.ts +36 -15
- package/packages/server/src/lib/browse-roots.ts +118 -17
- package/packages/server/src/lib/client-dist.ts +36 -21
- package/packages/server/src/lib/dashboard-state-guard.ts +230 -0
- package/packages/server/src/lib/diagram-render.ts +4 -6
- package/packages/server/src/lib/eml.ts +3 -8
- package/packages/server/src/lib/file-cwd-admission.ts +145 -0
- package/packages/server/src/lib/grep-worker.ts +23 -0
- package/packages/server/src/lib/grep.ts +93 -7
- package/packages/server/src/lib/index-html.ts +81 -0
- package/packages/server/src/lib/office-preview.ts +2 -3
- package/packages/server/src/lib/path-containment.ts +7 -0
- package/packages/server/src/lib/resolve-file-mention.ts +11 -9
- package/packages/server/src/lib/route-admission.ts +80 -0
- package/packages/server/src/lib/writable-md-target.ts +4 -0
- package/packages/server/src/lifecycle/recovery-server.ts +65 -18
- package/packages/server/src/live-server/capability-redact.ts +15 -0
- package/packages/server/src/live-server/live-browser-gate.ts +22 -0
- package/packages/server/src/live-server/live-capability.ts +224 -17
- package/packages/server/src/live-server/live-csp-report.ts +63 -0
- package/packages/server/src/live-server/live-csp.ts +93 -0
- package/packages/server/src/live-server/live-egress.ts +435 -0
- package/packages/server/src/live-server/live-exposure.ts +149 -0
- package/packages/server/src/live-server/live-log.ts +21 -0
- package/packages/server/src/live-server/live-origin-scan.ts +298 -0
- package/packages/server/src/live-server/live-server-manager.ts +209 -33
- package/packages/server/src/live-server/live-server-proxy.ts +162 -17
- package/packages/server/src/live-server/live-static.ts +228 -0
- package/packages/server/src/openspec/dependencies-file.ts +122 -0
- package/packages/server/src/openspec/openspec-change-watcher.ts +3 -1
- package/packages/server/src/openspec/openspec-dependency-inputs.ts +281 -0
- package/packages/server/src/openspec/openspec-poll-fs-helpers.ts +72 -26
- package/packages/server/src/openspec/openspec-poll-worker-pool.ts +48 -12
- package/packages/server/src/openspec/openspec-poll-worker.ts +95 -9
- package/packages/server/src/openspec/workflow-schema-status.ts +379 -0
- package/packages/server/src/openspec/workflow-schema.ts +141 -267
- package/packages/server/src/package/npm-search-proxy.ts +5 -2
- package/packages/server/src/package/provider-probe.ts +8 -2
- package/packages/server/src/pairing/browser-gateway.ts +188 -12
- package/packages/server/src/pairing/device-token-services.ts +26 -0
- package/packages/server/src/pairing/paired-devices.ts +335 -22
- package/packages/server/src/pairing/pairing.ts +34 -4
- package/packages/server/src/pairing/socket-locality.ts +26 -0
- package/packages/server/src/persistence/preferences-store.ts +9 -0
- package/packages/server/src/pi/bridge-channel.ts +33 -0
- package/packages/server/src/pi/bridge-upgrade-auth.ts +18 -3
- package/packages/server/src/pi/gateway-listeners.ts +9 -3
- package/packages/server/src/pi/host-project-trust.ts +14 -6
- package/packages/server/src/pi/pi-gateway.ts +191 -21
- package/packages/server/src/pi/resource-toggle-trust.ts +1 -1
- package/packages/server/src/plugin-discovery-wiring.ts +142 -0
- package/packages/server/src/plugin-event-seam.ts +116 -4
- package/packages/server/src/plugin-runtime-clients.ts +89 -0
- package/packages/server/src/routes/access-routes.ts +159 -9
- package/packages/server/src/routes/agent-event-stream-routes.ts +137 -0
- package/packages/server/src/routes/canvas-types-routes.ts +20 -6
- package/packages/server/src/routes/csp-violations-routes.ts +162 -0
- package/packages/server/src/routes/file-routes.ts +329 -209
- package/packages/server/src/routes/file-write-binary-routes.ts +77 -20
- package/packages/server/src/routes/folder-project-routes.ts +18 -12
- package/packages/server/src/routes/git-routes.ts +319 -203
- package/packages/server/src/routes/grep-routes.ts +38 -14
- package/packages/server/src/routes/known-servers-routes.ts +189 -91
- package/packages/server/src/routes/live-server-routes.ts +378 -15
- package/packages/server/src/routes/local-proof-routes.ts +14 -0
- package/packages/server/src/routes/nav-intent-routes.ts +46 -0
- package/packages/server/src/routes/openspec-group-routes.ts +53 -44
- package/packages/server/src/routes/openspec-routes.ts +379 -28
- package/packages/server/src/routes/package-routes.ts +58 -10
- package/packages/server/src/routes/pairing-routes.ts +146 -10
- package/packages/server/src/routes/pi-trust-query-routes.ts +330 -0
- package/packages/server/src/routes/plugin-activation-routes.ts +59 -0
- package/packages/server/src/routes/plugin-runtime-client-routes.ts +149 -0
- package/packages/server/src/routes/provider-auth-routes.ts +15 -2
- package/packages/server/src/routes/resource-activation-routes.ts +18 -4
- package/packages/server/src/routes/session-routes.ts +51 -4
- package/packages/server/src/routes/system-routes.ts +84 -15
- package/packages/server/src/routes/ui-link-base.ts +88 -0
- package/packages/server/src/runtime-overlay/runtime-io.ts +2 -9
- package/packages/server/src/server.ts +648 -137
- package/packages/server/src/session/hydration-state.ts +148 -0
- package/packages/server/src/session/memory-session-manager.ts +7 -0
- package/packages/server/src/session/replay-exit-controller.ts +221 -0
- package/packages/server/src/session/retained-transcript.ts +9 -2
- package/packages/server/src/session/session-load-worker.ts +11 -2
- package/packages/server/src/spawn-process/headless-pid-registry.ts +14 -9
- package/packages/server/src/terminal/terminal-manager.ts +54 -46
- package/packages/server/src/tls/tls-bridge-route.ts +61 -0
- package/packages/server/src/tls/tls-config-validation.ts +2 -0
- package/packages/server/src/vault/device-expiry-sweep.ts +36 -0
- package/packages/server/src/vault/vault-delivery-hub.ts +155 -25
- package/packages/server/src/watch-files-handler.ts +66 -0
- package/packages/shared/package.json +1 -1
- package/packages/shared/src/browser-protocol.ts +148 -2
- package/packages/shared/src/canvas-declare.ts +27 -0
- package/packages/shared/src/config.ts +372 -53
- package/packages/shared/src/containment-guard.ts +35 -0
- package/packages/shared/src/dashboard-plugin/anthropic-peer-names.ts +9 -0
- package/packages/shared/src/dashboard-plugin/event-type-owners.ts +50 -0
- package/packages/shared/src/dashboard-plugin/file-handler.ts +2 -0
- package/packages/shared/src/dashboard-plugin/host-api.ts +61 -0
- package/packages/shared/src/dashboard-plugin/host-fx-classes.ts +23 -0
- package/packages/shared/src/dashboard-plugin/host-import-map.ts +38 -0
- package/packages/shared/src/dashboard-plugin/index.ts +2 -0
- package/packages/shared/src/dashboard-plugin/manifest-types.ts +54 -1
- package/packages/shared/src/dashboard-plugin/plugin-status.ts +54 -0
- package/packages/shared/src/dashboard-plugin/slot-props.ts +45 -3
- package/packages/shared/src/dashboard-plugin/slot-types.ts +8 -0
- package/packages/shared/src/dashboard-plugin/subagent-types.ts +219 -0
- package/packages/shared/src/dashboard-plugin/ui-primitives.ts +28 -0
- package/packages/shared/src/display-prefs.ts +13 -0
- package/packages/shared/src/doctor-core.ts +94 -27
- package/packages/shared/src/live-server.ts +141 -0
- package/packages/shared/src/local-proof-signal.ts +16 -0
- package/packages/shared/src/loopback-host.ts +26 -0
- package/packages/shared/src/mcp/verb-tiers.generated.ts +178 -0
- package/packages/shared/src/mdns-discovery.ts +25 -6
- package/packages/shared/src/nav-intent.ts +29 -0
- package/packages/shared/src/openspec-dependencies.ts +760 -0
- package/packages/shared/src/openspec-poller.ts +3 -2
- package/packages/shared/src/pairing-knock-client.ts +44 -4
- package/packages/shared/src/pi-trust-live-query.ts +93 -0
- package/packages/shared/src/pi-trust-mirror-snapshot.ts +5 -7
- package/packages/shared/src/pi-trust-mirror-types.ts +36 -3
- package/packages/shared/src/pi-trust-mirror.ts +29 -3
- package/packages/shared/src/pi-trust-resource-digest.ts +255 -0
- package/packages/shared/src/platform/ensure-bundled-git.ts +57 -34
- package/packages/shared/src/platform/git-source.ts +88 -26
- package/packages/shared/src/platform/git.ts +14 -8
- package/packages/shared/src/platform/process.ts +48 -4
- package/packages/shared/src/platform/resolve-pi-shell.ts +76 -0
- package/packages/shared/src/platform/select-git-source.ts +7 -0
- package/packages/shared/src/plugin-route-cwd.ts +95 -0
- package/packages/shared/src/preview-egress.ts +138 -0
- package/packages/shared/src/project-root.ts +16 -0
- package/packages/shared/src/protocol.ts +40 -1
- package/packages/shared/src/recommended-extensions.ts +18 -0
- package/packages/shared/src/recovery-timing.ts +27 -0
- package/packages/shared/src/remote-credentials.ts +63 -0
- package/packages/shared/src/rest-api.ts +55 -8
- package/packages/shared/src/route-tiers.ts +55 -1
- package/packages/shared/src/runtime-overlay/archive-safety.d.mts +2 -0
- package/packages/shared/src/runtime-overlay/archive-safety.mjs +33 -0
- package/packages/shared/src/runtime-overlay/manifest.d.mts +7 -0
- package/packages/shared/src/runtime-overlay/manifest.mjs +22 -2
- package/packages/shared/src/safe-local-path.ts +24 -0
- package/packages/shared/src/sanitize-profiles.ts +98 -0
- package/packages/shared/src/server-launcher.ts +9 -1
- package/packages/shared/src/server-pinning.ts +55 -2
- package/packages/shared/src/server-routes.ts +462 -0
- package/packages/shared/src/session-ui-path.ts +11 -0
- package/packages/shared/src/tls-only-token.ts +16 -0
- package/packages/shared/src/tool-registry/definitions.ts +5 -5
- package/packages/shared/src/tool-registry/strategies.ts +12 -11
- package/packages/shared/src/types.ts +66 -0
- package/packages/shared/src/url-policy.ts +96 -0
- package/packages/shared/src/vault-delivery.ts +15 -0
- package/packages/shared/src/ws-message-tiers.ts +1 -0
package/docs/architecture.md
CHANGED
|
@@ -106,6 +106,7 @@ React-based responsive web UI that:
|
|
|
106
106
|
- Shows all active sessions organized by directory, with pinned directories always visible at the top
|
|
107
107
|
- Renders chat messages with markdown, syntax highlighting, streaming, and a small raw-HTML pass that strips React-only `ref` attributes before render
|
|
108
108
|
- Persists scroll position per session — switching sessions restores exact scroll position if locked, or scrolls to bottom if following
|
|
109
|
+
- Animates live arrivals, paces streamed text, glides follow-scroll; `chatMotion` pref (rollback: `PATCH /api/preferences/display {"chatMotion":false}`). Full ref: [`chat-motion.md`](chat-motion.md)
|
|
109
110
|
- Displays collapsed tool call steps with lazy-loaded content and elapsed time badges
|
|
110
111
|
- Shows live ticking elapsed counters on running operations (thinking, tool calls) and final duration on completed ones
|
|
111
112
|
- Provides command autocomplete with `/` prefix
|
|
@@ -774,6 +775,37 @@ On browser connect, gateway emits ONE `sessions_snapshot { sessions, orders, end
|
|
|
774
775
|
|
|
775
776
|
See change: `fix-connect-snapshot-frame-loss`.
|
|
776
777
|
|
|
778
|
+
### Session route resolution + deep links (change: add-session-ui-deep-links-for-agents)
|
|
779
|
+
|
|
780
|
+
Agents open `/session/:id[/diff|/editor]` with any id form. Client resolves to canonical held id.
|
|
781
|
+
|
|
782
|
+
- **Raw param.** Route `:id` stays RAW. `useSessionRouteResolution` (`packages/client/src/hooks/useSessionRouteResolution.ts`) resolves synchronously during render. `selectedId` in `App.tsx` = canonical id (`undefined` while pending / not found). Status: `none|pending|ok|ambiguous|notFound|vanished`.
|
|
783
|
+
- **Matching.** `resolveSessionRouteId` (`lib/session/resolve-session-route-id.ts`): raw exact wins; else case-insensitive exact; else unique prefix ≥ 8 chars (`MIN_SESSION_PREFIX`). Several prefix hits → `ambiguous` (candidate links). < 8 chars → `none`. Returned id = held live-cased id.
|
|
784
|
+
- **Prefix verification.** Prefix-only match commits only after this connection's `GET /api/sessions?id=` lookup merged. Prefix unique among held ids can be ambiguous across owner-visible registry (older ended sessions outside snapshot window). Merge → `ambiguous` (candidate links). Status `pending` meanwhile. Lookup network / 5xx failure → fall back to held match. Full id or case-only difference commits without lookup.
|
|
785
|
+
- **Canonical URL.** `useCanonicalRouteUrl` navigates with `replace` to canonical id. Keeps suffix + query.
|
|
786
|
+
- **Snapshot window gap.** Snapshot holds non-ended + newest ended only (see Sessions snapshot window). Older ended arrive via `sessions_page`. Miss after snapshot → one `GET /api/sessions?id=<routeId>` per route id per connection (`lib/api/sessions-lookup-api.ts`).
|
|
787
|
+
- **Server filter.** Single-valued `id`. Case-insensitive exact or prefix ≥ 8 chars. Applied after `filterOwned`. Array `id` → 400.
|
|
788
|
+
- **Merge.** Lookup rows merge into `sessions` Map ONLY. Stripped of `notifyLog`, `uiUrl`, `diffUrl`. Order map, `endedTotals`, paging untouched.
|
|
789
|
+
- **`lookupOnlyIds`.** Tracks merged ids. Excluded from held-ended count (`heldEndedByGroup`) until `sessions_page_result` delivers them or snapshot clears the set.
|
|
790
|
+
- **Reconnect / server switch.** `snapshotGeneration` resets to 0. Resolved id sticky per route visit → open session never blanks.
|
|
791
|
+
- **Stale lookup replies.** Connection epoch bumps every time snapshot gate flips (snapshot lands; reconnect / server switch resets `snapshotGeneration` to 0). Lookup started in one epoch discarded if epoch changed before reply. Reply from server A never merges into server B `sessions` / `lookupOnlyIds`.
|
|
792
|
+
- **Vanished.** Was held, lookup returns empty (archived while viewing, or switch to server lacking it) → `useVanishedRedirect` does `navigate("/", { replace: true })` once.
|
|
793
|
+
- **Never existed.** Inline `SessionNotFound` (`data-testid="session-not-found"`). No redirect — agent must see evidence.
|
|
794
|
+
- **Pending.** `session-resolving` placeholder.
|
|
795
|
+
- **Lookup errors.** 401/403 → auth-loss path (`loginRedirectFor`). Network / 5xx → `notFound` + retry.
|
|
796
|
+
- **`ShellContent`.** Takes `sessionRoute` prop. Ignored when `frozen`.
|
|
797
|
+
|
|
798
|
+
**Deep-link URLs.** `GET /api/sessions` rows carry `uiUrl` / `diffUrl` (`SessionListItem`, `packages/shared/src/rest-api.ts`; helper `sessionUiPath`, `packages/shared/src/session-ui-path.ts`).
|
|
799
|
+
|
|
800
|
+
- Base from `resolveRequestUiBase` (`packages/server/src/routes/ui-link-base.ts`).
|
|
801
|
+
- Order: configured origin (public bases, live tunnels, `auth.redirectBaseUrl`) whose hostname matches first `X-Forwarded-Host`, then `Host`; else admitted `Host`; else `http://localhost:<port>`.
|
|
802
|
+
- `X-Forwarded-Host` only selects among configured origins. Never mints one.
|
|
803
|
+
- `trustProxy` stays off.
|
|
804
|
+
- zrok public share forwards `Host: <share>.shares.zrok.io`. No `X-Forwarded-Host`. `X-Forwarded-Proto: https`.
|
|
805
|
+
- Agent panes append `?embed=1` (see `docs/embedding-chat-view.md`).
|
|
806
|
+
|
|
807
|
+
See change: `add-session-ui-deep-links-for-agents`.
|
|
808
|
+
|
|
777
809
|
### Notify Flow (`ctx.ui.notify` → browser, split from prompt_request)
|
|
778
810
|
|
|
779
811
|
Change: `split-notify-from-prompt-request`. `ctx.ui.notify` used to ship over `prompt_request`. Every consumer treated it as an unanswered ask → `trackPromptRequest` → `currentTool="ask_user"` re-armed on every quiescent moment → permanent "Needs you", false unread, `questionFirst` reorder, and a session the embed-lifecycle reaper could never reclaim. Now a dedicated `notify` message type end to end.
|
|
@@ -1097,9 +1129,45 @@ First-party slots (React, possibly also descriptor):
|
|
|
1097
1129
|
- `content-view` — full-screen content area (replaces every conditional branch in `App.tsx` for `ArchiveBrowserView`, `SpecsBrowserView`, `OpenSpecPreview`, `FlowAgentDetail`, `FlowArchitectDetail`, `MarkdownPreviewView`, `FileDiffView`, `FlowYamlPreview`). Descriptor variant reuses `management-modal`.
|
|
1098
1130
|
- `content-header-sticky` — sticky element above content-view (replaces sticky `FlowArchitect`/`FlowDashboard`). Descriptor variant reuses `breadcrumb`.
|
|
1099
1131
|
- `content-inline-footer` — inline element below content-view (replaces `FlowSummary`). React-only.
|
|
1100
|
-
- `composer-context-group` — labelled read-only context groups inside the
|
|
1132
|
+
- `composer-context-group` — labelled read-only context groups inside the composer dock's Context lane (`ContextLane.tsx`), ahead of the Status group. Formerly the session-action strip (`ComposerSessionActions`). Multiplicity `many`, tier `react-only`, claim `{ component }`, context props `{ session, pluginContext }`. Outside the Status group's streaming `<fieldset disabled>` — never working-gated, stays live mid-run. Runtime exports `ComposerContextGroupSlot` + primitive `ComposerContextGroup` (keeps signature, delegates to `ToolbarGroup` variant `info`). First claimant: quota plugin's `QuotaWidget`. See change: move-quota-to-context-strip; redesign-composer-session-strip; add-composer-dock.
|
|
1133
|
+
- `composer-dock-process-group` — group of running-work rows inside the composer dock's Processes lane, before core Commands + Background groups. Multiplicity `many`, tier `react-only`, claim `{ component }`, session-scoped (predicate input = `DashboardSession`). Props `{ session, pluginContext, mode: "summary"|"rows", reportSummary(summary: ProcessGroupSummary | null) }`. `ProcessGroupSummary = { count: number; noun: string }`. `summary` mode: always mounted while session bound, renders `null`, only reports; adds no DOM/focus/timer. `rows` mode: mounted only while lane body shown, renders `ComposerDockRow`s, never reports. `noun` printed verbatim after `count` — claim agrees noun with count (`subagent` / `subagents`). `null` or `count ≤ 0` = nothing runs. Dock keeps `Map<claimKey, summary>`, drops entry on unmount. Runtime exports `ComposerDockProcessGroupSlot({ session, mode, onReport?, wrapClaim? })` + primitive `ComposerDockRow` (`packages/dashboard-plugin-runtime/src/ComposerDockRow.tsx`: 32 px row, 16 px icon box, truncation, action targets ≥24 px / ≥44 px below `md`, elapsed from `startedAt` in leaf `DockRowElapsed` owning its 1 s tick). First claimant: subagents plugin `SubagentDockGroup` (`packages/subagents-plugin/src/client/SubagentDockGroup.tsx`; Open → `/session/:sid/subagent/:aid`; status `created` → `pending`; dedupes by `state.id`). Additive: `PLUGIN_HOST_API_VERSION` 1.0.0 → 1.1.0. See change: add-composer-dock.
|
|
1134
|
+
|
|
1135
|
+
**Composer stack (`ComposerDock`):** one dock above one composer card replaces the old stack (`composer-context-strip`, `StatusBar`, `QueuePanel`, `YoloComposerStrip`). `ComposerSessionActions` strip superseded — its OpenSpec + Git content split into lanes (paragraph below kept for `ToolbarGroup` primitive details).
|
|
1101
1136
|
|
|
1102
|
-
|
|
1137
|
+
```mermaid
|
|
1138
|
+
flowchart TB
|
|
1139
|
+
CV["ChatView (shrinkable)"] --> SB["SessionBanner (fixed)"]
|
|
1140
|
+
SB --> AN["composer-stack-anchor (fixed, 0 px)"]
|
|
1141
|
+
AN --> DK
|
|
1142
|
+
subgraph DK["composer-dock (shrinkable)"]
|
|
1143
|
+
direction TB
|
|
1144
|
+
SC["composer-dock-scroll: Processes · Changes · OpenSpec · Queue · Context"]
|
|
1145
|
+
YF["YOLO footer (flex-none, h-8)"]
|
|
1146
|
+
end
|
|
1147
|
+
DK --> CI["CommandInput card: textarea + one toolbar row"]
|
|
1148
|
+
```
|
|
1149
|
+
|
|
1150
|
+
- Sibling of `CommandInput`, never inside it. Mounted by `ComposerDockHost.tsx` (hook boundary for `App.tsx`; also `DirectoryHomeView.tsx`). Visual join CSS only: `mx-5` inset (8px inside card edges, drawer look), `-mb-6 pb-6` tucks bottom edge 12px under card; `composer-root` drops its full-width `border-t` while dock visible (index.css sibling rule). team-app `ChatPane` embeds `CommandInput` bare: no dock.
|
|
1151
|
+
- Nothing renders for `readOnly` (archived) views or when no lane and no YOLO footer.
|
|
1152
|
+
- Files (`packages/client/src/components/chat/`): `ComposerDock.tsx` (layout, accordion render, compact mode, YOLO footer, live region), `composer-dock-model.ts` (`DockLane`, `DockLaneKey`, `DOCK_LANE_ORDER`, `useDockAccordion`), `useComposerDockLanes.ts` (builds Changes/OpenSpec/Queue/Context lanes), `ProcessesLane.tsx` + `ProcessesLaneBody.tsx` (built into dock), `ChangesLane.tsx`, `QueueLane.tsx`, `ContextLane.tsx`, `useDockCompactMode.ts`.
|
|
1153
|
+
- Lane order fixed: Processes, Changes, OpenSpec, Queue, Context. Lane renders only with content. Lane = `DockLane { key, label, icon, title, meta, summary, summaryText, actions, renderBody, expandable, live }`.
|
|
1154
|
+
- Accordion: one `openLane: DockLaneKey | null`, controlled by `App.tsx` via `useDockAccordion(selectedId)`. Resets to `null` on every session bind. At most one lane open. Nothing auto-expands; nothing persisted.
|
|
1155
|
+
- Row layout (composer column ≥ 32.5rem): each lane `role="group"`; expandable header = one stretched disclosure button (`aria-expanded`/`aria-controls`); actions siblings of it, never nested.
|
|
1156
|
+
- Compact mode (< 32.5rem = 520 px at 16 px root, `DOCK_COMPACT_REM`): one sticky chip per lane, every lane incl. Context + unattached OpenSpec; chip opens sheet below chips. Width via `ResizeObserver` on composer column (`bottom` stack), not dock → no feedback loop. Flip evaluated ≤ once per animation frame; exact at threshold, no hysteresis; width 0 never flips. `openLane` survives flip; focus moves to chip/toggle only if it was inside open lane.
|
|
1157
|
+
- Scroll: lanes in `composer-dock-scroll` (`min-h-0 overflow-y-auto`). YOLO footer `flex-none` outside it: never collapsed, never chip, never scrolled away. Dock shrinks before transcript.
|
|
1158
|
+
- Live region: one sr-only polite `role="status"`, sibling of lanes, never ancestor of YOLO footer. Announces count strings only. Elapsed clocks tick in leaves outside it.
|
|
1159
|
+
- Processes lane: subagents via `composer-dock-process-group` slot (summary + rows mounts); Commands from `useInflightBashTools` (Show → scroll to tool card; includes bash nested in `Agent` calls); Background from `DashboardSession.processes` (Kill → `kill_process { pgid }`, SIGTERM to group). Header count = core counts + claim summaries. Turn stops only via composer Stop.
|
|
1160
|
+
- Changes lane: header = Git worktree identity + worktree actions (`GitIdentity`, `WorktreeActionsMenu`) + `N files +A −D` + Review. Renders when `session.gitWorktree` set or diff lists files. Body lists session-owned in-cwd files from `GET /api/session-diff`; out-of-cwd entries listed apart, no diff link, outside count. Server cap `MAX_FILES = 200` → header shows `200+`.
|
|
1161
|
+
- `useDockDiff(sessionId, { working, dirtyCount, expanded })` (`packages/client/src/hooks/useDockDiff.ts`) wraps `useSessionDiff`. Triggers: first load; working→idle falling edge (`isComposerWorking`); `gitStatus.dirtyCount` change while idle; lane expand; Retry. Coalescing: ≤ 1 request in flight; trigger during request or inside window sets one pending flag; never dropped. `DOCK_DIFF_WINDOW_MS` 2000 min gap between starts. `DOCK_DIFF_SETTLE_MS` 1000 delay for turn-end/dirty triggers → same-second signals = one request. Back-off: request slower than `DOCK_DIFF_SLOW_MS` 300 ms doubles gap (2 s → 4 → 8, cap 30 s); fast request resets.
|
|
1162
|
+
- OpenSpec lane: `ComposerSessionActions.tsx` split, not rewritten; keeps readiness gate, attach flow, traceable archived/missing attachments (`showTrace`), single primary action, working-state rules. Title = attached change name + task count. Open proposal / Refresh / Detach in `⋯`. Expand → next open tasks via `fetchTasks(cwd, change)`.
|
|
1163
|
+
- Queue lane: embeds `QueuePanel` cycler (`embedded` prop hides own subtitle + clear-all; Clear all in lane header). Context lane: `composer-context-group` claims (never gated) + Status group (`<fieldset disabled={working}>`, keeps working gate).
|
|
1164
|
+
- YOLO footer: former `YoloComposerStrip`, height `YOLO_FOOTER_HEIGHT` = 32 px (`h-8`), `whitespace-nowrap`, sentence ellipsized. Test id `yolo-composer-strip` kept.
|
|
1165
|
+
- Composer card: one toolbar row (`composer-settings-row`). `+` = only fold host (absorbs Terminal; no `⋯` overflow). `Steer ▾` dropdown, folds into `+` below 420 px (`@[26.25rem]`). Working status word via `workingStatusLabel` (`packages/client/src/lib/chat/working-status.ts`; `StatusBar.tsx` deleted). One merged `model · thinking` chip wrapping `ModelSelector`. Round send/stop button at toolbar end, token fills only. Fold thresholds `@[55rem]`/`@[40rem]`/`@[26.25rem]`.
|
|
1166
|
+
- Pane height budget (`packages/client/src/lib/layout/chat-pane-row-class.ts`, `CHAT_PANE_ROW_TABLE`): `composer-context-strip`, `status-bar`, `queue-panel` entries removed. Added `composer-dock` (shrinkable, weight `DOCK_WEIGHT` 1, floor = `YOLO_FOOTER_HEIGHT` 32 + `DOCK_LANE_HEADER_FLOOR` 41 = 73, bound 32) and `composer-dock:footer-only` (YOLO, no lanes; floor 33, bound 32). App picks key by state. `chat-pane-row-completeness.test.ts` asserts `floor > bound` per entry and every rendered row listed.
|
|
1167
|
+
- Test ids: surviving ids kept; removed `composer-context-strip`, `status-bar`, `composer-session-actions`, composer `overflow-button`/`overflow-menu`; new dock root `composer-dock`.
|
|
1168
|
+
- No server, bridge protocol or persisted-data change. Rollback = revert client + shared slot decl + runtime + subagents plugin together; remove plugin claim before slot (validator rejects unknown slot id). See change: add-composer-dock.
|
|
1169
|
+
|
|
1170
|
+
**Composer session-action strip (`ComposerSessionActions`, superseded by `ComposerDock`; `ToolbarGroup` primitive still used by lanes):** host groups (OpenSpec, Git, Status) + plugin `composer-context-group` contributions render through one primitive `ToolbarGroup({ label, variant: "actions"|"info", testId?, labelTestId?, contentAs?: "div"|"fieldset", contentProps?, className? })` (`packages/dashboard-plugin-runtime/src/slot-consumers.tsx`). Renders `<div data-group role="group" aria-labelledby>` + label `<span id>` (`useId`) + content element carrying `data-group-content`. `actions` variant: solid outline, `--bg-tertiary` fill, label segment on `--bg-surface`, hairlines between direct children, children ≥24 px targets. `info` variant: dashed outline, no fill (read-only readouts). Label test id = `labelTestId ?? (testId ? `${testId}-label` : undefined)` — never `undefined-label`. a11y contract change: every claimant becomes a named `role="group"` region; contributions drop own chip borders (quota plugin did). Host containers `composer-{openspec,git,status}-container`; legacy ids `composer-{openspec,git,status}-group-label`, `composer-git-group`, `composer-status-group` kept (Status content is `<fieldset disabled={working}>`). `packages/client/src/index.css`: `[data-group]:has(> [data-group-content]:empty) { display:none }` hides empty group (e.g. all badge claims render null). See change: redesign-composer-session-strip.
|
|
1103
1171
|
- `anchored-popover` — popover anchored to a triggering UI element (replaces `TasksPopover`).
|
|
1104
1172
|
- `command-route` — maps a slash command or URL route to a `content-view` (replaces today's hand-wired routing in `App.tsx`).
|
|
1105
1173
|
- `settings-section` — a section in the Settings page (replaces today's hardcoded `Background polling (OpenSpec)` section). React for first-party plugins; descriptor (RJSF/UiField) for third-party extensions.
|
|
@@ -1192,7 +1260,7 @@ Authoring rules: [`plugin-seams.md`](plugin-seams.md#lazy-claim-modules-module).
|
|
|
1192
1260
|
|
|
1193
1261
|
**Bundled-by-default plugins:** The plugin loader treats all plugins identically (same manifest, same discovery, same `enabled` flag, same failure isolation). What distinguishes "bundled-by-default" plugins (initial set: `git-plugin`) is purely operational — the build pipeline always includes them in `packages/`. Their absence is a deliberate user opt-out, not a normal state. OpenSpec, Flows, and Subagents plugins are bundled in standard builds but their absence is a normal use case (e.g. a workspace without OpenSpec).
|
|
1194
1262
|
|
|
1195
|
-
**
|
|
1263
|
+
**External plugin discovery (shipped):** `decouple-plugins-from-core` adds the `settings.json#packages[]` discovery source, manifest `hostApi` pinning, operator trust, and runtime-delivered clients. See "Plugin Discovery, Trust and Runtime Delivery" below and `docs/runtime-plugin-clients.md`.
|
|
1196
1264
|
|
|
1197
1265
|
#### JSX slot wrappers and `??` fallback chains — anti-pattern
|
|
1198
1266
|
|
|
@@ -1254,7 +1322,7 @@ All producers hash deterministic manifest serialization via `pluginRegistryHash(
|
|
|
1254
1322
|
|
|
1255
1323
|
**Served-artifact build declaration (`pi-dashboard-build.json`):**
|
|
1256
1324
|
Production Vite build writes `packages/client/dist/pi-dashboard-build.json`:
|
|
1257
|
-
- Schema: `{ schemaVersion: 1, pluginRegistryHash: "<sha256>", fixturePolicy: "excluded" | "included" }`.
|
|
1325
|
+
- Schema: `{ schemaVersion: 1, pluginRegistryHash: "<sha256>", fixturePolicy: "excluded" | "included", bundledPluginIds?: string[] }`. `bundledPluginIds` = sorted ids of plugins the build bundled (additive; decides bundled-vs-runtime on every host — see "Plugin Discovery, Trust and Runtime Delivery").
|
|
1258
1326
|
- Byte-reproducible: no timestamps, no host paths. Dev/HMR emits nothing.
|
|
1259
1327
|
- SDK: `build-declaration-sdk.ts` + `build-metadata.ts` in `dashboard-plugin-runtime`.
|
|
1260
1328
|
|
|
@@ -1327,6 +1395,110 @@ Client banner flow: `PluginStalenessBanner` fetches `/api/health` on mount. Comp
|
|
|
1327
1395
|
|
|
1328
1396
|
See change: `add-served-build-coherence-and-hash-parity`.
|
|
1329
1397
|
|
|
1398
|
+
#### Plugin Discovery, Trust and Runtime Delivery (`decouple-plugins-from-core`)
|
|
1399
|
+
|
|
1400
|
+
Plugins separable from core. Core imports no plugin. Plugin client reaches stock dashboard at runtime. Detail: `docs/runtime-plugin-clients.md`, `docs/plugin-seams.md`, `docs/publishing-plugins.md`, `docs/plugin-ui-primitives.md`.
|
|
1401
|
+
|
|
1402
|
+
**Discovery sources.** `discoverPlugins()` (`packages/dashboard-plugin-runtime/src/server/loader.ts`). `source` on `DiscoveredPlugin` + `PluginStatus`.
|
|
1403
|
+
|
|
1404
|
+
| Priority | `source` | Location |
|
|
1405
|
+
|---|---|---|
|
|
1406
|
+
| 1 | `workspace` | `<repo>/packages` |
|
|
1407
|
+
| 2 | `installed` | `~/.pi/dashboard/plugins` |
|
|
1408
|
+
| 3 | `bundled` | `resources/plugins` (Electron) |
|
|
1409
|
+
| 4 | `pi-package` | `~/.pi/agent/settings.json#packages[]` via `listPiPackages({scope:"user"})` (`packages/shared/src/pi-package-resolver.ts`) |
|
|
1410
|
+
| report only | `local-detected` | `<cwd>/.pi/settings.json#packages[]` of active sessions |
|
|
1411
|
+
|
|
1412
|
+
- `pi-package` entries: package dirs carrying a manifest. Files + manifest-less dirs skipped silently. Missing install paths invisible. `npm root -g` memoized once per process.
|
|
1413
|
+
- Exception to priority: id ∈ served build's `bundledPluginIds` → build's own copy wins (`workspace` if a copy exists, else `bundled`, else plain priority), both halves.
|
|
1414
|
+
- Discovery cache keyed by effective root set + digest of `bundledPluginIds` (absent → fixed "undeclared" key). Server reads declaration (`readBuildDeclaration`, `client-dist.ts`) at startup + on every refresh, before any discovery call.
|
|
1415
|
+
- Vite build-time call (explicit `repoRoot`) scans only workspace. No declaration. Unaffected.
|
|
1416
|
+
|
|
1417
|
+
**One row per id (shadowing).** Losing duplicate → winner's `shadowed: {source, packageDir}[]`. Logged at warn. Never loaded. No second `loaded:false` row. `PluginsSection` renders `shadowed` as sub-line.
|
|
1418
|
+
|
|
1419
|
+
**Local-scope detection** (`local-scope-detector.ts`).
|
|
1420
|
+
- Per active-session cwd: `listPiPackages({scope:"project", cwd})` entries with plugin manifest → row `source: "local-detected"`, `loaded: false`, `enabled: false`, error "Local-scope plugins are not loaded in this release. Install globally with --scope global to enable."
|
|
1421
|
+
- Same id already has a row → local copy goes to that row's `shadowed[]`.
|
|
1422
|
+
- Server entry, bridge, claims, client never loaded.
|
|
1423
|
+
- Rerun: each discovery refresh, session registers a new cwd, after each successful local-scope package op, on session end (prunes rows no active session has).
|
|
1424
|
+
- `plugins_changed` on session end only when the detected set changed.
|
|
1425
|
+
|
|
1426
|
+
**Refresh on completion.** Hook: package-operation completion listener (`setCompleteListener`, `packages/server/src/server.ts`), not `package-routes.ts` (routes return 202 before completion). Wiring: `packages/server/src/plugin-discovery-wiring.ts`. Implementation: `plugin-refresh.ts` `refreshPluginDiscovery()`.
|
|
1427
|
+
|
|
1428
|
+
```mermaid
|
|
1429
|
+
flowchart TD
|
|
1430
|
+
OP["package op completes"] --> SC{"success?"}
|
|
1431
|
+
SC -- no --> NOP["no refresh"]
|
|
1432
|
+
SC -- "yes, scope local" --> LOC["rerun local-scope detection"]
|
|
1433
|
+
SC -- "yes, scope global/user" --> R1["re-read served declaration"]
|
|
1434
|
+
R1 --> R2["clear discovery cache + content-hash stat cache"]
|
|
1435
|
+
R2 --> R3["discoverPlugins()"]
|
|
1436
|
+
R3 --> R4["flag changed/vanished loaded plugins restartRequired"]
|
|
1437
|
+
R4 --> R5["additive loadServerEntries: NEW ids only; hostApi-gated; pi-package server-trust-gated"]
|
|
1438
|
+
R5 --> LOC
|
|
1439
|
+
LOC --> R6["probe refresh + status store update"]
|
|
1440
|
+
R6 --> BC["ONE plugins_changed {plugins: PluginStatus[]} broadcast"]
|
|
1441
|
+
```
|
|
1442
|
+
|
|
1443
|
+
- Calls coalesce: refresh requested while one runs → exactly one follow-up.
|
|
1444
|
+
- Server entry throwing during refresh → `loaded:false` + error, broadcast, refresh continues.
|
|
1445
|
+
- Server entries load additively. Loaded plugin changed/vanished → `restartRequired: true`. Routes + handlers stay until restart.
|
|
1446
|
+
- Hot-added entry registering Fastify routes: refused (`FST_ERR_INSTANCE_ALREADY_LISTENING`). Recorded `loaded:false`, `restartRequired:true`, `HOT_ROUTE_RESTART_ERROR`.
|
|
1447
|
+
- Re-enable of discovered plugin whose server entry never loaded → restart.
|
|
1448
|
+
- Terminal `pi install` NOT visible live: only dashboard installs (Packages tab / `POST /api/packages/install`) reach the listener. Appears after dashboard restart. `pi-resources-watcher.ts` not wired to discovery.
|
|
1449
|
+
- `POST /api/plugins/:id/toggle` keeps contract (dependency graph, 409, cascade). Also broadcasts one `plugins_changed`.
|
|
1450
|
+
|
|
1451
|
+
**`plugins_changed`.** WS message `{type: "plugins_changed", plugins: PluginStatus[]}` (`packages/shared/src/browser-protocol.ts`). Emitted after refresh, toggle, trust write, local detection change. Client re-fetches runtime listing, recomputes enabled set, feeds `pluginAvailability`.
|
|
1452
|
+
|
|
1453
|
+
**Status shape (additive).** `PluginStatus.{source, shadowed, restartRequired, hostApi, client, serveApp}` (`packages/shared/src/dashboard-plugin/plugin-status.ts`).
|
|
1454
|
+
- `/api/health.plugins[]`: unauthenticated, tunnel-reachable → path- and hash-free subset only (`source`, `restartRequired`, `hostApi`, `client.delivery`, `client.refusedReason`, `serveApp`).
|
|
1455
|
+
- Paths, `client.sha256`, `shadowed[].packageDir`, `local-detected` rows → guarded `GET /api/plugins` + `plugins_changed` only.
|
|
1456
|
+
|
|
1457
|
+
**Host API version gate.** `PLUGIN_HOST_API_VERSION` (`packages/shared/src/dashboard-plugin/host-api.ts`) vs manifest `hostApi` caret range. Checked at discovery for BOTH halves.
|
|
1458
|
+
- `workspace`/`bundled`: warn only.
|
|
1459
|
+
- `installed`/`pi-package`: refuse server entry (error `host-api`) + client (`refused`, `host-api`).
|
|
1460
|
+
- Required for `pi-package` + `clientBundle` plugins.
|
|
1461
|
+
|
|
1462
|
+
**Trust defaults.**
|
|
1463
|
+
|
|
1464
|
+
| Thing | Default | Opt-in |
|
|
1465
|
+
|---|---|---|
|
|
1466
|
+
| `workspace` / `bundled` / `installed` server entry | loads (as before) | n/a |
|
|
1467
|
+
| `pi-package` server entry + bridge | DENIED (`server-untrusted`) | local `POST /api/plugins/:id/trust {server:true}` |
|
|
1468
|
+
| Runtime client (`clientBundle`) | refused (`untrusted`) | local `POST /api/plugins/:id/trust {sha256}`, pinned to content hash |
|
|
1469
|
+
| `serveApp` mount | trusted if bundled ∨ in `auth.trustedPlugins` ∨ in legacy `auth.capabilityRoutePlugins` | edit list; restart-effective |
|
|
1470
|
+
| `local-detected` | never loaded | install globally |
|
|
1471
|
+
|
|
1472
|
+
- `isServeAppTrusted` (`packages/server/src/auth/serve-app-host.ts`): bundled = source ∈ {`workspace`,`bundled`,`installed`} + realpath containment + basename in `piDashboard.bundledPlugins`. Basename alone no longer trusts. `pi-package` + `local-detected` never bundled.
|
|
1473
|
+
- `auth.trustedPlugins: {id, clientSha256?, server?}[]` written only by trust endpoints (`plugin-trust-store.ts`). `PUT /api/config` cannot write it.
|
|
1474
|
+
- Grant needs `operate` + genuinely local. Revoke needs `operate`. Tiers in `packages/shared/src/route-tiers.ts`.
|
|
1475
|
+
|
|
1476
|
+
**Runtime delivery pipeline.**
|
|
1477
|
+
|
|
1478
|
+
```mermaid
|
|
1479
|
+
flowchart LR
|
|
1480
|
+
DECL["pi-dashboard-build.json bundledPluginIds"] --> ADM["admission: not bundled, enabled, deps loaded, hostApi ok, trusted + pin"]
|
|
1481
|
+
DISC["discoverPlugins"] --> ADM
|
|
1482
|
+
TRUST["auth.trustedPlugins"] --> ADM
|
|
1483
|
+
ADM --> LIST["GET /api/plugins/runtime-clients"]
|
|
1484
|
+
ADM --> ASSETS["GET /plugin-assets/id/sha/*"]
|
|
1485
|
+
IDX["sendIndexWithImportMap: / and /index.html"] --> MAP["importmap -> /host/*.js shims"]
|
|
1486
|
+
LIST --> LOADER["runtime-plugin-loader.ts"]
|
|
1487
|
+
ASSETS --> LOADER
|
|
1488
|
+
MAP --> LOADER
|
|
1489
|
+
LOADER --> REG["claims, i18n, routes, reducers, eventTypes owners, bumpSlotClaimsVersion"]
|
|
1490
|
+
```
|
|
1491
|
+
|
|
1492
|
+
- Server pieces: `packages/dashboard-plugin-runtime/src/server/{runtime-client-registry,runtime-client-listing,plugin-assets-route,confined-static}.ts`, `packages/server/src/{plugin-runtime-clients,lib/index-html}.ts`, `routes/plugin-runtime-client-routes.ts`.
|
|
1493
|
+
- Client pieces: `packages/client/src/lib/plugins/runtime-plugin-loader.ts`, `packages/client/src/host-shims/*`.
|
|
1494
|
+
- Remote-server mode (`getApiBase()` non-empty) + Vite `--dev` page: loader does nothing.
|
|
1495
|
+
|
|
1496
|
+
**Core/plugin boundary.** `npm run check:plugin-boundary` (`scripts/check-plugin-boundary.mjs`, ratcheting `scripts/plugin-boundary-allowlist.json`, vitest wrapper). Plugin set from manifests. Shared contracts + `packages/mcp-core` in `docs/plugin-seams.md`.
|
|
1497
|
+
|
|
1498
|
+
**Absent-owner UX.** Manifest `eventTypes` → one group row per owned event type; availability decided at render time by `pluginAvailability`. Subagent state written by subagents-plugin slice + finalizers; generic heals in core. See `docs/plugin-seams.md`.
|
|
1499
|
+
|
|
1500
|
+
See change: decouple-plugins-from-core.
|
|
1501
|
+
|
|
1330
1502
|
#### Plugin Activation UI
|
|
1331
1503
|
|
|
1332
1504
|
Settings ▸ Plugins tab lists every discovered plugin (enabled or not) with display name, description, enable/disable toggle, missing-requirement chips, inline Install affordances.
|
|
@@ -2146,7 +2318,7 @@ Primitive: `useAsyncAction(fn, opts)` in `packages/client/src/hooks/useAsyncActi
|
|
|
2146
2318
|
|
|
2147
2319
|
Two completion modes:
|
|
2148
2320
|
|
|
2149
|
-
- `confirm:"http"` (default, fast ops): pending ends when `fetch()` settles.
|
|
2321
|
+
- `confirm:"http"` (default, fast ops): pending ends when `fetch()` settles. Remote access dialog (opened from the connection menu) connect/disconnect, ProviderAuthSection sign-out/remove-key.
|
|
2150
2322
|
- `confirm:"ws"` (slow ops): pending holds after HTTP ack until correlated `ServerToBrowserMessage` matches `opts.confirmEvent(msg, requestId)`. `opts.confirmTimeoutMs` (default 15000ms) fallback clears pending + info toast. Never stuck-spins.
|
|
2151
2323
|
|
|
2152
2324
|
Correlation contract: client generates requestId, sends in REST body, registers WS handler on `run()` BEFORE fn fires (race-free). Server echoes requestId into completion broadcast.
|
|
@@ -2217,7 +2389,7 @@ Opt-in grammar + spell + writing-improvement check for composer draft. LLM-only
|
|
|
2217
2389
|
- Offset-safe `applyAll()` / `accept()` / `dismiss()`.
|
|
2218
2390
|
|
|
2219
2391
|
**UI.** Grammar panel mounts in two places:
|
|
2220
|
-
- Composer draft (main chat): `packages/client/src/components/chat/GrammarPanel.tsx` renders above composer (sibling
|
|
2392
|
+
- Composer draft (main chat): `packages/client/src/components/chat/GrammarPanel.tsx` renders above composer (sibling above the composer dock in `App.tsx`).
|
|
2221
2393
|
- Explore/New Change dialogs: `ComposerPanelSlot` in draft editors (explorers, change filer).
|
|
2222
2394
|
- Diff-highlighted corrections + summary. Per-suggestion Accept/Dismiss + Apply-all button.
|
|
2223
2395
|
- `CommandInput.tsx` Check toolbar button + ⌘G shortcut (`onGrammarCheck` prop). Same panel renders both surfaces.
|
|
@@ -2940,7 +3112,7 @@ See change: widen-containment-to-resolved-checkout (was: git-root-file-containme
|
|
|
2940
3112
|
|
|
2941
3113
|
### Filesystem Browser (PathPicker)
|
|
2942
3114
|
|
|
2943
|
-
The dashboard's reusable directory chooser (`PathPicker`) is backed by three
|
|
3115
|
+
The dashboard's reusable directory chooser (`PathPicker`) is backed by three endpoints (full picker for local callers; remote callers confined, see Remote confinement below):
|
|
2944
3116
|
|
|
2945
3117
|
- `GET /api/browse?path=<dir>&q=<query>&detect=<0|1>` — lists subdirectories of `<dir>` (or `$HOME` when omitted). By default this is a single-`readdir` enumeration with no per-entry filesystem probes; `isGit` / `isPi` are absent from each `BrowseEntry`. Pass `detect=1` (only the literal string `"1"` is truthy) to opt into eager `.git` / `.pi` classification on every entry — useful for skill recipes that consumed the legacy shape. When `q` is non-empty, entries are case-insensitive substring-filtered and ranked:
|
|
2946
3118
|
- **Tier 0** exact match → **Tier 1** prefix → **Tier 2** word-boundary substring (after `-`, `_`, `.`, space, `/`) → **Tier 3** plain substring.
|
|
@@ -2959,6 +3131,70 @@ If a debounced query is still pending when Enter fires, the client flushes it sy
|
|
|
2959
3131
|
|
|
2960
3132
|
New folders can be created from two entry points — a footer **+ New folder** button (inline name entry), or an inline **+ Create "<name>" here** row shown when the typed partial has no exact match. The create-here row is suppressed if the parsed parent differs from the last-successfully-fetched directory (prevents creating inside a stale parent after a mid-path typo). On success the picker refetches and descends into the new directory.
|
|
2961
3133
|
|
|
3134
|
+
#### Remote confinement (change: harden-server-capability-bounds)
|
|
3135
|
+
|
|
3136
|
+
`/api/browse`, `/api/browse/flags`, `/api/browse/mkdir` confine non-local callers. Local callers (`isLocallyTrusted` true) unchanged: full picker.
|
|
3137
|
+
|
|
3138
|
+
- Not genuinely local = tunnel, LAN, relayed loopback with forwarding header. Confined to shared roots.
|
|
3139
|
+
- Shared roots = `$HOME` + pinned dirs + session cwds + workspace folders + worktree-init trust roots + project-scope access-grant subjects.
|
|
3140
|
+
- Compare by realpath. Symlink escape refused.
|
|
3141
|
+
- Forbidden: `/`, `$HOME` itself as pinned root, system roots, ancestors of those, `~/.ssh`, `~/.pi`. `~/.pi` subtree refused even under `$HOME`.
|
|
3142
|
+
- Outside roots → 403 `path outside allowed roots`.
|
|
3143
|
+
- Listing: `confined: true`; `parent: null` at root top.
|
|
3144
|
+
- Flags: any outside path → 403 whole request.
|
|
3145
|
+
- mkdir: parent outside → 403 before any write.
|
|
3146
|
+
- Remote sockets cannot widen roots. `pin_directory`, `add_folder_to_workspace`, `move_folder_to_workspace` outside roots dropped. Server sends `folder_refused {path, reason: outside_allowed_roots}`. Client toast: "Ask the host to pin it".
|
|
3147
|
+
- Locality bit stamped per socket once at `/ws` upgrade. Unstamped = remote.
|
|
3148
|
+
- Docker: host browser hits container via port mapping = non-loopback peer. Confined to container `$HOME` + auto-pinned `PI_WORKSPACES`. Recovery actions refused there; use `docker compose restart` / `docker exec`. Set `browse.confineRemote: false` to lift it.
|
|
3149
|
+
- Residual: marker-less relay (`ssh -R`, no forwarding headers) looks loopback = local unless `requireLocalProof: false` (opt-out). Default on: refused without proof.
|
|
3150
|
+
- Operator opt-out: `config.json` `browse.confineRemote` (default `true`). Only explicit `false` disables. Read at server start (restart to apply). Off → remote callers browse / mkdir / pin like local callers. Used by the Docker e2e harness (browser = remote peer via port mapping; specs pin per-test dirs outside `$HOME`); harness env `PI_E2E_BROWSE_CONFINEMENT=1` keeps it on. Shipping installs stay confined.
|
|
3151
|
+
- Threat model: guards observe-tier remote viewer. Caller that may spawn session/terminal already has FS reach.
|
|
3152
|
+
- Shell output over tunnel (change: harden-bridge-inbound-and-discovery): `!` / `!!` / exec-template bash output (`bash_output`, `packages/extension/src/command-handler.ts`) reaches every tunnel viewer by design.
|
|
3153
|
+
- Only credential-vault values masked (`packages/extension/src/vault-redaction.ts`). No pattern redaction of secrets in output.
|
|
3154
|
+
- Operator rule: no secrets printed by shell commands on a tunneled session.
|
|
3155
|
+
|
|
3156
|
+
#### Bridge inbound bounds (change: harden-bridge-inbound-and-discovery)
|
|
3157
|
+
|
|
3158
|
+
Bridge caps per-unit-time work that server or bridge-socket holder can trigger. Limiter: `packages/extension/src/inbound-limits.ts`.
|
|
3159
|
+
|
|
3160
|
+
- `PI_DASHBOARD_BRIDGE_MAX_BASH` = max concurrent `!` / `!!` / exec-template bash per session. Default `4`.
|
|
3161
|
+
- `PI_DASHBOARD_BRIDGE_PROMPT_RATE` = `<burst>/<refillPerSec>`. One token bucket per bridge process. Default `30/10`.
|
|
3162
|
+
- Prompt bucket shared by: `send_prompt`, `retry_session`, `git_commit_draft`, flow_management run, `plugin_emit_event`, `promote_followup_entry`.
|
|
3163
|
+
- Valid values: positive integers only. Invalid (`0`, negative, non-integer, empty) → default + one log line per process per variable. `0` ≠ unlimited.
|
|
3164
|
+
- Bucket survives WS reconnect and `/reload` (per bridge process). Keyed on process-global shared state (`inst.shared`), not the connection: a per-connection key let the server refill it via `send_prompt /reload`.
|
|
3165
|
+
- Refusal visible: inline `command_feedback` error in chat. Never silent drop.
|
|
3166
|
+
- Bash refusal text: `bash concurrency limit reached (N in flight per session)`.
|
|
3167
|
+
- Prompt refusal text: `inbound command rate limit reached (burst B, refill R/s)`.
|
|
3168
|
+
- `server_restarting.quiesceMs` normalized in `ConnectionManager.pauseAutoStart` (`packages/extension/src/connection.ts`): invalid / ≤0 ignored; fraction rounded up; capped at `MAX_QUIESCE_MS` = `120000` (`packages/shared/src/recovery-timing.ts`). Later pause never shortens active one.
|
|
3169
|
+
|
|
3170
|
+
#### Bridge loopback counter-proof (change: harden-bridge-inbound-and-discovery)
|
|
3171
|
+
|
|
3172
|
+
- Bridge holding local token (`~/.pi/dashboard/local/token`) requires server counter-proof on EVERY loopback dial (`ws:` and `wss:`): configured endpoint, auto-start, discovered mDNS advert, retarget, reconnect. `ws+unix:` exempt.
|
|
3173
|
+
- Independent of `PI_DASHBOARD_REQUIRE_SERVER_PROOF`.
|
|
3174
|
+
- Refusal: no register, no session data. Log cause `server_proof_missing` (no proof) or `server_proof_invalid` (bad MAC / timeout). Then backoff.
|
|
3175
|
+
- Opt-out: `PI_DASHBOARD_ALLOW_UNPROVEN_LOCAL_SERVER=1` (exactly `1`). Logged each dial. Needed for same-host server older than 0.10.0.
|
|
3176
|
+
- Same-user rogue process out of scope (can read token).
|
|
3177
|
+
- Device bearer (`PI_DASHBOARD_TOKEN`) sent only to pinned endpoint: configured, or pin-store `lastEndpoint`. Canonical host:port equality. Lone pin is no fallback.
|
|
3178
|
+
- Discovered host → log `bridge ticket unpinned_discovered_host`. No request sent.
|
|
3179
|
+
|
|
3180
|
+
#### Git remote credentials (change: harden-bridge-inbound-and-discovery)
|
|
3181
|
+
|
|
3182
|
+
- Bridge strips userinfo from remotes before building links and before `vault_sync_request.origin`: http(s) all userinfo; ssh:// password only. Hub strips again.
|
|
3183
|
+
- Unparseable remote with userinfo → no origin, no links.
|
|
3184
|
+
|
|
3185
|
+
#### Recovery server lockdown (change: harden-server-capability-bounds)
|
|
3186
|
+
|
|
3187
|
+
`recovery-server.ts` serves recovery page when main server fails. Imports node built-ins only.
|
|
3188
|
+
|
|
3189
|
+
- Binds `config.host` (default `127.0.0.1`). Never all interfaces unless operator sets `bindHost`.
|
|
3190
|
+
- `GET /` and `GET /api/health` stay open.
|
|
3191
|
+
- `POST /api/recovery/retry|reinstall` admitted iff either:
|
|
3192
|
+
- local token: `x-pi-local-token`, timing-safe compare; or
|
|
3193
|
+
- loopback peer AND none of 8 forwarding headers (`x-forwarded-for`, `x-forwarded-host`, `x-forwarded-proto`, `x-real-ip`, `forwarded`, `via`, `x-forwarded-server`, `x-forwarded-port`) AND loopback `Host` AND `Origin` absent or same host:port as `Host` (default port stripped; `Origin: null` refused).
|
|
3194
|
+
- Else 403 `text/plain` with remedy. Page shows it in `role=alert` callout. Buttons stay enabled.
|
|
3195
|
+
- One log line per refusal: route only, no token.
|
|
3196
|
+
- Residual: `ssh -R` rewriting `Host` to localhost and sending no `Origin` passes.
|
|
3197
|
+
|
|
2962
3198
|
### Pi Resources Browser
|
|
2963
3199
|
|
|
2964
3200
|
The dashboard can display pi extensions, skills, and prompts installed for each workspace. The server-side scanner (`pi-resource-scanner.ts`) discovers resources from three sources:
|
|
@@ -3171,6 +3407,47 @@ File-open surfaces: internal Monaco pane and preview overlay only.
|
|
|
3171
3407
|
|
|
3172
3408
|
v2–v4 follow-on (pin-to-split, create-file, edit-with-conflicts) deferred to separate proposals.
|
|
3173
3409
|
|
|
3410
|
+
### Editor pane chrome
|
|
3411
|
+
|
|
3412
|
+
Client only. No API change. Code: `packages/client/src/components/editor-pane/`. See change: scope-anchor-editor-pane-controls.
|
|
3413
|
+
|
|
3414
|
+
Pane bar (`EditorPane.tsx`): `tree-toggle` (Files, labelled) · `EditorTabs` tablist (`min-w-0 overflow-x-auto`) · `new-tab-menu-toggle` (`+`) · spacer · `tab-search-toggle` (`⌄`) · `editor-pane-close` (✕). Tablist is the only flexible item.
|
|
3415
|
+
|
|
3416
|
+
Document bar (`DocumentBar.tsx`, `doc-bar`):
|
|
3417
|
+
- file tab: `doc-breadcrumb` · mode switcher (`file-mode-*`, `FileModeSwitcher`) · Reload · `tab-open-in-app` · `tab-reveal-in-file-manager` · `doc-more-menu` (`⋯`).
|
|
3418
|
+
- url tab: `tab-open-in-browser`.
|
|
3419
|
+
- diff / live / terminal / plugin tab: title line only.
|
|
3420
|
+
- no tab: bar hidden.
|
|
3421
|
+
- Open + Reveal gated on `systemOpen`. Reveal label from `/api/health` `platform`: Finder / Explorer / file manager.
|
|
3422
|
+
- Breadcrumb folder segment: expand-only reveal (`expandTreeRoots {relPaths}`), `railView="files"`, `setTreeVisible(true)`. Leaf opens `⋯`: Show in file tree, Copy full/relative/file name. Outside-cwd file: no relative copy, no show-in-tree.
|
|
3423
|
+
- Narrow (`ResizeObserver`, `width < 640`): Open + Reveal move into `⋯` (first items, each test id once). Ancestors → `…`.
|
|
3424
|
+
|
|
3425
|
+
`+` menu (`NewTabMenu.tsx`, session panes): Terminal (`new-terminal-launch`), Live preview (`live-preview-launch`), Open file… (`open-file-launch`).
|
|
3426
|
+
|
|
3427
|
+
Search = rail view. Session panes only (`hasFileSearch`, true when provider has `onFilenameSearch`).
|
|
3428
|
+
- State: `railView: "files" | "search"`, `searchMode: "filenames" | "contents"`. Reset on `sessionId` change.
|
|
3429
|
+
- Rail switch: `rail-view-files` / `editor-search-toggle`. Rail visible = `treeVisible || railView === "search"`.
|
|
3430
|
+
- Cmd/Ctrl-P filenames, Cmd/Ctrl-Shift-F contents. Same key closes. Other key switches mode. Esc closes view only when focus inside rail.
|
|
3431
|
+
- Only persisted value: `treeVisible`; search never writes it. Folder panes: no Search view, no `open-file-launch`, Cmd-P not intercepted.
|
|
3432
|
+
|
|
3433
|
+
Bulk close:
|
|
3434
|
+
- Reducer `closeTabs {paths}` (path-keyed, unknown ignored). Single close: `reduceCloseTab`.
|
|
3435
|
+
- `handlerCloseRisk(tab, remaining, lookups, {unknownIsRisky})` → `"unsaved" | null` (`file-handler/close-risk.ts`). Shared by `guardTabClose` (`unknownIsRisky: true`) and `planBulkClose`.
|
|
3436
|
+
- `planBulkClose(openFiles, targetPaths, lookups)` → `{ targets, risky }`. `risky` = deduped `{ kind, id | key, reason, tabPaths[] }`.
|
|
3437
|
+
- Unknown dirty state: silent in bulk, prompts in single close. Single terminal close: silent.
|
|
3438
|
+
- Risky set non-empty → `BulkCloseConfirm` (`bulk-close-confirm`): Cancel (focused) · Close all but these N · Close all & discard. Empty → closes without asking.
|
|
3439
|
+
- Runner closes open menus first, recomputes plan on confirm. `paneOverlayOpen` makes Cmd/Ctrl-W no-op.
|
|
3440
|
+
- Tab context menu `tab-context-menu`: Close · Close other tabs · Close tabs to the right · Close all tabs · Show in file tree · Copy path. Opens on right-click, ContextMenu key, Shift+F10.
|
|
3441
|
+
|
|
3442
|
+
Search tabs (`TabSearchPopover.tsx`, input `tab-search-input`):
|
|
3443
|
+
- `matchTabs` (`lib/layout/match-tabs.ts`). Haystack = display label + location (never raw path prefix).
|
|
3444
|
+
- Token AND. Fold per code point: NFD, strip U+0300–U+036F, lower-case. Index map keeps highlight ranges. `ß` `ø` `ł` match only themselves. Order = tab-strip order; first match preselected.
|
|
3445
|
+
- ↑ ↓ move · Enter activate · Esc close, refocus `⌄` · Delete/Backspace on empty field closes selected (single-close path).
|
|
3446
|
+
- Footer: empty query → `Close all but the active tab`; query → `Close N matching tabs` (same confirm).
|
|
3447
|
+
- No match: Enter opens rail Search prefilled (`{ query, nonce }`) when `hasFileSearch`; else `No open tab matches`.
|
|
3448
|
+
|
|
3449
|
+
Menus (`+`, document `⋯`, tab context): `Popover` + `role=menu` + `ActionList`. Keys in `menu-keys.ts`: ↑ ↓ wrap, Home/End, Enter/Space, Esc closes + refocuses trigger, disabled items skipped, first item focused on open.
|
|
3450
|
+
|
|
3174
3451
|
### Split editor workspace
|
|
3175
3452
|
|
|
3176
3453
|
`SplitWorkspaceProvider` lifts split state + editor-pane state per session.
|
|
@@ -3221,6 +3498,97 @@ Shell overlays dispatch by route match (see Shell overlay routing). Mutual exclu
|
|
|
3221
3498
|
|
|
3222
3499
|
Plugin content-view claims (flows-plugin) still predicate-driven via SlotRegistry. See change `overlay-url-routing`.
|
|
3223
3500
|
|
|
3501
|
+
### Live Preview: Static Targets, Exposure, Egress (change: improve-canvas-html-and-url-ux)
|
|
3502
|
+
|
|
3503
|
+
Source: `packages/server/src/live-server/` (`live-static.ts`, `live-csp.ts`, `live-exposure.ts`, `live-browser-gate.ts`, `live-egress.ts`, `live-csp-report.ts`, `live-origin-scan.ts`, `live-capability.ts`), `packages/server/src/access/planes.ts`, `packages/shared/src/live-server.ts`, `packages/shared/src/preview-egress.ts`. Design: `openspec/changes/improve-canvas-html-and-url-ux/design.md` (D1-D10).
|
|
3504
|
+
|
|
3505
|
+
#### Target kinds
|
|
3506
|
+
- `port`: proxied loopback `host:port`. Persisted only when `addedBy:"user"`. Preset (agent declare, confirm-chip tap) in memory, ≤16/session LRU. Rejects dashboard listen ports.
|
|
3507
|
+
- `static`: `{cwd, root}` via `POST /api/live-server/start-static`. In memory, keyed `(cwd, root)`, ≤32/session LRU.
|
|
3508
|
+
- Eviction: LRU. Evicted target tokens revoked. "Use" = register or accepted request.
|
|
3509
|
+
|
|
3510
|
+
#### Static roots and servable files (D2)
|
|
3511
|
+
- In cwd: nearest ancestor (inclusive, ≤ cwd) with `index.html` or `package.json`. None → file dir. No whole-cwd fallback.
|
|
3512
|
+
- Granted file outside cwd: root = file dir. Per-request gate limits to grant.
|
|
3513
|
+
- Extension allowlist (`STATIC_WEB_EXTENSIONS`): html htm css js mjs json svg png jpg jpeg gif webp avif ico woff woff2 ttf otf mp4 webm ogg mp3 wav m4a. No `.map`, `.txt`.
|
|
3514
|
+
- 404: dot / `.git` / `node_modules` segments, forbidden subjects, `isCredentialName` names.
|
|
3515
|
+
- Realpath containment. `%2e`/`%2f` decoded once, re-checked. Symlink escape → 404.
|
|
3516
|
+
- Single `Range` → 206. Headers: `Cache-Control: no-store`, `nosniff`, `Referrer-Policy: no-referrer`.
|
|
3517
|
+
- Every request re-runs `gateFilePath(cwd, <real path>)`. Revoked grant or pin applies next request.
|
|
3518
|
+
|
|
3519
|
+
#### Capability URL and policy (D1, D4)
|
|
3520
|
+
- Mint: `POST /api/live-server/:id/capability` → `/live/<id>/~c/<token>/`. Body `{egress:"open"|"restricted", scripts:boolean, runScripts?:true}`.
|
|
3521
|
+
- Fail-closed: absent/invalid `egress` → `restricted`. Absent `scripts` → `false`.
|
|
3522
|
+
- Policy stored on token. Never read from request path, query or header.
|
|
3523
|
+
- Idle / max: port 30 min / 12 h; static 10 min / 2 h (`CAPABILITY_*_MS`).
|
|
3524
|
+
- `POST /api/live-server/:id/touch {tokenId}` every 5 min while viewer mounted + visible.
|
|
3525
|
+
- Token reused only when (target, policy, exposure epoch, viewer) unchanged.
|
|
3526
|
+
- Logs: `redactCapability` → `/~c/<redacted>`.
|
|
3527
|
+
|
|
3528
|
+
#### Response isolation (D3)
|
|
3529
|
+
| Mode | Frame `sandbox` | Response CSP |
|
|
3530
|
+
|---|---|---|
|
|
3531
|
+
| open, scripts | `allow-scripts allow-forms allow-popups allow-downloads` | `sandbox …; object-src 'none'; frame-ancestors 'self'` |
|
|
3532
|
+
| restricted, scripts | `allow-scripts allow-forms` | `sandbox …` + egress directives |
|
|
3533
|
+
| scripts off | empty | `sandbox` (+ egress directives if restricted) |
|
|
3534
|
+
- Applies to port AND static targets on every capability response (`buildLiveCsp`).
|
|
3535
|
+
- Our CSP appended to upstream CSP. Upstream never stripped. Browser enforces intersection.
|
|
3536
|
+
- Restricted: `default-src 'none'`; `script-src` / `style-src` = `<P> 'unsafe-inline'` (+ `'unsafe-eval'` with scripts) + `<G>`; `connect-src <P> <G>`; `form-action 'none'`; `base-uri 'none'`; `frame-src 'none'`; `object-src 'none'`; `worker-src <P> blob:`; `manifest-src 'none'`; `frame-ancestors 'self'`; `report-uri` / `report-to`.
|
|
3537
|
+
- `<P>` = prefix from validated `Host`. Never `'self'`. Never dashboard origin.
|
|
3538
|
+
- `<G>` = project grants ∪ viewer allow-once set.
|
|
3539
|
+
|
|
3540
|
+
#### Exposure policy (D5)
|
|
3541
|
+
- `exposed` if ANY: bind host not loopback (unparseable → exposed); `collectEndpoints()` non-empty (tunnel, `publicBaseUrls`, TLS); forwarding-header request seen since start (sticky); `liveServer.previewExposure: "exposed"` in `config.json`. Else `local-only`.
|
|
3542
|
+
- Same-host relay adding no header (`ssh -L`, socat) is undetectable. Operators set `previewExposure`. Residual.
|
|
3543
|
+
- `GET /api/live-server/policy` (observe) → `{exposure, epoch, promptingEnabled}`.
|
|
3544
|
+
- Epoch bumps on every change. Change to `exposed`: revoke restricted scripts-on `local-only` tokens; broadcast `preview_exposure_changed {epoch}`; viewers re-mint without scripts within 2 s.
|
|
3545
|
+
- Scripts on restricted mint: `local-only` → allowed. `exposed` → refused unless `runScripts:true` (viewer "Run scripts" only).
|
|
3546
|
+
- Frames cannot mint: opaque origin, CORS rejects `null`, no token on `/api`. Client-asserted marker is safe.
|
|
3547
|
+
- Local-minted token accepted only from genuinely-local requests.
|
|
3548
|
+
- Residual: remote operator open with scripts → token valid to expiry. Documented in viewer tooltip.
|
|
3549
|
+
- Provenance: operator open → `open`. Agent / undeclared → `restricted`. Confirm-chip tap → restricted preset (consents to connect, not egress).
|
|
3550
|
+
- Agent-declared loopback URL never auto-opened. Routed to confirm chip.
|
|
3551
|
+
|
|
3552
|
+
#### Browser-capability rule (D10)
|
|
3553
|
+
- `isBrowserOriginated(headers)`: `Origin: null` or any `Sec-Fetch-*` header.
|
|
3554
|
+
- Browser-originated `/live/` HTTP or WS upgrade without valid capability → 404 (`live-server-proxy.ts`).
|
|
3555
|
+
- Non-browser local callers (curl, `fastify.inject`) keep admission for port targets.
|
|
3556
|
+
- Static targets: never reachable without capability, by any caller.
|
|
3557
|
+
|
|
3558
|
+
```mermaid
|
|
3559
|
+
flowchart TD
|
|
3560
|
+
A["Request /live/:id/…"] --> B{"Browser-originated?<br/>Origin null or Sec-Fetch-*"}
|
|
3561
|
+
B -- yes --> C{"Valid capability?<br/>/~c/token/"}
|
|
3562
|
+
C -- no --> X["404"]
|
|
3563
|
+
C -- yes --> K{"Target kind"}
|
|
3564
|
+
B -- no --> D{"Capability present?"}
|
|
3565
|
+
D -- yes --> K
|
|
3566
|
+
D -- no --> E{"Port target admitted?<br/>static never"}
|
|
3567
|
+
E -- no --> X
|
|
3568
|
+
E -- yes --> P["Proxy upstream<br/>no capability CSP"]
|
|
3569
|
+
K -- port --> Q["Proxy upstream<br/>CSP from token policy"]
|
|
3570
|
+
K -- static --> G{"gateFilePath(cwd, real path)<br/>per request"}
|
|
3571
|
+
G -- denied --> X
|
|
3572
|
+
G -- ok --> S["serveStatic<br/>CSP from token policy"]
|
|
3573
|
+
```
|
|
3574
|
+
|
|
3575
|
+
#### Preview egress plane (D6, D7)
|
|
3576
|
+
- Origin scan (`live-origin-scan.ts`): HTML ≤ 2 MiB (`SCAN_MAX_HTML_BYTES`) + same-root CSS. Reads `src`, `srcset`, `poster`, `data`, `<link href>`, `@import`. Plain `<a href>` ignored.
|
|
3577
|
+
- Output `{source:"markup"}`. Truncation → `scanIncomplete`. Root-absolute refs → `rootAbsolute`.
|
|
3578
|
+
- Runtime reports: `POST /live/<id>/~c/<token>/__pi/csp-report` (`CSP_REPORT_SUBPATH`). Types `application/csp-report`, `application/reports+json`.
|
|
3579
|
+
- Limits: body ≤ 64 KiB (413), 20/s and 600/h per token (429). Reads `blocked-uri` only.
|
|
3580
|
+
- Runtime reports best-effort. Page may forge → labelled "reported by this page", allow-once only.
|
|
3581
|
+
- Blocked set per token ≤ 64 (`MAX_BLOCKED_ORIGINS`). Eviction drops runtime entries first.
|
|
3582
|
+
- `GET /api/live-server/:id/egress?token=` and `POST /api/live-server/:id/allow-once {tokenId, origin}`: control tier. Minting principal only.
|
|
3583
|
+
- Allow-once keyed by client `viewerId` (per tab), ≤ 32.
|
|
3584
|
+
- Grant = deferred plane `preview-egress` (`planes.ts`). `allow-always` / `deny`. Never YOLO-eligible.
|
|
3585
|
+
- "Allow for this project" (operator click) → deferred registry entry → standard dialog. Prompting off (default) → Allow once only.
|
|
3586
|
+
- Subject: `canonicalHttpsOrigin` (https only, no userinfo, punycode, default port elided).
|
|
3587
|
+
- Ungrantable (`isUngrantableEgressOrigin`): non-https, `localhost`, loopback / private / link-local / CGNAT / ULA IP literals, single-label, `.local` `.internal` `.lan` `.home.arpa`, IPv4-embedding labels, dashboard origins.
|
|
3588
|
+
- Grant-time DNS: 3 s (`EGRESS_DNS_TIMEOUT_MS`). Private / loopback / fail → "Could not verify this origin; try again". Later rebinding = residual.
|
|
3589
|
+
- Store: `~/.pi/dashboard/preview-egress.json` `{[projectKey]: string[]}` via `auth/locked-json-file.ts`. Override `PI_PREVIEW_EGRESS_STORE`.
|
|
3590
|
+
- `projectKey` = canonical subject of git common root, else cwd.
|
|
3591
|
+
|
|
3224
3592
|
### Network Access Control
|
|
3225
3593
|
|
|
3226
3594
|
One universal network guard plus the auth plugin. Universal guard runs whether or not auth is configured.
|
|
@@ -3285,25 +3653,53 @@ Both honor same matching logic. Both work independently of whether `auth.provide
|
|
|
3285
3653
|
|
|
3286
3654
|
Hardens five residual trust / credential-boundary weaknesses from audit. Each mitigates a confirmed finding; none is a standalone RCE.
|
|
3287
3655
|
|
|
3288
|
-
**Strict local proof (`requireLocalProof`).** Top-level config key, default `
|
|
3289
|
-
- `pi_dash_local` httpOnly `SameSite=Strict` cookie
|
|
3290
|
-
- `X-Pi-Local-
|
|
3291
|
-
-
|
|
3656
|
+
**Strict local proof (`requireLocalProof`).** Top-level config key, default `true` (change `close-container-loopback-impersonation`). Missing or non-boolean value → `true`; server logs one warning per distinct raw value (`liveRequireLocalProof`, `packages/server/src/config-snapshot.ts`). Only explicit boolean `false` opts out. Read live from `config.json` per request — toggling needs no restart. Default on = the network guard admits a bare-loopback request (loopback peer, no forwarding header) only on `observe`-tier REST reads (`isObserveApiRequest` in `localhost-guard.ts`) and `/v1/*` (`packages/shared/src/route-tiers.ts`). Everything else needs PROOF, one of:
|
|
3657
|
+
- `pi_dash_local` httpOnly `SameSite=Strict` cookie (format below);
|
|
3658
|
+
- `X-Pi-Local-Proof` header (CLI, bridge);
|
|
3659
|
+
- desktop app (Electron loads `/auth/local-proof`);
|
|
3660
|
+
- signed-in or paired principal (`request.isAuthenticated`).
|
|
3292
3661
|
|
|
3293
3662
|
Gated surfaces: `control` / `operate` REST routes, browser WS (`/ws`, `/ws/terminal/*`, `/live/*`), plugin-registered WS scopes (`isPluginScopePeerLocal`), bridge-ticket mint (`decideBridgeTicketMint`), and the route-tier exemption (`tierRefusalFor`). A `127.0.0.1` entry in `trustedNetworks` / `auth.bypassHosts` no longer re-admits a relay under strict — `isTrustedSource` refuses a loopback-range peer without proof.
|
|
3294
3663
|
|
|
3295
|
-
|
|
3664
|
+
```mermaid
|
|
3665
|
+
flowchart TD
|
|
3666
|
+
R["Bare-loopback request<br/>(loopback peer, no X-Forwarded-*)"] --> O{"requireLocalProof<br/>explicit false?"}
|
|
3667
|
+
O -- yes --> T["Trusted (opt-out, legacy)"]
|
|
3668
|
+
O -- no --> V{"observe-tier REST<br/>or /v1/*?"}
|
|
3669
|
+
V -- yes --> A["Admit"]
|
|
3670
|
+
V -- no --> P{"Proof present?<br/>cookie / X-Pi-Local-Proof /<br/>principal"}
|
|
3671
|
+
P -- yes --> A
|
|
3672
|
+
P -- no --> D["403 network_not_allowed<br/>reason local_proof_required"]
|
|
3673
|
+
```
|
|
3674
|
+
|
|
3675
|
+
**Why it exists.** A header-injecting tunnel (zrok) presents as loopback but carries `X-Forwarded-*`, so it already fails `isGenuinelyLocal`. A marker-less relay (`ssh -R`, `socat`) terminates on `127.0.0.1` and injects NO forwarding header — indistinguishable from a same-host browser, so it inherits full unauthenticated access to code-exec routes. Default on closes this. Opt-out (`false`) re-opens it; only zrok-class tunnels stay safe under opt-out.
|
|
3676
|
+
|
|
3677
|
+
**Denial.** Under strict, a proof-less bare-loopback denial is `403 { success: false, error: "network_not_allowed", reason: "local_proof_required", hint: … }` — same `error` literal as every other network denial, so clients keep branching on `error`; `reason` carries the strict-mode signal and `hint` names `pi-dashboard open`. `GET /api/health` adds `localProof: "required"` only for a bare-loopback caller without proof. Client `useNetworkDenied` probes on `offline` + `auth_required` and shows a banner with copyable `pi-dashboard open`. `/auth/login` shows the same remedy instead of single-provider auto-redirect. Signed-in loopback tab admitted on observe routes: session cookie tagged before the strict observe return (`packages/server/src/auth/auth-plugin.ts`).
|
|
3678
|
+
|
|
3679
|
+
**Bootstrap.** `pi-dashboard open [--print]` mints a one-time code (`POST /api/local-proof`, `X-Pi-Local-Token` only, 60 s TTL, single use via `LocalProofCodeStore`) and opens `/auth/local-proof?code=…`, which redeems it, sets the `pi_dash_local` cookie, and redirects `/`. Electron always loads that URL. Server not running → `open` exits `1` ("server not running"). Bootstrap routes register regardless of the flag. `pi-dashboard login --local` (break-glass) prints a link through `/auth/local-proof?code=…&next=/?pi_local=<code>` so a plain tab authorizes first.
|
|
3680
|
+
|
|
3681
|
+
**Forwarded loopback.** `ssh -L`, VS Code port forward, WSL arrive as bare loopback. Run `pi-dashboard open --print` on the server; open the printed URL through a SAME-PORT forward (cookie is port-bound).
|
|
3682
|
+
|
|
3683
|
+
**`pi_dash_local` cookie.** Format `id.issuedAt.lastUse.port.HMAC`, `HMAC` keyed `k_local = HMAC(localToken, "pi-dashboard/local-proof/v1")`. Bound to issuing listener `port` (`packages/server/src/auth/local-proof.ts`). Idle expiry 12 h. Re-signed on use when last refresh > 1 h old. Absolute cap 30 d. Rotating local token invalidates all cookies. Accepted residual: browsers send the cookie to every `localhost:<port>` site, so a local web app can capture and replay it to the same port within the idle window. Follow-up: dedicated loopback host.
|
|
3684
|
+
|
|
3685
|
+
**Opt-out.** `requireLocalProof: false` re-exposes the control plane to every container on the host: a container reaching host `127.0.0.1` (Docker Desktop `host.docker.internal`, `--network host`, `ssh -R`, `socat`) looks like bare loopback. See change: close-container-loopback-impersonation.
|
|
3686
|
+
|
|
3687
|
+
**One-time secret rotation.** `rotateSecretsOnce()` (`packages/server/src/auth/secret-rotation.ts`) runs at start of `createServer`. Claims `~/.pi/dashboard/local/rotation.lock` (exclusive link; stale after 30 s or dead pid; wait cap 35 s). If `local/rotation-epoch` < `REQUIRED_ROTATION_EPOCH` (=1): writes new 0600 `local/token` and new `auth.secret` (`writeConfigFileSecure`), then epoch file last. Effect: everyone signs in once; proof cookies reissued. Failure fails CLOSED: exit 1 before listening, one log line naming step + lock + epoch paths. Upgrade: stop every dashboard instance first (older instance on same HOME keeps old token until restart). No rollback needed; delete `local/rotation-epoch` only to force another rotation.
|
|
3296
3688
|
|
|
3297
|
-
**
|
|
3689
|
+
**Dashboard state guard** (`packages/server/src/lib/dashboard-state-guard.ts`). Always refused, every caller, every mode, not undone by opt-out: `~/.pi/dashboard/local/**` and `identity.key` (post-open fstat dev/ino recheck defeats symlink swap). Trust-gated: rest of `~/.pi/dashboard/` (`config.json` holds auth HMAC secret), refused unless caller locally trusted now or logged in (paired-device bearer not enough). Covers `/api/file*`, `/api/session-file`, `/api/file/write*`, `/api/grep`, mention resolve, open-in-system, reveal, live static gates. Unproven local caller's containment miss is prompt-ineligible (no operator access prompt).
|
|
3298
3690
|
|
|
3299
|
-
|
|
3691
|
+
**`pi-dashboard api <METHOD> <path> [--data <json>] [--port n]`** (`cmdApi`, `packages/server/src/cli.ts`). Mints fresh proof per request; dials loopback address literal; no redirect follow. Path: single leading `/`, no `#`, no control chars. Exit `0` on 2xx (body → stdout), `1` other status (body → stderr), `2` usage error or server not running. Unknown subcommand → exit 2 + usage. Older binaries without `api` fall through to foreground start: require the first release shipping `api`. Slash-command exec templates get env `PI_DASHBOARD_CLI` (absolute, shell-quoted): `eval "$PI_DASHBOARD_CLI" api GET /api/config`.
|
|
3692
|
+
|
|
3693
|
+
**Browser relay tickets.** `cdpUrl` and extension `mcpRelayUrl` carry single-use `?ticket=` (32 random bytes base64url, 60 s TTL, bound to guid + role `ext`|`cdp`, consumed by first presenting dial, in-memory, digest-only, never logged). Pass whole `cdpUrl` to `agent-browser connect`; dropped client needs fresh `browser_connect`. Plugin WS scopes may set `peerCredential: "plugin"` (skips only strict proof; host/origin/locality still enforced). Spike: `openspec/changes/close-container-loopback-impersonation/relay-ticket-spike.md`.
|
|
3694
|
+
|
|
3695
|
+
**Accepted residuals.** Observe-tier reads open to containers: transcripts, session lists, files inside session cwds and under `~/.pi` outside the dashboard dir (e.g. `~/.pi/agent/auth.json`); `$HOME`-cwd session also exposes `~/.ssh`. `/v1/*` spend. Live capability URLs (`/live/<token>/…`) judged without proof (Electron "Open in browser" needs it): a capability URL leaked into a transcript lets a container open that preview. A container that MOUNTS `~/.pi` or `$HOME` can read the token: NEVER mount `~/.pi/dashboard` into a container. Bridge gateway loopback grace + recovery server unchanged (out of scope).
|
|
3300
3696
|
|
|
3301
3697
|
**Trade-offs (stated, not implied).**
|
|
3302
3698
|
- `/v1/*` model proxy keeps bare-loopback admission even under strict: local pi processes call it, and a marker-less relay can spend model credentials but cannot execute code.
|
|
3303
3699
|
- `/api/health` posture disclosure unchanged.
|
|
3304
|
-
-
|
|
3700
|
+
- Raw `curl` to `control` / `operate` routes from this host is refused (`403 local_proof_required`). Use `pi-dashboard api <METHOD> <path>`. `npm run reload` and the CLI `restart` already send proof.
|
|
3305
3701
|
|
|
3306
|
-
**Pairing approval never honors bare loopback (any mode).** `createApprovalGuard` on `POST /api/pair/approve` and `/api/pair/approve-pending` admits only a login session, a valid proof cookie, or `X-Pi-Local-Token`; a device bearer is refused first, and Host admission still applies.
|
|
3702
|
+
**Pairing approval never honors bare loopback (any mode).** `createApprovalGuard` on `POST /api/pair/approve` and `/api/pair/approve-pending` admits only a login session, a valid proof cookie, or `X-Pi-Local-Token`; a device bearer is refused first, and Host admission still applies. Applies in every `requireLocalProof` mode, including opt-out. A hand-typed `http://localhost:8000` on an auth-off install must use `pi-dashboard open` or Electron to approve; the dialog shows the hint.
|
|
3307
3703
|
|
|
3308
3704
|
**Credential + trust hardening in the same change.**
|
|
3309
3705
|
- Login OAuth state carried in a signed `pi_dash_oauth_state` cookie, verified before code exchange; `returnUrl` restricted to same-origin relative paths (closes CSRF + open redirect).
|
|
@@ -3336,7 +3732,7 @@ Durable dashboard trust counts as trusted project for pi sessions on SAME machin
|
|
|
3336
3732
|
| `folderWorkspaces` | Folder workspaces. |
|
|
3337
3733
|
| `accessGrants` | Project-root subjects only. Default OFF. |
|
|
3338
3734
|
|
|
3339
|
-
NOT counted: server-lifetime trust (session worktree trust, session access grants, YOLO), KB source trust.
|
|
3735
|
+
NOT counted in snapshot: server-lifetime trust (session worktree trust, session access grants, YOLO), KB source trust. Server-lifetime trust + remote bridges now served by live query (see Live trust query).
|
|
3340
3736
|
|
|
3341
3737
|
**Matching.**
|
|
3342
3738
|
- Key form `piTrustKey` = `realpathSync(path.resolve)`. No Unicode-space normalisation. Source: `packages/shared/src/pi-trust-mirror.ts`.
|
|
@@ -3368,11 +3764,11 @@ flowchart TD
|
|
|
3368
3764
|
- Recorded pi entry (true or false, nearest ancestor) beats dashboard trust.
|
|
3369
3765
|
|
|
3370
3766
|
**Bridge** `decideBridgeProjectTrust` (`packages/extension/src/project-trust.ts`).
|
|
3371
|
-
- No server round trip.
|
|
3767
|
+
- No server round trip on snapshot step. Live query only on snapshot miss (see Live trust query).
|
|
3372
3768
|
- Per event: reads `config.json`, `trust.json` (lockless; BOM stripped; null = absent; bad shape/parse = undecided `store-unreadable`), snapshot.
|
|
3373
3769
|
- Returns `{trusted:"yes", remember:false}` or undecided.
|
|
3374
3770
|
- Dashboard-spawned headless sessions consult mirror always. Other sessions only if `coverInteractive`.
|
|
3375
|
-
- Reason codes logged when withheld: `forbidden-folder`, `recorded-entry`, `identity-mismatch`, `hook-changed`, `not-project-root`, `source-off`, `source-not-installed`, `choice-unreadable`, `store-unreadable`, `not-covered-session
|
|
3771
|
+
- Reason codes logged when withheld: `forbidden-folder`, `recorded-entry`, `identity-mismatch`, `hook-changed`, `not-project-root`, `source-off`, `source-not-installed`, `choice-unreadable`, `store-unreadable`, `not-covered-session`, `identity-weak` + 7 `live-*` (see Live trust query).
|
|
3376
3772
|
- p95 < 20 ms (1,000 entries, 20-deep cwd).
|
|
3377
3773
|
- Spawn token: `PI_DASHBOARD_SPAWN_TOKEN` read + removed from env at bridge activation (`packages/extension/src/spawn-token.ts`). Process-global until first `session_register`. Agent-started nested pi never counts as dashboard-spawned.
|
|
3378
3774
|
|
|
@@ -3412,6 +3808,127 @@ flowchart TD
|
|
|
3412
3808
|
|
|
3413
3809
|
See change: mirror-dashboard-trust-to-pi.
|
|
3414
3810
|
|
|
3811
|
+
#### Live trust query (change: mirror-dashboard-trust-live-remote)
|
|
3812
|
+
|
|
3813
|
+
Extends mirror to server-lifetime trust + remote bridges. Live entries never written to disk. Snapshot carries count only. Bridge asks server on snapshot miss.
|
|
3814
|
+
|
|
3815
|
+
```mermaid
|
|
3816
|
+
sequenceDiagram
|
|
3817
|
+
participant P as pi project_trust
|
|
3818
|
+
participant B as bridge decideBridgeProjectTrust
|
|
3819
|
+
participant S as server POST /api/pi-trust/query
|
|
3820
|
+
P->>B: project_trust(cwd)
|
|
3821
|
+
B->>B: store, recorded entry, activation rule, snapshot cover
|
|
3822
|
+
Note over B: snapshot miss, ask conditions hold
|
|
3823
|
+
B->>S: { cwd } + local proof OR Bearer PI_DASHBOARD_TOKEN
|
|
3824
|
+
S->>S: auth, rate limit, cap 8 KiB, deny rules, cover lookup
|
|
3825
|
+
alt local requester
|
|
3826
|
+
S-->>B: { covered, key, sourceKind, dev, ino, birthtimeMs? }
|
|
3827
|
+
B->>B: identityMatches vs own stat
|
|
3828
|
+
else paired device
|
|
3829
|
+
S-->>B: { covered, salt, digest }
|
|
3830
|
+
B->>B: trustResourceManifest + HMAC, compare digests
|
|
3831
|
+
end
|
|
3832
|
+
B-->>P: trusted yes (remember false) OR undecided + reason code
|
|
3833
|
+
```
|
|
3834
|
+
|
|
3835
|
+
**Route.** `POST /api/pi-trust/query` body `{cwd}`. Source: `packages/server/src/routes/pi-trust-query-routes.ts`. Path const `PI_TRUST_QUERY_PATH` (`packages/shared/src/pi-trust-live-query.ts`).
|
|
3836
|
+
- `ROUTE_TIERS` tier `operate` (same as `POST /api/ws-ticket`). Registered in `http-road-classification.ts`. Not PRE_AUTH.
|
|
3837
|
+
- Body cap 8 KiB → 413. Bad `cwd` (relative, NUL, length) → 400, never 500.
|
|
3838
|
+
- Server re-canonicalises: `piTrustKey(cwd) !== cwd` → not covered.
|
|
3839
|
+
- Handler order: auth → rate limit → body → switches + deny rules → cover lookup → proof → YOLO liveness re-check.
|
|
3840
|
+
|
|
3841
|
+
**Admission.**
|
|
3842
|
+
- Local = loopback + no forwarding headers + VERIFIED endpoint-bound `X-Pi-Local-Proof` (`kind === "proof"`). Shared `isLoopbackHost`.
|
|
3843
|
+
- Remote = paired device bearer at `operate`.
|
|
3844
|
+
- Refused: raw legacy local token, browser login cookie, trusted-network admission.
|
|
3845
|
+
- Proof binds method + path, not body. `cwd` = unauthenticated input.
|
|
3846
|
+
|
|
3847
|
+
**When bridge asks** (all must hold):
|
|
3848
|
+
- `enabled` ∧ `liveQuery` in `config.json`.
|
|
3849
|
+
- session allowed by `coverInteractive` rule.
|
|
3850
|
+
- no recorded pi entry.
|
|
3851
|
+
- `!isMirrorDenied(cwd)`.
|
|
3852
|
+
- snapshot gives no cover (any reason, incl `identity-mismatch`).
|
|
3853
|
+
- `liveCount > 0` ∨ remote bridge (non-loopback endpoint + `PI_DASHBOARD_TOKEN`).
|
|
3854
|
+
|
|
3855
|
+
Bridge `decideBridgeProjectTrust` now async. Snapshot step stays sync (p95 < 20 ms). Handler never throws: every path resolves `{trusted:"undecided"}` on failure.
|
|
3856
|
+
|
|
3857
|
+
**Live sources** (`piTrustMirror.sources.*`, in-memory, listed by provider in mirror service):
|
|
3858
|
+
|
|
3859
|
+
| Source | Covers | Lifetime |
|
|
3860
|
+
|---|---|---|
|
|
3861
|
+
| worktree-init session trust | `listSessionTrust()`, hook hash re-checked | until server restart |
|
|
3862
|
+
| session access grants | project-root subjects, `scope==="session"` | until server restart |
|
|
3863
|
+
| `yolo` (default ON) | roots of `yolo.status()` | scoped: until expiry. env activation: while server runs. unscoped: never |
|
|
3864
|
+
|
|
3865
|
+
- Identity `{dev, ino, birthtimeMs?}` recorded at entry creation, in-memory map keyed `<source>\0<key>`. Unstatable folder never counts.
|
|
3866
|
+
- Fixed listener gaps: session branches of `recordTrust`/`revokeTrust`/`recordGrant`/`revokeGrant` notify. `YoloController.setChangeListener` + unref'd expiry timer.
|
|
3867
|
+
- Snapshot field `liveCount` only. Never paths or identities. Boot writes `0`. Rewritten only when count changes, synchronously in the changing action. Failed rewrite logged, action succeeds. Reader treats missing/invalid as 0. Snapshot `version` stays 1.
|
|
3868
|
+
- Stale count = extra or missed query, never wrong yes.
|
|
3869
|
+
- Server consumers (`host.isProjectTrusted`, `projectTrustSource`, MCP view) run `decidePiTrust` over durable + live entries, no folder proof.
|
|
3870
|
+
|
|
3871
|
+
**Proofs.**
|
|
3872
|
+
- Local: recorded `dev`+`ino`[+`birthtimeMs`]. Bridge compares via `identityMatches`. Re-created folder → `identity-mismatch`.
|
|
3873
|
+
- Remote: `{covered:true, salt, digest}`. No source kind, no identity. Salt 16 random bytes.
|
|
3874
|
+
- `digest = HMAC-SHA256(salt, "pi-trust-live/v1\n" + cwdKey + "\n" + manifest)`. cwd key binds answer to path.
|
|
3875
|
+
- `manifest` = sorted entries of pi's trust-requiring resources: cwd `.pi/{settings.json,mcp.json,extensions,skills,prompts,themes,SYSTEM.md,APPEND_SYSTEM.md}` (recursive, label `c/<rel>`) + `<d>/.agents/skills` for cwd and each ancestor except `~/.agents/skills` (label `a<k>/<rel>`, `k`=levels above cwd).
|
|
3876
|
+
- Entry: file → `label\0f\0sha256(content)`. Dir → `label\0d`. Other type → null.
|
|
3877
|
+
- Shared fn `trustResourceManifest(cwd, {home, signal})` in `packages/shared/src/pi-trust-resource-digest.ts`. Async `fs/promises`, `AbortSignal`, one read per file.
|
|
3878
|
+
- Fail-closed → null → `identity-weak`: empty set, any symlink, `.pi/settings.json` unparseable/unknown ref shape/refs outside set (`packages` entry, ext/skill path outside), >1,000 files, >16 MiB, read failure.
|
|
3879
|
+
- Bridge compares two non-null digests only. Unequal → `identity-mismatch`.
|
|
3880
|
+
- Resource-name list = literal (pi does not export it). Golden test `packages/shared/src/__tests__/pi-trust-resource-golden.test.ts` asserts equality with installed pi `trust-manager.js` + `hasTrustRequiringProjectResources` parity.
|
|
3881
|
+
|
|
3882
|
+
**One deadline** `piTrustMirror.liveQueryTimeoutMs`.
|
|
3883
|
+
- Default 300 ms local / 1000 ms remote. Clamp 50–1000. Non-finite → default. Resolver `effectiveLiveQueryTimeoutMs` (`packages/shared/src/config.ts`).
|
|
3884
|
+
- Bounds request + proof. `Promise.race([work, deadline→live-timeout])`. `AbortController` per call aborts `fetch` (`redirect:"error"`) + every `fs/promises` read.
|
|
3885
|
+
- After race: `inst.isActive()` re-check. Stale instance → undecided.
|
|
3886
|
+
|
|
3887
|
+
**Reason codes** (`MirrorWithheldReason`, `packages/shared/src/pi-trust-mirror-types.ts`; 18, labels in `MIRROR_WITHHELD_LABELS`):
|
|
3888
|
+
- Parent (7): `forbidden-folder`, `not-project-root`, `hook-changed`, `source-off`, `source-not-installed`, `identity-mismatch`, `choice-unreadable`.
|
|
3889
|
+
- Bridge (4): `recorded-entry`, `store-unreadable`, `not-covered-session`, `identity-weak`.
|
|
3890
|
+
- Live (7): `live-timeout`, `live-unreachable`, `live-refused`, `live-unsupported`, `live-rate-limited`, `live-not-covered`, `live-error`.
|
|
3891
|
+
|
|
3892
|
+
| Outcome | Code |
|
|
3893
|
+
|---|---|
|
|
3894
|
+
| connection refused | `live-unreachable` |
|
|
3895
|
+
| 401 / 403 | `live-refused` |
|
|
3896
|
+
| 404 (old server) | `live-unsupported` |
|
|
3897
|
+
| 429 | `live-rate-limited` |
|
|
3898
|
+
| abort / deadline | `live-timeout` |
|
|
3899
|
+
| answer `covered:false` | `live-not-covered` |
|
|
3900
|
+
| 5xx, redirect, malformed body, covered answer missing proof fields | `live-error` |
|
|
3901
|
+
|
|
3902
|
+
**Rate limits.**
|
|
3903
|
+
- Fixed window 10 s. 20 queries per paired device. 200 for `local` requester.
|
|
3904
|
+
- Proof permits: 4 global, 1 per device. Excess → 429. One log line per window. Control chars stripped from logged `cwd`/device.
|
|
3905
|
+
- Local identity answers take no permit.
|
|
3906
|
+
- No manifest cache (staleness in security decision).
|
|
3907
|
+
|
|
3908
|
+
**Health.** `/api/health` `piTrustMirror.live` = `{covered, notCovered, refused, rateLimited, budgetMissed}`. Same disclosure gate as access-grant health block (`access-health.ts`). Server-side only. `budgetMissed` = handling time > server `liveQueryTimeoutMs` for requester class. Bridge logs own reason codes. Remote bridge with shorter timeout can log `live-timeout` while server counts `covered`.
|
|
3909
|
+
|
|
3910
|
+
**Settings + rollback.**
|
|
3911
|
+
- `piTrustMirror.liveQuery` (default `true`), `liveQueryTimeoutMs`, `sources.yolo` (default `true`).
|
|
3912
|
+
- `liveQuery=false`: no queries. Bridge reads `config.json`, works with server down.
|
|
3913
|
+
- `sources.yolo=false`: YOLO roots stop counting. Other live sources stay.
|
|
3914
|
+
- `enabled=false`: everything off.
|
|
3915
|
+
- Old bridge never queries. New bridge + old server → 404 → `live-unsupported` → undecided.
|
|
3916
|
+
- Nothing live persisted.
|
|
3917
|
+
|
|
3918
|
+
**Residuals.**
|
|
3919
|
+
- YOLO default ON widens YOLO from file access to project-code execution in its roots. Disclosed at activation + Access page. Unscoped YOLO never counts. Deny rules apply.
|
|
3920
|
+
- npm packages named in `.pi/settings.json` bound by reference, not fetched bytes.
|
|
3921
|
+
- Marker-less relay (`ssh -R`, `socat`) + shared home can look local. Needs same-user access + dev+ino(+birth) match. Accepted.
|
|
3922
|
+
- `ssh -L` tunnel + shared home: loopback → classed local → `identity-mismatch`, fail-closed. Dial non-loopback endpoint with device token.
|
|
3923
|
+
- Symlinked (pnpm-style) trees, >1,000 files, >16 MiB → no remote trust (`identity-weak`).
|
|
3924
|
+
- Benign `.pi/settings.json` edit on one side drops remote trust.
|
|
3925
|
+
- Local-rate-limit key shared by all local pi. 200/10 s sized for fleet spawns.
|
|
3926
|
+
- Snapshot step sync: hung mount blocks before live deadline starts (parent residual).
|
|
3927
|
+
- Non-goal: no path mapping between machines. Canonical paths must be equal.
|
|
3928
|
+
- Non-goal: no defence against malicious bridge. Bridge decides only for own pi process.
|
|
3929
|
+
|
|
3930
|
+
See change: mirror-dashboard-trust-live-remote.
|
|
3931
|
+
|
|
3415
3932
|
### Access Grants and Denial Remedies (change: add-access-grants-and-review)
|
|
3416
3933
|
|
|
3417
3934
|
Companion to **Network Access Control** above. That section's universal `onRequest` guard is the network plane; this one is the filesystem plane. Both turn a terminal refusal into a remedy an operator can accept. Network plane: `403 network_not_allowed` → `BlockEventBuffer` → "Trust this network". Filesystem plane: a containment refusal → `denialId` → **grant** → next read admitted, no restart. The guard above is not re-explained here; see it for the network plane.
|
|
@@ -3640,7 +4157,7 @@ YOLO requires `hostGate.mode === "enforce"` and a HELD-eligible denial; there is
|
|
|
3640
4157
|
|
|
3641
4158
|
An operator's explicit `deny` on a YOLO-eligible plane or the `agent-path` surface is remembered in the **refusal ledger** (`access/refusal-ledger.ts`, `access-refusals.json`, `PI_ACCESS_REFUSALS_STORE` overrides the path) — durable, cleared only by the operator — so a later YOLO session refuses that subject (`refused-by-prior-refusal`) instead of auto-allowing it. Auto-answers are logged `(no human answered)` and kept in a bounded in-memory history. Store conventions mirror `access-grants.json`: atomic temp+rename, missing/malformed = empty, a failed write leaves the cache unchanged.
|
|
3642
4159
|
|
|
3643
|
-
**Opt-in and env vars** (D10). Prompting
|
|
4160
|
+
**Opt-in and env vars** (D10). Prompting is gated by `accessGrants.promptEnabled` (**default `true`** since D16 of `add-access-provisioning`; was `false`. Absent key = on; explicit `false` is kept). `PI_DASHBOARD_DISABLE_GRANT_PROMPT=1` is the kill switch — it engages only on the exact value `1` (`isGrantPromptKilled`). Both suppress *prompting only*: existing grants stay in force and denials still land in the pending list. The no-audience rule is necessary but not sufficient for automation — Playwright E2E runs with a browser connected, so CI relies on the env var. `PI_DASHBOARD_GRANT_YOLO` (`parseYoloEnv`) takes one plain absolute path, a JSON array of absolute paths for several, or the literal `unscoped`; anything else (`1`, `true`, relative, `[]`, malformed JSON, `UNSCOPED`) is `invalid` and leaves YOLO inactive.
|
|
3644
4161
|
|
|
3645
4162
|
**REST** (`packages/server/src/routes/access-prompt-routes.ts`):
|
|
3646
4163
|
|
|
@@ -3653,6 +4170,108 @@ Access-page mutations (`POST /api/access/prompts/:promptId`, `POST`/`DELETE /api
|
|
|
3653
4170
|
|
|
3654
4171
|
**Coverage.** Browser E2E `tests/e2e/access-grant-dialog.spec.ts`; clean-install VM smoke `qa/tests/36-access-grant-dialog.sh`.
|
|
3655
4172
|
|
|
4173
|
+
### Access provisioning (change: add-access-provisioning)
|
|
4174
|
+
|
|
4175
|
+
Companion to **Access-Grant Prompts and YOLO** above. Denial dialogs ask one subject at a time, after a denial. Provisioning asks once, up front: agent submits a project's declared folder needs, operator approves per line, approved lines become persisted grants.
|
|
4176
|
+
|
|
4177
|
+
Design: `openspec/changes/add-access-provisioning/design.md` (D1–D16).
|
|
4178
|
+
|
|
4179
|
+
**Flow.**
|
|
4180
|
+
- Agent runs skill `project-access` (`packages/extension/.pi/skills/project-access/SKILL.md`, beside `project-init`). Modes: `map` (read-only), `suggest` (drafts profile, writes after `ask_user` confirm), `provision` (submit + poll).
|
|
4181
|
+
- Profile `.pi/access.json`: `{ version: 1, folders: [{path, why}], remote: ("lan"|"internet"|"device")[] }`. Optional. Only the skill reads it. Server never reads it. Unknown `version` → skill refuses.
|
|
4182
|
+
- Skill calls `POST /api/access/provision`. Route validates, classifies, records pending request, delivers `provision_request`. Route writes no grant, no config.
|
|
4183
|
+
- Operator answers per line in `ProvisionPromptDialog` (`packages/client/src/components/access-grant/`). Answer settles request. Settle writes grants.
|
|
4184
|
+
- Skill polls `GET /api/access/provision/:id` until terminal. 404 (server restart) → reported "unknown".
|
|
4185
|
+
|
|
4186
|
+
```mermaid
|
|
4187
|
+
flowchart TD
|
|
4188
|
+
S["skill project-access: POST /api/access/provision"] --> L{"eligibility ladder (D7)"}
|
|
4189
|
+
L -->|fail| X["refused: 503 / 409; nothing recorded"]
|
|
4190
|
+
L -->|pass| V["validate root (D8) + classify lines (D4) + bounds (D6)"]
|
|
4191
|
+
V -->|fail| X
|
|
4192
|
+
V --> R[("provisioning registry (in memory)")]
|
|
4193
|
+
R --> O["provision_request to operator sockets only"]
|
|
4194
|
+
O --> A{"provision_response / POST :id/settle"}
|
|
4195
|
+
A -->|no live capability| DR["dropped + counted; request stays pending"]
|
|
4196
|
+
A -->|capability held| RS["re-check ladder + root; re-verify lines; one sync write section"]
|
|
4197
|
+
RS --> G["recordGrant(via: provision, evict: false)"]
|
|
4198
|
+
O -.->|terminal transition| DM["provision_dismiss to all tabs"]
|
|
4199
|
+
```
|
|
4200
|
+
|
|
4201
|
+
**Registry.** `packages/server/src/access/provisioning.ts` (`ProvisioningRegistry`; `create` / `get` / `settle` / `dismiss` / `dismissAll` / `expire` / `list` / `stats`; `now` injected). Wiring `access/provisioning-wiring.ts`: operator-socket delivery, expiry timer, `provision_dismiss`, capability-gated `onResponse`. Own registry, not an access plane (D1): one record, N lines, one dialog. Never touches `PendingGrantRegistry`. Never consults YOLO. Memory only; restart loses pending requests, grants already written stay.
|
|
4202
|
+
|
|
4203
|
+
**Routes** (`packages/server/src/routes/access-routes.ts`; all `networkGuard`).
|
|
4204
|
+
- `POST /api/access/provision` — create. Operate tier.
|
|
4205
|
+
- `GET /api/access/provision` — list pending. Observe tier.
|
|
4206
|
+
- `GET /api/access/provision/:id` — status + per-line outcome. Pending or last 50 ended.
|
|
4207
|
+
- `POST /api/access/provision/:id/settle` — answer. Needs `isPromptEligible(request)`, else 403 `no-capability`.
|
|
4208
|
+
- `POST /api/access/provision/dismiss-all` — dismiss every pending. Needs `isPromptEligible(request)`. Counts as dismissal per request; starts each root's cooldown.
|
|
4209
|
+
|
|
4210
|
+
**WS messages** (`packages/shared/src/browser-protocol.ts`).
|
|
4211
|
+
- `provision_request` — server → browser. Carries lines + classification. Sent only to operator sockets.
|
|
4212
|
+
- `provision_response` — browser → server. `{requestId, lines: [{lineId, verdict: "approve"|"reject", piTrust?}]}`. Omitted line = reject. Tier `operate` (`ws-message-tiers.ts`).
|
|
4213
|
+
- `provision_dismiss` — server → browser. Sent on every terminal transition. Closes dialog in other tabs.
|
|
4214
|
+
|
|
4215
|
+
**Capability-targeted delivery + settle** (D2/D3).
|
|
4216
|
+
- Operator socket = holds live prompt capability AND operate tier. New gateway send helper; not `broadcastToAll`. `no-operator` counts the same set.
|
|
4217
|
+
- `provision_response` settles only if `holdsLiveCapability(ws)` (`pairing/browser-gateway.ts`). Backed by `WeakMap<WebSocket, grantSocketId>` filled at capability issue, cleared at release, checked against live channel table in `prompt-channel.ts`. Capability A never authorises socket B. Failing message dropped + counted (`droppedResponses`).
|
|
4218
|
+
- HTTP settle needs `isPromptEligible(request)`. Client already attaches `X-Pi-Grant-Channel` to same-origin `/api/*` (`grant-channel.ts`). Access page needs no allowlist change.
|
|
4219
|
+
- Dialog close sends `provision_response` with every line rejected. Same gate.
|
|
4220
|
+
- Plain operate-tier request from agent (no capability) cannot settle.
|
|
4221
|
+
- Settle re-checks ladder. Now failing → answer refused; request stays pending until TTL.
|
|
4222
|
+
- Terminal transitions first-wins. Later answer → 409 `already-settled`.
|
|
4223
|
+
|
|
4224
|
+
**Eligibility ladder** (D7; coupled to `accessGrants.promptEnabled`). Creation refused in order:
|
|
4225
|
+
1. `PI_DASHBOARD_DISABLE_GRANT_PROMPT=1` → 503 `disabled`.
|
|
4226
|
+
2. `accessGrants.promptEnabled === false` → 409 `prompting-disabled`.
|
|
4227
|
+
3. host gate `report` mode → 409 `report-mode`.
|
|
4228
|
+
4. `promptChannelCount() === 0` → 409 `no-operator`.
|
|
4229
|
+
|
|
4230
|
+
Same ladder gates settle. One switch covers every dialog.
|
|
4231
|
+
|
|
4232
|
+
**Project root** (D8). `projectRoot` absolute, exists, directory, holds `.git` or `.pi`, not ungrantable. Real path = pending key + grant `origin`. Agent can create `.git` anywhere it can write → origin is a *claimed* label. UI says "requested for `<path>`", never "belongs to".
|
|
4233
|
+
|
|
4234
|
+
**Line classification** (D4; first match wins). Expand (absolute, `~/`, project-relative) → `invalid` | real path + must be directory → `missing` (file line is `missing`, never grants parent) → `forbidden` (`isUngrantableSubject`) → `sensitive` (D5a) → `in-root` → `covered` (persisted grant admits) → `grantable`. Same real path collapses; first `why` kept. Only `grantable` approvable. `why` capped 200 chars, control chars stripped, rendered as React text only, JSON-quoted in logs.
|
|
4235
|
+
|
|
4236
|
+
**Bounds** (D6; `PROVISION_*` constants).
|
|
4237
|
+
|
|
4238
|
+
| Bound | Value | On breach |
|
|
4239
|
+
|---|---|---|
|
|
4240
|
+
| Lines per request | 32 | 400 `too-many-lines` |
|
|
4241
|
+
| Pending per project root | 1 | 409 `pending-exists` + existing id |
|
|
4242
|
+
| Pending total | 4 | 429 `capacity` |
|
|
4243
|
+
| Creations per project root | 1 / 60 s | 429 `rate-limited` + retry-after |
|
|
4244
|
+
| Cooldown after request ended with no approved line | 5 min per root | 429 `cooldown` |
|
|
4245
|
+
| Creations total | 3 / 10 min | 429 `rate-limited` |
|
|
4246
|
+
| Request TTL | 10 min | `expired`; nothing granted |
|
|
4247
|
+
|
|
4248
|
+
Residual: per-root limits do not bind an agent that creates `.git` in fresh directories. Global limit still allows 18 dialogs/hour; rotating agent can hold all 4 slots → legitimate requests get `429 capacity`. Mitigation: Access page lists every pending request with claimed root; "Dismiss all pending". Block-by-requester = follow-up.
|
|
4249
|
+
|
|
4250
|
+
**Approval** (D5). Settle runs two phases.
|
|
4251
|
+
- Async: re-check ladder, re-validate root (fail → every approved line `refused`, `root-changed`), re-classify approved lines.
|
|
4252
|
+
- Sync, no `await`: `realpathSync` each approved line vs shown real path. Mismatch or no longer `grantable` → `changed` / `refused` before any write. Count net-new subjects; `persisted + net-new > 200` → every approved line `refused` (`capacity`). Else `recordGrant({subject, scope: "project", via: "provision", origin, evict: false})` per line. Write failure → `failed`; later lines still run.
|
|
4253
|
+
- Node runs sync section uninterleaved: no other grant write in this server process lands between compare, capacity check, writes. Home lock is advisory; other-process writers not serialised (they can write the file directly anyway).
|
|
4254
|
+
- Outcomes: `granted`, `rejected`, `changed`, `refused`, `failed`, `handed-off`.
|
|
4255
|
+
|
|
4256
|
+
**Provisioned grants are never evicted.** `enforceCap` skips `via: "provision"`. Denial-path write at the 200 cap evicts oldest *non-provisioned* grant. All 200 provisioned → denial-path write refused like any failed write. Eviction logs `[access-grants] evicted subject= via=`. "Permanent" = until operator revokes on the Access page. Grants are machine-wide by folder (`scope: "project"` = persisted, not per-project); dialog copy says so.
|
|
4257
|
+
|
|
4258
|
+
**Credential-folder refusal** (D5a). `forbiddenGrantSubjects().sensitive` covers only `~/.ssh`, `~/.pi`. Provisioning also classifies `sensitive` any line at, below, **or an ancestor of** `~/.aws`, `~/.gnupg`, `~/.kube`, `~/.docker`, macOS `~/Library/Keychains` (grant admits whole subtree; `~/Library` would admit `Keychains`). Known gap, not closed here: denial path can still grant these folders and ancestors, no warning. Follow-up.
|
|
4259
|
+
|
|
4260
|
+
**pi trust per line** (D9). `grantable` line whose real path holds `.git` or `.pi` shows `PiTrustCheckbox`, unchecked by default, with consequence statement. Approved project-root line with omitted `piTrust` → `false` (explicit choice always stored). Applied only to lines ending `granted`, via `mirror.setChoice("accessGrants", subject, piTrust)`.
|
|
4261
|
+
|
|
4262
|
+
**Remote goals** (D10). `remote` entries render as "Open Remote access" actions naming the wizard task (lan → "Allow devices on my network"; internet → "Share over the internet"; device → "Let a phone or laptop in"). Action opens `RemoteAccessDialog` on its landing. Outcome `handed-off`. Provisioning writes nothing remote.
|
|
4263
|
+
|
|
4264
|
+
**Observability** (D14). Logs `[access-provision] created|settled|dismissed|expired|refused id= project=<json> lines= approved= reason=`; dropped response `[access-provision] response-dropped reason=no-capability`; per-grant `[access-grant] persisted … via=provision`. `/api/health` `accessGrants.provisioning = {pending, created, approved, rejected, dismissed, expired, refused, droppedResponses}` (cumulative except `pending`; additive, optional) via `snapshotAccessGrantHealth` (`access/access-health.ts`).
|
|
4265
|
+
|
|
4266
|
+
**Stated trust limit** (D11, operator decision A). Consent + audit on the honest path. **Not containment.** Approval proves a capability-holding connection answered, nothing more. Local process running as operator (incl. agent `bash`) can: write `access-grants.json` directly; create `.git` to claim a root; forge a browser-shaped WS to obtain a capability and settle its own request; already settle denial prompts via `POST /api/access/prompts/:promptId` (no capability check). What it does stop: *casual* self-approval via plain operate-tier request. Dialog, skill and docs state this. Operator-presence proof (passkey user verification) = follow-up.
|
|
4267
|
+
|
|
4268
|
+
**Reversal of archived D12/D15** (`add-access-grants-and-review`; design D15 here).
|
|
4269
|
+
- D12 "Access tab reviews and revokes, never creates": *kept* — no free-form add control anywhere. *Revised* — Access page may answer a pending provisioning request it lists; same per-line verdict as dialog.
|
|
4270
|
+
- D15 "grant names only a subject a recorded denial named": *kept* — forbidden subjects on stored value, real-path subjects, authentication, no cross-origin. *Replaced for this path only* — binding becomes "line operator approved on a capability-holding connection, re-verified at approval".
|
|
4271
|
+
- Rationale: D15 protects callers that cannot see the denial. Provisioning protects the same property (operator saw this exact real path) through the dialog. Stricter than denial path in two ways: credential folders refused (D5a); settle requires capability (D3).
|
|
4272
|
+
|
|
4273
|
+
**Default flip** (D16). `accessGrants.promptEnabled` default `true`; explicit value kept; no config migration. Denial dialogs now appear on default installs with host gate `enforce` and an operator browser open. Automation sets `PI_DASHBOARD_DISABLE_GRANT_PROMPT=1`. Agent path gate does not read `promptEnabled` (own `agentPathGate` switch). Rollback: revert change; provisioned grants stay ordinary revocable grants.
|
|
4274
|
+
|
|
3656
4275
|
### Plugin cwd admission (change: harden-plugin-cwd-admission)
|
|
3657
4276
|
|
|
3658
4277
|
Plugin route `cwd` gate. Async tri-state (`admitCwd`, `packages/shared/src/cwd-guard.ts`): `admit{token}` | `refuse` | `indeterminate{failedProbes, elapsedMs}`.
|
|
@@ -3684,6 +4303,59 @@ flowchart TD
|
|
|
3684
4303
|
G -->|refuse| F
|
|
3685
4304
|
```
|
|
3686
4305
|
|
|
4306
|
+
### Core cwd admission (git / openspec routes)
|
|
4307
|
+
|
|
4308
|
+
Git routes + caller-`cwd` openspec routes admit via `admitRouteCwd` (`packages/server/src/lib/route-admission.ts`) → shared `admitCwd` (`packages/shared/src/cwd-guard.ts`). Same tri-state as plugin cwd admission (above).
|
|
4309
|
+
|
|
4310
|
+
- Route branches `admissionAllows(admission, cwd)` on RAW request value (same var passed to `admitRouteCwd`).
|
|
4311
|
+
- Git ops run on `token.canonCwd`.
|
|
4312
|
+
- Openspec ops + keys keep raw `cwd`. Guard sanitizes the variable itself.
|
|
4313
|
+
- Known set = `listKnownFolderCwds` (session cwds ∪ pinned dirs, unfiltered). Same fn behind `host.knownFolderCwds`.
|
|
4314
|
+
- Openspec fallbacks (`knownCwds()[0]`, `update {all}`) unchanged, not admitted.
|
|
4315
|
+
|
|
4316
|
+
Admitted: known cwd; subdirs + linked worktrees of known main checkout.
|
|
4317
|
+
Refused: sibling worktree of known worktree; main checkout of known worktree; child repo of pinned non-repo folder; symlink to unknown; regular file (`checkoutRootsClassifiedAsync` reads `spawn ENOTDIR` as `none` → refuse; Windows errno may differ → 503).
|
|
4318
|
+
|
|
4319
|
+
Gated openspec writes (`init`, `workflow-schema`, dependencies GET/PUT): admit first, then exact `knownInitTargets` membership + opt-out (raw + canonical) + global-dir exclusion. Refusal bodies unchanged.
|
|
4320
|
+
|
|
4321
|
+
Codes:
|
|
4322
|
+
|
|
4323
|
+
| Condition | Status | Body |
|
|
4324
|
+
|---|---|---|
|
|
4325
|
+
| git refuse | 400 | `code: cwd_unknown` |
|
|
4326
|
+
| ungated openspec refuse | 403 | `code: cwd_unknown`, `reason`, `hint` |
|
|
4327
|
+
| indeterminate | 503 + `Retry-After: 1` | `success:false`, `code` = `error` = `cwd-admission-unavailable`, `message`, `retryAfterMs:1000` |
|
|
4328
|
+
| non-portable `change` segment | 400 | `code: invalid_name` |
|
|
4329
|
+
| git cwd missing / not dir (admitted only) | 400 | `code: cwd_invalid` |
|
|
4330
|
+
| folder-project | 503 | own body `{error, message, retryAfterMs}`, no `code` |
|
|
4331
|
+
|
|
4332
|
+
`remove-batch`: items admitted sequentially, memo per raw cwd. Whole-batch budget 10 s; per-admission deadline `min(3000, remaining)`. Budget spent → only direct matches decided, rest `cwd-admission-unavailable`. Per-item codes (`cwd_unknown` / `cwd_invalid` / `cwd-admission-unavailable`). Envelope 200, no `Retry-After`. Classification memo keyed by `token.canonCwd`.
|
|
4333
|
+
|
|
4334
|
+
Token: released on `reply.raw` close (git + openspec helpers); `finally` in `remove-batch` and folder-project.
|
|
4335
|
+
|
|
4336
|
+
Client: text via `err.cwd_unknown`, `err.cwd_admission_unavailable`, `err.invalid_name`. `fetchWorktreeInitStatus` reports `cwdUnknown`. Post-spawn auto-init (`autoInitWorktreeOnSpawn` ON) re-probes every 500 ms, up to 10 s, on `cwd_unknown`. MCP server plugin tools surface refusals as tool errors.
|
|
4337
|
+
|
|
4338
|
+
```mermaid
|
|
4339
|
+
flowchart TD
|
|
4340
|
+
R["request cwd (raw)"] --> A["admitRouteCwd"]
|
|
4341
|
+
A --> D{"admitCwd decision"}
|
|
4342
|
+
D -->|"admit"| B{"admissionAllows(adm, cwd)"}
|
|
4343
|
+
B -->|"true"| OK["200 path: git on token.canonCwd, openspec on raw cwd"]
|
|
4344
|
+
B -->|"false"| RF["refuse"]
|
|
4345
|
+
D -->|"refuse"| RF
|
|
4346
|
+
D -->|"indeterminate"| IND["503 cwd-admission-unavailable, Retry-After 1"]
|
|
4347
|
+
RF -->|"git"| E400["400 cwd_unknown"]
|
|
4348
|
+
RF -->|"ungated openspec"| E403["403 cwd_unknown"]
|
|
4349
|
+
RF -->|"gated openspec"| EG["today's refusal body"]
|
|
4350
|
+
```
|
|
4351
|
+
|
|
4352
|
+
Latency (`evidence/latency.md`, 84 known folders, direct match):
|
|
4353
|
+
|
|
4354
|
+
- `git status`: +0.66 ms p50 / +1.48 ms p99 (gate ≤2 / ≤15). `openspec tasks`: +0.30 ms p50 / +0.36 ms p99.
|
|
4355
|
+
- Derivation path: 0 indeterminate / 200; p99 < 0.5 s.
|
|
4356
|
+
|
|
4357
|
+
See change: core-cwd-admission.
|
|
4358
|
+
|
|
3687
4359
|
### OAuth Authentication Flow
|
|
3688
4360
|
|
|
3689
4361
|
Optional OAuth2 authentication protects the dashboard when accessed remotely.
|
|
@@ -3943,6 +4615,37 @@ sequenceDiagram
|
|
|
3943
4615
|
|
|
3944
4616
|
`request-access` remedy on `operate_required`: present iff no credential + knock pre-switch gates pass (`knockPeerGate`). Discloses only `host_not_admitted` | `knock_not_lan`. Never reads `acceptLanRequests`. See `docs/credential-vault.md` §10. See change: add-request-access-remedy.
|
|
3945
4617
|
|
|
4618
|
+
#### Route delegation and pair action (change: group-servers-by-identity)
|
|
4619
|
+
|
|
4620
|
+
Identity challenge is public and separate from access check:
|
|
4621
|
+
|
|
4622
|
+
- `POST /api/pair/challenge {nonce}` → `{fingerprint, publicKey, signature, v}`. Public (`PUBLIC_PAIRING_PREFIXES`, `pairing-routes.ts`). Answers where `/api/health` returns `403 network_not_allowed`.
|
|
4623
|
+
- Proof: Node `proveServerIdentity` (`packages/shared/src/server-pinning.ts`); browser `challengeIdentity` (`packages/client/src/lib/pairing/pair-protocol.ts`).
|
|
4624
|
+
|
|
4625
|
+
Delegation (D7):
|
|
4626
|
+
|
|
4627
|
+
- `POST /api/pair/poll` `approved` answer → `{status, token, routes}`. `routes` = `reachableUrls()` filtered to `https:`, origin-normalised (`httpsOrigins`, `pairing-routes.ts`). `wss://` and `PI_E2E_SEED` loopback `http` stay in QR `urls`, never in `routes`.
|
|
4628
|
+
- `routes` only on the one `approved` answer carrying the one-shot token. Never on `pending` / `rejected` / `unknown`, `/api/pair/challenge`, or TXT.
|
|
4629
|
+
- Receiver validates (`validateDeliveredRoutes`): `https`, origin only, DNS name (no IP literal, `localhost`, `*.local`), ≤ 8 routes, host ≤ 253 chars.
|
|
4630
|
+
- Receiver stores only after challenge at that origin proves pinned `F` (`recordDeliveredRoutes`, `packages/electron/src/lib/delivered-routes.ts`). Source `pairing`.
|
|
4631
|
+
- Browser ignores `routes`: no own store for them. Electron keyring keeps ≤ 3 delivered (`MAX_DELIVERED_STORED`), then 5-host cap, https first.
|
|
4632
|
+
|
|
4633
|
+
Pair action per row (`pairAction`, `packages/shared/src/server-routes.ts`; hook `use-pair-action.ts`):
|
|
4634
|
+
|
|
4635
|
+
- Browser, on-link route: "Request access…" → `window.open("http://<host>:<port>/pair?request", "_blank", "noopener")`. URL via `buildRequestPageUrl`; refused unless it round-trips. No fp check (Electron only).
|
|
4636
|
+
- Browser, otherwise: "Pair with code…" → pasted payload; local check payload `id` = entry `F`; new tab `<https origin>/pair#<payload>`. Landing runs `challengeIdentity` before redeem.
|
|
4637
|
+
- Electron, no `F`, on-link route discovered: "Verify and request access…" (TOFU compare).
|
|
4638
|
+
- Electron, on-link route discovered or in keyring: "Request access…" → `piDashboard.openServerWindow({host, port})`. Connecting window proves identity first.
|
|
4639
|
+
- Otherwise: "Pair with code…".
|
|
4640
|
+
- Knock refusals: `knock_disabled` → remedy text; `knock_not_lan` → "Pair with code instead"; `knock_pending`, `knock_busy` unchanged.
|
|
4641
|
+
|
|
4642
|
+
Electron bridges (main window only, local-origin gate):
|
|
4643
|
+
|
|
4644
|
+
- `piDashboard.listServers()` → `servers:list`. Renderer-safe state (`pairedRow`, `discovered`); no bearer.
|
|
4645
|
+
- `piDashboard.pairWithCode({fingerprint})` → `servers:pair-with-code` → `serverWindows.pairWithCode(fp)` → Connecting window code mode. Pasted text travels only on `servers:submit-code` from the connecting window.
|
|
4646
|
+
- In-app redeem (`packages/electron/src/lib/pairing-code-client.ts`): decode; payload `F` ≠ pin → no request; prove first payload `https` URL that proves pin; `POST /api/pair/redeem`; poll for approval (compare code shown in Connecting window only); bearer → keyring (`safeStorage` rules); routes validated + proven.
|
|
4647
|
+
- Pasted text, pairing code, bearer never reach dashboard page or logs.
|
|
4648
|
+
|
|
3946
4649
|
#### Bearer device auth — D5/D7
|
|
3947
4650
|
|
|
3948
4651
|
Approval mints long-lived opaque bearer token. Registry `~/.pi/dashboard/paired-devices.json` (0600). Stores only SHA-256 hash. Revoke = row delete (Settings → Security → Paired Devices). Auth branch: `Authorization: Bearer` (REST) feeds existing `request.isAuthenticated` — one OR branch, registered before OAuth plugin. Modules `paired-devices.ts`, `bearer-auth.ts`.
|
|
@@ -3959,7 +4662,7 @@ Windows credential ACLs now OBSERVED, not assumed. `chmod` no-op on Windows —
|
|
|
3959
4662
|
|
|
3960
4663
|
#### CORS default
|
|
3961
4664
|
|
|
3962
|
-
`https://pi-dashboard.dev` built-in allowed origin
|
|
4665
|
+
`https://pi-dashboard.dev` built-in allowed origin. CORS (origin-keyed) distinct from auth (bearer). Config `cors.allowedOrigins` extends. zrok wildcard NOT default — opt-in `cors.allowZrokWildcard`. See § CORS. See change: harden-cors-and-csp-reporting.
|
|
3963
4666
|
|
|
3964
4667
|
#### Versioned protocol — D9
|
|
3965
4668
|
|
|
@@ -4216,6 +4919,23 @@ The web client includes a Settings panel (gear icon in sidebar header → `/sett
|
|
|
4216
4919
|
4. Server preserves `***` secrets (doesn't overwrite real values), writes to disk, and applies runtime-safe changes
|
|
4217
4920
|
5. Port/piPort changes flag `restartRequired` in the response
|
|
4218
4921
|
|
|
4922
|
+
### Sidebar header grouping
|
|
4923
|
+
- Header = Tailwind `@container`. Row 1 `flex-wrap` (wraps, never clips).
|
|
4924
|
+
- Icon buttons (Discord, Appearance, Focus, Settings, row-2 filter funnel) share one recipe: HEADER_ICON_BTN + HEADER_ICON_SIZE in packages/client/src/components/primitives/header-icon-button.ts. 28 px box (size-7 rounded-md), 18 px glyph, --text-secondary, --bg-hover fill on hover/aria-expanded, selected-chip look on aria-pressed. Core-only. Named exceptions in ui-contract.md row "icon button (header)".
|
|
4925
|
+
- Row 1 left: logo · Discord (`discord-btn`) · divider · Appearance (`ThemePicker`, `theme-picker-trigger`) · Focus (`focus-toggle-btn`).
|
|
4926
|
+
- Appearance dropdown: trigger glyph mdiBrightness6. 300 px @container panel (usePopoverFlip clamps to viewport). "Mode" heading + segmented ThemeToggle (icon + label Light/System/Dark). "Palette" heading + scrolling grid-cols-2 palette grid (theme-palette-grid; 1 column when panel < 254 px). Active palette = aria-pressed + selected-chip fill, no check glyph. Only the grid scrolls on short viewport.
|
|
4927
|
+
- Row 1 right: open-questions pill (`QuestionStack`) · update badge · connection chip (`connection-chip`, `ServerSelector`) · Settings (`settings-btn`).
|
|
4928
|
+
- Electron RuntimeUpdateBadge glyph-only in header; version in title/aria-label.
|
|
4929
|
+
- Connection chip: server-kind glyph (connection-chip-glyph; mdiLaptop local, mdiServerNetwork remote; offline = mdiLaptopOff / mdiServerNetworkOff form in --accent-red-text, carries connection-chip-offline-glyph) with aria-hidden top-right status dot badge · server name (max-w-24, max-w-40 from header container 480 px; hidden < 400 px) · offline word (>= 480 px) · remote-access tone glyph (internet/partial/failed) · waiting-device badge (tunnel-btn-badge) · chevron (hidden < 400 px). Collapsed chip 32 px. Kind from currentServerKind(entry, host) in ServerSelector.tsx. title = "{server}: switch server".
|
|
4930
|
+
- Chip menu: servers · "Manage servers…" · Access group.
|
|
4931
|
+
- Access group: Remote access (`tunnel-btn`, opens `RemoteAccessDialog`) · Install as app (`install-btn`, only when installable).
|
|
4932
|
+
- `useRemoteAccessIndicator` (hooks): tunnel-status poll, reachability, pending-pairing count, saved-run resume. Called once in `App.tsx`.
|
|
4933
|
+
- `App` hosts lazy `RemoteAccessDialog`.
|
|
4934
|
+
- `TunnelButton` and `InstallButton` deleted.
|
|
4935
|
+
- Row 2: one scoped search box. Scope toggle Sessions|Folders. Inactive query = chip with switch + clear buttons.
|
|
4936
|
+
- Filter funnel (`filter-funnel-btn`) opens popover. Badge counts Include archive + Show hidden.
|
|
4937
|
+
- Layout floors: common state (quiet remote access, update count < 10) one line at >= 280 px sidebar. With tunnel on or 2-digit count, right group wraps at ~280-300 px, never clips. Worst state, short server name, one line at >= 400 px.
|
|
4938
|
+
|
|
4219
4939
|
### Reconnection Flow
|
|
4220
4940
|
1. Browser reconnects with `subscribe` message including `lastSeq`
|
|
4221
4941
|
2. Server compacts the in-memory window via `compactEventsForReplay`, then replays missed events in async batches of 200 (`REPLAY_BATCH_SIZE`) with backpressure handling
|
|
@@ -4337,10 +5057,10 @@ See change: `lazy-load-session-history`, `add-tail-only-replay-window`.
|
|
|
4337
5057
|
### Bridge Reconnection (State Reset)
|
|
4338
5058
|
When a bridge extension reconnects (e.g., after `pnpm run reload` or network recovery):
|
|
4339
5059
|
1. Bridge sends `session_register` with `eventCount` to re-register the session
|
|
4340
|
-
2. Server checks
|
|
4341
|
-
3. **Full replay path** (
|
|
4342
|
-
4. **Skip replay path** (
|
|
4343
|
-
5. Bridge replays full session history as individual `event_forward` messages
|
|
5060
|
+
2. Server checks skip-wipe fingerprint (see Event Broadcast During Replay): `eventCount` + `leafEntryId` match, store intact → wipe skipped (fast reconnect path). Old bridge (no leaf) always wipes.
|
|
5061
|
+
3. **Full replay path** (wipe): Server clears the in-memory event store, broadcasts `session_state_reset` to browsers, stores replayed events, and sends them as `event_replay` batch after `replay_complete`
|
|
5062
|
+
4. **Skip replay path** (no wipe): Server keeps existing events in the store. Replayed marked events are NOT inserted (preventing exponential duplication). Status updates are still processed for session state accuracy. After `replay_complete`, the `event_replay` batch is skipped since browsers already have the events.
|
|
5063
|
+
5. Bridge replays full session history as individual `event_forward` messages, each marked `replay: true`
|
|
4344
5064
|
6. Bridge sends `replay_complete` to signal replay is done
|
|
4345
5065
|
7. If the agent is currently mid-turn (bridge tracks `isAgentStreaming` flag in persistent `BridgeState`), a synthetic `agent_start` event is sent after `replay_complete` so the session card shows "Thinking…" instead of "Waiting for input"
|
|
4346
5066
|
8. Server clears the replaying flag, broadcasts the final accumulated session status
|
|
@@ -4348,7 +5068,7 @@ When a bridge extension reconnects (e.g., after `pnpm run reload` or network rec
|
|
|
4348
5068
|
|
|
4349
5069
|
Without the `session_state_reset` message (full replay path), replayed events would duplicate existing messages in the browser's accumulated state.
|
|
4350
5070
|
|
|
4351
|
-
**Replay status suppression**: During step 5, replayed events like `agent_start`/`agent_end` would normally trigger rapid `session_updated` broadcasts (e.g., `status: "streaming"` → `status: "idle"` for each turn), causing visible flicker on session cards. The server suppresses these status broadcasts while replaying, accumulating them in the session manager. Only the final status is broadcast after `replay_complete`.
|
|
5071
|
+
**Replay status suppression**: During step 5, replayed events like `agent_start`/`agent_end` would normally trigger rapid `session_updated` broadcasts (e.g., `status: "streaming"` → `status: "idle"` for each turn), causing visible flicker on session cards. The server suppresses these status broadcasts while replaying, accumulating them in the session manager. Only the final status is broadcast after `replay_complete`. Fallback for unmarked (older) bridges: idle exit after 5s with no bridge message, or cap exit after 60s (see Event Broadcast During Replay). `replay_complete` never arriving no longer leaves the flag set.
|
|
4352
5072
|
|
|
4353
5073
|
**Agent streaming state recovery**: The bridge tracks `isAgentStreaming` in process-level `BridgeState` (survives reload). Set `true` on `agent_start`, `false` on `agent_end`/`session_shutdown`. Since the replay doesn't include `agent_start`/`agent_end` events, the session status would otherwise stay "active" (displayed as "Waiting for input") when the agent is mid-turn during reconnect.
|
|
4354
5074
|
|
|
@@ -4578,8 +5298,84 @@ When a browser subscribes to a session whose events have been evicted from memor
|
|
|
4578
5298
|
### Flows Refresh Deduplication
|
|
4579
5299
|
When a session sends `flows_list`, the server notifies other sessions in the same cwd to rediscover flows. To prevent infinite loops (A→refresh B→B sends flows→refresh A→...), a per-session 5-second cooldown (`recentFlowsRefresh` set) suppresses duplicate refresh requests.
|
|
4580
5300
|
|
|
4581
|
-
### Event Broadcast During Replay
|
|
4582
|
-
|
|
5301
|
+
### Event Broadcast During Replay (change: fix-large-session-resume-replay, #928/#929)
|
|
5302
|
+
|
|
5303
|
+
**Replay marking (bridge).**
|
|
5304
|
+
- Bridge sets `replay: true` on every replayed `event_forward`. Sites: `replaySessionEntries` (`packages/extension/src/session-sync.ts`); ACP event-log replay (`packages/server/src/acp-bridge/acp-session-adapter.ts`).
|
|
5305
|
+
- Live forwards never marked.
|
|
5306
|
+
- Field optional: `EventForwardMessage.replay?: true` (`packages/shared/src/protocol.ts`). Old server ignores it.
|
|
5307
|
+
|
|
5308
|
+
**Classification (server).** `isReplayedForward(sessionId, msg)` in `packages/server/src/event-wiring.ts`:
|
|
5309
|
+
`msg.replay === true || replayingSessions.has(sessionId)`.
|
|
5310
|
+
- Marked event never live: no broadcast, unread, push, `lastActivityAt`, card order, OpenSpec detection.
|
|
5311
|
+
- Marked event after exit → controller `reopen` → next exit flushes it.
|
|
5312
|
+
- Skipped replay: marked events never inserted until next register.
|
|
5313
|
+
|
|
5314
|
+
**Replay mode owner.** `packages/server/src/session/replay-exit-controller.ts`, one per session.
|
|
5315
|
+
- API: `begin`, `touch`, `reopen`, `complete`, `release`.
|
|
5316
|
+
- State: flush epoch, `flushPending`, waiter registry.
|
|
5317
|
+
|
|
5318
|
+
```mermaid
|
|
5319
|
+
stateDiagram-v2
|
|
5320
|
+
[*] --> Replaying: session_register (begin)
|
|
5321
|
+
Replaying --> Exit: replay_complete (complete)
|
|
5322
|
+
Replaying --> Exit: 5s idle, unmarked bridge (idle)
|
|
5323
|
+
Replaying --> Exit: 60s cap, unmarked bridge (cap)
|
|
5324
|
+
Replaying --> Exit: unregister
|
|
5325
|
+
Exit --> Flush: flushPending
|
|
5326
|
+
Flush --> [*]: isLast true
|
|
5327
|
+
Exit --> [*]: no pending flush
|
|
5328
|
+
```
|
|
5329
|
+
|
|
5330
|
+
**Fallback exits (unmarked old bridges only).**
|
|
5331
|
+
- `idle`: no processed bridge message of any type for `REPLAY_IDLE_MS` (5000).
|
|
5332
|
+
- `idle` re-check runs via one `setImmediate`, so queued input handled first. Busy server does not force idle exit.
|
|
5333
|
+
- `cap`: `REPLAY_CAP_MS` (60000) after register.
|
|
5334
|
+
- One timer set per session. Each new register cancels old set.
|
|
5335
|
+
- Test seam: `createServer({ replayTimings: { idleMs, capMs, keepaliveMs } })`.
|
|
5336
|
+
|
|
5337
|
+
**Exit (`exitReplay(sessionId, cause)`).** Single implementation.
|
|
5338
|
+
- Causes: `complete | idle | cap | unregister`.
|
|
5339
|
+
- Log: `[replay] exit <id> cause=<cause>`. `warn` level for `idle` / `cap`.
|
|
5340
|
+
- Work, fixed order:
|
|
5341
|
+
1. clear OpenSpec phase/change.
|
|
5342
|
+
2. reconcile + recompute prompts (not on `unregister`).
|
|
5343
|
+
3. one `session_updated` broadcast.
|
|
5344
|
+
4. windowed flush when `flushPending`.
|
|
5345
|
+
- Late `replay_complete` after `idle` / `cap` exit = no-op.
|
|
5346
|
+
|
|
5347
|
+
**Pending proposal.**
|
|
5348
|
+
- Bridge replay neither raises nor clears `pendingReplaceProposal`.
|
|
5349
|
+
- `register()` carries `pendingReplaceProposal` + `rejectedReplaceProposals` across re-register (`packages/server/src/session/memory-session-manager.ts`).
|
|
5350
|
+
|
|
5351
|
+
**Windowed abortable flush.** `BrowserGateway.replayStoreToSubscribers(sessionId, isStale)` (`packages/server/src/pairing/browser-gateway.ts`). Per WebSocket subscriber:
|
|
5352
|
+
- Exactly one `session_state_reset`.
|
|
5353
|
+
- Store windowed like subscribe-time full replay: `sendEventBatches` with `maxReplayEvents`, `history_window` when window applies.
|
|
5354
|
+
- Ends `isLast: true`. Empty store → terminal empty batch.
|
|
5355
|
+
- In-process subscribers: one full `event_replay`.
|
|
5356
|
+
- `isStale` polled before each batch. Re-register / unregister → flush stops, socket unmuted, no catch-up.
|
|
5357
|
+
- `flushPending` stays set until flush completes → next exit sends full flush even after skipped register.
|
|
5358
|
+
|
|
5359
|
+
**Skip-wipe fingerprint.**
|
|
5360
|
+
- `session_register` (`SessionRegisterMessage`) carries `eventCount`, optional `leafEntryId`, `liveTailOpen`.
|
|
5361
|
+
- Skip wipe only when `leafEntryId` valid (string, 1–128 chars) AND one of:
|
|
5362
|
+
- bridge-learned: `eventCount` + leaf match previous register.
|
|
5363
|
+
- hydration-learned: cold hydration recorded `{entryCount, leafEntryId, storeMaxSeq}` (`packages/server/src/session/hydration-state.ts`); needs `liveTailOpen === false` and unchanged store.
|
|
5364
|
+
- Old bridge (no leaf) always wipes.
|
|
5365
|
+
- Log: `[replay] register <id> skipWipe=<bool> reason=<...>`.
|
|
5366
|
+
- `LoadResult` carries `entryCount` + `leafEntryId` (`session-load-worker.ts`, `directory-service.ts`).
|
|
5367
|
+
|
|
5368
|
+
**Register supersedes cold hydration.**
|
|
5369
|
+
- `session_register` bumps per-session generation (`hydration-state.ts`) → calls `directoryService.cancelLoad`.
|
|
5370
|
+
- Subscription handler drops hydration result whose generation changed before insert; stops its fan-out.
|
|
5371
|
+
- Subscribe during bridge replay, store empty: no cold load (works without `sessionFile`).
|
|
5372
|
+
- Immediate `event_replay{events:[],isLast:false}`.
|
|
5373
|
+
- Keepalive every `keepaliveMs` (10000 default) until exit flush.
|
|
5374
|
+
- Keepalive stops before terminal batch.
|
|
5375
|
+
|
|
5376
|
+
**Mixed versions.**
|
|
5377
|
+
- New server + old bridge: timer fallback + full wipe.
|
|
5378
|
+
- Old server + new bridge: extra fields ignored.
|
|
4583
5379
|
|
|
4584
5380
|
### Per-message entry id stamping (live vs replay)
|
|
4585
5381
|
|
|
@@ -4799,7 +5595,7 @@ The client can connect/disconnect the tunnel via `POST /api/tunnel-connect` and
|
|
|
4799
5595
|
|
|
4800
5596
|
**Reserved/persistent URLs (v2 namespaces+names).** Config keys `tunnel.zrok.reservedName` + `tunnel.zrok.persistent` (default false). Mint name: `zrok2 create name -n public <name>` (reuse-on-exists for same account; taken-by-other → warn + ephemeral). Share: `zrok2 share public --headless -n public:<name> localhost:<port>` → stable `<name>.shares.zrok.io`. Release: `zrok2 delete name <name>` invoked only by explicit forget (see below). Reserved name SURVIVES disconnect/restart; released ONLY by `POST /api/tunnel-disconnect {forget:true}`. Ephemeral (no name, default persistent=false) yields rotating `*.shares.zrok.io` URL. Legacy v1 `tunnel.reservedToken` preserved on read (downgrade) but IGNORED by v2 provider — never promoted to reservedName.
|
|
4801
5597
|
|
|
4802
|
-
**URL format + CORS.** v2 emits bare `<t>.shares.zrok.io` (plural, no scheme); provider prepends `https://`. urlRegex anchored so `*.shares.zrok.io.attacker.com` NOT matched as zrok host. CORS allows `*.shares.zrok.io
|
|
5598
|
+
**URL format + CORS.** v2 emits bare `<t>.shares.zrok.io` (plural, no scheme); provider prepends `https://`. urlRegex anchored so `*.shares.zrok.io.attacker.com` NOT matched as zrok host. CORS allows the live dashboard tunnel origin always; `*.shares.zrok.io` wildcard only with opt-in `cors.allowZrokWildcard: true` (see § CORS).
|
|
4803
5599
|
|
|
4804
5600
|
**Doctor + version check.** "zrok API reachable" probes `api-v2.zrok.io` (or enrolled env `api_endpoint`). NEW check "zrok version compatible" warns when major < 2 (v1 = 0.4.x) — real root-cause detector for field 500s.
|
|
4805
5601
|
|
|
@@ -4830,8 +5626,19 @@ The Fastify CORS callback in `server.ts` allows:
|
|
|
4830
5626
|
- Same-origin navigations (no `Origin` header).
|
|
4831
5627
|
- `localhost`, `127.0.0.1`, `[::1]` on any port.
|
|
4832
5628
|
- The currently-active zrok tunnel URL (looked up dynamically via `getTunnelUrl()` so URL rotation picks up without a restart).
|
|
4833
|
-
-
|
|
5629
|
+
- Every live tunnel origin (`getLiveTunnelOrigins()`, any provider; includes the live zrok URL).
|
|
5630
|
+
- Any `*.share.zrok.io` / `*.shares.zrok.io` host — **opt-in only**, `cors.allowZrokWildcard: true`. Default `false`.
|
|
5631
|
+
- Neutral shell `https://pi-dashboard.dev`.
|
|
4834
5632
|
- Explicitly-configured `corsAllowedOrigins` from config.
|
|
5633
|
+
- Origin host in a trusted network.
|
|
5634
|
+
|
|
5635
|
+
**Zrok wildcard is opt-in.** `cors.allowZrokWildcard` — boolean, only literal `true` enables (parser: `=== true`; default `false`; `packages/shared/src/config.ts`). Read live via `liveCorsAllowZrokWildcard()` (`config-snapshot.ts`) through `corsOpts()`. Branch test in `classifyCorsOrigin` is `allowZrokWildcard === true`. Live dashboard tunnel always allowed via branches 4 / 4b, never via wildcard. Admission (WS + REST gate) never consults the wildcard. Reason: zrok shares free + self-service; stranger share is likely same-site to victim tunnel.
|
|
5636
|
+
|
|
5637
|
+
**Canonical compare.** `canonicalOrigin(raw)` in `auth/cors-origin.ts`: lowercase scheme + host, default port elided, ONE trailing hostname dot stripped, path/query dropped. Returns `null` for padded input, control chars, non-http(s), bad port. Used on both sides of the tunnel branches (4, 4b) and in `isSameOriginByHost`. `https://X.share.zrok.io.` equals dotless form — matches host admission. Padded / control-char origins denied. Throwing `getTunnelUrl` / `getLiveTunnelOrigins` getters = no live tunnels (never a 500). Live reload parity: `cors.allowZrokWildcard` and `cors.allowedOrigins` both applied on edit, no restart.
|
|
5638
|
+
|
|
5639
|
+
**Stale second zrok frontend.** Page on zrok A calling server on zrok B loses CORS after upgrade. Escape hatch: set `cors.allowZrokWildcard: true` in `~/.pi/dashboard/config.json`. Rollback = same key.
|
|
5640
|
+
|
|
5641
|
+
See change: harden-cors-and-csp-reporting (D6, D7).
|
|
4835
5642
|
|
|
4836
5643
|
On a mismatch the callback returns `cb(null, false)` — **not** `cb(new Error(…), false)`. The `Error` form causes `@fastify/cors` to surface the error as HTTP 500 on every asset response, which is exactly what caused the long-running “zrok returns 500 on assets” debugging saga: Vite emits `<script type="module" crossorigin>` entry tags, which per HTML spec browsers always fetch in CORS mode (even same-origin), so the tunnel URL appearing in `Origin` is unavoidable. Returning `cb(null, false)` simply omits CORS headers; the browser enforces same-origin policy on its own. CORS answers READ-authority only (may this origin see the response); ADMISSION — may this origin open a socket or mutate state — is decided by the next subsection.
|
|
4837
5644
|
|
|
@@ -4842,7 +5649,7 @@ Issue #625. CORS hides a response, never blocks the request. Gate blocks the act
|
|
|
4842
5649
|
**Shared decision** — `packages/server/src/auth/cors-origin.ts`, `isOriginAdmitted(origin, hostHeader, opts)` = `isCorsOriginAllowed` plus 2 deltas.
|
|
4843
5650
|
|
|
4844
5651
|
- Delta 1, Host match: Origin `host[:port]` equals request `Host` → admit. Both normalized with `new URL()`; origin scheme applied to Host so default ports elide. Covers mDNS `http://mac.local:8000` + plain-LAN pages. `isBypassedHost` matches IP literals only; without this rule hostname-addressed clients 403.
|
|
4845
|
-
- Delta 2, no zrok wildcard: `isCorsOriginAllowed` gains `allowZrokWildcard` — default `
|
|
5652
|
+
- Delta 2, no zrok wildcard: `isCorsOriginAllowed` gains `allowZrokWildcard` — default `false` for CORS (opt-in config `cors.allowZrokWildcard`) and always `false` for admission. `*.share.zrok.io` / `*.shares.zrok.io` skipped for admission. Zrok shares are free + self-service, so a stranger share is likely same-site to the victim tunnel. Dashboard-run tunnels are live tunnel origins, still admitted.
|
|
4846
5653
|
- Absent `Origin` → admit. Bridge, `pi-dashboard` CLI, `curl`, skill send none. Browsers cannot omit it. Empty `""`, whitespace-padded, malformed → deny.
|
|
4847
5654
|
|
|
4848
5655
|
**WebSocket gate** — `server.ts`, `fastify.server.on("upgrade")`, `isWsOriginTrusted(origin, host, scope, corsOpts())`.
|
|
@@ -4865,7 +5672,7 @@ Issue #625. CORS hides a response, never blocks the request. Gate blocks the act
|
|
|
4865
5672
|
|
|
4866
5673
|
**Logs** — `[ws-gate] rejected upgrade origin=… scope=… peer=…`; `[csrf-gate] rejected <method> <path> origin=…`; `[pi-gateway] … browser-origin`. Fields are attacker-controlled; `sanitizeHeaderForLog` strips control chars, caps 256.
|
|
4867
5674
|
|
|
4868
|
-
**Escape hatch** — a hand-run `zrok share public` (not the dashboard tunnel feature) needs its origin in `cors.allowedOrigins` (`~/.pi/dashboard/config.json`).
|
|
5675
|
+
**Escape hatch** — a hand-run `zrok share public` (not the dashboard tunnel feature) needs its origin in `cors.allowedOrigins` (`~/.pi/dashboard/config.json`). `cors.allowZrokWildcard: true` widens CORS reads only; admission still refuses the wildcard.
|
|
4869
5676
|
|
|
4870
5677
|
### Host Admission Gate
|
|
4871
5678
|
|
|
@@ -5132,9 +5939,11 @@ Electron-bound presentation concerns (tray icons, menu template, dock behavior,
|
|
|
5132
5939
|
|
|
5133
5940
|
### Windows runtime dependencies (git + bash)
|
|
5134
5941
|
|
|
5135
|
-
On Windows agent needs `git.exe` +
|
|
5942
|
+
On Windows agent needs `git.exe` + bash. git backs repo ops. bash backs agent `bash` tool, `!`/`!!` bang commands, `!cmd` config values. Pi resolves bash itself (`getShellConfig()`, pi-coding-agent 1.3.0). Dashboard never calls `pi.exec("sh")`. macOS/Linux ship both system-wide; Windows-only problem.
|
|
5136
5943
|
|
|
5137
|
-
Installers embed dugite-native (git 2.53.0
|
|
5944
|
+
Installers embed dugite-native (git 2.53.0.windows.4). Bundle ships GNU bash only as `usr/bin/sh.exe`. Config key `windowsGitSource`: `"auto"`\|`"host"`\|`"bundled"`, default `"auto"`.
|
|
5945
|
+
|
|
5946
|
+
Bundled bash copy: `ensureBundledBashExe` (`packages/electron/scripts/lib/ensure-bundled-bash-exe.mjs`) byte-copies `usr/bin/sh.exe` → `usr/bin/bash.exe`. `sh.exe` kept. Throws if `sh.exe` missing. MSYS bash picks `posix off` from argv[0] `bash` (`posix on` for `sh`). Cost: +~2.5 MB per Windows artifact. See change: fix-windows-bundled-bash-exe.
|
|
5138
5947
|
|
|
5139
5948
|
- `auto` → host when git+bash both on PATH, else bundled (atomic).
|
|
5140
5949
|
- `host` → host, bundled fallback + Doctor error.
|
|
@@ -5142,13 +5951,59 @@ Installers embed dugite-native (git 2.53.0 + GNU bash as `usr/bin/sh.exe`). Conf
|
|
|
5142
5951
|
|
|
5143
5952
|
`selectGitSource()` decides. Cached process-lifetime (`git-source.ts`); invalidated on `/api/restart` (fresh process) + config-write.
|
|
5144
5953
|
|
|
5145
|
-
`ensureBundledGitOnPath()` prepends
|
|
5954
|
+
`ensureBundledGitOnPath()` prepends to PATH (after `ensureWindowsSystemPath`, lands before System32). Sets `GIT_EXEC_PATH` + `SSL_CERT_FILE`. `<libdir>` = `mingw64` (x64) / `clangarm64` (arm64).
|
|
5955
|
+
|
|
5956
|
+
- `windowsBashSource: "bundled"` (default) → prepends `resources/git/{cmd,usr/bin,<libdir>/bin}`. pi picks bundled `bash.exe` only if no Git for Windows under `%ProgramFiles%` / `%ProgramFiles(x86)%`.
|
|
5957
|
+
- `windowsBashSource: "host"` → prepends `resources/git/{cmd,<libdir>/bin}`. Appends `usr/bin` LAST. pi picks host's first `bash.exe` on PATH only if no Git for Windows under `%ProgramFiles%` / `%ProgramFiles(x86)%`.
|
|
5958
|
+
- Both modes: installed Git for Windows `bash.exe` in `%ProgramFiles%\Git\bin` wins over PATH (pi step 2 precedes `where bash.exe`). `windowsBashSource` only orders PATH; it does not override that check.
|
|
5959
|
+
- Mode applies only while active git source is bundled. Windows-only.
|
|
5146
5960
|
|
|
5147
5961
|
Hooked into `ToolResolver.buildSpawnEnv` (covers server-launcher + process-manager) and `terminal-manager` PTY env separately (PTY bypasses `buildSpawnEnv`).
|
|
5148
5962
|
|
|
5149
|
-
Build-time: `download-git-windows.mjs` runs in `bundle-server.mjs`, SHA-256 fail-closed, GO/NO-GO.
|
|
5963
|
+
Build-time: `download-git-windows.mjs` runs in `bundle-server.mjs`, SHA-256 fail-closed, calls `ensureBundledBashExe`. GO/NO-GO in `bundle-server.mjs` + `assert-runnable-bundle.mjs` requires `usr/bin/bash.exe`.
|
|
5964
|
+
|
|
5965
|
+
PATH semantics: bundled entries lead (except `usr/bin` under `windowsBashSource: "host"`). Takes effect for newly spawned sessions only (existing children keep old PATH). No-op on macOS/Linux.
|
|
5966
|
+
|
|
5967
|
+
**Pi bash resolution** (`getShellConfig()`, never `sh.exe`, never `pi.exec("sh")`). Order:
|
|
5968
|
+
|
|
5969
|
+
1. pi `shellPath` setting (bash tool + `!` only; not `!cmd`).
|
|
5970
|
+
2. `%ProgramFiles%\Git\bin\bash.exe`, then `%ProgramFiles(x86)%\Git\bin\bash.exe`.
|
|
5971
|
+
3. First `where bash.exe` hit.
|
|
5972
|
+
4. Else throw `No bash shell found`.
|
|
5150
5973
|
|
|
5151
|
-
|
|
5974
|
+
First `where` hit `C:\Windows\System32\bash.exe` (WSL launcher):
|
|
5975
|
+
|
|
5976
|
+
- No WSL distro → `no installed distributions` failure.
|
|
5977
|
+
- Distro present → commands run inside Linux.
|
|
5978
|
+
|
|
5979
|
+
Dashboard never writes pi `shellPath`. Git for Windows in `%ProgramFiles%` wins regardless of `windowsBashSource`.
|
|
5980
|
+
|
|
5981
|
+
**`windowsBashSource`** (`"bundled"` default \| `"host"`). Setter `setWindowsBashSourceSetting` (`packages/shared/src/platform/git-source.ts`). Seeded at startup by `seedWindowsSourceSettings()` (`packages/server/src/config-api.ts`). UI: Settings → Sessions → Worktrees → "Bash for agent commands" (beside "Git & Bash source"). PATCH `/api/config` applies live to new sessions/terminals, no restart. Persists.
|
|
5982
|
+
|
|
5983
|
+
Side effects:
|
|
5984
|
+
|
|
5985
|
+
- `bundled`: every child resolving `bash` by name (pi, dashboard terminal `bash`, `#!/usr/bin/env bash` git hooks) gets bundled bash. WSL-distro users who got WSL bash before now get bundled Windows bash unless `host`.
|
|
5986
|
+
- `host`: MSYS tools in `usr/bin` (`find`, `sort`) shadowed by System32 tools for children. No host `bash.exe` on PATH → falls back to bundled bash. Bundled git still works incl. `#!/bin/sh` hooks.
|
|
5987
|
+
|
|
5988
|
+
**Diagnostics.** `resolvePiShell({env, exists})` (`packages/shared/src/platform/resolve-pi-shell.ts`) replicates pi order over augmented spawn env. `/api/health` `gitSource` = `{ setting, source, gitPath, gitVersion, shellPath, bashSetting, shellIsWslLauncher }` (null on macOS/Linux). `shellPath` = bash pi would resolve, never `sh.exe`.
|
|
5989
|
+
|
|
5990
|
+
Doctor "bash source" row:
|
|
5991
|
+
|
|
5992
|
+
- No shell → warning `doctor.no_posix_shell`.
|
|
5993
|
+
- WSL launcher, `bashSetting` ≠ `host` → warning `doctor.bash_is_wsl_launcher`.
|
|
5994
|
+
- WSL launcher, `host` → ok "requires an installed WSL distro".
|
|
5995
|
+
|
|
5996
|
+
Residuals: process cwd searched first by `where.exe`. User pi `shellPath` wins for bash tool/`!`.
|
|
5997
|
+
|
|
5998
|
+
**Build gate.** `packages/electron/scripts/assert-bundled-bash-resolvable.mjs`, step "Assert pi resolves bundled bash" in `.github/workflows/_electron-build.yml` (win32 full-bundle legs):
|
|
5999
|
+
|
|
6000
|
+
- Loads SHIPPED pi `getShellConfig` + shipped shared helpers.
|
|
6001
|
+
- `ProgramFiles*` → empty dir. Stub host `bash.exe` on PATH.
|
|
6002
|
+
- Bundled mode → expects `usr\bin\bash.exe`. Host mode → expects stub.
|
|
6003
|
+
- Exec checks (`posix off`, git commit through `#!/bin/sh` hook) only when target arch == runner arch. win32-arm64 = resolution-only.
|
|
6004
|
+
- Re-verify on pi version bump.
|
|
6005
|
+
|
|
6006
|
+
See change: fix-windows-bundled-bash-exe.
|
|
5152
6007
|
|
|
5153
6008
|
### Session spawn dispatch
|
|
5154
6009
|
|
|
@@ -5293,42 +6148,84 @@ The dashboard uses mDNS (via `bonjour-service`) for zero-config server discovery
|
|
|
5293
6148
|
|
|
5294
6149
|
### Known Servers
|
|
5295
6150
|
- Users can persist remote servers in `config.json` via `knownServers: KnownServer[]`
|
|
5296
|
-
-
|
|
5297
|
-
- REST API: `GET /api/known-servers` (list + `canManage`, `networkGuard`), `POST
|
|
6151
|
+
- Entry = one server instance, keyed by `fingerprint` (`sha256:` prefix, pinned). Shape `{fingerprint?, label?, addedAt, routes[], host, port}`. `host`/`port` mirror primary route (first `http` route, else first route). See Routes and identity grouping.
|
|
6152
|
+
- REST API: `GET /api/known-servers` (list + `canManage`, `networkGuard`; entries carry `routes[]`), `POST /api/known-servers {host, port, scheme?, label?, fingerprint?}` (attach route, operator-only), `DELETE /api/known-servers` by `{host, port, scheme?}` (route; entry removed with its last route) or `{fingerprint}` (whole entry), `POST /api/known-servers/accept-move` (operator), `POST /api/known-servers/probe {host, port, scheme?}` (operator), `POST /api/discover-servers` for on-demand mDNS scan
|
|
5298
6153
|
- Mutations and probe are operator-only: `preHandler: [networkGuard, operatorGuard]`. Network-trusted browsers can list entries but not change them. Breaking, see release note.
|
|
5299
6154
|
- Localhost is always implicitly available (not stored)
|
|
5300
6155
|
- The data model is extensible for future key exchange / auth tokens
|
|
5301
6156
|
|
|
5302
6157
|
### Known-server identity pinning (change: stabilize-mdns-server-identity)
|
|
5303
|
-
- Uniqueness
|
|
6158
|
+
- Uniqueness: per `http` route `(fingerprint, port)`; https routes join oldest entry holding F. `parseKnownServers` (`packages/shared/src/config.ts`) passes `sha256:` fingerprints through; legacy `{host, port}` reads as one route (`https` on port 443, else `http`); duplicate entries merged on load, first stored wins.
|
|
5304
6159
|
- Proof: `proveServerIdentity(baseUrl, {timeoutMs})` (`packages/shared/src/server-pinning.ts`). Fresh nonce → `POST /api/pair/challenge`. `redirect: "manual"`. Response read with 4 KiB cap. Fingerprint recomputed from presented key. Signature verified.
|
|
5305
6160
|
- `challengePinnedServer` unchanged (remote-registration gate relies on it).
|
|
5306
6161
|
- Pin written only after proof. Two paths: operator add; backfill (operator probe reports `reachable` for unpinned entry).
|
|
5307
|
-
- Add:
|
|
5308
|
-
- Proven `F`, no
|
|
5309
|
-
-
|
|
5310
|
-
-
|
|
5311
|
-
-
|
|
6162
|
+
- Add: challenge over route scheme runs outside write queue. `scheme` allowlist `http`|`https` (else `400 invalid_scheme`). Queued write re-reads config and re-validates.
|
|
6163
|
+
- Proven `F` → route attached per grouping rule. No `409 already_known`, no holder re-probe.
|
|
6164
|
+
- Route already stored → label refresh / pin → `{success: true}`.
|
|
6165
|
+
- New route attached to existing entry → `{updated: true}`. New entry → `{success: true}`.
|
|
6166
|
+
- Route stored under pin `G ≠ F` → `409 identity_changed {expected, proven}`.
|
|
6167
|
+
- Label replaced only when non-empty label supplied. `addedAt` kept.
|
|
5312
6168
|
- Add never clears or replaces a pin. Failed challenge keeps existing pin.
|
|
5313
|
-
- Backfill: proven `F` pinned at
|
|
6169
|
+
- Backfill: proven `F` pinned at primary route (own scheme). Existing `(F, port)` holder → merged into verified entry (survivor keeps routes, gains other's missing routes; label kept when verified entry has none), other entry removed, dropped host logged.
|
|
5314
6170
|
- All known-server writes (add, delete, backfill, accept-move) → one module-level serialized queue (`known-servers-routes.ts`). Challenges run before enqueue. Each write aborts if target entry gone.
|
|
5315
6171
|
|
|
6172
|
+
### Routes and identity grouping (change: group-servers-by-identity)
|
|
6173
|
+
|
|
6174
|
+
- Entry = one server instance. Key = fingerprint `F`. Route = address proven to be `F`.
|
|
6175
|
+
- Route item: `{host, port, scheme: "http"|"https", source: "saved"|"mdns"|"pairing"}`. Pure helpers in `packages/shared/src/server-routes.ts` (server, client, Electron): `classifyRoute`, `groupRoutes`, `findAttachTarget`, `rankRoutes`, `pairAction`, `buildRequestPageUrl`, `validateDeliveredRoutes`, `originToRoute`. Constants: `SIMILAR_LATENCY_MS = 50`, `MAX_DELIVERED_ROUTES = 8`.
|
|
6176
|
+
- Route kind derived, never stored: `loopback` (127/8, `::1`, `localhost`); `lan` (RFC1918, CGNAT 100.64/10, link-local, `fc00::/7`, `fe80::/10`, internal names); `mdns` (`*.local`); `tunnel` (https under `zrok.io`); else `public`. Kind picks label and pair action only.
|
|
6177
|
+
- Grouping (`findAttachTarget`): proven route joins entry holding `F` when route is `https`, or entry has no `http` route, or entry has `http` route on same port. Else new entry with same `F`, labelled "same identity as …". Two `http` ports = two rows.
|
|
6178
|
+
- https route joins oldest entry holding `F` (stored list order).
|
|
6179
|
+
- Unpinned entry: single route, keyed `host:port` until proof.
|
|
6180
|
+
- Merge, same identity: on load first stored wins; on backfill proven entry wins. Survivor keeps routes, gains missing routes, keeps or takes label.
|
|
6181
|
+
- Host normalised (`normalizeHost`): lower-case, one trailing dot removed, brackets and zone id stripped, IPv4-mapped IPv6 as IPv4.
|
|
6182
|
+
- Route proof, two concurrent calls per route:
|
|
6183
|
+
- identity challenge (`POST /api/pair/challenge`, route scheme): proof + latency.
|
|
6184
|
+
- `GET /api/health`: access. `403 network_not_allowed` → "Network not allowed".
|
|
6185
|
+
|
|
6186
|
+
| Challenge | Health | Route state |
|
|
6187
|
+
| --- | --- | --- |
|
|
6188
|
+
| proves `F` | ok | proven, usable |
|
|
6189
|
+
| proves `F` | `403 network_not_allowed` | proven, network not allowed |
|
|
6190
|
+
| proves `F′ ≠ F` | any | refused: different identity; no credential sent |
|
|
6191
|
+
| bad signature / bad key | any | refused: invalid identity proof |
|
|
6192
|
+
| non-200 or no `publicKey`/`signature` | ok | can't prove identity (older server) |
|
|
6193
|
+
| transport failure | n/a | unreachable |
|
|
6194
|
+
|
|
6195
|
+
- Server proof scheme-aware: `proveServerIdentity("<scheme>://host:port")`. Normal TLS verification, `redirect: "manual"`, 2 s, 4 KiB body cap.
|
|
6196
|
+
- Browser proof: `challengeIdentity` (`packages/client/src/lib/pairing/pair-protocol.ts`), same CORS and mixed-content limits as health. Blocked routes explained by server probe.
|
|
6197
|
+
- Concurrency: at most 6 route checks in flight; 2 s each.
|
|
6198
|
+
- mDNS advert `fp` unauthenticated: picks display group only. Route used only after proof of that `F`.
|
|
6199
|
+
- Best route, `rankRoutes(routes, {credentialed})`, proven routes only:
|
|
6200
|
+
- `credentialed: false` (list marker, browser switch): https wins when `https − http ≤ 50 ms` (inclusive); else lowest latency.
|
|
6201
|
+
- `credentialed: true` (Electron open that sends stored bearer): stored https, then stored http, then discovered https, then discovered. First proven wins; latency ignored. Prevents bearer downgrade to cleartext.
|
|
6202
|
+
|
|
6203
|
+
```mermaid
|
|
6204
|
+
flowchart TD
|
|
6205
|
+
R["proven routes"] --> C{"credentialed?"}
|
|
6206
|
+
C -- "no" --> L["fastest http, fastest https"]
|
|
6207
|
+
L --> G{"https − http ≤ 50 ms?"}
|
|
6208
|
+
G -- "yes" --> HS["https"]
|
|
6209
|
+
G -- "no" --> F["lowest latency"]
|
|
6210
|
+
C -- "yes" --> O["stored https, then stored http, then discovered https, then discovered; first proven, no latency"]
|
|
6211
|
+
```
|
|
6212
|
+
|
|
5316
6213
|
### Move suggestions (change: stabilize-mdns-server-identity)
|
|
5317
6214
|
- Trigger: `up` / `srv-update` / refresh sweep for peer whose `(fp, port)` matches pinned entry at different host.
|
|
5318
6215
|
- Rate: one challenge per `(fp, port)` per `MOVE_CHALLENGE_INTERVAL_MS` (60 s).
|
|
5319
|
-
-
|
|
6216
|
+
- Primary route still proves `F` → no action.
|
|
5320
6217
|
- Else challenge peer address only if on-link (inside a subnet of a local interface, or IPv6 prefix match) and not loopback / link-local / unspecified / multicast. Else skip, logged `move-skipped`.
|
|
5321
6218
|
- Proof → in-memory suggestion `{entry, host, port, verifiedAt}`. Not persisted. Fn: `known-server-moves.ts`.
|
|
5322
6219
|
- `GET /api/known-servers` returns `movedTo` per entry.
|
|
5323
6220
|
- Dropped when: stored address proves `F` again; peer disappears; not re-verified within `MOVE_SUGGESTION_TTL_MS` (10 min).
|
|
5324
6221
|
- Advert alone never writes config.
|
|
5325
|
-
- Accept: `POST /api/known-servers/accept-move {host, port}` (operator). Re-verifies:
|
|
6222
|
+
- Accept: `POST /api/known-servers/accept-move {host, port}` (operator). Re-verifies: primary route fails + suggested address proves `F`. Rewrites primary route `host`/`port` (scheme `http`); other routes, label, `fingerprint`, `addedAt` kept.
|
|
5326
6223
|
- Logs: `[known-servers] move-suggested|move-withdrawn|move-skipped fp=<short> <old> -> <new>`; accept logs `[known-servers] moved fp=<short> <old> -> <new>`. `<short>` = fingerprint without `sha256:`, 16 chars.
|
|
5327
6224
|
|
|
5328
6225
|
### Operator probe (change: stabilize-mdns-server-identity)
|
|
5329
|
-
- `POST /api/known-servers/probe {host, port}` (operator). Refuses unless `normalizeHostKey(host):port` matches
|
|
5330
|
-
- Order: DNS lookup first (own budget `PROBE_DNS_TIMEOUT_MS`), then `GET
|
|
5331
|
-
- One in-flight probe per
|
|
6226
|
+
- `POST /api/known-servers/probe {host, port, scheme?}` (operator). Refuses unless `normalizeHostKey(host):port` + scheme matches a stored route.
|
|
6227
|
+
- Order: DNS lookup first (own budget `PROBE_DNS_TIMEOUT_MS`), then `GET <scheme>://<formatHostPort>/api/health` (`redirect: "manual"`, `PROBE_HTTP_TIMEOUT_MS`). Separate budgets: slow negative `.local` lookup ≠ HTTP timeout.
|
|
6228
|
+
- One in-flight probe per route. On `reachable`, challenge over same route adds `fingerprint`. Result carries `scheme`.
|
|
5332
6229
|
- States:
|
|
5333
6230
|
- `name-not-resolved`: `ENOTFOUND` / `EAI_NONAME`.
|
|
5334
6231
|
- `timeout`: DNS timeout, `EAI_AGAIN`, HTTP `AbortError` / `TimeoutError`.
|
|
@@ -5338,7 +6235,7 @@ The dashboard uses mDNS (via `bonjour-service`) for zero-config server discovery
|
|
|
5338
6235
|
|
|
5339
6236
|
### Server Selector UI
|
|
5340
6237
|
- The header dropdown shows persisted known servers (from config) plus localhost, not raw mDNS results
|
|
5341
|
-
- Each
|
|
6238
|
+
- Each row is one identity: label (or hostname), best route `host:port`, Local/Remote badge, availability status. Routes listed per row with kind and proof state (`ServerRouteTable.tsx`, `server-route-chips.tsx`).
|
|
5342
6239
|
- **Probe lifecycle**: availability is probed via `/api/health` **only when the dropdown opens** — once per open. No mount probe, no timer, no probing while the dropdown is closed. Current-server status is derived from the live WebSocket state, not a separate probe.
|
|
5343
6240
|
- **Unreachable entries** are rendered with `opacity-50`, `cursor-not-allowed`, and the `disabled` attribute set; clicks are no-ops. To re-probe, close and reopen the dropdown. The transactional switch (below) still protects against races between the last probe and a click on a reachable entry.
|
|
5344
6241
|
- Last-used server persisted in `localStorage` (`pi-dashboard-last-server`) — **only after** a successful switch (see transactional switching below).
|
|
@@ -5380,9 +6277,8 @@ An `inFlightSwitchKey` ref guards against duplicate clicks; the clicked dropdown
|
|
|
5380
6277
|
`ConnectionStatusBanner` (`packages/client/src/components/ConnectionStatusBanner.tsx`) mounts above `<MobileShell>`. It shows "Disconnected from <host>. Retrying…" when the active WebSocket has been non-`OPEN` for more than 3 seconds continuously. The threshold is implemented via `setTimeout` cleared on any return-to-`OPEN` or unmount, so brief reconnects (laptop sleep, wifi hiccup) never flash the banner. During an in-flight staging switch the banner is suppressed — the live socket is still open, so no disconnection has actually occurred.
|
|
5381
6278
|
|
|
5382
6279
|
### Server Management (Settings Panel)
|
|
5383
|
-
- **
|
|
5384
|
-
-
|
|
5385
|
-
- Already-known servers show "Already added" badge in discovery results
|
|
6280
|
+
- **Servers section** (`ServersTab` → `KnownServersSection`): one merged section, saved + discovered servers, one row per identity. Replaces separate Known Servers and Network Discovery sections. Per-row pair action (see Routes and identity grouping; Route delegation and pair action).
|
|
6281
|
+
- Add form takes host, port, scheme, label. Scan triggers `POST /api/discover-servers`.
|
|
5386
6282
|
- Electron loading page shows known servers as fallback when primary server is unreachable
|
|
5387
6283
|
|
|
5388
6284
|
## Bridge↔Server Connection — transport & identity (designed)
|
|
@@ -5780,12 +6676,35 @@ Inline `!!` ephemeral cards (`InlineTerminalCard`) unchanged, excluded from tabs
|
|
|
5780
6676
|
|
|
5781
6677
|
See change: terminals-in-tabbed-panes.
|
|
5782
6678
|
|
|
6679
|
+
### Terminal Caps and Orphan Reaping (change: harden-server-capability-bounds)
|
|
6680
|
+
|
|
6681
|
+
`TerminalManager` bounds live PTYs. Config block `terminals` in `config.json`:
|
|
6682
|
+
|
|
6683
|
+
| Key | Default | Meaning |
|
|
6684
|
+
|-----|---------|---------|
|
|
6685
|
+
| `maxConcurrent` | 32 | Global live PTY cap. Tab + inline both count. |
|
|
6686
|
+
| `maxPerOwner` | 16 | Per `{iss,sub}` owner. Only while identity plane stamps owners. Ownerless PTYs count global only. |
|
|
6687
|
+
| `inlineOrphanTtlMs` | 600000 | Inline PTY TTL with no client attached. |
|
|
6688
|
+
|
|
6689
|
+
- Each value integer >= 1, else default + one warn line.
|
|
6690
|
+
- Restart server to apply.
|
|
6691
|
+
- Refused spawn starts nothing. Requesting socket gets `terminal_limit_reached {scope: global|owner, limit, cwd, inline}`. UI shows dismissible notice.
|
|
6692
|
+
- Tab terminals never reaped on idleness.
|
|
6693
|
+
- Inline (ephemeral) PTY: clock starts at spawn, restarts at last detach. Expiry kills PTY. Transcript tombstone kept.
|
|
6694
|
+
|
|
5783
6695
|
### Known Servers Configuration
|
|
5784
6696
|
|
|
5785
6697
|
```json
|
|
5786
6698
|
{
|
|
5787
6699
|
"knownServers": [
|
|
5788
|
-
{
|
|
6700
|
+
{
|
|
6701
|
+
"host": "office-mac.local", "port": 8000, "label": "Office Mac", "addedAt": "2024-01-15T10:30:00Z",
|
|
6702
|
+
"fingerprint": "sha256:<43 chars>",
|
|
6703
|
+
"routes": [
|
|
6704
|
+
{ "host": "office-mac.local", "port": 8000, "scheme": "http", "source": "saved" },
|
|
6705
|
+
{ "host": "office.example.ts.net", "port": 443, "scheme": "https", "source": "pairing" }
|
|
6706
|
+
]
|
|
6707
|
+
},
|
|
5789
6708
|
{ "host": "build-server", "port": 8000, "addedAt": "2024-01-20T14:00:00Z" }
|
|
5790
6709
|
]
|
|
5791
6710
|
}
|
|
@@ -5793,6 +6712,10 @@ See change: terminals-in-tabbed-panes.
|
|
|
5793
6712
|
|
|
5794
6713
|
Managed via REST API (`/api/known-servers`) or Settings panel. Localhost is always implicit.
|
|
5795
6714
|
|
|
6715
|
+
- `routes[]` item: `{host, port, scheme, source}`. Kind derived, never stored.
|
|
6716
|
+
- Legacy entry (no `routes`) reads as one route. Startup never rewrites file; first mutation writes `routes[]` + mirror. One log line.
|
|
6717
|
+
- Rollback: previous build reads `host`/`port` mirror only; drops `routes` on its next write. Secondary routes lost (re-learned via mDNS / pairing). `https` route read back as `http`; legacy port-443 entries read as `https` again on re-upgrade. No entry lost.
|
|
6718
|
+
|
|
5796
6719
|
## Bundled Skill: pi-dashboard
|
|
5797
6720
|
|
|
5798
6721
|
The `.pi/skills/pi-dashboard/` directory is both a local project skill (discovered by pi from `.pi/skills/`) and shipped with the npm package (discovered via `pi.skills` in `package.json`). This means any pi session in the dashboard project or any project that installs the dashboard package gets access to the skill.
|
|
@@ -6112,12 +7035,14 @@ See change: repair-corrupted-main-specs.
|
|
|
6112
7035
|
|
|
6113
7036
|
## OpenSpec workflow schema (`pi-spec-driven`)
|
|
6114
7037
|
|
|
6115
|
-
Dashboard-managed project schema. Base: OpenSpec built-in `spec-driven` + patch set (`CURRENT_PATCH =
|
|
7038
|
+
Dashboard-managed project schema. Base: OpenSpec built-in `spec-driven` + patch set (`CURRENT_PATCH = 2`). Opt-in per project. Never enabled on existing projects by default.
|
|
6116
7039
|
|
|
6117
7040
|
Code:
|
|
6118
7041
|
- `packages/server/src/openspec/workflow-schema.ts` — generation, stamp, state table, write guard, actions.
|
|
6119
7042
|
- `packages/server/src/routes/openspec-routes.ts` — `POST /api/openspec/workflow-schema`, init chain.
|
|
6120
|
-
- `packages/server/src/
|
|
7043
|
+
- `packages/server/src/openspec/workflow-schema-status.ts` — worker-safe fs-only status (`computeSchemaStatus`, `inspectSchema`, stamp parse/compare, `fingerprintDir`, config + change enumeration). No CLI/semaphore imports.
|
|
7044
|
+
- `packages/server/src/openspec/openspec-poll-worker.ts` + `openspec-poll-worker-pool.ts` — `schemaStatus` request kind: `{cwd, localVersion, packageSchemasDir, userSchemasDir}` → `{status, validateFingerprint?}`.
|
|
7045
|
+
- `packages/server/src/directory-service.ts` — `requestSchemaStatus` enqueues it.
|
|
6121
7046
|
- `packages/shared/src/types.ts` — `WorkflowSchemaGenerated`, `OpenSpecWorkflowSchemaStatus`.
|
|
6122
7047
|
- `packages/shared/src/openspec-poller.ts`, `.pi/skills/openspec-shared/scripts/effective-status.sh` — R-rule skip.
|
|
6123
7048
|
|
|
@@ -6246,11 +7171,40 @@ Remove sees only local working tree. Unmerged branches pinning `pi-spec-driven`
|
|
|
6246
7171
|
|
|
6247
7172
|
`OpenSpecData.workflowSchema?: OpenSpecWorkflowSchemaStatus` = `{ configured, generated, missing, unpinnedChanges, affectedChanges }`.
|
|
6248
7173
|
- Attached only to successful-poll payloads. Failure payload carries no schema status (`hasWorkflowSchemaStatus(readiness)` gate in `directory-service.ts`).
|
|
6249
|
-
- Computed
|
|
6250
|
-
- Only `newer` / `conflict` `schema validate
|
|
7174
|
+
- Computed by poll worker `schemaStatus` request. See Poll status below.
|
|
7175
|
+
- Only `newer` / `conflict` spawn `schema validate`. Main thread, shared spawn semaphore, memoized.
|
|
6251
7176
|
- Readiness untouched. Missing schema dir → per-change `Unknown schema` errors, not `STALE`. `STALE` would disable every OpenSpec control on session cards.
|
|
6252
7177
|
- Settings section: `/settings/openspec#workflow-schema` (`OpenSpecWorkflowSchemaSection.tsx`). Folder-section chip only links there.
|
|
6253
7178
|
|
|
7179
|
+
### Poll status
|
|
7180
|
+
|
|
7181
|
+
```mermaid
|
|
7182
|
+
sequenceDiagram
|
|
7183
|
+
participant M as main
|
|
7184
|
+
participant W as poll worker
|
|
7185
|
+
M->>W: schemaStatus {cwd, localVersion, packageSchemasDir, userSchemasDir}
|
|
7186
|
+
W-->>M: {status, validateFingerprint?}
|
|
7187
|
+
opt newer / conflict
|
|
7188
|
+
M->>M: openspec schema validate pi-spec-driven (semaphore, memoized)
|
|
7189
|
+
end
|
|
7190
|
+
```
|
|
7191
|
+
|
|
7192
|
+
- Computed by worker `schemaStatus` request on EVERY tick, gate hit included.
|
|
7193
|
+
- Gate does not track: CLI version, `config.yml`, user/package schema dirs, fallback `list` path.
|
|
7194
|
+
- Enqueued once per tick:
|
|
7195
|
+
- status-all path: right after `pool.probe`.
|
|
7196
|
+
- fallback `list` path: before `list` spawn.
|
|
7197
|
+
- `build` never waits on it. Only finalize awaits.
|
|
7198
|
+
- Stamp compare decided from stamp alone.
|
|
7199
|
+
- Whole-dir fingerprint only for `newer` / `conflict`. `.openspec.yaml` reads bounded (16).
|
|
7200
|
+
- `newer` / `conflict`: worker returns `validateFingerprint`. Main runs `openspec schema validate pi-spec-driven` via shared semaphore. Memoized by (cwd, fingerprint, CLI version). Failure → `incompatible`.
|
|
7201
|
+
- Worker error / timeout / disabled → in-process fallback `schemaStatusImpl`.
|
|
7202
|
+
- Both fail → `workflowSchema` key omitted for tick. Logged once per failure run per cwd.
|
|
7203
|
+
- `finalizeOpenSpecData` never carries previous tick's `workflowSchema`.
|
|
7204
|
+
- One spawn semaphore: `DirectoryService.semaphore` shared with REST route (`server.ts` passes as `spawnSemaphore`). `reconfigurePolling` resize applies to both.
|
|
7205
|
+
|
|
7206
|
+
See change: move-workflow-schema-status-to-poll-worker.
|
|
7207
|
+
|
|
6254
7208
|
### REST endpoint
|
|
6255
7209
|
|
|
6256
7210
|
`POST /api/openspec/workflow-schema`. Body: `{ cwd, action, confirm?, pinTo?, changes?, previousDefault? }`. `action` ∈ `enable | disable | update | adopt | pin | remove`.
|
|
@@ -6276,6 +7230,176 @@ Design-evidence promotion (R1 split files, R2 `design/` dir, R3 no design + task
|
|
|
6276
7230
|
- Skills: `.pi/skills/openspec-shared/scripts/effective-status.sh` — `jq -r '.schemaName'` gate on `openspec status --change <name> --json`.
|
|
6277
7231
|
- Other schemas: rules unchanged. Fallback `list` path (no `schemaName`): keeps promoting.
|
|
6278
7232
|
|
|
7233
|
+
## OpenSpec change dependencies (`add-openspec-change-dependencies`)
|
|
7234
|
+
|
|
7235
|
+
Per-change execution order. Declared + inferred edges → graph → cycle/unknown validation → waves. Pure parser in shared; server builds inputs; client renders chips, dialog, "Execution order" board mode.
|
|
7236
|
+
|
|
7237
|
+
Code:
|
|
7238
|
+
- `packages/shared/src/openspec-dependencies.ts` — pure: `parse`, `scanProposal`, `scanDelta`, `computeDependencyGraph`, `serializeDependencies`.
|
|
7239
|
+
- `packages/shared/src/types.ts` — `ChangeDependencies`, `DependencyEdge`, `DependencyIssue`; `OpenSpecChange.dependencies`.
|
|
7240
|
+
- `packages/server/src/openspec/openspec-dependency-inputs.ts` — per-file + per-change parse cache; `computeDependencies`.
|
|
7241
|
+
- `packages/server/src/openspec/openspec-poll-worker.ts` — `buildFromStatusAll` calls `computeDependencies` (worker and in-process identical).
|
|
7242
|
+
- `packages/server/src/openspec/dependencies-file.ts` — read/write helper for `dependencies.yaml`.
|
|
7243
|
+
- `packages/server/src/routes/openspec-routes.ts` — `GET`/`PUT /api/openspec/dependencies`.
|
|
7244
|
+
- `packages/client/src/components/openspec/DependencyChips.tsx`, `DependenciesDialog.tsx`.
|
|
7245
|
+
- `packages/client/src/lib/openspec/openspec-dependencies-view.ts` (pure helpers), `openspec-dependencies-api.ts` (fetch).
|
|
7246
|
+
- `.pi/skills/ship-it/scripts/openspec-deps-gate.ts` — ship-it step 1.5 gate.
|
|
7247
|
+
|
|
7248
|
+
Spec: `openspec/specs/openspec-change-dependencies/spec.md`. Archived change: `openspec/changes/archive/2026-10-21-add-openspec-change-dependencies/`. See change: add-openspec-change-dependencies.
|
|
7249
|
+
|
|
7250
|
+
### Pipeline
|
|
7251
|
+
|
|
7252
|
+
```mermaid
|
|
7253
|
+
flowchart LR
|
|
7254
|
+
DECL["declared: dependencies.yaml"] --> MERGE
|
|
7255
|
+
L1["L1: proposal labelled lines + prose refs"] --> MERGE
|
|
7256
|
+
L23["L2 capability birth / L3 shared capability"] --> MERGE
|
|
7257
|
+
MERGE["merge per ordered pair (blocked, blocker)"] --> RES["resolve: open / satisfied / unknown"]
|
|
7258
|
+
RES --> VAL["validate: cycle check x2"]
|
|
7259
|
+
VAL --> WAVE["waves: Kahn over open edges"]
|
|
7260
|
+
WAVE --> OUT["OpenSpecChange.dependencies"]
|
|
7261
|
+
```
|
|
7262
|
+
|
|
7263
|
+
### File: `openspec/changes/<name>/dependencies.yaml`
|
|
7264
|
+
|
|
7265
|
+
Keys:
|
|
7266
|
+
- `blocked_by: [name | {change, reason?}]`.
|
|
7267
|
+
- `not_blocked_by: [name]`.
|
|
7268
|
+
- `related: [name]`.
|
|
7269
|
+
|
|
7270
|
+
Rules:
|
|
7271
|
+
- Unknown top-level key → `invalid-file`.
|
|
7272
|
+
- Bad name → `invalid-file`. Name grammar `/^[a-z0-9]+(?:-[a-z0-9]+)*$/` (OpenSpec change-id).
|
|
7273
|
+
- `reason` > 500 chars → `invalid-file`. Alias → `invalid-file`.
|
|
7274
|
+
- File > 64 KiB → `invalid-file`. Symlink / non-regular file → `invalid-file`.
|
|
7275
|
+
- Empty file or empty key → no deps (not an error).
|
|
7276
|
+
- Parse: `yaml` `failsafe` schema + `maxAliasCount: 0`.
|
|
7277
|
+
- Reader `readDependenciesFile`: `lstat` regular-file check, read ≤ 64 KiB + 1, `O_NOFOLLOW`.
|
|
7278
|
+
- Only `blocked_by` stored. `blocks` always computed (inverse).
|
|
7279
|
+
|
|
7280
|
+
### Inference layers
|
|
7281
|
+
|
|
7282
|
+
- Declared edges: from `dependencies.yaml`. Highest precedence.
|
|
7283
|
+
- L1 proposal text: labelled lines `Blocked by` / `Depends on` / `Builds on` / `Blocks`.
|
|
7284
|
+
- List item or paragraph. Optional bold + parenthetical. Value after `:` or as backticked token. Continuation lines allowed.
|
|
7285
|
+
- `Blocks on` is NOT a label.
|
|
7286
|
+
- Fenced code blocks skipped.
|
|
7287
|
+
- Self, unknown, and archived-under-`Blocks` ignored.
|
|
7288
|
+
- Other backticked active change names in prose → `related`. Never blocking.
|
|
7289
|
+
- L2 capability birth: capability with no `openspec/specs/<cap>/spec.md` is unborn.
|
|
7290
|
+
- Sole ADDED-only birther blocks every other change that has a delta header.
|
|
7291
|
+
- ≥ 2 birthers → `duplicate-capability` warning. No edge.
|
|
7292
|
+
- L3 shared capability: `overlaps` edge. Undirected. Never blocking.
|
|
7293
|
+
|
|
7294
|
+
### Merge
|
|
7295
|
+
|
|
7296
|
+
- Key: `(blocked, blocker)`.
|
|
7297
|
+
- Precedence: declared > inferred-text > inferred-capability.
|
|
7298
|
+
- `not_blocked_by` suppresses any edge for that pair.
|
|
7299
|
+
- Name in both `blocked_by` and `not_blocked_by` → `conflicting-entry` warning. `not_blocked_by` wins.
|
|
7300
|
+
|
|
7301
|
+
### Resolution
|
|
7302
|
+
|
|
7303
|
+
| Blocker state | Result |
|
|
7304
|
+
|---|---|
|
|
7305
|
+
| active change dir `openspec/changes/<name>/` | open |
|
|
7306
|
+
| archive dir exactly `<YYYY-MM-DD>-<name>` | satisfied |
|
|
7307
|
+
| `<date>-SHELVED-<name>` | NOT satisfied |
|
|
7308
|
+
| unknown, in declared `blocked_by` | `unknown-change` warning |
|
|
7309
|
+
| unknown, inferred | silent |
|
|
7310
|
+
| self | `self-reference` error |
|
|
7311
|
+
|
|
7312
|
+
### Validation
|
|
7313
|
+
|
|
7314
|
+
- Errors: `invalid-file`, `self-reference`, `cycle` (declared-only).
|
|
7315
|
+
- Warnings: `cycle` (inferred edge involved), `blocked-by-cycle`, `unknown-change`, `conflicting-entry`, `duplicate-capability`.
|
|
7316
|
+
- Cycle path: shortest cycle through smallest-named SCC member. Lexicographic tie-break. Format `a → b → a`.
|
|
7317
|
+
|
|
7318
|
+
### Waves
|
|
7319
|
+
|
|
7320
|
+
- Kahn over open edges among active changes.
|
|
7321
|
+
- Wave 1 = no open blockers.
|
|
7322
|
+
- Cycle members + their dependents → `wave: null`.
|
|
7323
|
+
|
|
7324
|
+
### Tracked paths (poll gate + watcher)
|
|
7325
|
+
|
|
7326
|
+
- Per-change `dependencies.yaml` in gate probe + watcher filter.
|
|
7327
|
+
- cwd-level: `changes/archive/`, `openspec/specs/`, `openspec/specs/<cap>/spec.md` for capability ids of previous build (`DirCache.allCapIds`).
|
|
7328
|
+
- `allCapIds === null` → gate never skips.
|
|
7329
|
+
- Capability set change → re-stamp cwd mtime.
|
|
7330
|
+
|
|
7331
|
+
### Schema patch v2
|
|
7332
|
+
|
|
7333
|
+
- `CURRENT_PATCH = 2` in `packages/server/src/openspec/workflow-schema-status.ts` (`workflow-schema.ts` re-exports it).
|
|
7334
|
+
- Inserts artifact `dependencies` before `tasks`. Generates `dependencies.yaml` from `templates/dependencies.yaml`. Requires `[proposal, specs]`.
|
|
7335
|
+
- `tasks.requires = [specs, design, dependencies]`.
|
|
7336
|
+
- Anchor must be exactly `[specs, design]`. Otherwise generation aborts.
|
|
7337
|
+
- Patch-1 stamp → `generated: outdated`. Only explicit Update regenerates.
|
|
7338
|
+
- Undeclared change stays `PLANNING`. Board shows "Declare dependencies" hint, artifact letter `L`.
|
|
7339
|
+
- `OpenSpecData.workflowSchema.undeclaredChanges`: `affectedChanges` members without regular `dependencies.yaml`. Lstat only; symlink or dir counts as undeclared. Sorted.
|
|
7340
|
+
- Computed each poll tick by `listUndeclared` in `packages/server/src/openspec/workflow-schema-status.ts`. Worker-safe. Reads bounded by `mapLimit` 16.
|
|
7341
|
+
- Consumed by Settings → OpenSpec Update confirmation (patch 2): count of affected changes returning to `PLANNING`. Update applies patch v2 only on explicit action; enable never regenerates.
|
|
7342
|
+
|
|
7343
|
+
### REST
|
|
7344
|
+
|
|
7345
|
+
`GET /api/openspec/dependencies?cwd=&change=` (tier `observe`) → `{dependencies, declared, declaredError, file}`.
|
|
7346
|
+
|
|
7347
|
+
`PUT /api/openspec/dependencies` (tier `control`). Body: `{cwd, change, blockedBy, notBlockedBy, related, expected}`.
|
|
7348
|
+
|
|
7349
|
+
Both `networkGuard`.
|
|
7350
|
+
|
|
7351
|
+
Gate order and codes:
|
|
7352
|
+
1. `400` `invalid-request`.
|
|
7353
|
+
2. `403` `cwd-not-tracked`.
|
|
7354
|
+
3. `403` `openspec-disabled`.
|
|
7355
|
+
4. `403` `opted-out`.
|
|
7356
|
+
5. `404` `no-openspec-dir`.
|
|
7357
|
+
6. `409` `status-all-unsupported`.
|
|
7358
|
+
7. `503` `pending`.
|
|
7359
|
+
8. `404` `unknown-change`.
|
|
7360
|
+
|
|
7361
|
+
PUT after gate:
|
|
7362
|
+
1. `writeGuard` → `403` `write-refused`.
|
|
7363
|
+
2. Shared per-cwd lock `inFlightInits` → `409` `locked`.
|
|
7364
|
+
3. `expected` precondition (mtime + size) → `409` `modified`.
|
|
7365
|
+
4. YAML serializer → temp file → `rename` (replace) or `link` (create, no replace).
|
|
7366
|
+
|
|
7367
|
+
Log event: `openspec.dependencies`.
|
|
7368
|
+
|
|
7369
|
+
MCP tools: `get_openspec_dependencies`, `openspec_dependencies`.
|
|
7370
|
+
|
|
7371
|
+
### Client
|
|
7372
|
+
|
|
7373
|
+
- `DependencyChips` + `DependenciesDialog` (edit `blocked_by` / `not_blocked_by` / `related`).
|
|
7374
|
+
- Chips visible when default schema is `pi-spec-driven` or any change `hasFile`.
|
|
7375
|
+
- Board toggle "Execution order": sorts columns by wave. Within-column reorder off. Cross-column drop appends.
|
|
7376
|
+
|
|
7377
|
+
### ship-it gate
|
|
7378
|
+
|
|
7379
|
+
`.pi/skills/ship-it/scripts/openspec-deps-gate.ts --change <name>` (step 1.5).
|
|
7380
|
+
|
|
7381
|
+
- Online: `GET` per request, 5 s timeout. 503 retried ≤ 3× at 2 s.
|
|
7382
|
+
- Offline fallback: shared parser. Cycles and inferred edges NOT checked.
|
|
7383
|
+
- Open blockers archived on `origin/develop` count satisfied.
|
|
7384
|
+
- Output JSON: `{status: ok|warn|blocked, mode, blockers[{change,state,source}], issues, notes}`.
|
|
7385
|
+
- Errors → block via `SHIP_IT_BLOCKED.md`. Open blockers → warn.
|
|
7386
|
+
|
|
7387
|
+
### Cost
|
|
7388
|
+
|
|
7389
|
+
- Debug line: `[openspec-deps] changes=N edges declared=.. inferred-text=.. inferred-capability=.. issues error=.. warning=.. ms=..`. Shown when `DEBUG` matches `openspec-poll`.
|
|
7390
|
+
- Budget: < 20 ms median for 100 changes after one input edit.
|
|
7391
|
+
- Caches: per-file (path + mtime + size); per-change keyed by gate probe mtime.
|
|
7392
|
+
- Measured (#P2, macOS 26.4, Apple M5 Pro, this repo, 85 active changes):
|
|
7393
|
+
- cold first run: 73 ms (cold fs cache) / 24 ms (warm fs cache).
|
|
7394
|
+
- warm, nothing changed: 2.0 ms.
|
|
7395
|
+
- one input touched: 2.3 ms.
|
|
7396
|
+
- Windows 11 QA VM: pending (manual-only row P2).
|
|
7397
|
+
|
|
7398
|
+
### Compat / rollback
|
|
7399
|
+
|
|
7400
|
+
- Additive. No migration.
|
|
7401
|
+
- Rollback: revert commit. Leftover `dependencies.yaml` files inert.
|
|
7402
|
+
|
|
6279
7403
|
## Electron Server Lifecycle
|
|
6280
7404
|
|
|
6281
7405
|
Paired remote dashboards open in per-server Electron windows (own origin, device cookie): see [electron-server-windows.md](./electron-server-windows.md).
|
|
@@ -6558,10 +7682,15 @@ Configuration lives in `pnpm-workspace.yaml` (NOT `package.json` `pnpm.*` — ya
|
|
|
6558
7682
|
|
|
6559
7683
|
1. `npm publish --provenance` in `publish.yml` — OIDC Trusted Publishing. Needs no npm-installed tree. `publish` job upgrades to `npm@latest` only for OIDC ≥11.5.1 floor.
|
|
6560
7684
|
2. Column C runtime `npm install` on END-USER machines: `pi-core-updater.ts`, `pi-core-checker.ts`, `recovery-server.ts`, electron `update-checker.ts`.
|
|
6561
|
-
3. `bundle-server.mjs` internal
|
|
6562
|
-
|
|
7685
|
+
3. `bundle-server.mjs` internal npm for electron bundle runtime tree:
|
|
7686
|
+
- `npm install --omit=dev` (floating mode, default).
|
|
7687
|
+
- `npm pack @blackbelt-technology/pi-dashboard-server@X` (`fetchPublishedLock`, release-lock mode).
|
|
7688
|
+
- `npm ci --omit=dev --allow-remote=all` on rebased `package-lock.json` (release-lock mode).
|
|
7689
|
+
4. Runtime-lock generation: `scripts/generate-runtime-lock.mjs` (publish + nightly). Rebase check: `scripts/lint-runtime-lock.mjs --version X`.
|
|
7690
|
+
5. `deploy-site.yml` `site/` job (separate `site/package-lock.json`; `site/` NOT a pnpm workspace member).
|
|
6563
7691
|
|
|
6564
7692
|
See change: adopt-pnpm-for-dev-ci.
|
|
7693
|
+
See change: pin-electron-bundle-dependency-tree.
|
|
6565
7694
|
|
|
6566
7695
|
## Doctor Diagnostics
|
|
6567
7696
|
|
|
@@ -7270,7 +8399,7 @@ Residuals:
|
|
|
7270
8399
|
- NAT / published-port callers (docker): `binding-mismatch`. BREAKING for `pi-dashboard login --local|open|token create` through a published port. Run inside container or log in.
|
|
7271
8400
|
|
|
7272
8401
|
Deploy + rollback:
|
|
7273
|
-
- Order: restart server FIRST (`
|
|
8402
|
+
- Order: restart server FIRST (`pi-dashboard api POST /api/restart`; dev checkout: `npx tsx .pi/skills/implement/scripts/restart-server.ts`), THEN `npm run reload`.
|
|
7274
8403
|
- Reverse order: proof-only bridges hit pre-proof server → refused / quarantined.
|
|
7275
8404
|
- Rollback: revert server. Marked sessions quarantine (`server-proof-missing`) → restart those sessions.
|
|
7276
8405
|
|
|
@@ -7691,3 +8820,180 @@ flowchart LR
|
|
|
7691
8820
|
- Revert change. Delete `~/.pi/dashboard/role-bindings.json` (optional).
|
|
7692
8821
|
- Targets keep last concrete value.
|
|
7693
8822
|
- Grammar `llm.role` configs fall back to "pick a model".
|
|
8823
|
+
|
|
8824
|
+
## Client sink hardening (Trusted Types, URL policy, navigation intents)
|
|
8825
|
+
|
|
8826
|
+
### Trusted Types mode
|
|
8827
|
+
- Env `PI_DASHBOARD_TRUSTED_TYPES=off|report|enforce`.
|
|
8828
|
+
- Unset → `off` iff `PI_DASHBOARD_CSP=off`, else `report`. Independent of `PI_DASHBOARD_CSP`.
|
|
8829
|
+
- Resolver: `packages/server/src/auth/csp.ts` `resolveTrustedTypesMode`.
|
|
8830
|
+
- `registerCsp` appends `require-trusted-types-for 'script'` to baseline header when modes match. Else sets other header kind with directive alone.
|
|
8831
|
+
- Add-if-absent per header kind. `/live/` skipped. `serveApp` mounts keep own enforcing policy.
|
|
8832
|
+
- Server injects `<meta name="pi-trusted-types" content="<mode>">` into index.html (`lib/index-html.ts`).
|
|
8833
|
+
- Dev: `trustedTypesDevPlugin` in `packages/client/vite.config.ts` injects same meta.
|
|
8834
|
+
- Missing meta → client treats as `report`.
|
|
8835
|
+
|
|
8836
|
+
### Client policies
|
|
8837
|
+
- File: `packages/client/src/lib/security/trusted-types.ts`. Registered before first render (`lib/boot/client-boot.ts` `bootClient`).
|
|
8838
|
+
- `pi-sanitized-html`: profiles from `packages/shared/src/sanitize-profiles.ts` (same configs as server sanitizers).
|
|
8839
|
+
- No mermaid parse policy. MermaidBlock colorize runs on sanitized DOM: DOMPurify `RETURN_DOM` (mermaid profile) → tint → XML serialize. No string parse of unsanitized output. Final `sanitizeMermaidSvg` + `pi-sanitized-html` still run before injection.
|
|
8840
|
+
- `pi-worker-url`: `/sw.js`, `/assets/<file>.m?js`.
|
|
8841
|
+
- `default`: mode-aware.
|
|
8842
|
+
- report: pass-through + count.
|
|
8843
|
+
- enforce: sanitize, `createScript` → null, script-URL allowlist.
|
|
8844
|
+
- Team app: `pi-static-svg` in `packages/team-app/src/ui/trusted-static-svg.ts`.
|
|
8845
|
+
|
|
8846
|
+
### Violation channel
|
|
8847
|
+
- Client batches `securitypolicyviolation` events + default hits every 30 s and on `pagehide`.
|
|
8848
|
+
- Dedupe key: directive/sink/source. Cap ≤ 50 keys + `overflow`. No samples. Source without query/fragment.
|
|
8849
|
+
- `POST /api/csp-violations`: network guard, 8 KiB cap, per-principal burst 3 / 12 per min → 429, counters only, LRU 500.
|
|
8850
|
+
- `GET /api/csp-violations` (operate tier): returns counters.
|
|
8851
|
+
- Unrelated to live-preview `/__pi/csp-report`.
|
|
8852
|
+
- Shadow aggregate: `shadow: {<outcome>: n}` per report. Outside 50-key cap and `overflow`. Report mode only.
|
|
8853
|
+
- Shadow totals clamp 1,000,000 per report. Remainder carried to next report.
|
|
8854
|
+
- Totals-only report sent when shadow totals non-empty.
|
|
8855
|
+
- Totals subtracted on 2xx. Kept on failure except 400: discarded + 1 `shadow-error` added.
|
|
8856
|
+
- Body priority: violations → default hits → per-source `trusted-types-shadow` detail.
|
|
8857
|
+
- Body ≤ 7,168 B. Every `source` cut to 512 UTF-16 units.
|
|
8858
|
+
- `pagehide` keepalive send not retried. Residual: last ≤ 30 s lost.
|
|
8859
|
+
- Server `parseReport`: `shadow` non-object or bad known count → 400. Unknown keys ignored.
|
|
8860
|
+
- Server after schema + limiter: `recordShadow` → persisted `ttShadow`. Never `record()`.
|
|
8861
|
+
- Shadow detail: own in-memory LRU 500. Never evicts violation keys.
|
|
8862
|
+
- See change: add-trusted-types-shadow-enforce.
|
|
8863
|
+
|
|
8864
|
+
### URL policy
|
|
8865
|
+
- `packages/shared/src/url-policy.ts` `classifyUrl(raw, origin|null)` → `internal|loopback|external|mailto|blocked`.
|
|
8866
|
+
- Chokepoints in `packages/dashboard-plugin-runtime/src/safe-navigation.tsx` (plugin SDK, host API 1.2.0): `SafeLink`, `openExternalUrl`, `assignLocation`, `useSafeNavigation`.
|
|
8867
|
+
- Re-used by `packages/client/src/lib/nav/safe-navigation.tsx`.
|
|
8868
|
+
- Electron `isAllowedExternalUrl` delegates to `classifyUrl`.
|
|
8869
|
+
- CI guard: `scripts/check-client-sinks.mjs` (ci.yml step + ship-it 4.4). Rejects raw nav / html / script sinks.
|
|
8870
|
+
- Exemption: `// client-sinks: allow — <reason>`.
|
|
8871
|
+
|
|
8872
|
+
### Navigation intents
|
|
8873
|
+
- `POST /api/nav-intent` mints `ni = b64url(e).b64url(HMAC-SHA256(key, principal\0kind\0target\0e))`. TTL 600 s. Per-process key (restart invalidates).
|
|
8874
|
+
- `POST /api/nav-intent/verify` → `{ok}`. Constant-time compare.
|
|
8875
|
+
- Route-backed overlays (`/folder/:cwd/view?path=`, `/pi-view?url=`):
|
|
8876
|
+
- verified `ni` → operator provenance (≤ 2 s pending, then agent on failure).
|
|
8877
|
+
- no `ni` → agent provenance (restricted egress).
|
|
8878
|
+
- Minted only from operator Expand on operator-provenance `PreviewCard`. Modifier / middle clicks and agent cards never mint.
|
|
8879
|
+
- `returnTo` / `returnUrl` not intent-gated.
|
|
8880
|
+
|
|
8881
|
+
### OIDC discovery
|
|
8882
|
+
- `packages/client-utils/src/identity/login-flow.ts` rejects non-`https:` discovery endpoints (loopback `http:` allowed).
|
|
8883
|
+
- Throws `LoginFlowError("discovery-failed")` before any navigation or token request.
|
|
8884
|
+
|
|
8885
|
+
### Electron bundled pages
|
|
8886
|
+
- `src/renderer/{doctor,remote-connect,connecting}.html`, `resources/loading.html`.
|
|
8887
|
+
- Meta CSP `require-trusted-types-for 'script'` from day one. Not governed by env knob.
|
|
8888
|
+
|
|
8889
|
+
See change: harden-client-sinks.
|
|
8890
|
+
|
|
8891
|
+
## Baseline CSP: strict policy + report sink (S3b)
|
|
8892
|
+
|
|
8893
|
+
Two policies, one sink, persisted counter. Default mode stays `report`; nothing breaks by default. Code: `packages/server/src/auth/{csp,csp-report-paths,csp-report-sink,csp-report-store}.ts`.
|
|
8894
|
+
|
|
8895
|
+
### Modes (`PI_DASHBOARD_CSP`)
|
|
8896
|
+
|
|
8897
|
+
| Mode | Headers |
|
|
8898
|
+
|---|---|
|
|
8899
|
+
| `report` (default) | `baseline` Report-Only → `/__pi/csp-report/baseline` AND `strict` Report-Only → `/__pi/csp-report/strict` |
|
|
8900
|
+
| `enforce` (explicit opt-in) | `strict` ENFORCED → `/__pi/csp-report/strict`. `baseline` NOT emitted. |
|
|
8901
|
+
| `off` | no baseline or strict header |
|
|
8902
|
+
| any, Vite `--dev` (per proxied response) | baseline only (legacy `script-src`), enforcing under `enforce`. No strict header. No report destination. Dev never feeds strict counter. |
|
|
8903
|
+
|
|
8904
|
+
- Strict = baseline with `script-src 'self' 'nonce-<n>'`. No `'unsafe-inline'`, no `'unsafe-eval'`. Enforced only under explicit `enforce`.
|
|
8905
|
+
- Every emitted policy carries `report-uri /__pi/csp-report/<label>` + `report-to csp-<label>`; `Reporting-Endpoints` header declares them.
|
|
8906
|
+
- Route-level per-response policies (`/api/file/raw` sandbox, `ctx.serveApp` mounts, `/live/`) untouched by mode.
|
|
8907
|
+
- Release note: explicit `enforce` now enforces the STRICT policy (before: baseline). Existing `enforce` deployments see it.
|
|
8908
|
+
|
|
8909
|
+
### Trusted Types interaction
|
|
8910
|
+
|
|
8911
|
+
- TT follows `PI_DASHBOARD_TRUSTED_TYPES`, independent of CSP mode (see § Client sink hardening).
|
|
8912
|
+
- Matching modes append `require-trusted-types-for 'script'`: `report` → baseline Report-Only header; `enforce` → strict enforcing header. Reports go to that header's label.
|
|
8913
|
+
- Differing modes → other header kind carries TT directive alone, labelled `trusted-types` → `/__pi/csp-report/trusted-types`.
|
|
8914
|
+
- TT violations count in `require-trusted-types-for` bucket. Never in strict `script-src*` measure.
|
|
8915
|
+
- Client counters `/api/csp-violations` (in-memory, harden-client-sinks) untouched. Distinct namespace.
|
|
8916
|
+
|
|
8917
|
+
#### Shadow enforce (report mode)
|
|
8918
|
+
|
|
8919
|
+
- Runs only in `default` policy, `report` mode (`packages/client/src/lib/security/trusted-types.ts`). `off` / `enforce`: no shadow work.
|
|
8920
|
+
- Returns input unchanged. Output and `defaultHit` counts unchanged. Never throws into sink.
|
|
8921
|
+
- Outcomes (`SHADOW_OUTCOMES`): `would-block-script`, `would-block-script-url`, `would-alter-html`, `would-throw-html`, `not-evaluated`, `shadow-error`.
|
|
8922
|
+
- `would-block-script`: every report-mode `createScript` call.
|
|
8923
|
+
- `would-block-script-url`: `createScriptURL` failing `isAllowedScriptUrl`.
|
|
8924
|
+
- `inShadow` flag: nested `default` call returns input, counts nothing.
|
|
8925
|
+
- HTML tag-free input (no `<`): no outcome, no work.
|
|
8926
|
+
- HTML uses separate `DOMPurify(window)` instance. Shared instance untouched.
|
|
8927
|
+
- Parse policy `pi-shadow-parse`: module-private, never exported, never a document sink.
|
|
8928
|
+
- Shared `enforceProfileFor(s)` picks profile for both enforce and classifier.
|
|
8929
|
+
- Pass 1: enforce profile. `removed > 0` → `would-alter-html`.
|
|
8930
|
+
- Pass 2: only if pass 1 clean and input leads with `style|link|meta|title|base|script|noscript|template`. `FORCE_BODY`. Output differs → `would-alter-html`.
|
|
8931
|
+
- Throw in `assertPurify` or pass 1 → `would-throw-html`. Other throw → `shadow-error`.
|
|
8932
|
+
- Memo: exact-string LRU. 512 entries / 4 Mi UTF-16 units.
|
|
8933
|
+
- Budget per 30 s window: 200 classifications / 2 Mi UTF-16 units / 50 ms (`performance.now()`).
|
|
8934
|
+
- Over budget: `not-evaluated` once per distinct input per window. Not memoized.
|
|
8935
|
+
- Perf gate: report-mode variant of `tests/e2e/trusted-types-perf.spec.ts`. Median of 5 runs ≤ 20 ms.
|
|
8936
|
+
|
|
8937
|
+
#### Shadow persistence, health and flip gate
|
|
8938
|
+
|
|
8939
|
+
- Store: `ttShadow: {since, counts: {<outcome>: {count, firstSeen, lastSeen}}}` in `csp-reports.json`. `version` stays `1`.
|
|
8940
|
+
- `ttShadow.since` renewed on: fresh store; missing block (older-server rewrite after rollback); malformed block (1 warning, core kept, no `.corrupt`).
|
|
8941
|
+
- `POST /api/csp-reports/reset`: zeroes `ttShadow`, sets its `since` to core `since`.
|
|
8942
|
+
- In-memory per-source shadow rows not cleared by reset. Split view until restart.
|
|
8943
|
+
- Crash loses ≤ 5 s of shadow counts.
|
|
8944
|
+
- Health: `cspReports.ttShadow` = `{since, <6 outcome counts>}`. Flat. Zeros included. No per-key timestamps. Absent = server predates change.
|
|
8945
|
+
- Flip gate (`enforce-trusted-types-default`): evidence valid only from `ttShadow.since`.
|
|
8946
|
+
- Flip gate: `not-evaluated` and `shadow-error` = 0.
|
|
8947
|
+
- Flip gate: `would-alter-html` = 0 necessary, not sufficient. Visual spec under enforce stays a gate.
|
|
8948
|
+
- See change: add-trusted-types-shadow-enforce.
|
|
8949
|
+
|
|
8950
|
+
### Nonce lifecycle
|
|
8951
|
+
|
|
8952
|
+
- `cspNonceFor(reply)`: 16 random bytes base64, minted per HTML response, memoized per reply. `onSend` hook reads it.
|
|
8953
|
+
- Import map `<script type="importmap">` gets same nonce (`injectImportMap`, `sendIndexWithImportMap` in `server.ts`).
|
|
8954
|
+
- Non-HTML responses: strict header without nonce.
|
|
8955
|
+
- Passkey pages (`auth/passkey/passkey-pages.ts`): no inline script. Static same-origin assets `/auth/passkey/*.js|css`. Per-request data in non-executable `<script type="application/json" id="pk-data">` island. No nonce needed.
|
|
8956
|
+
- Plugin bundles load via same-origin `import()` → covered by `'self'`. `blob:` / `data:` stay forbidden.
|
|
8957
|
+
- pdf.js: client sets `isEvalSupported:false` → no `new Function` probe report.
|
|
8958
|
+
|
|
8959
|
+
### Report sink
|
|
8960
|
+
|
|
8961
|
+
`POST /__pi/csp-report/:policy`, `:policy` ∈ `baseline|strict|trusted-types`.
|
|
8962
|
+
|
|
8963
|
+
- Mounted at root, OUTSIDE guard jurisdiction (`/api`, `/v1`, `/editor`, `/live`). Mutation-origin gate does not apply.
|
|
8964
|
+
- Public to OAuth gate (`auth-plugin.ts` skip beside `/api/health`). Signed-out pages (login, passkey) can report.
|
|
8965
|
+
- Host admission gate still applies.
|
|
8966
|
+
- Live sink `/live/<id>/__pi/csp-report` separate, unchanged.
|
|
8967
|
+
- Refusal precedence: 404 (bad label) → 405 (`Allow: POST`) → 429 → 415 → 413 / 408 / 400.
|
|
8968
|
+
- Content-Type `application/csp-report` | `application/reports+json`, else 415.
|
|
8969
|
+
- Own byte-counting body read. Cap 8 KiB, chunked included → 413. Independent of `content-length`, `bodyLimit`, parser order.
|
|
8970
|
+
- Body read deadline 5 s → 408.
|
|
8971
|
+
- Empty / malformed / non-report / content-encoded body → 400, uncounted.
|
|
8972
|
+
- Limiter: per socket peer, token bucket capacity 20, refill 1 token/s. Every request consumes one token (Reporting API batch too). Loopback NOT exempt (global `@fastify/rate-limit` allow-lists loopback → would exempt all tunnel traffic). Excess → 429.
|
|
8973
|
+
- Accepted → 204, empty body. No response reflects input. Raw reports never logged or stored.
|
|
8974
|
+
- Log: throttled `[csp] violation policy=<label> directive=<x>`.
|
|
8975
|
+
- Limiter / size cap / deadline refusals bump persisted `dropped`.
|
|
8976
|
+
- Tunnel users share peer `127.0.0.1` → flood can push real reports into `dropped`. Sink = signal, not access control.
|
|
8977
|
+
|
|
8978
|
+
### Counter store
|
|
8979
|
+
|
|
8980
|
+
- File `~/.pi/dashboard/csp-reports.json`, mode 0600, tmp-file + rename.
|
|
8981
|
+
- Debounced write 5 s (`FLUSH_DEBOUNCE_MS`). Flush on server close. Write failure never throws.
|
|
8982
|
+
- Key `policy × effective-directive`. Fixed directive allow-set, else `other`.
|
|
8983
|
+
- Bounded document-path breakdown (path only, top 20 per policy, rest `other`). Persisted, never in health.
|
|
8984
|
+
- Fields: counts, `dropped`, `since`, `firstSeen`/`lastSeen`.
|
|
8985
|
+
- Corrupt at boot → moved to `csp-reports.json.corrupt`, counting restarts at zero, new `since`.
|
|
8986
|
+
- Reset: `POST /api/csp-reports/reset` (operate tier, `packages/shared/src/route-tiers.ts`) or delete file while server stopped. Both set new `since`, zero `dropped`.
|
|
8987
|
+
- Health: `GET /api/health` carries `cspReports` `{since, dropped, counts}` ONLY when `canDiscloseAccessPosture(request)` passes (same predicate as `accessGrants`). Else block omitted. Health never refuses.
|
|
8988
|
+
- Predicate ignores `requireLocalProof`: bare loopback caller sees block. Accepted — counts only.
|
|
8989
|
+
- Counter inflation fails safe: forged reports can only delay flip, never hide real violation.
|
|
8990
|
+
|
|
8991
|
+
### Rollout / rollback
|
|
8992
|
+
|
|
8993
|
+
- Default `report`. Release adds sink + dual Report-Only. No page breaks.
|
|
8994
|
+
- `enforce` = strict, opt-in.
|
|
8995
|
+
- Rollback: `PI_DASHBOARD_CSP=report` or `off` + server restart.
|
|
8996
|
+
- Follow-up `enforce-strict-csp-default` owns soak + default flip. Exit gate: ≥ 14 d window, zero strict `script-src*` violations, `dropped == 0`, ≥ 1 release shipped, enforce-lane E2E green. Inspect directive / document breakdown before flip.
|
|
8997
|
+
- E2E lanes: see `docs/faq.md` § "CSP enforce + OAuth real-gate E2E lanes".
|
|
8998
|
+
|
|
8999
|
+
See change: harden-cors-and-csp-reporting (D8, D9, D10).
|