@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
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `worker_threads` entry for the `GET /api/grep` JS-fallback scan. Runs `grepWithJsScan`
|
|
3
|
+
* off the main event loop so a caller-supplied catastrophic regex cannot stall the server;
|
|
4
|
+
* the parent (`grepWithJsScanInWorker`) terminates the thread after the scan timeout.
|
|
5
|
+
*
|
|
6
|
+
* Bootstrap runs only when `!isMainThread`, mirroring `attachments/fit-worker.ts`.
|
|
7
|
+
* Input comes through `workerData`; only the match array crosses back.
|
|
8
|
+
*
|
|
9
|
+
* See change: triage-codeql-alert-debt (D3, #216).
|
|
10
|
+
*/
|
|
11
|
+
import { isMainThread, parentPort, workerData } from "node:worker_threads";
|
|
12
|
+
import { type GrepWorkerReply, type GrepWorkerRequest, grepWithJsScan } from "./grep.js";
|
|
13
|
+
|
|
14
|
+
if (!isMainThread && parentPort) {
|
|
15
|
+
const { cwd, query, opts } = workerData as GrepWorkerRequest;
|
|
16
|
+
let reply: GrepWorkerReply;
|
|
17
|
+
try {
|
|
18
|
+
reply = { ok: true, matches: grepWithJsScan(cwd, query, opts) };
|
|
19
|
+
} catch (err) {
|
|
20
|
+
reply = { ok: false, error: err instanceof Error ? err.message : String(err) };
|
|
21
|
+
}
|
|
22
|
+
parentPort.postMessage(reply);
|
|
23
|
+
}
|
|
@@ -4,13 +4,20 @@
|
|
|
4
4
|
* `rg` is absent. Both return ranked `{ path, line, col, snippet }[]` with caps
|
|
5
5
|
* on files, bytes per file, and total matches to bound response size.
|
|
6
6
|
*
|
|
7
|
-
*
|
|
7
|
+
* The JS fallback scan runs on a `worker_thread` (`grep-worker.ts`) terminated after
|
|
8
|
+
* `RG_TIMEOUT_MS`, so a catastrophic caller regexp cannot stall the server.
|
|
9
|
+
*
|
|
10
|
+
* See change: split-editor-workspace, triage-codeql-alert-debt (#216).
|
|
8
11
|
*/
|
|
9
12
|
|
|
10
13
|
import { execFile } from "node:child_process"; // ban:child_process-ok rg spawn; needs promisify({stdout,stderr}) shape
|
|
11
14
|
import { readdirSync, readFileSync } from "node:fs";
|
|
12
|
-
import { join, relative } from "node:path";
|
|
15
|
+
import { dirname, join, relative, resolve } from "node:path";
|
|
16
|
+
import { fileURLToPath, pathToFileURL } from "node:url";
|
|
13
17
|
import { promisify } from "node:util";
|
|
18
|
+
import { Worker } from "node:worker_threads";
|
|
19
|
+
import { workerExecArgv } from "../attachments/fit-worker-pool.js";
|
|
20
|
+
import { isDashboardStateDirSync } from "./dashboard-state-guard.js";
|
|
14
21
|
|
|
15
22
|
const execFileAsync = promisify(execFile);
|
|
16
23
|
|
|
@@ -207,6 +214,10 @@ export function grepWithJsScan(cwd: string, query: string, opts: GrepOptions = {
|
|
|
207
214
|
const rel = relative(cwd, full).replace(/\\/g, "/");
|
|
208
215
|
if (isIgnored(rel)) continue;
|
|
209
216
|
if (entry.isDirectory()) {
|
|
217
|
+
// Never walk into the dashboard state dir (token, identity key, config): the route also
|
|
218
|
+
// filters its matches, but a secret should not even be read. See change:
|
|
219
|
+
// close-container-loopback-impersonation (D8).
|
|
220
|
+
if (isDashboardStateDirSync(full)) continue;
|
|
210
221
|
queue.push({ dir: full, depth: depth + 1 });
|
|
211
222
|
continue;
|
|
212
223
|
}
|
|
@@ -240,20 +251,95 @@ export function grepWithJsScan(cwd: string, query: string, opts: GrepOptions = {
|
|
|
240
251
|
return matches;
|
|
241
252
|
}
|
|
242
253
|
|
|
243
|
-
/**
|
|
254
|
+
/** Rejection of a fallback scan that outlived its timeout (the route maps it to 504). */
|
|
255
|
+
export class GrepTimeoutError extends Error {
|
|
256
|
+
constructor(timeoutMs: number) {
|
|
257
|
+
super(`search timed out after ${timeoutMs}ms`);
|
|
258
|
+
this.name = "GrepTimeoutError";
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
|
|
262
|
+
/** Test seams for the worker-backed scan. */
|
|
263
|
+
interface GrepScanOptions {
|
|
264
|
+
/** Scan timeout in ms. Default `RG_TIMEOUT_MS`. */
|
|
265
|
+
scanTimeoutMs?: number;
|
|
266
|
+
/** Worker entry URL override (tests force a failing entry). Default: sibling `grep-worker.ts`. */
|
|
267
|
+
scanWorkerUrl?: string;
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** Message the worker posts back: the scan result, or the error it threw. */
|
|
271
|
+
export type GrepWorkerReply = { ok: true; matches: GrepMatch[] } | { ok: false; error: string };
|
|
272
|
+
|
|
273
|
+
/** What the worker receives through `workerData`. */
|
|
274
|
+
export interface GrepWorkerRequest {
|
|
275
|
+
cwd: string;
|
|
276
|
+
query: string;
|
|
277
|
+
opts: GrepOptions;
|
|
278
|
+
}
|
|
279
|
+
|
|
280
|
+
function defaultScanWorkerUrl(): string {
|
|
281
|
+
return pathToFileURL(resolve(dirname(fileURLToPath(import.meta.url)), "grep-worker.ts")).href;
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
/**
|
|
285
|
+
* `grepWithJsScan` on a `worker_thread`, terminated after `scanTimeoutMs`. The caller's
|
|
286
|
+
* pattern is compiled and run only inside the worker, so catastrophic backtracking
|
|
287
|
+
* (`(a+)+$`) cannot stall the server's event loop. Rejects with `GrepTimeoutError` on
|
|
288
|
+
* timeout, or with the worker's error (throw on start, crash, early exit). The worker is
|
|
289
|
+
* always terminated before this settles; never leaves a rejection unhandled.
|
|
290
|
+
*/
|
|
291
|
+
function grepWithJsScanInWorker(
|
|
292
|
+
cwd: string,
|
|
293
|
+
query: string,
|
|
294
|
+
opts: GrepOptions & GrepScanOptions = {},
|
|
295
|
+
): Promise<GrepMatch[]> {
|
|
296
|
+
const { scanTimeoutMs = RG_TIMEOUT_MS, scanWorkerUrl, ...scanOpts } = opts;
|
|
297
|
+
const workerUrl = scanWorkerUrl ?? defaultScanWorkerUrl();
|
|
298
|
+
return new Promise<GrepMatch[]>((resolveScan, rejectScan) => {
|
|
299
|
+
let settled = false;
|
|
300
|
+
let worker: Worker | null = null;
|
|
301
|
+
let timer: ReturnType<typeof setTimeout> | null = null;
|
|
302
|
+
const settle = (done: () => void): void => {
|
|
303
|
+
if (settled) return;
|
|
304
|
+
settled = true;
|
|
305
|
+
if (timer) clearTimeout(timer);
|
|
306
|
+
// Fire-and-forget: terminate() rejects only if the worker is already gone.
|
|
307
|
+
if (worker) void worker.terminate().catch(() => {});
|
|
308
|
+
done();
|
|
309
|
+
};
|
|
310
|
+
try {
|
|
311
|
+
const request: GrepWorkerRequest = { cwd, query, opts: scanOpts };
|
|
312
|
+
worker = new Worker(new URL(workerUrl), { workerData: request, execArgv: workerExecArgv(workerUrl) });
|
|
313
|
+
} catch (err) {
|
|
314
|
+
settle(() => rejectScan(err));
|
|
315
|
+
return;
|
|
316
|
+
}
|
|
317
|
+
timer = setTimeout(() => settle(() => rejectScan(new GrepTimeoutError(scanTimeoutMs))), scanTimeoutMs);
|
|
318
|
+
worker.on("message", (reply: GrepWorkerReply) => {
|
|
319
|
+
settle(() => (reply.ok ? resolveScan(reply.matches) : rejectScan(new Error(reply.error))));
|
|
320
|
+
});
|
|
321
|
+
worker.on("error", (err) => settle(() => rejectScan(err)));
|
|
322
|
+
worker.on("exit", (code) => settle(() => rejectScan(new Error(`grep worker exited (code ${code}) without a result`))));
|
|
323
|
+
});
|
|
324
|
+
}
|
|
325
|
+
|
|
326
|
+
/**
|
|
327
|
+
* Run a content search, preferring `rg` when `rgPath` is set, else the worker-backed JS
|
|
328
|
+
* scan. An rg failure degrades to that scan, which is bounded by `scanTimeoutMs`.
|
|
329
|
+
*/
|
|
244
330
|
export async function runGrep(
|
|
245
331
|
cwd: string,
|
|
246
332
|
query: string,
|
|
247
|
-
opts: GrepOptions & { rgPath?: string | null } = {},
|
|
333
|
+
opts: GrepOptions & GrepScanOptions & { rgPath?: string | null } = {},
|
|
248
334
|
): Promise<GrepMatch[]> {
|
|
249
335
|
const { rgPath, ...grepOpts } = opts;
|
|
250
336
|
if (rgPath) {
|
|
251
337
|
try {
|
|
252
338
|
return await grepWithRipgrep(rgPath, cwd, query, grepOpts);
|
|
253
339
|
} catch {
|
|
254
|
-
// rg failed (spawn / parse) — degrade to the
|
|
255
|
-
return
|
|
340
|
+
// rg failed (spawn / parse / rejected pattern) — degrade to the bounded scan.
|
|
341
|
+
return grepWithJsScanInWorker(cwd, query, grepOpts);
|
|
256
342
|
}
|
|
257
343
|
}
|
|
258
|
-
return
|
|
344
|
+
return grepWithJsScanInWorker(cwd, query, grepOpts);
|
|
259
345
|
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `sendIndexWithImportMap`: the ONE function every HTML response built from the production
|
|
3
|
+
* `index.html` passes (`/`, `/index.html`, the SPA not-found fallbacks, the `--dev` fallback).
|
|
4
|
+
* It reads the plain `index.html` (never its `.gz`, mtime-cached), inserts the static host import map
|
|
5
|
+
* before the first module script / modulepreload, and answers `no-cache`.
|
|
6
|
+
*
|
|
7
|
+
* `nonce` is optional: `server.ts` passes the per-response `cspNonceFor(reply)` so the inline map runs
|
|
8
|
+
* under the strict policy's `script-src 'self' 'nonce-…'` (the CSP onSend hook reads the same memoized
|
|
9
|
+
* nonce). Omitted → no `nonce` attribute (CSP off, tests). See change: harden-cors-and-csp-reporting (D9).
|
|
10
|
+
*
|
|
11
|
+
* It also inserts `<meta name="pi-trusted-types" content="<mode>">` (the resolved
|
|
12
|
+
* `PI_DASHBOARD_TRUSTED_TYPES` mode) so the client's `default` policy knows whether to
|
|
13
|
+
* pass through (`report`) or sanitize (`enforce`). See change: harden-client-sinks (D6).
|
|
14
|
+
*
|
|
15
|
+
* See change: decouple-plugins-from-core (task 6.4, design D21).
|
|
16
|
+
*/
|
|
17
|
+
import fs from "node:fs";
|
|
18
|
+
import path from "node:path";
|
|
19
|
+
import { hostImportMapJson } from "@blackbelt-technology/pi-dashboard-shared/dashboard-plugin/host-import-map.js";
|
|
20
|
+
import type { FastifyReply } from "fastify";
|
|
21
|
+
|
|
22
|
+
const INDEX_HTML_CACHE_CONTROL = "no-cache, no-store, must-revalidate";
|
|
23
|
+
|
|
24
|
+
const FIRST_MODULE_ENTRY = /<script\b[^>]*\btype\s*=\s*["']?module["']?[^>]*>|<link\b[^>]*\brel\s*=\s*["']?modulepreload["']?[^>]*>/i;
|
|
25
|
+
|
|
26
|
+
/** Pure: `html` with one import-map `<script>` inserted before the first module script / modulepreload (else before `</head>`, else first). */
|
|
27
|
+
export function injectImportMap(html: string, opts: { nonce?: string } = {}): string {
|
|
28
|
+
const nonceAttr = opts.nonce ? ` nonce="${opts.nonce.replace(/[^A-Za-z0-9+/=_-]/g, "")}"` : "";
|
|
29
|
+
const tag = `<script type="importmap"${nonceAttr}>${hostImportMapJson()}</script>`;
|
|
30
|
+
const at = html.search(FIRST_MODULE_ENTRY);
|
|
31
|
+
if (at >= 0) return `${html.slice(0, at)}${tag}\n ${html.slice(at)}`;
|
|
32
|
+
const head = html.search(/<\/head>/i);
|
|
33
|
+
if (head >= 0) return `${html.slice(0, head)}${tag}\n${html.slice(head)}`;
|
|
34
|
+
return `${tag}\n${html}`;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** Pure: `html` with the Trusted Types mode meta inserted right after `<head>` (else first). */
|
|
38
|
+
function injectTrustedTypesMeta(html: string, mode: "off" | "report" | "enforce"): string {
|
|
39
|
+
const tag = `<meta name="pi-trusted-types" content="${mode}">`;
|
|
40
|
+
const head = html.match(/<head\b[^>]*>/i);
|
|
41
|
+
if (head?.index !== undefined) {
|
|
42
|
+
const at = head.index + head[0].length;
|
|
43
|
+
return `${html.slice(0, at)}\n ${tag}${html.slice(at)}`;
|
|
44
|
+
}
|
|
45
|
+
return `${tag}\n${html}`;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export interface IndexHtmlSender {
|
|
49
|
+
/** Send `index.html` + import map; resolves the reply. */
|
|
50
|
+
sendIndexWithImportMap(reply: FastifyReply, opts?: { nonce?: string }): Promise<FastifyReply>;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Sender over `<clientDir>/index.html`. The mtime-cached read holds the raw file; the map is inserted per call (nonce varies). */
|
|
54
|
+
export function createIndexHtmlSender(
|
|
55
|
+
clientDir: string,
|
|
56
|
+
opts: { trustedTypesMode?: "off" | "report" | "enforce" } = {},
|
|
57
|
+
): IndexHtmlSender {
|
|
58
|
+
const ttMode = opts.trustedTypesMode ?? "report";
|
|
59
|
+
const file = path.join(clientDir, "index.html");
|
|
60
|
+
let cached: { mtimeMs: number; size: number; html: string } | undefined;
|
|
61
|
+
|
|
62
|
+
function read(): string {
|
|
63
|
+
const st = fs.statSync(file);
|
|
64
|
+
if (!cached || cached.mtimeMs !== st.mtimeMs || cached.size !== st.size) {
|
|
65
|
+
cached = { mtimeMs: st.mtimeMs, size: st.size, html: fs.readFileSync(file, "utf-8") };
|
|
66
|
+
}
|
|
67
|
+
return cached.html;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
return {
|
|
71
|
+
async sendIndexWithImportMap(reply, opts) {
|
|
72
|
+
let html: string;
|
|
73
|
+
try {
|
|
74
|
+
html = injectTrustedTypesMeta(injectImportMap(read(), opts), ttMode);
|
|
75
|
+
} catch {
|
|
76
|
+
return reply.code(404).send({ error: "index.html not found" });
|
|
77
|
+
}
|
|
78
|
+
return reply.code(200).header("Cache-Control", INDEX_HTML_CACHE_CONTROL).type("text/html; charset=utf-8").send(html);
|
|
79
|
+
},
|
|
80
|
+
};
|
|
81
|
+
}
|
|
@@ -16,6 +16,7 @@ import os from "node:os";
|
|
|
16
16
|
import path from "node:path";
|
|
17
17
|
import { OFFICE_SIZE_CAPS } from "@blackbelt-technology/pi-dashboard-shared/file-kind.js";
|
|
18
18
|
import { execFileAsync } from "@blackbelt-technology/pi-dashboard-shared/platform/exec.js";
|
|
19
|
+
import { DOCX_PROFILE } from "@blackbelt-technology/pi-dashboard-shared/sanitize-profiles.js";
|
|
19
20
|
import { loadPurify } from "./purify.js";
|
|
20
21
|
|
|
21
22
|
/** Bounded-preview + size caps (design D3). Overridable per-call for tests. */
|
|
@@ -218,9 +219,7 @@ export async function renderDocx(
|
|
|
218
219
|
{ transformDocument: hyperlinkGuard, convertImage },
|
|
219
220
|
);
|
|
220
221
|
const DOMPurify = await loadPurify();
|
|
221
|
-
const clean = DOMPurify.sanitize(result.value ?? "",
|
|
222
|
-
FORBID_TAGS: ["script", "style"],
|
|
223
|
-
});
|
|
222
|
+
const clean = DOMPurify.sanitize(result.value ?? "", DOCX_PROFILE);
|
|
224
223
|
const { html, truncated } = applyImageCap(clean, imageCount, caps);
|
|
225
224
|
return {
|
|
226
225
|
success: true,
|
|
@@ -39,6 +39,7 @@ import fs from "node:fs/promises";
|
|
|
39
39
|
import path from "node:path";
|
|
40
40
|
import { checkoutRootsAsync, isBoundCheckoutAsync } from "@blackbelt-technology/pi-dashboard-shared/platform/git.js";
|
|
41
41
|
import { samePath } from "@blackbelt-technology/pi-dashboard-shared/platform/paths.js";
|
|
42
|
+
import { dashboardStateRefuses } from "./dashboard-state-guard.js";
|
|
42
43
|
|
|
43
44
|
/** Per-probe budget for the async resolver and for each binding re-resolution. */
|
|
44
45
|
const PROBE_TIMEOUT_MS = 2_000;
|
|
@@ -132,6 +133,8 @@ export async function isGrantAdmitted(
|
|
|
132
133
|
subjects: readonly string[],
|
|
133
134
|
): Promise<boolean> {
|
|
134
135
|
if (subjects.length === 0) return false;
|
|
136
|
+
// Dashboard secrets are never granted away. See change: close-container-loopback-impersonation (D8).
|
|
137
|
+
if (await dashboardStateRefuses(resolved)) return false;
|
|
135
138
|
let real: string;
|
|
136
139
|
try {
|
|
137
140
|
real = await fs.realpath(resolved);
|
|
@@ -150,6 +153,10 @@ export async function isAllowed(
|
|
|
150
153
|
resolved: string,
|
|
151
154
|
{ anchors }: { anchors: string[] },
|
|
152
155
|
): Promise<boolean> {
|
|
156
|
+
// The dashboard state dir (token, identity key, config) is outside every anchor, whatever the
|
|
157
|
+
// anchor: a `$HOME` cwd or the `~/.pi` anchor would otherwise contain it. Decided on REAL paths.
|
|
158
|
+
// See change: close-container-loopback-impersonation (D8).
|
|
159
|
+
if (await dashboardStateRefuses(resolved)) return false;
|
|
153
160
|
// Layer ① — logical, no spawn. Catches ~every real read.
|
|
154
161
|
for (const anchor of anchors) {
|
|
155
162
|
if (within(resolved, anchor)) return true;
|
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
* - `cwd` is untrusted request input — the ENDPOINT gates it against the
|
|
9
9
|
* known-session set BEFORE calling this resolver. This function assumes the
|
|
10
10
|
* caller already trusts `cwd`.
|
|
11
|
-
* - Containment (`isAllowed`) runs BEFORE any `fs.stat`, anchored on
|
|
11
|
+
* - Containment (`decidePassive` → `isAllowed` / grants, then `containmentAllows`) runs BEFORE any `fs.stat`, anchored on
|
|
12
12
|
* `cwd` + a FIXED, server-derived `<os.homedir()>/.pi` allowlist. git-common
|
|
13
13
|
* -root widening is supplied by `isAllowed`'s layer ② (symlink-safe realpath),
|
|
14
14
|
* so a plain (logical) git-root anchor is deliberately NOT added here.
|
|
@@ -24,8 +24,8 @@
|
|
|
24
24
|
import fs from "node:fs/promises";
|
|
25
25
|
import os from "node:os";
|
|
26
26
|
import path from "node:path";
|
|
27
|
-
import {
|
|
28
|
-
import {
|
|
27
|
+
import { containmentAllows } from "@blackbelt-technology/pi-dashboard-shared/containment-guard.js";
|
|
28
|
+
import { decidePassive } from "../access/containment-gate.js";
|
|
29
29
|
|
|
30
30
|
export type MentionKind = "abs" | "tilde" | "relative";
|
|
31
31
|
|
|
@@ -40,7 +40,8 @@ function homePiAnchor(): string {
|
|
|
40
40
|
}
|
|
41
41
|
|
|
42
42
|
/**
|
|
43
|
-
* Resolve `mention` to an existing in-scope absolute path, or null.
|
|
43
|
+
* Resolve `mention` to an existing in-scope absolute path, or null. `canonCwd` (the admitted
|
|
44
|
+
* canonical cwd, when it differs from `cwd`) is an additional containment anchor.
|
|
44
45
|
*
|
|
45
46
|
* Candidate + kind:
|
|
46
47
|
* - leading `~/` → `<homedir>/…` kind `tilde`
|
|
@@ -51,7 +52,7 @@ function homePiAnchor(): string {
|
|
|
51
52
|
*/
|
|
52
53
|
export async function resolveFileMention(
|
|
53
54
|
mention: string,
|
|
54
|
-
{ cwd }: { cwd: string },
|
|
55
|
+
{ cwd, canonCwd }: { cwd: string; canonCwd?: string },
|
|
55
56
|
): Promise<ResolvedMention | null> {
|
|
56
57
|
if (!mention) return null;
|
|
57
58
|
|
|
@@ -73,12 +74,13 @@ export async function resolveFileMention(
|
|
|
73
74
|
candidate = path.resolve(candidate);
|
|
74
75
|
|
|
75
76
|
// Containment BEFORE stat (design D2). Anchors: cwd + fixed `~/.pi`; git-root
|
|
76
|
-
// widening comes from
|
|
77
|
+
// widening comes from the layer ② of `isAllowed` (via `decidePassive`).
|
|
77
78
|
// Consumes grants; returns null rather than a body, so it can never
|
|
78
79
|
// originate a grant (design D12).
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
80
|
+
// The canonical cwd joins the request spelling when it differs (core-file-cwd-admission D2), so a
|
|
81
|
+
// mention resolved here opens through the same anchor set as `/api/file`.
|
|
82
|
+
const anchors = canonCwd !== undefined && canonCwd !== cwd ? [cwd, canonCwd, homePiAnchor()] : [cwd, homePiAnchor()];
|
|
83
|
+
if (!containmentAllows(await decidePassive(candidate, anchors, { allowGrant: true }), candidate)) return null;
|
|
82
84
|
try {
|
|
83
85
|
await fs.stat(candidate);
|
|
84
86
|
} catch {
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Route-boundary cwd admission for the core git / openspec routes (change:
|
|
3
|
+
* core-cwd-admission, D1). One thin wrapper over the shared tri-state `admitCwd`
|
|
4
|
+
* so every route admits against the SAME known set as the plugin routes and
|
|
5
|
+
* answers an undecidable verdict with the SAME 503 body.
|
|
6
|
+
*
|
|
7
|
+
* The wrapper does NOT branch for the caller: each route (or the one helper that
|
|
8
|
+
* already validates, `validateCwd` / `depGates`) branches on
|
|
9
|
+
* `admissionAllows(admission, cwd)` itself so static analysis keeps the modelled
|
|
10
|
+
* path-injection barrier, then releases the token in `finally`.
|
|
11
|
+
*/
|
|
12
|
+
import { type Admission, type AdmitCwdOptions, admitCwd } from "@blackbelt-technology/pi-dashboard-shared/cwd-guard.js";
|
|
13
|
+
|
|
14
|
+
/** Sources of the known-folder set: session cwds ∪ pinned directories ∪ workspace folders. */
|
|
15
|
+
export interface KnownFolderSources {
|
|
16
|
+
sessionManager: { listAll(): ReadonlyArray<{ cwd?: string }> };
|
|
17
|
+
preferencesStore: {
|
|
18
|
+
getPinnedDirectories(): readonly string[];
|
|
19
|
+
/** Optional so a minimal store (tests, a store without workspaces) contributes no workspace folders. */
|
|
20
|
+
getWorkspaces?(): ReadonlyArray<{ folders: readonly string[] }>;
|
|
21
|
+
};
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* The known-folder set: every session cwd ∪ every pinned directory ∪ every
|
|
26
|
+
* workspace folder, unfiltered (no `hasOpenSpecRoot` / opt-out filtering). The
|
|
27
|
+
* single implementation behind `host.knownFolderCwds` (plugin routes) and the
|
|
28
|
+
* core route admission. Workspace folders joined the set in
|
|
29
|
+
* core-file-cwd-admission (D8): a workspace-only folder already reaches the
|
|
30
|
+
* package / canvas / resources routes.
|
|
31
|
+
*/
|
|
32
|
+
export function listKnownFolderCwds(src: KnownFolderSources): string[] {
|
|
33
|
+
const set = new Set<string>();
|
|
34
|
+
for (const s of src.sessionManager.listAll()) if (s.cwd) set.add(s.cwd);
|
|
35
|
+
for (const d of src.preferencesStore.getPinnedDirectories()) set.add(d);
|
|
36
|
+
for (const w of src.preferencesStore.getWorkspaces?.() ?? []) for (const f of w.folders) if (f) set.add(f);
|
|
37
|
+
return [...set];
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export interface RouteAdmissionDeps {
|
|
41
|
+
/** Live known-folder set (see {@link listKnownFolderCwds}). Fail-closed default: nothing is known. */
|
|
42
|
+
knownCwds?: () => string[];
|
|
43
|
+
/**
|
|
44
|
+
* `admitCwd` options: the host's throttled `onIndeterminate` logger, plus the
|
|
45
|
+
* test seams (`runner`, `realpath`, `deadlineMs`, token capture).
|
|
46
|
+
*/
|
|
47
|
+
admitOptions?: AdmitCwdOptions;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
const NONE_KNOWN = (): string[] => [];
|
|
51
|
+
|
|
52
|
+
/**
|
|
53
|
+
* Admit a request `cwd` against the known set. Returns the shared `Admission`
|
|
54
|
+
* unchanged: the caller maps `indeterminate` → {@link sendAdmissionUnavailable}
|
|
55
|
+
* and a non-`admit` / non-`admissionAllows` verdict to its own refusal.
|
|
56
|
+
*/
|
|
57
|
+
export function admitRouteCwd(cwd: string, deps: RouteAdmissionDeps = {}): Promise<Admission> {
|
|
58
|
+
return admitCwd(cwd, deps.knownCwds ?? NONE_KNOWN, deps.admitOptions);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Body of the 503 for an admission that could not be decided (design D3). */
|
|
62
|
+
export const CWD_ADMISSION_UNAVAILABLE_BODY = {
|
|
63
|
+
success: false,
|
|
64
|
+
code: "cwd-admission-unavailable",
|
|
65
|
+
error: "cwd-admission-unavailable",
|
|
66
|
+
message: "cwd admission could not be decided right now",
|
|
67
|
+
retryAfterMs: 1000,
|
|
68
|
+
} as const;
|
|
69
|
+
|
|
70
|
+
/** The minimal reply surface needed to send the 503. */
|
|
71
|
+
interface ReplyLike {
|
|
72
|
+
code(status: number): ReplyLike;
|
|
73
|
+
header(name: string, value: string): ReplyLike;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** Set `503` + `Retry-After: 1` on `reply` and return the shared body. */
|
|
77
|
+
export function sendAdmissionUnavailable(reply: ReplyLike): typeof CWD_ADMISSION_UNAVAILABLE_BODY {
|
|
78
|
+
reply.code(503).header("Retry-After", "1");
|
|
79
|
+
return CWD_ADMISSION_UNAVAILABLE_BODY;
|
|
80
|
+
}
|
|
@@ -23,6 +23,7 @@
|
|
|
23
23
|
import fs from "node:fs/promises";
|
|
24
24
|
import os from "node:os";
|
|
25
25
|
import path from "node:path";
|
|
26
|
+
import { dashboardStateRefuses } from "./dashboard-state-guard.js";
|
|
26
27
|
import { safeRealpath, within } from "./path-containment.js";
|
|
27
28
|
|
|
28
29
|
/**
|
|
@@ -98,6 +99,9 @@ export async function isWritableMdTarget(
|
|
|
98
99
|
const root = await allowedRoot(opts);
|
|
99
100
|
if (!root) return false;
|
|
100
101
|
const real = await safeRealpath(path.resolve(absPath));
|
|
102
|
+
// The dashboard state dir (token, identity key, config) is never an editable or readable "markdown target",
|
|
103
|
+
// whatever root admits it. See change: close-container-loopback-impersonation (D8).
|
|
104
|
+
if (await dashboardStateRefuses(real)) return false;
|
|
101
105
|
// Extension is checked on the *resolved* target so a same-dir symlink to a
|
|
102
106
|
// non-markdown file (e.g. notes.md → secret.txt) is rejected.
|
|
103
107
|
const ext = extOf(real);
|
|
@@ -12,13 +12,14 @@
|
|
|
12
12
|
* missing — and the recovery server itself would fail to load. Keep it
|
|
13
13
|
* dependency-free.
|
|
14
14
|
*/
|
|
15
|
-
|
|
15
|
+
|
|
16
16
|
import { spawn } from "node:child_process";
|
|
17
|
-
import { fileURLToPath } from "node:url";
|
|
18
|
-
import path from "node:path";
|
|
19
|
-
import os from "node:os";
|
|
20
|
-
import fs from "node:fs";
|
|
21
17
|
import crypto from "node:crypto";
|
|
18
|
+
import fs from "node:fs";
|
|
19
|
+
import http from "node:http";
|
|
20
|
+
import os from "node:os";
|
|
21
|
+
import path from "node:path";
|
|
22
|
+
import { fileURLToPath } from "node:url";
|
|
22
23
|
|
|
23
24
|
export interface RecoveryInfo {
|
|
24
25
|
/** Port to bind. */
|
|
@@ -49,7 +50,7 @@ export interface RecoveryInfo {
|
|
|
49
50
|
const LOCAL_TOKEN_HEADER = "x-pi-local-token";
|
|
50
51
|
|
|
51
52
|
const isLoopbackAddress = (addr: string | undefined): boolean =>
|
|
52
|
-
!!addr && (addr === "::1" || addr
|
|
53
|
+
!!addr && (addr === "::1" || LOOPBACK_IPV4.test(addr) || LOOPBACK_IPV4.test(addr.replace(/^::ffff:/, "")));
|
|
53
54
|
|
|
54
55
|
/** Hostname part of a `Host` header / Origin URL (no port, no IPv6 brackets). */
|
|
55
56
|
const hostnameOf = (hostPort: string): string => {
|
|
@@ -57,16 +58,43 @@ const hostnameOf = (hostPort: string): string => {
|
|
|
57
58
|
if (h.startsWith("[")) return h.slice(1, h.indexOf("]"));
|
|
58
59
|
return h.split(":")[0] ?? "";
|
|
59
60
|
};
|
|
60
|
-
|
|
61
|
+
// A literal IPv4 in 127.0.0.0/8 only: a DNS NAME such as `127.attacker.example` merely STARTS with
|
|
62
|
+
// "127." and is exactly what DNS rebinding presents (CodeRabbit r1).
|
|
63
|
+
const LOOPBACK_IPV4 = /^127(?:\.(?:25[0-5]|2[0-4]\d|1?\d?\d)){3}$/;
|
|
64
|
+
const isLoopbackName = (name: string): boolean => name === "localhost" || name === "::1" || LOOPBACK_IPV4.test(name);
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Proxy / tunnel forwarding headers. An INLINE copy of the guard's extended
|
|
68
|
+
* list (`PLUGIN_PROXY_FORWARDING_HEADERS` in `auth/localhost-guard.ts`): this
|
|
69
|
+
* module may import only node built-ins, and a unit test pins the two equal.
|
|
70
|
+
*/
|
|
71
|
+
export const RECOVERY_FORWARDING_HEADERS = [
|
|
72
|
+
"x-forwarded-for",
|
|
73
|
+
"x-forwarded-host",
|
|
74
|
+
"x-forwarded-proto",
|
|
75
|
+
"x-real-ip",
|
|
76
|
+
"forwarded",
|
|
77
|
+
"via",
|
|
78
|
+
"x-forwarded-server",
|
|
79
|
+
"x-forwarded-port",
|
|
80
|
+
] as const;
|
|
81
|
+
|
|
82
|
+
/** `Host` header with the scheme's default port stripped, lower-cased (compare to `URL.host`). */
|
|
83
|
+
function normalisedHost(hostHeader: string, scheme: string): string {
|
|
84
|
+
const h = hostHeader.trim().toLowerCase();
|
|
85
|
+
const defaultPort = scheme === "https:" ? ":443" : scheme === "http:" ? ":80" : "";
|
|
86
|
+
return defaultPort && h.endsWith(defaultPort) ? h.slice(0, -defaultPort.length) : h;
|
|
87
|
+
}
|
|
61
88
|
|
|
62
89
|
/**
|
|
63
90
|
* Gate for the mutating recovery actions (`retry`, `reinstall`). The recovery
|
|
64
91
|
* server has no auth of its own, so a mutating request is accepted only when it
|
|
65
|
-
* (a) presents the local IPC token, or (b) comes from a loopback peer
|
|
66
|
-
* loopback `Host
|
|
67
|
-
*
|
|
68
|
-
*
|
|
69
|
-
*
|
|
92
|
+
* (a) presents the local IPC token, or (b) comes from a loopback peer carrying
|
|
93
|
+
* NO proxy-forwarding header, a loopback `Host`, and either no `Origin` or an
|
|
94
|
+
* `Origin` that is the SAME origin as `Host`. Forwarding headers stop a tunnel
|
|
95
|
+
* relaying from loopback; the loopback `Host` stops DNS rebinding; same-origin
|
|
96
|
+
* (not "any loopback origin") stops a page served from another local port.
|
|
97
|
+
* See change: harden-server-capability-bounds (B9, D4).
|
|
70
98
|
*/
|
|
71
99
|
export function isRecoveryActionAllowed(
|
|
72
100
|
req: { remoteAddress: string | undefined; headers: Record<string, string | string[] | undefined> },
|
|
@@ -82,17 +110,18 @@ export function isRecoveryActionAllowed(
|
|
|
82
110
|
}
|
|
83
111
|
|
|
84
112
|
if (!isLoopbackAddress(req.remoteAddress)) return false;
|
|
113
|
+
if (RECOVERY_FORWARDING_HEADERS.some((h) => req.headers[h] != null)) return false;
|
|
85
114
|
const host = first(req.headers.host);
|
|
86
115
|
if (!host || !isLoopbackName(hostnameOf(host))) return false;
|
|
87
116
|
const origin = first(req.headers.origin);
|
|
88
117
|
if (origin !== undefined) {
|
|
89
|
-
let
|
|
118
|
+
let parsed: URL;
|
|
90
119
|
try {
|
|
91
|
-
|
|
120
|
+
parsed = new URL(origin);
|
|
92
121
|
} catch {
|
|
93
|
-
return false;
|
|
122
|
+
return false;
|
|
94
123
|
}
|
|
95
|
-
if (
|
|
124
|
+
if (parsed.host === "" || parsed.host !== normalisedHost(host, parsed.protocol)) return false; // includes `Origin: null`
|
|
96
125
|
}
|
|
97
126
|
return true;
|
|
98
127
|
}
|
|
@@ -251,6 +280,9 @@ export function buildRecoveryHtml(info: RecoveryInfo): string {
|
|
|
251
280
|
button.secondary:hover { background: #4b5563; }
|
|
252
281
|
button:disabled { background: #9ca3af; cursor: not-allowed; }
|
|
253
282
|
#status { margin-top: 1rem; font-size: .9em; color: #4b5563; }
|
|
283
|
+
#refusal { margin-top: 1rem; padding: .6rem .75rem; border-radius: 6px; font-size: .9em;
|
|
284
|
+
background: #fef2f2; border: 1px solid #fecaca; color: #991b1b; }
|
|
285
|
+
#refusal[hidden] { display: none; }
|
|
254
286
|
</style>
|
|
255
287
|
</head>
|
|
256
288
|
<body>
|
|
@@ -265,31 +297,41 @@ export function buildRecoveryHtml(info: RecoveryInfo): string {
|
|
|
265
297
|
<button id="reinstall" class="secondary">Reinstall dependencies</button>
|
|
266
298
|
</div>
|
|
267
299
|
<div id="status"></div>
|
|
300
|
+
<div id="refusal" role="alert" hidden></div>
|
|
268
301
|
<h3 style="margin-top: 1.5rem;">Error details</h3>
|
|
269
302
|
<pre>${stack}</pre>
|
|
270
303
|
</main>
|
|
271
304
|
<script>
|
|
272
305
|
const $ = (id) => document.getElementById(id);
|
|
273
306
|
const status = $("status");
|
|
307
|
+
const refusal = $("refusal");
|
|
274
308
|
function setBusy(b, msg) {
|
|
275
309
|
$("retry").disabled = b; $("reinstall").disabled = b;
|
|
276
310
|
status.textContent = msg;
|
|
277
311
|
}
|
|
312
|
+
// A 403 means the request was refused (not same-origin loopback): show the
|
|
313
|
+
// server's remedy as an alert and leave both buttons enabled.
|
|
314
|
+
function showRefusal(text) { refusal.textContent = text; refusal.hidden = false; }
|
|
315
|
+
function clearRefusal() { refusal.textContent = ""; refusal.hidden = true; }
|
|
278
316
|
async function post(path) {
|
|
279
317
|
const res = await fetch(path, { method: "POST" });
|
|
280
318
|
const text = await res.text();
|
|
281
|
-
return { ok: res.ok, text };
|
|
319
|
+
return { ok: res.ok, status: res.status, text };
|
|
282
320
|
}
|
|
283
321
|
$("retry").addEventListener("click", async () => {
|
|
322
|
+
clearRefusal();
|
|
284
323
|
setBusy(true, "Retrying…");
|
|
285
324
|
const r = await post("/api/recovery/retry");
|
|
325
|
+
if (r.status === 403) { setBusy(false, ""); showRefusal(r.text); return; }
|
|
286
326
|
status.textContent = r.text;
|
|
287
327
|
if (r.ok) setTimeout(() => location.reload(), 1500);
|
|
288
328
|
else setBusy(false, "Retry failed: " + r.text);
|
|
289
329
|
});
|
|
290
330
|
$("reinstall").addEventListener("click", async () => {
|
|
331
|
+
clearRefusal();
|
|
291
332
|
setBusy(true, "Reinstalling… this may take a minute.");
|
|
292
333
|
const r = await post("/api/recovery/reinstall");
|
|
334
|
+
if (r.status === 403) { setBusy(false, ""); showRefusal(r.text); return; }
|
|
293
335
|
status.textContent = r.text;
|
|
294
336
|
setBusy(false, r.text);
|
|
295
337
|
});
|
|
@@ -415,8 +457,13 @@ export async function startRecoveryServer(info: RecoveryInfo): Promise<number> {
|
|
|
415
457
|
(url === "/api/recovery/retry" || url === "/api/recovery/reinstall") &&
|
|
416
458
|
!isRecoveryActionAllowed({ remoteAddress: req.socket.remoteAddress, headers: req.headers }, info.localToken)
|
|
417
459
|
) {
|
|
460
|
+
// Route only: never log a header or token value.
|
|
461
|
+
console.error(`[recovery] refused ${req.method} ${url}: not a same-origin loopback request`);
|
|
418
462
|
res.writeHead(403, { "content-type": "text/plain" });
|
|
419
|
-
res.end(
|
|
463
|
+
res.end(
|
|
464
|
+
"Recovery actions only work on the machine running the dashboard. Open this page at http://localhost:" +
|
|
465
|
+
`${info.port || "<port>"} on that machine, or run \`pi-dashboard stop\` then \`pi-dashboard start\` there.`,
|
|
466
|
+
);
|
|
420
467
|
return;
|
|
421
468
|
}
|
|
422
469
|
if (req.method === "POST" && url === "/api/recovery/retry") {
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Redaction of a live-preview capability token (`/~c/<token>`) from a log field / path.
|
|
3
|
+
* Its own module so the guard (which logs refused paths) and the capability store (which
|
|
4
|
+
* needs the guard's locality predicate) do not import each other.
|
|
5
|
+
*
|
|
6
|
+
* See change: retire-trusted-networks-bypass (D5).
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
/** `/~c/<token>` anywhere in a path or `Referer`. Tokens are base64url. */
|
|
10
|
+
export const CAPABILITY_SEGMENT = /\/~c\/[A-Za-z0-9_-]+/g;
|
|
11
|
+
|
|
12
|
+
/** Replace any `/~c/<token>` in a log field / path with a redaction marker. */
|
|
13
|
+
export function redactCapability(text: string): string {
|
|
14
|
+
return text.replace(CAPABILITY_SEGMENT, "/~c/<redacted>");
|
|
15
|
+
}
|
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Browser-originated `/live/` requests need a capability.
|
|
3
|
+
*
|
|
4
|
+
* A sandboxed preview frame has an opaque origin: its requests carry
|
|
5
|
+
* `Origin: null` and `Sec-Fetch-*` metadata. Without this rule a genuinely
|
|
6
|
+
* local operator's opaque frame would reach any registered port target with no
|
|
7
|
+
* capability at all (loopback peer, no forwarding header ⇒ "genuinely local").
|
|
8
|
+
* A request (HTTP or WS upgrade) carrying either marker must therefore present
|
|
9
|
+
* a valid capability; non-browser local callers (`curl`, `fastify.inject`) keep
|
|
10
|
+
* today's admission for port targets.
|
|
11
|
+
*
|
|
12
|
+
* See change: improve-canvas-html-and-url-ux (design D10).
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
/** True when the headers mark the request as browser-originated (opaque origin or fetch metadata). */
|
|
16
|
+
export function isBrowserOriginated(headers: Record<string, unknown>): boolean {
|
|
17
|
+
if (headers.origin === "null") return true;
|
|
18
|
+
for (const name of Object.keys(headers)) {
|
|
19
|
+
if (name.toLowerCase().startsWith("sec-fetch-")) return true;
|
|
20
|
+
}
|
|
21
|
+
return false;
|
|
22
|
+
}
|