@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
|
@@ -12,9 +12,14 @@
|
|
|
12
12
|
* See change: improve-content-editor (live-server-preview §6).
|
|
13
13
|
*/
|
|
14
14
|
import net from "node:net";
|
|
15
|
-
import type {
|
|
16
|
-
import {
|
|
15
|
+
import type { LiveServerTarget, StaticTarget } from "@blackbelt-technology/pi-dashboard-shared/live-server.js";
|
|
16
|
+
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
|
|
17
|
+
import { isBrowserOriginated } from "./live-browser-gate.js";
|
|
18
|
+
import { type LiveCapabilityGrant, stripCapabilitySegment } from "./live-capability.js";
|
|
19
|
+
import { buildLiveCsp, type LiveCspResult } from "./live-csp.js";
|
|
20
|
+
import { registerCspReportParsers } from "./live-csp-report.js";
|
|
17
21
|
import type { LiveServerManager } from "./live-server-manager.js";
|
|
22
|
+
import { serveStatic } from "./live-static.js";
|
|
18
23
|
|
|
19
24
|
/** Dashboard cookie namespace (`pi_dash_token`, `pi_dash_device`, `pi_dash_local`, …). */
|
|
20
25
|
const DASHBOARD_COOKIE_PREFIX = "pi_dash_";
|
|
@@ -43,6 +48,10 @@ function filterSetCookie(value: string | string[] | undefined): string[] | undef
|
|
|
43
48
|
/** A request/upgrade header bag the credential stripper edits in place. */
|
|
44
49
|
type HeaderBag = Record<string, unknown>;
|
|
45
50
|
|
|
51
|
+
/** The request shape the channel classifier reads (`socket.encrypted` + headers). */
|
|
52
|
+
type ProxyRequestLike = Pick<import("node:http").IncomingMessage, "socket" | "headers">;
|
|
53
|
+
type DeviceBearerCheck = (token: string, req: ProxyRequestLike | undefined) => boolean;
|
|
54
|
+
|
|
46
55
|
/**
|
|
47
56
|
* Strip dashboard credentials from headers bound for the preview upstream:
|
|
48
57
|
* every `pi_dash_*` cookie, and an `Authorization` header that verifies as a
|
|
@@ -50,7 +59,9 @@ type HeaderBag = Record<string, unknown>;
|
|
|
50
59
|
*/
|
|
51
60
|
function stripDashboardCredentials(
|
|
52
61
|
headers: HeaderBag,
|
|
53
|
-
isDeviceBearer:
|
|
62
|
+
isDeviceBearer: DeviceBearerCheck,
|
|
63
|
+
req: ProxyRequestLike | undefined,
|
|
64
|
+
isKnownBearer: (token: string) => boolean,
|
|
54
65
|
): HeaderBag {
|
|
55
66
|
const cookie = headers.cookie;
|
|
56
67
|
if (typeof cookie === "string") {
|
|
@@ -62,7 +73,10 @@ function stripDashboardCredentials(
|
|
|
62
73
|
if (typeof authz === "string") {
|
|
63
74
|
const m = /^Bearer\s+(.+)$/i.exec(authz.trim());
|
|
64
75
|
// Device bearers and the host's own operator (`pi_op_`) bearer are dashboard credentials.
|
|
65
|
-
|
|
76
|
+
// `isDeviceBearer` judges (and records the channel of) the request; `isKnownBearer` then strips EVERY
|
|
77
|
+
// registry-known bearer, so a refused `pi_tls_` bearer is never forwarded off-hub.
|
|
78
|
+
// See change: prove-vault-bridge-tls (D4).
|
|
79
|
+
if (m && (isDeviceBearer(m[1], req) || isKnownBearer(m[1]) || m[1].startsWith("pi_op_"))) delete headers.authorization;
|
|
66
80
|
}
|
|
67
81
|
return headers;
|
|
68
82
|
}
|
|
@@ -104,8 +118,60 @@ function staysInside(path: string, prefix: string): boolean {
|
|
|
104
118
|
}
|
|
105
119
|
|
|
106
120
|
export interface LiveProxyDeps {
|
|
107
|
-
/**
|
|
108
|
-
|
|
121
|
+
/**
|
|
122
|
+
* Does this token verify as a dashboard device bearer on THIS request's channel? Absent ⇒ never
|
|
123
|
+
* strip `Authorization`. Receives the request so the registry can record a non-proven channel.
|
|
124
|
+
*/
|
|
125
|
+
isDeviceBearer?: DeviceBearerCheck;
|
|
126
|
+
/** Is this token ANY bearer the registry knows (valid, expired or refused)? Always stripped. */
|
|
127
|
+
isKnownBearer?: (token: string) => boolean;
|
|
128
|
+
/**
|
|
129
|
+
* The raw file-read gate for a static target's real path, re-run on EVERY static
|
|
130
|
+
* request. Absent ⇒ static targets serve nothing (fail closed).
|
|
131
|
+
*/
|
|
132
|
+
staticGate?: (cwd: string, absPath: string) => Promise<boolean>;
|
|
133
|
+
/**
|
|
134
|
+
* Granted egress origins `<G>` for a token's CSP: project grants ∪ the viewer's
|
|
135
|
+
* allow-once set. Absent ⇒ none.
|
|
136
|
+
*/
|
|
137
|
+
grantedOrigins?: (grant: LiveCapabilityGrant) => readonly string[];
|
|
138
|
+
/** An HTML document of a static target was served under this token (feeds the lazy origin scan). */
|
|
139
|
+
onStaticHtmlServed?: (grant: LiveCapabilityGrant, realPath: string) => void;
|
|
140
|
+
/**
|
|
141
|
+
* Handler for the reserved `/__pi/…` namespace under a valid capability prefix
|
|
142
|
+
* (CSP reports, …). It is never forwarded upstream and never served from disk;
|
|
143
|
+
* absent ⇒ 404. Return the reply you sent.
|
|
144
|
+
*/
|
|
145
|
+
reservedHandler?: (
|
|
146
|
+
request: FastifyRequest,
|
|
147
|
+
reply: FastifyReply,
|
|
148
|
+
ctx: { grant: LiveCapabilityGrant; subPath: string },
|
|
149
|
+
) => Promise<FastifyReply> | FastifyReply;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
/** `/__pi` as a whole path segment (the reserved namespace under a capability prefix). */
|
|
153
|
+
const isReservedPath = (subPath: string): boolean => {
|
|
154
|
+
const q = subPath.search(/[?#]/);
|
|
155
|
+
const p = q >= 0 ? subPath.slice(0, q) : subPath;
|
|
156
|
+
return p === "/__pi" || p.startsWith("/__pi/");
|
|
157
|
+
};
|
|
158
|
+
|
|
159
|
+
/** The scheme the dashboard is reached on, as far as this hop can tell. `http` is the safe default (`http://` matches https too). */
|
|
160
|
+
const schemeOf = (request: FastifyRequest): "http" | "https" => (request.protocol === "https" ? "https" : "http");
|
|
161
|
+
|
|
162
|
+
/**
|
|
163
|
+
* APPEND our CSP (and `Reporting-Endpoints` entry) to the upstream's response headers —
|
|
164
|
+
* never replacing or stripping the upstream's: browsers enforce every header, so the
|
|
165
|
+
* result is the stricter intersection.
|
|
166
|
+
*/
|
|
167
|
+
function appendCsp(headers: Record<string, unknown>, csp: LiveCspResult): void {
|
|
168
|
+
const upstreamCsp = headers["content-security-policy"];
|
|
169
|
+
const existing = upstreamCsp === undefined ? [] : Array.isArray(upstreamCsp) ? upstreamCsp : [upstreamCsp];
|
|
170
|
+
headers["content-security-policy"] = [...existing, csp.csp];
|
|
171
|
+
if (!csp.reportingEndpoints) return;
|
|
172
|
+
const re = headers["reporting-endpoints"];
|
|
173
|
+
headers["reporting-endpoints"] =
|
|
174
|
+
typeof re === "string" && re.length > 0 ? `${re}, ${csp.reportingEndpoints}` : csp.reportingEndpoints;
|
|
109
175
|
}
|
|
110
176
|
|
|
111
177
|
/** localhost/::1 resolve to 127.0.0.1 for the upstream TCP connect. */
|
|
@@ -119,6 +185,7 @@ export function registerLiveServerProxy(
|
|
|
119
185
|
deps: LiveProxyDeps = {},
|
|
120
186
|
) {
|
|
121
187
|
const isDeviceBearer = deps.isDeviceBearer ?? (() => false);
|
|
188
|
+
const isKnownBearer = deps.isKnownBearer ?? (() => false);
|
|
122
189
|
// Register the `@fastify/reply-from` proxy plugin. live-server-proxy is now
|
|
123
190
|
// the SOLE consumer of the `from` decorator — the editor proxy that used to
|
|
124
191
|
// provide it was deleted in change: remove-external-editor-integration, which
|
|
@@ -126,6 +193,8 @@ export function registerLiveServerProxy(
|
|
|
126
193
|
// `/live/:id/*`. Owning the dependency here keeps the proxy self-contained.
|
|
127
194
|
// See change: improve-content-editor, fix-live-server-proxy-reply-from.
|
|
128
195
|
fastify.register(import("@fastify/reply-from"));
|
|
196
|
+
// CSP reports arrive as `application/csp-report` / `application/reports+json`.
|
|
197
|
+
if (deps.reservedHandler) registerCspReportParsers(fastify);
|
|
129
198
|
|
|
130
199
|
/**
|
|
131
200
|
* `capabilityPrefix` is set (by the capability hook, only after the token
|
|
@@ -135,21 +204,62 @@ export function registerLiveServerProxy(
|
|
|
135
204
|
function resolve(url: string, capabilityPrefix?: string) {
|
|
136
205
|
const match = url.match(/^\/live\/([^/?]+)(.*)$/);
|
|
137
206
|
if (!match) return null;
|
|
138
|
-
const target = manager.get(match[1]);
|
|
139
|
-
if (!target) return null;
|
|
140
207
|
let rest = match[2] || "";
|
|
141
208
|
if (capabilityPrefix && url.startsWith(capabilityPrefix)) rest = url.slice(capabilityPrefix.length);
|
|
142
209
|
const subPath = rest.startsWith("?") ? `/${rest}` : rest.startsWith("/") ? rest : "/";
|
|
143
|
-
return {
|
|
210
|
+
return { id: match[1], subPath };
|
|
144
211
|
}
|
|
145
212
|
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
const
|
|
149
|
-
if (
|
|
150
|
-
|
|
213
|
+
/** CSP for a capability response, or `null` (fail closed) when no safe header can be built. */
|
|
214
|
+
function cspFor(request: FastifyRequest, grant: LiveCapabilityGrant, prefix: string): LiveCspResult | null {
|
|
215
|
+
const host = request.headers.host;
|
|
216
|
+
if (typeof host !== "string") return null;
|
|
217
|
+
let granted: readonly string[] = [];
|
|
218
|
+
try {
|
|
219
|
+
granted = deps.grantedOrigins?.(grant) ?? [];
|
|
220
|
+
} catch {
|
|
221
|
+
granted = []; // a failing grant lookup must not widen the policy
|
|
151
222
|
}
|
|
152
|
-
|
|
223
|
+
return buildLiveCsp({ policy: grant.policy, host, scheme: schemeOf(request), prefix, granted });
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
const notFoundReply = (reply: FastifyReply) => reply.code(404).send({ error: "live-server target not found" });
|
|
227
|
+
|
|
228
|
+
/** A static target, reachable ONLY through a valid capability, by any caller. */
|
|
229
|
+
const forwardStatic = (
|
|
230
|
+
request: FastifyRequest,
|
|
231
|
+
reply: FastifyReply,
|
|
232
|
+
target: StaticTarget,
|
|
233
|
+
subPath: string,
|
|
234
|
+
grant: LiveCapabilityGrant | undefined,
|
|
235
|
+
capabilityPrefix: string | undefined,
|
|
236
|
+
) => {
|
|
237
|
+
if (!grant || !capabilityPrefix) return notFoundReply(reply);
|
|
238
|
+
if (isReservedPath(subPath)) return reservedOr404(request, reply, grant, subPath);
|
|
239
|
+
const csp = cspFor(request, grant, capabilityPrefix);
|
|
240
|
+
if (!csp) return notFoundReply(reply);
|
|
241
|
+
manager.use(target.id);
|
|
242
|
+
const extra: Record<string, string> = { "content-security-policy": csp.csp };
|
|
243
|
+
if (csp.reportingEndpoints) extra["reporting-endpoints"] = csp.reportingEndpoints;
|
|
244
|
+
return serveStatic(request, reply, target, subPath, extra, {
|
|
245
|
+
gate: deps.staticGate ?? (async () => false),
|
|
246
|
+
onHtmlServed: (real) => deps.onStaticHtmlServed?.(grant, real),
|
|
247
|
+
});
|
|
248
|
+
};
|
|
249
|
+
|
|
250
|
+
const forwardPort = (
|
|
251
|
+
request: FastifyRequest,
|
|
252
|
+
reply: FastifyReply,
|
|
253
|
+
target: LiveServerTarget,
|
|
254
|
+
subPath: string,
|
|
255
|
+
grant: LiveCapabilityGrant | undefined,
|
|
256
|
+
capabilityPrefix: string | undefined,
|
|
257
|
+
) => {
|
|
258
|
+
if (grant && isReservedPath(subPath)) return reservedOr404(request, reply, grant, subPath);
|
|
259
|
+
const csp = grant && capabilityPrefix ? cspFor(request, grant, capabilityPrefix) : null;
|
|
260
|
+
// A capability response without a buildable CSP would be less isolated than promised.
|
|
261
|
+
if (grant && !csp) return notFoundReply(reply);
|
|
262
|
+
manager.use(target.id);
|
|
153
263
|
// Redirects stay inside the capability prefix when the request used one.
|
|
154
264
|
const prefix = capabilityPrefix ?? `/live/${target.id}`;
|
|
155
265
|
const host = upstreamHost(target.host);
|
|
@@ -158,7 +268,10 @@ export function registerLiveServerProxy(
|
|
|
158
268
|
headers.host = `${host}:${target.port}`;
|
|
159
269
|
// Dashboard credentials never reach the previewed app; its own cookies
|
|
160
270
|
// and bearer pass through. See change: retire-trusted-networks-bypass (D5).
|
|
161
|
-
stripDashboardCredentials(headers as HeaderBag, isDeviceBearer);
|
|
271
|
+
stripDashboardCredentials(headers as HeaderBag, isDeviceBearer, request.raw, isKnownBearer);
|
|
272
|
+
// The hop to the loopback upstream is a PROXIED hop: mark it so nothing the
|
|
273
|
+
// upstream does with this request can pass for "genuinely local".
|
|
274
|
+
headers["x-forwarded-for"] = [headers["x-forwarded-for"], request.ip].filter(Boolean).join(", ");
|
|
162
275
|
// A forwarded Referer must not carry the capability token upstream.
|
|
163
276
|
if (typeof headers.referer === "string") headers.referer = stripCapabilitySegment(headers.referer);
|
|
164
277
|
return headers;
|
|
@@ -173,6 +286,7 @@ export function registerLiveServerProxy(
|
|
|
173
286
|
if (capabilityPrefix && headers["referrer-policy"] === undefined) {
|
|
174
287
|
headers["referrer-policy"] = "no-referrer";
|
|
175
288
|
}
|
|
289
|
+
if (csp) appendCsp(headers, csp);
|
|
176
290
|
const location = headers.location;
|
|
177
291
|
if (typeof location === "string") {
|
|
178
292
|
headers.location = rewriteLocation(location, prefix, host, target.port);
|
|
@@ -182,6 +296,26 @@ export function registerLiveServerProxy(
|
|
|
182
296
|
});
|
|
183
297
|
};
|
|
184
298
|
|
|
299
|
+
const forward = (request: FastifyRequest, reply: FastifyReply) => {
|
|
300
|
+
const capabilityPrefix = (request as { liveCapabilityPrefix?: string }).liveCapabilityPrefix;
|
|
301
|
+
const grant = (request as { liveCapability?: LiveCapabilityGrant }).liveCapability;
|
|
302
|
+
// A browser-originated request (opaque `Origin: null` / `Sec-Fetch-*`) needs a capability.
|
|
303
|
+
if (!grant && isBrowserOriginated(request.headers as Record<string, unknown>)) return notFoundReply(reply);
|
|
304
|
+
const resolved = resolve(request.url, capabilityPrefix);
|
|
305
|
+
if (!resolved) return notFoundReply(reply);
|
|
306
|
+
const { id, subPath } = resolved;
|
|
307
|
+
const staticTarget = manager.getStatic(id);
|
|
308
|
+
if (staticTarget) return forwardStatic(request, reply, staticTarget, subPath, grant, capabilityPrefix);
|
|
309
|
+
const target = manager.get(id);
|
|
310
|
+
if (!target) return notFoundReply(reply);
|
|
311
|
+
return forwardPort(request, reply, target, subPath, grant, capabilityPrefix);
|
|
312
|
+
};
|
|
313
|
+
|
|
314
|
+
const reservedOr404 = (request: FastifyRequest, reply: FastifyReply, grant: LiveCapabilityGrant, subPath: string) =>
|
|
315
|
+
deps.reservedHandler
|
|
316
|
+
? deps.reservedHandler(request, reply, { grant, subPath })
|
|
317
|
+
: notFoundReply(reply);
|
|
318
|
+
|
|
185
319
|
fastify.all("/live/:id/*", forward);
|
|
186
320
|
fastify.all("/live/:id", forward);
|
|
187
321
|
}
|
|
@@ -232,17 +366,24 @@ export function handleLiveServerUpgrade(
|
|
|
232
366
|
socket.destroy();
|
|
233
367
|
return;
|
|
234
368
|
}
|
|
369
|
+
// A browser-originated upgrade (opaque `Origin: null` / `Sec-Fetch-*`) needs a capability.
|
|
370
|
+
if (!deps.capabilityPrefix && isBrowserOriginated(request.headers as Record<string, unknown>)) {
|
|
371
|
+
socket.destroy();
|
|
372
|
+
return;
|
|
373
|
+
}
|
|
235
374
|
const target = manager.get(match[1]);
|
|
236
375
|
if (!target) {
|
|
237
376
|
socket.destroy();
|
|
238
377
|
return;
|
|
239
378
|
}
|
|
379
|
+
manager.use(target.id);
|
|
240
380
|
const capabilityPrefix = deps.capabilityPrefix;
|
|
241
381
|
let rest = match[2] || "";
|
|
242
382
|
if (capabilityPrefix && request.url?.startsWith(capabilityPrefix)) rest = request.url.slice(capabilityPrefix.length);
|
|
243
383
|
const subPath = rest.startsWith("?") ? `/${rest}` : rest.startsWith("/") ? rest : "/";
|
|
244
384
|
const host = upstreamHost(target.host);
|
|
245
385
|
const isDeviceBearer = deps.isDeviceBearer ?? (() => false);
|
|
386
|
+
const isKnownBearer = deps.isKnownBearer ?? (() => false);
|
|
246
387
|
|
|
247
388
|
const upstream = net.connect(target.port, host, () => {
|
|
248
389
|
// Clear the connect-phase timeout once the socket is established; the pipe
|
|
@@ -250,7 +391,11 @@ export function handleLiveServerUpgrade(
|
|
|
250
391
|
upstream.setTimeout(0);
|
|
251
392
|
// Dashboard credentials never reach the previewed app (same rule as the
|
|
252
393
|
// HTTP path); a forwarded Referer loses any capability segment.
|
|
253
|
-
const forwarded = stripDashboardCredentials({ ...request.headers } as HeaderBag, isDeviceBearer);
|
|
394
|
+
const forwarded = stripDashboardCredentials({ ...request.headers } as HeaderBag, isDeviceBearer, request, isKnownBearer);
|
|
395
|
+
// A proxied hop: the upstream must never see this upgrade as genuinely local.
|
|
396
|
+
forwarded["x-forwarded-for"] = [forwarded["x-forwarded-for"], request.socket?.remoteAddress]
|
|
397
|
+
.filter(Boolean)
|
|
398
|
+
.join(", ");
|
|
254
399
|
if (typeof forwarded.referer === "string") forwarded.referer = stripCapabilitySegment(forwarded.referer);
|
|
255
400
|
const headers = Object.entries(forwarded)
|
|
256
401
|
.filter(([k]) => !["host", "origin"].includes(k.toLowerCase()))
|
|
@@ -0,0 +1,228 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Static-target serving for `/live/<id>/~c/<token>/<path>`.
|
|
3
|
+
*
|
|
4
|
+
* Every refusal is a bare 404 (a caller cannot tell "missing" from "forbidden").
|
|
5
|
+
* The checks, in order, follow the `harden-path-matcher-vs-router` checklist:
|
|
6
|
+
*
|
|
7
|
+
* 1. the path is decoded exactly ONCE; a decoded segment that still carries an
|
|
8
|
+
* encoded `/`, `.` or `\` (double encoding), a NUL / control character, a
|
|
9
|
+
* backslash, an empty / `.` / `..` segment is refused;
|
|
10
|
+
* 2. dot segments (`.git`, `.env`, …), `node_modules` and secret-like names
|
|
11
|
+
* (`isCredentialName`) are refused in every segment;
|
|
12
|
+
* 3. only the web-asset allowlist (`isStaticWebAsset`) is served — no `.map`,
|
|
13
|
+
* no `.txt`, no databases;
|
|
14
|
+
* 4. the REAL path (symlinks resolved) must lie inside the REAL root, and its
|
|
15
|
+
* own segments pass the same name checks — a symlink out of the root is a 404;
|
|
16
|
+
* 5. the raw file-read gate (`gate`) is re-run on the real path for EVERY
|
|
17
|
+
* request, so a revoked grant or pin takes effect on the next request;
|
|
18
|
+
* 6. the opened handle must be a regular file (checked on the handle itself).
|
|
19
|
+
*
|
|
20
|
+
* Streams from the file handle with single-`Range` support, never buffering a
|
|
21
|
+
* file. See change: improve-canvas-html-and-url-ux (design D1, D2).
|
|
22
|
+
*/
|
|
23
|
+
import fs from "node:fs";
|
|
24
|
+
import path from "node:path";
|
|
25
|
+
import {
|
|
26
|
+
isCredentialName,
|
|
27
|
+
isStaticWebAsset,
|
|
28
|
+
type StaticTarget,
|
|
29
|
+
} from "@blackbelt-technology/pi-dashboard-shared/live-server.js";
|
|
30
|
+
import type { FastifyReply, FastifyRequest } from "fastify";
|
|
31
|
+
|
|
32
|
+
export interface StaticServeDeps {
|
|
33
|
+
/** The raw file-read gate for an absolute real path under `cwd`. `true` = admitted. */
|
|
34
|
+
gate: (cwd: string, absPath: string) => Promise<boolean>;
|
|
35
|
+
/** Called with the real path of an HTML document about to be served in full (the origin scan reads it later). */
|
|
36
|
+
onHtmlServed?: (realPath: string) => void;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
const MIME: Readonly<Record<string, string>> = {
|
|
40
|
+
html: "text/html; charset=utf-8",
|
|
41
|
+
htm: "text/html; charset=utf-8",
|
|
42
|
+
css: "text/css; charset=utf-8",
|
|
43
|
+
js: "text/javascript; charset=utf-8",
|
|
44
|
+
mjs: "text/javascript; charset=utf-8",
|
|
45
|
+
json: "application/json; charset=utf-8",
|
|
46
|
+
svg: "image/svg+xml",
|
|
47
|
+
png: "image/png",
|
|
48
|
+
jpg: "image/jpeg",
|
|
49
|
+
jpeg: "image/jpeg",
|
|
50
|
+
gif: "image/gif",
|
|
51
|
+
webp: "image/webp",
|
|
52
|
+
avif: "image/avif",
|
|
53
|
+
ico: "image/x-icon",
|
|
54
|
+
woff: "font/woff",
|
|
55
|
+
woff2: "font/woff2",
|
|
56
|
+
ttf: "font/ttf",
|
|
57
|
+
otf: "font/otf",
|
|
58
|
+
mp4: "video/mp4",
|
|
59
|
+
webm: "video/webm",
|
|
60
|
+
ogg: "audio/ogg",
|
|
61
|
+
mp3: "audio/mpeg",
|
|
62
|
+
wav: "audio/wav",
|
|
63
|
+
m4a: "audio/mp4",
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
/** Content type for a served file name (`application/octet-stream` for the unreachable fallthrough). */
|
|
67
|
+
function mimeOf(name: string): string {
|
|
68
|
+
const i = name.lastIndexOf(".");
|
|
69
|
+
return (i >= 0 ? MIME[name.slice(i + 1).toLowerCase()] : undefined) ?? "application/octet-stream";
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
const CONTROL = /[\u0000-\u001f\u007f]/;
|
|
73
|
+
const DOUBLE_ENCODED = /%(?:2e|2f|5c|00)/i;
|
|
74
|
+
|
|
75
|
+
/** A single name that a static target must never serve (dot, dependency dir, credential-like). */
|
|
76
|
+
function isForbiddenName(name: string): boolean {
|
|
77
|
+
if (name.startsWith(".")) return true;
|
|
78
|
+
if (name.toLowerCase() === "node_modules") return true;
|
|
79
|
+
return isCredentialName(name);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Is one DECODED request segment unsafe (empty, dot, backslash, control, double-encoded, drive-like)? */
|
|
83
|
+
function isUnsafeSegment(seg: string): boolean {
|
|
84
|
+
if (seg === "" || seg === "." || seg === "..") return true;
|
|
85
|
+
if (seg.includes("\\") || CONTROL.test(seg) || DOUBLE_ENCODED.test(seg)) return true;
|
|
86
|
+
return process.platform === "win32" && seg.includes(":"); // platform-branch-ok: reject NTFS drive/ADS segments on Windows only
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/**
|
|
90
|
+
* Decode the request path once and split it into safe segments, or `null`.
|
|
91
|
+
* `pathname` is the raw pathname after the capability prefix (leading `/`, no query).
|
|
92
|
+
* A path ending in `/` (or the root) maps to `index.html`.
|
|
93
|
+
*/
|
|
94
|
+
export function safeSegments(pathname: string): string[] | null {
|
|
95
|
+
let decoded: string;
|
|
96
|
+
try {
|
|
97
|
+
decoded = decodeURIComponent(pathname);
|
|
98
|
+
} catch {
|
|
99
|
+
return null;
|
|
100
|
+
}
|
|
101
|
+
if (!decoded.startsWith("/")) return null;
|
|
102
|
+
const trailingSlash = decoded.endsWith("/");
|
|
103
|
+
const segments = decoded.slice(1).split("/");
|
|
104
|
+
if (trailingSlash) segments.pop();
|
|
105
|
+
if (segments.some(isUnsafeSegment)) return null;
|
|
106
|
+
if (trailingSlash || segments.length === 0) segments.push("index.html");
|
|
107
|
+
if (segments.some(isForbiddenName)) return null;
|
|
108
|
+
return isStaticWebAsset(segments[segments.length - 1]) ? segments : null;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const isInside = (child: string, parent: string): boolean => {
|
|
112
|
+
const rel = path.relative(parent, child);
|
|
113
|
+
return rel !== "" && !rel.startsWith("..") && !path.isAbsolute(rel);
|
|
114
|
+
};
|
|
115
|
+
|
|
116
|
+
type RangeResult = { kind: "full" } | { kind: "range"; start: number; end: number } | { kind: "unsatisfiable" };
|
|
117
|
+
|
|
118
|
+
/** Parse a single `bytes=` range; anything else (multi-range, bad syntax) serves the full body. */
|
|
119
|
+
function parseRange(header: string | undefined, size: number): RangeResult {
|
|
120
|
+
if (!header || size === 0) return { kind: "full" };
|
|
121
|
+
const m = /^bytes=(\d*)-(\d*)$/.exec(header.trim());
|
|
122
|
+
if (!m) return { kind: "full" };
|
|
123
|
+
const [, a, b] = m;
|
|
124
|
+
if (a === "" && b === "") return { kind: "full" };
|
|
125
|
+
if (a === "") {
|
|
126
|
+
const n = Number(b);
|
|
127
|
+
if (n === 0) return { kind: "unsatisfiable" };
|
|
128
|
+
return { kind: "range", start: Math.max(0, size - n), end: size - 1 };
|
|
129
|
+
}
|
|
130
|
+
const start = Number(a);
|
|
131
|
+
const end = b === "" ? size - 1 : Math.min(Number(b), size - 1);
|
|
132
|
+
if (!Number.isSafeInteger(start) || start >= size) return { kind: "unsatisfiable" };
|
|
133
|
+
if (end < start) return { kind: "full" };
|
|
134
|
+
return { kind: "range", start, end };
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Resolve the request to the REAL path of a servable file, or `null`: realpath containment
|
|
139
|
+
* inside the real root, name checks on the resolved name, then the raw-read gate.
|
|
140
|
+
*/
|
|
141
|
+
async function locateFile(target: StaticTarget, segments: string[], deps: StaticServeDeps): Promise<string | null> {
|
|
142
|
+
let realRoot: string;
|
|
143
|
+
let real: string;
|
|
144
|
+
try {
|
|
145
|
+
realRoot = await fs.promises.realpath(target.root);
|
|
146
|
+
real = await fs.promises.realpath(path.join(realRoot, ...segments));
|
|
147
|
+
} catch {
|
|
148
|
+
return null;
|
|
149
|
+
}
|
|
150
|
+
if (!isInside(real, realRoot)) return null;
|
|
151
|
+
// The symlink-resolved name must be servable too (`ok.html -> .env` is not).
|
|
152
|
+
const realSegments = path.relative(realRoot, real).split(path.sep);
|
|
153
|
+
if (realSegments.some(isForbiddenName) || !isStaticWebAsset(realSegments[realSegments.length - 1])) return null;
|
|
154
|
+
return (await deps.gate(target.cwd, real)) ? real : null;
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/** Open `real` and verify, on the handle itself, that it is a regular file. */
|
|
158
|
+
async function openRegular(real: string): Promise<{ fh: fs.promises.FileHandle; size: number } | null> {
|
|
159
|
+
let fh: fs.promises.FileHandle;
|
|
160
|
+
try {
|
|
161
|
+
fh = await fs.promises.open(real, "r");
|
|
162
|
+
} catch {
|
|
163
|
+
return null;
|
|
164
|
+
}
|
|
165
|
+
try {
|
|
166
|
+
const st = await fh.stat();
|
|
167
|
+
if (st.isFile()) return { fh, size: st.size };
|
|
168
|
+
} catch {
|
|
169
|
+
/* fall through to close */
|
|
170
|
+
}
|
|
171
|
+
await fh.close().catch(() => undefined);
|
|
172
|
+
return null;
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/** Tell the origin scan which HTML document is about to be served in full. */
|
|
176
|
+
function noteHtmlServed(deps: StaticServeDeps, method: string, real: string): void {
|
|
177
|
+
if (method === "GET" && /\.html?$/i.test(real)) deps.onHtmlServed?.(real);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
/**
|
|
181
|
+
* Serve `rest` (the path + query after the capability prefix) from `target`.
|
|
182
|
+
* `extraHeaders` carries the CSP set built from the token's policy.
|
|
183
|
+
*/
|
|
184
|
+
export async function serveStatic(
|
|
185
|
+
request: FastifyRequest,
|
|
186
|
+
reply: FastifyReply,
|
|
187
|
+
target: StaticTarget,
|
|
188
|
+
rest: string,
|
|
189
|
+
extraHeaders: Record<string, string>,
|
|
190
|
+
deps: StaticServeDeps,
|
|
191
|
+
): Promise<FastifyReply> {
|
|
192
|
+
const notFound = () => reply.code(404).send({ error: "live-server target not found" });
|
|
193
|
+
if (request.method !== "GET" && request.method !== "HEAD") {
|
|
194
|
+
return reply.code(405).header("allow", "GET, HEAD").send({ error: "method not allowed" });
|
|
195
|
+
}
|
|
196
|
+
const q = rest.search(/[?#]/);
|
|
197
|
+
const segments = safeSegments(q >= 0 ? rest.slice(0, q) : rest);
|
|
198
|
+
const real = segments ? await locateFile(target, segments, deps) : null;
|
|
199
|
+
const opened = real ? await openRegular(real) : null;
|
|
200
|
+
if (!real || !opened) return notFound();
|
|
201
|
+
const { fh, size } = opened;
|
|
202
|
+
noteHtmlServed(deps, request.method, real);
|
|
203
|
+
|
|
204
|
+
const headers: Record<string, string> = {
|
|
205
|
+
...extraHeaders,
|
|
206
|
+
"content-type": mimeOf(real),
|
|
207
|
+
"cache-control": "no-store",
|
|
208
|
+
"x-content-type-options": "nosniff",
|
|
209
|
+
"referrer-policy": "no-referrer",
|
|
210
|
+
"accept-ranges": "bytes",
|
|
211
|
+
};
|
|
212
|
+
const range = parseRange(request.headers.range, size);
|
|
213
|
+
if (range.kind === "unsatisfiable") {
|
|
214
|
+
await fh.close();
|
|
215
|
+
return reply.code(416).headers({ ...headers, "content-range": `bytes */${size}` }).send();
|
|
216
|
+
}
|
|
217
|
+
const start = range.kind === "range" ? range.start : 0;
|
|
218
|
+
const end = range.kind === "range" ? range.end : size - 1;
|
|
219
|
+
headers["content-length"] = String(size === 0 ? 0 : end - start + 1);
|
|
220
|
+
if (range.kind === "range") headers["content-range"] = `bytes ${start}-${end}/${size}`;
|
|
221
|
+
reply.code(range.kind === "range" ? 206 : 200).headers(headers);
|
|
222
|
+
if (request.method === "HEAD" || size === 0) {
|
|
223
|
+
await fh.close();
|
|
224
|
+
return reply.send();
|
|
225
|
+
}
|
|
226
|
+
// The stream owns the handle and closes it on end / error / client abort.
|
|
227
|
+
return reply.send(fh.createReadStream({ start, end, autoClose: true }));
|
|
228
|
+
}
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Filesystem half of `GET` / `PUT /api/openspec/dependencies`: a fresh read of
|
|
3
|
+
* one change's `dependencies.yaml` and the contained, preconditioned, atomic
|
|
4
|
+
* write. Route gates, the workflow-schema write guard and the per-cwd lock live
|
|
5
|
+
* in the route; this module owns containment, symlink refusal and the write.
|
|
6
|
+
*
|
|
7
|
+
* See change: add-openspec-change-dependencies.
|
|
8
|
+
*/
|
|
9
|
+
import { randomBytes } from "node:crypto";
|
|
10
|
+
import fsp from "node:fs/promises";
|
|
11
|
+
import path from "node:path";
|
|
12
|
+
import {
|
|
13
|
+
DEPENDENCIES_FILE,
|
|
14
|
+
type DeclaredDependencies,
|
|
15
|
+
type FileStat,
|
|
16
|
+
readDependenciesFile,
|
|
17
|
+
} from "@blackbelt-technology/pi-dashboard-shared/openspec-dependencies.js";
|
|
18
|
+
|
|
19
|
+
export interface DeclaredRead {
|
|
20
|
+
declared: DeclaredDependencies | null;
|
|
21
|
+
declaredError: string | null;
|
|
22
|
+
file: FileStat | null;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
async function lstatOrNull(p: string): Promise<import("node:fs").Stats | null> {
|
|
26
|
+
try {
|
|
27
|
+
return await fsp.lstat(p);
|
|
28
|
+
} catch {
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
/** `<root>/openspec/changes/<change>` for a canonical project root. */
|
|
34
|
+
const changeDirOf = (root: string, change: string): string => path.join(root, "openspec", "changes", change);
|
|
35
|
+
|
|
36
|
+
/** Read the file fresh under the read rules; a symlinked change directory is never read through. */
|
|
37
|
+
export async function readDeclared(root: string, change: string): Promise<DeclaredRead> {
|
|
38
|
+
const dir = changeDirOf(root, change);
|
|
39
|
+
const st = await lstatOrNull(dir);
|
|
40
|
+
if (!st?.isDirectory()) {
|
|
41
|
+
return { declared: null, declaredError: st ? "change directory is a symlink or not a directory" : null, file: null };
|
|
42
|
+
}
|
|
43
|
+
const r = await readDependenciesFile(path.join(dir, DEPENDENCIES_FILE));
|
|
44
|
+
if (r.kind === "absent") return { declared: null, declaredError: null, file: null };
|
|
45
|
+
if (r.kind === "invalid") return { declared: null, declaredError: r.error, file: r.stat ?? null };
|
|
46
|
+
return { declared: r.value, declaredError: null, file: r.stat };
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export type WriteOutcome =
|
|
50
|
+
| { ok: true; file: FileStat }
|
|
51
|
+
| { ok: false; status: 403 | 409 | 500; reason: "write-refused" | "modified" | "write-failed"; error: string };
|
|
52
|
+
|
|
53
|
+
const refused = (error: string): WriteOutcome => ({ ok: false, status: 403, reason: "write-refused", error });
|
|
54
|
+
const modified = (error: string): WriteOutcome => ({ ok: false, status: 409, reason: "modified", error });
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Write `content` as the change's `dependencies.yaml`.
|
|
58
|
+
*
|
|
59
|
+
* Containment first: the change directory and an existing file must be real
|
|
60
|
+
* (non-symlink) and the directory's realpath must sit under the canonical
|
|
61
|
+
* `<root>/openspec/changes/`. Then the precondition `expected` (the `file` value
|
|
62
|
+
* GET returned): `null` = the file must not exist; otherwise mtime and size must
|
|
63
|
+
* both match. The content goes to a temp file in the same directory and is moved
|
|
64
|
+
* into place — `rename` when replacing, `link` (no replace) when creating.
|
|
65
|
+
*/
|
|
66
|
+
export async function writeDependenciesFile(args: {
|
|
67
|
+
root: string;
|
|
68
|
+
change: string;
|
|
69
|
+
content: string;
|
|
70
|
+
expected: FileStat | null;
|
|
71
|
+
}): Promise<WriteOutcome> {
|
|
72
|
+
const { root, change, content, expected } = args;
|
|
73
|
+
const dir = changeDirOf(root, change);
|
|
74
|
+
const dirStat = await lstatOrNull(dir);
|
|
75
|
+
if (!dirStat || dirStat.isSymbolicLink() || !dirStat.isDirectory()) {
|
|
76
|
+
return refused("the change directory is missing, a symlink, or not a directory");
|
|
77
|
+
}
|
|
78
|
+
let changesReal: string;
|
|
79
|
+
let dirReal: string;
|
|
80
|
+
try {
|
|
81
|
+
changesReal = await fsp.realpath(path.join(root, "openspec", "changes"));
|
|
82
|
+
dirReal = await fsp.realpath(dir);
|
|
83
|
+
} catch {
|
|
84
|
+
return refused("cannot resolve the change directory");
|
|
85
|
+
}
|
|
86
|
+
// Strictly below `changes/` (the directory itself, e.g. change "." or "", is not a change directory).
|
|
87
|
+
if (dirReal === changesReal || !(dirReal + path.sep).startsWith(changesReal + path.sep)) {
|
|
88
|
+
return refused("the change directory resolves outside openspec/changes/");
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
const target = path.join(dirReal, DEPENDENCIES_FILE);
|
|
92
|
+
const existing = await lstatOrNull(target);
|
|
93
|
+
if (existing && (existing.isSymbolicLink() || !existing.isFile())) {
|
|
94
|
+
return refused("dependencies.yaml is a symlink or not a regular file");
|
|
95
|
+
}
|
|
96
|
+
if (expected === null) {
|
|
97
|
+
if (existing) return modified("dependencies.yaml was created after it was read");
|
|
98
|
+
} else if (!existing || existing.mtimeMs !== expected.mtimeMs || existing.size !== expected.size) {
|
|
99
|
+
return modified("dependencies.yaml changed since it was read");
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
const tmp = path.join(dirReal, `.dependencies.yaml.${process.pid}-${randomBytes(6).toString("hex")}.tmp`);
|
|
103
|
+
try {
|
|
104
|
+
await fsp.writeFile(tmp, content, { flag: "wx", mode: 0o644 });
|
|
105
|
+
if (expected === null) {
|
|
106
|
+
try {
|
|
107
|
+
await fsp.link(tmp, target); // exclusive: never replaces
|
|
108
|
+
} catch (err) {
|
|
109
|
+
if ((err as NodeJS.ErrnoException).code === "EEXIST") return modified("dependencies.yaml was created after it was read");
|
|
110
|
+
throw err;
|
|
111
|
+
}
|
|
112
|
+
} else {
|
|
113
|
+
await fsp.rename(tmp, target);
|
|
114
|
+
}
|
|
115
|
+
const st = await fsp.stat(target);
|
|
116
|
+
return { ok: true, file: { mtimeMs: st.mtimeMs, size: st.size } };
|
|
117
|
+
} catch (err) {
|
|
118
|
+
return { ok: false, status: 500, reason: "write-failed", error: `could not write dependencies.yaml: ${(err as Error).message}` };
|
|
119
|
+
} finally {
|
|
120
|
+
await fsp.rm(tmp, { force: true }).catch(() => undefined);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
@@ -25,6 +25,8 @@ import { matchesOutputPattern } from "@blackbelt-technology/pi-dashboard-shared/
|
|
|
25
25
|
* - `tasks.md`, `proposal.md`, `design.md` at the change root
|
|
26
26
|
* - any `*.md` under any `specs/` subtree
|
|
27
27
|
* - `.openspec.yaml` (change metadata — affects schema / error state)
|
|
28
|
+
* - `dependencies.yaml` (declared change dependencies; spec-driven changes do
|
|
29
|
+
* not declare it as an artifact). See change: add-openspec-change-dependencies.
|
|
28
30
|
*
|
|
29
31
|
* The watcher event filename is the relative path from the watch root
|
|
30
32
|
* (`openspec/changes/`), so a typical match is
|
|
@@ -34,7 +36,7 @@ import { matchesOutputPattern } from "@blackbelt-technology/pi-dashboard-shared/
|
|
|
34
36
|
* (`my-change\\tasks.md`) match too.
|
|
35
37
|
*/
|
|
36
38
|
const FILTER_RE =
|
|
37
|
-
/^[^/]+\/(?:tasks\.md|proposal\.md|design\.md|\.openspec\.yaml|specs(?:\/.*)?\.md)$/;
|
|
39
|
+
/^[^/]+\/(?:tasks\.md|proposal\.md|design\.md|\.openspec\.yaml|dependencies\.yaml|specs(?:\/.*)?\.md)$/;
|
|
38
40
|
|
|
39
41
|
/**
|
|
40
42
|
* Relevant events under `openspec/changes/` (path relative to that dir):
|