@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
|
@@ -20,10 +20,14 @@
|
|
|
20
20
|
* (see `ws-ticket.ts`).
|
|
21
21
|
*/
|
|
22
22
|
import type { TLSSocket } from "node:tls";
|
|
23
|
-
import type { FastifyInstance, FastifyRequest } from "fastify";
|
|
23
|
+
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
|
|
24
|
+
import { TLS_ONLY_TOKEN_UNTRUSTED_CHANNEL } from "@blackbelt-technology/pi-dashboard-shared/tls-only-token.js";
|
|
24
25
|
import type { PairedDeviceRegistry } from "../pairing/paired-devices.js";
|
|
26
|
+
import { auditLine, auditPrefix } from "./audit-log.js";
|
|
25
27
|
import { hasProxyForwardingHeaders } from "./localhost-guard.js";
|
|
26
28
|
import { isLoopbackRange } from "./loopback.js";
|
|
29
|
+
import { bearerChannelOf } from "./proven-tls.js";
|
|
30
|
+
import { isSecureOrigin } from "./secure-origin.js";
|
|
27
31
|
|
|
28
32
|
/** Extract a `Bearer` token from an Authorization header, or null. */
|
|
29
33
|
export function parseBearerHeader(authorization: string | undefined): string | null {
|
|
@@ -39,6 +43,16 @@ export function parseBearerHeader(authorization: string | undefined): string | n
|
|
|
39
43
|
}
|
|
40
44
|
|
|
41
45
|
export const DEVICE_COOKIE = "pi_dash_device";
|
|
46
|
+
/** Route pattern of the browser-bearer rotation (the one route whose refusals are audited, D2). */
|
|
47
|
+
export const ROTATE_ROUTE = "/api/paired-devices/rotate";
|
|
48
|
+
/** 401 body for an expired browser bearer (distinct from revoked/unknown, which carry no `code`). */
|
|
49
|
+
/** 401 body for a `pi_tls_` bearer presented off a proven channel (a named cause, not "unpaired or revoked"). */
|
|
50
|
+
const TLS_ONLY_UNTRUSTED_BODY = {
|
|
51
|
+
success: false as const,
|
|
52
|
+
error: TLS_ONLY_TOKEN_UNTRUSTED_CHANNEL,
|
|
53
|
+
code: TLS_ONLY_TOKEN_UNTRUSTED_CHANNEL,
|
|
54
|
+
};
|
|
55
|
+
const BEARER_EXPIRED_BODY = { success: false as const, error: "bearer_expired", code: "bearer_expired" as const };
|
|
42
56
|
/** 400 days — `PairedDeviceRegistry` rows carry no expiry; revocation is the kill switch. */
|
|
43
57
|
const DEVICE_COOKIE_MAX_AGE_S = 400 * 24 * 60 * 60;
|
|
44
58
|
|
|
@@ -58,7 +72,10 @@ function deviceCookieSecure(request: FastifyRequest, globalSecure: () => boolean
|
|
|
58
72
|
// DIRECT only: a request carrying proxy-forwarding headers came through a TLS-terminating
|
|
59
73
|
// proxy that may sit on another host/container (peer 172.x), and keeps the global rule.
|
|
60
74
|
if (peer && !isLoopbackRange(peer) && !hasProxyForwardingHeaders(request.headers)) return false;
|
|
61
|
-
|
|
75
|
+
// The global rule is the ONE predicate shared with the OAuth state + session cookies:
|
|
76
|
+
// https base || loopback socket peer + Host equal to a live https tunnel origin.
|
|
77
|
+
// See change: harden-auth-credentials (D3).
|
|
78
|
+
return isSecureOrigin(request, globalSecure());
|
|
62
79
|
}
|
|
63
80
|
|
|
64
81
|
/** Pathname of a request URL (no query/fragment). */
|
|
@@ -67,6 +84,23 @@ function pathnameOf(url: string): string {
|
|
|
67
84
|
return q < 0 ? url : url.slice(0, q);
|
|
68
85
|
}
|
|
69
86
|
|
|
87
|
+
/**
|
|
88
|
+
* The device cookie's bearer. Authorization wins: the cookie is a fallback for
|
|
89
|
+
* `/api/*` URLs only and is never consulted when an Authorization header is present.
|
|
90
|
+
*/
|
|
91
|
+
function deviceCookieToken(request: FastifyRequest): string | null {
|
|
92
|
+
if (request.headers.authorization || !pathnameOf(request.url).startsWith("/api/")) return null;
|
|
93
|
+
return (request.cookies as Record<string, string | undefined> | undefined)?.[DEVICE_COOKIE] ?? null;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** 401 `bearer_expired`; a refused ROTATION of a known device is also audited (A-G4): id prefix, reason, socket peer only. */
|
|
97
|
+
function refuseExpired(request: FastifyRequest, reply: FastifyReply, deviceId: string): FastifyReply {
|
|
98
|
+
if (request.method === "POST" && request.routeOptions?.url === ROTATE_ROUTE) {
|
|
99
|
+
auditLine("pairing", "rotate_refused", { id: auditPrefix(deviceId), reason: "bearer_expired", ip: request.ip });
|
|
100
|
+
}
|
|
101
|
+
return reply.code(401).send(BEARER_EXPIRED_BODY);
|
|
102
|
+
}
|
|
103
|
+
|
|
70
104
|
/** Register the REST bearer onRequest branch. */
|
|
71
105
|
export function registerBearerAuth(
|
|
72
106
|
fastify: FastifyInstance,
|
|
@@ -80,17 +114,23 @@ export function registerBearerAuth(
|
|
|
80
114
|
/* already decorated by another plugin */
|
|
81
115
|
}
|
|
82
116
|
}
|
|
83
|
-
fastify.addHook("onRequest", async (request: FastifyRequest) => {
|
|
117
|
+
fastify.addHook("onRequest", async (request: FastifyRequest, reply: FastifyReply) => {
|
|
84
118
|
if ((request as any).isAuthenticated) return;
|
|
85
119
|
const headerToken = parseBearerHeader(request.headers.authorization);
|
|
86
|
-
|
|
87
|
-
//
|
|
88
|
-
const
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
120
|
+
const token = headerToken ?? deviceCookieToken(request);
|
|
121
|
+
// The channel is judged from the request itself and the registry records any off-channel use.
|
|
122
|
+
const verdict = token ? deps.registry.verifyDetailed(token, bearerChannelOf(request.raw)) : null;
|
|
123
|
+
// A TLS-only bearer off a proven channel is marked, then refused with a distinct, named cause.
|
|
124
|
+
// See change: prove-vault-bridge-tls (D4, D9).
|
|
125
|
+
if (verdict?.status === "tls_only_refused") return reply.code(401).send(TLS_ONLY_UNTRUSTED_BODY);
|
|
126
|
+
// A PRESENTED Authorization bearer is always judged, before any network
|
|
127
|
+
// trust: an expired browser bearer is a distinct 401 the client re-pairs
|
|
128
|
+
// on, even from a loopback / trusted peer. (A cookie-carried bearer that
|
|
129
|
+
// expired falls through unauthenticated, like a revoked one.) Revoked,
|
|
130
|
+
// unknown and superseded-after-grace bearers stay a plain denial.
|
|
131
|
+
// See change: harden-auth-credentials (D5, A-G12).
|
|
132
|
+
if (verdict?.status === "expired" && headerToken) return refuseExpired(request, reply, verdict.id);
|
|
133
|
+
const verified = verdict?.status === "ok" ? verdict : null;
|
|
94
134
|
if (verified) {
|
|
95
135
|
(request as any).isAuthenticated = true;
|
|
96
136
|
// Additive marker: HOW the request authenticated. `operatorGuard` on the
|
|
@@ -117,7 +157,7 @@ export function registerDeviceSessionRoutes(
|
|
|
117
157
|
): void {
|
|
118
158
|
fastify.post("/api/device-session", async (request, reply) => {
|
|
119
159
|
const bearer = parseBearerHeader(request.headers.authorization);
|
|
120
|
-
if (!bearer || !deps.registry.verify(bearer)) {
|
|
160
|
+
if (!bearer || !deps.registry.verify(bearer, bearerChannelOf(request.raw))) {
|
|
121
161
|
reply.code(401);
|
|
122
162
|
return { success: false as const, error: "device bearer required" };
|
|
123
163
|
}
|
|
@@ -44,13 +44,14 @@ export interface CorsOriginOptions {
|
|
|
44
44
|
/**
|
|
45
45
|
* Allow ANY `*.share.zrok.io` / `*.shares.zrok.io` host (branch 5).
|
|
46
46
|
*
|
|
47
|
-
*
|
|
48
|
-
*
|
|
49
|
-
*
|
|
50
|
-
*
|
|
51
|
-
*
|
|
52
|
-
* tunnel origins (branch
|
|
53
|
-
*
|
|
47
|
+
* Opt-in: only the boolean `true` enables it (`cors.allowZrokWildcard`,
|
|
48
|
+
* default `false`). Zrok shares are free and self-service, so a stranger
|
|
49
|
+
* share is very likely same-site to the victim's tunnel; the wildcard would
|
|
50
|
+
* let it read responses (CORS) and, for admission (WS upgrade, mutating
|
|
51
|
+
* REST), defeat even the OAuth'd gate — admission therefore ALWAYS forces it
|
|
52
|
+
* off. Tunnels the dashboard itself runs are live tunnel origins (branch
|
|
53
|
+
* 4/4b) and stay allowed with the wildcard off.
|
|
54
|
+
* See change: fix-ws-origin-cswsh (D1 rule 2), harden-cors-and-csp-reporting (B19).
|
|
54
55
|
*/
|
|
55
56
|
allowZrokWildcard?: boolean;
|
|
56
57
|
/** Top-level `allowedHosts` (live) — host-admission only. */
|
|
@@ -71,6 +72,41 @@ export interface CorsOriginOptions {
|
|
|
71
72
|
hostGateMode?: "report" | "enforce";
|
|
72
73
|
}
|
|
73
74
|
|
|
75
|
+
// biome-ignore lint/suspicious/noControlCharactersInRegex: detecting them is the point.
|
|
76
|
+
const HAS_CONTROL = /[\u0000-\u001f\u007f]/;
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Canonical form of an origin or URL for tunnel comparison: lowercase scheme
|
|
80
|
+
* and host, default port elided, ONE trailing hostname dot stripped, path /
|
|
81
|
+
* query dropped. `null` for anything that is not a well-formed http(s) origin
|
|
82
|
+
* (padding, control characters, bad port, other schemes).
|
|
83
|
+
*
|
|
84
|
+
* A trailing-dot origin equals its dotless form, matching host admission.
|
|
85
|
+
* See change: harden-cors-and-csp-reporting (R2).
|
|
86
|
+
*/
|
|
87
|
+
export function canonicalOrigin(raw: string): string | null {
|
|
88
|
+
if (typeof raw !== "string" || raw !== raw.trim() || HAS_CONTROL.test(raw)) return null;
|
|
89
|
+
try {
|
|
90
|
+
const u = new URL(raw);
|
|
91
|
+
if (u.protocol !== "http:" && u.protocol !== "https:") return null;
|
|
92
|
+
const host = u.hostname.endsWith(".") ? u.hostname.slice(0, -1) : u.hostname;
|
|
93
|
+
if (host === "") return null;
|
|
94
|
+
return `${u.protocol}//${host}${u.port ? `:${u.port}` : ""}`;
|
|
95
|
+
} catch {
|
|
96
|
+
return null;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Run a dynamic getter; a throwing getter means "nothing live", never a 500. */
|
|
101
|
+
function safely<T>(read: (() => T) | undefined, fallback: T): T {
|
|
102
|
+
if (!read) return fallback;
|
|
103
|
+
try {
|
|
104
|
+
return read() ?? fallback;
|
|
105
|
+
} catch {
|
|
106
|
+
return fallback;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
|
|
74
110
|
/**
|
|
75
111
|
* Why a CORS origin decision came out the way it did.
|
|
76
112
|
*
|
|
@@ -111,7 +147,8 @@ export interface CorsAllowance {
|
|
|
111
147
|
* 3. Loopback host (any port) → allow.
|
|
112
148
|
* 4. Active zrok tunnel URL → allow.
|
|
113
149
|
* 4b. Any CURRENTLY connected tunnel origin (any provider) → allow.
|
|
114
|
-
* 5. Any `*.share.zrok.io` / `*.shares.zrok.io` (zrok v2) host → allow
|
|
150
|
+
* 5. Any `*.share.zrok.io` / `*.shares.zrok.io` (zrok v2) host → allow, ONLY
|
|
151
|
+
* when `allowZrokWildcard === true` (opt-in, default off).
|
|
115
152
|
* 6. Neutral static PWA shell `https://pi-dashboard.dev` → allow.
|
|
116
153
|
* 7. Explicitly configured origin → allow.
|
|
117
154
|
* 8. Origin host matches a trusted network (CIDR / wildcard / exact) → allow.
|
|
@@ -130,6 +167,9 @@ export function classifyCorsOrigin(
|
|
|
130
167
|
// 2. Opaque-origin document. Never echo an ACAO for it, so an embedded
|
|
131
168
|
// untrusted app cannot call dashboard APIs even cross-origin.
|
|
132
169
|
if (origin === "null") return { allowed: false, revocable: false, kind: "opaque" };
|
|
170
|
+
// Padding / control characters are never sent by a browser; `new URL()`
|
|
171
|
+
// silently strips them, so do not normalize them into a trusted value.
|
|
172
|
+
if (origin !== origin.trim() || HAS_CONTROL.test(origin)) return { allowed: false, revocable: false, kind: "denied" };
|
|
133
173
|
try {
|
|
134
174
|
const u = new URL(origin);
|
|
135
175
|
const host = u.hostname;
|
|
@@ -137,26 +177,25 @@ export function classifyCorsOrigin(
|
|
|
137
177
|
if (host === "localhost" || host === "127.0.0.1" || host === "[::1]" || host === "::1") {
|
|
138
178
|
return allow("loopback");
|
|
139
179
|
}
|
|
180
|
+
// Tunnel branches compare CANONICAL origins (case, default port, one
|
|
181
|
+
// trailing dot, path), so the recorded URL and the browser's Origin agree.
|
|
182
|
+
const requestOrigin = canonicalOrigin(origin);
|
|
140
183
|
// 4. Active zrok tunnel URL (dynamic — rotation without restart).
|
|
141
|
-
const tunnelUrl = opts.getTunnelUrl
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
//
|
|
145
|
-
//
|
|
146
|
-
//
|
|
147
|
-
for (const raw of opts.getLiveTunnelOrigins
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
candidate = new URL(raw).origin;
|
|
151
|
-
} catch {
|
|
152
|
-
continue;
|
|
153
|
-
}
|
|
154
|
-
if (candidate === u.origin) return allow("live-tunnel");
|
|
184
|
+
const tunnelUrl = safely(opts.getTunnelUrl, null);
|
|
185
|
+
const canonicalTunnel = tunnelUrl ? canonicalOrigin(tunnelUrl) : null;
|
|
186
|
+
if (requestOrigin && canonicalTunnel && requestOrigin === canonicalTunnel) return allow("active-tunnel");
|
|
187
|
+
// 4b. Any live tunnel's origin, for every provider. Compared as canonical
|
|
188
|
+
// ORIGINS, not URLs: a provider reports `https://host/path`, and a
|
|
189
|
+
// browser sends `https://host`. Malformed entries are skipped.
|
|
190
|
+
for (const raw of safely(opts.getLiveTunnelOrigins, [] as string[])) {
|
|
191
|
+
const candidate = canonicalOrigin(raw);
|
|
192
|
+
if (candidate && requestOrigin && candidate === requestOrigin) return allow("live-tunnel");
|
|
155
193
|
}
|
|
156
|
-
// 5.
|
|
194
|
+
// 5. Opt-in only: any *.share.zrok.io (v1) or *.shares.zrok.io (v2) host.
|
|
195
|
+
const bareHost = host.endsWith(".") ? host.slice(0, -1) : host;
|
|
157
196
|
if (
|
|
158
|
-
opts.allowZrokWildcard
|
|
159
|
-
(
|
|
197
|
+
opts.allowZrokWildcard === true &&
|
|
198
|
+
(bareHost.endsWith(".share.zrok.io") || bareHost.endsWith(".shares.zrok.io"))
|
|
160
199
|
) {
|
|
161
200
|
return allow("zrok-wildcard");
|
|
162
201
|
}
|
|
@@ -227,7 +266,11 @@ export function isSameOriginByHost(
|
|
|
227
266
|
try {
|
|
228
267
|
const o = new URL(origin);
|
|
229
268
|
const h = new URL(`${o.protocol}//${hostHeader}`);
|
|
230
|
-
if (h.host === ""
|
|
269
|
+
if (h.host === "") return false;
|
|
270
|
+
// Canonical compare: case, default port and one trailing dot all agree.
|
|
271
|
+
const co = canonicalOrigin(origin);
|
|
272
|
+
const ch = canonicalOrigin(`${o.protocol}//${hostHeader}`);
|
|
273
|
+
if (!co || !ch || co !== ch) return false;
|
|
231
274
|
} catch {
|
|
232
275
|
return false;
|
|
233
276
|
}
|
|
@@ -265,16 +308,20 @@ export function isOriginAdmitted(
|
|
|
265
308
|
* WS upgrade admission, per route scope.
|
|
266
309
|
*
|
|
267
310
|
* `live` admits the opaque `Origin: null` — the sandboxed preview iframe is its
|
|
268
|
-
* only intended client and rejecting it would silently break HMR (D3)
|
|
269
|
-
*
|
|
311
|
+
* only intended client and rejecting it would silently break HMR (D3) — but ONLY
|
|
312
|
+
* for an upgrade that carries a VALID capability (`liveCapabilityValid`): an
|
|
313
|
+
* opaque frame without one would otherwise reach any port target. Every other
|
|
314
|
+
* scope (including `bridge` and the unrouted `null` scope) is strict.
|
|
315
|
+
* See change: improve-canvas-html-and-url-ux (design D10).
|
|
270
316
|
*/
|
|
271
317
|
export function isWsOriginTrusted(
|
|
272
318
|
origin: string | undefined,
|
|
273
319
|
hostHeader: string | undefined,
|
|
274
320
|
scope: WsRouteScope | null,
|
|
275
321
|
opts: CorsOriginOptions,
|
|
322
|
+
liveCapabilityValid = false,
|
|
276
323
|
): boolean {
|
|
277
|
-
if (scope === "live" && origin === "null") return
|
|
324
|
+
if (scope === "live" && origin === "null") return liveCapabilityValid;
|
|
278
325
|
return isOriginAdmitted(origin, hostHeader, opts);
|
|
279
326
|
}
|
|
280
327
|
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared path contract for the baseline CSP report sink. Emission (`csp.ts`)
|
|
3
|
+
* and the sink route (`csp-report-sink.ts`) both import from here so the
|
|
4
|
+
* `report-uri` a header advertises can never drift from the route that serves it.
|
|
5
|
+
*
|
|
6
|
+
* `/__pi/csp-report/:policy` sits at the root, OUTSIDE guard jurisdiction
|
|
7
|
+
* (`/api`, `/v1`, `/editor`, `/live`), and is distinct from the per-preview
|
|
8
|
+
* `/live/<id>/__pi/csp-report` sink.
|
|
9
|
+
*
|
|
10
|
+
* See change: harden-cors-and-csp-reporting (D8).
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
export const CSP_REPORT_PREFIX = "/__pi/csp-report/";
|
|
14
|
+
|
|
15
|
+
/** Policy labels a report can be filed under; anything else → 404. */
|
|
16
|
+
export const CSP_REPORT_POLICIES = ["baseline", "strict", "trusted-types"] as const;
|
|
17
|
+
export type CspReportPolicy = (typeof CSP_REPORT_POLICIES)[number];
|
|
18
|
+
|
|
19
|
+
export function isCspReportPolicy(v: string): v is CspReportPolicy {
|
|
20
|
+
return (CSP_REPORT_POLICIES as readonly string[]).includes(v);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** `/__pi/csp-report/<policy>` */
|
|
24
|
+
export function cspReportPath(policy: CspReportPolicy): string {
|
|
25
|
+
return `${CSP_REPORT_PREFIX}${policy}`;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** Reporting API endpoint name declared in `Reporting-Endpoints` (`csp-<policy>`). */
|
|
29
|
+
export function cspReportEndpointName(policy: CspReportPolicy): string {
|
|
30
|
+
return `csp-${policy}`;
|
|
31
|
+
}
|
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Baseline CSP violation report sink — `POST /__pi/csp-report/:policy`
|
|
3
|
+
* (`:policy` ∈ baseline | strict | trusted-types) — and the operator reset
|
|
4
|
+
* `POST /api/csp-reports/reset`.
|
|
5
|
+
*
|
|
6
|
+
* The sink is mounted at the root, OUTSIDE guard jurisdiction, and is public to the OAuth
|
|
7
|
+
* gate (`auth-plugin.ts`) so signed-out pages can report. It is unauthenticated, so it is
|
|
8
|
+
* hardened: 8 KiB cap by its OWN byte-counting read (chunked bodies included, independent of
|
|
9
|
+
* `Content-Length`, `bodyLimit` and parser registration order — it lives in an encapsulated
|
|
10
|
+
* Fastify scope with only a pass-through stream parser), exact content types, a dedicated
|
|
11
|
+
* per-socket-peer token bucket (capacity 20, 1 token/s; loopback NOT exempt), a 5 s body
|
|
12
|
+
* deadline, compressed bodies refused undecompressed. Nothing from a report is reflected in a
|
|
13
|
+
* response or logged; the only log line is `[csp] violation policy=<label> directive=<x>`.
|
|
14
|
+
*
|
|
15
|
+
* Order of refusal: 404 (label) → 405 (method) → 429 → 415 → 413 / 408 / 400. Refused-by-limiter,
|
|
16
|
+
* size cap or deadline reports bump the persisted `dropped` counter.
|
|
17
|
+
*
|
|
18
|
+
* See change: harden-cors-and-csp-reporting (D8).
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import type { IncomingMessage } from "node:http";
|
|
22
|
+
import type { FastifyInstance, FastifyReply, FastifyRequest } from "fastify";
|
|
23
|
+
import type { NetworkGuard } from "../routes/route-deps.js";
|
|
24
|
+
import { CSP_REPORT_PREFIX, type CspReportPolicy, isCspReportPolicy } from "./csp-report-paths.js";
|
|
25
|
+
import { type CspReportStore, normalizeDirective } from "./csp-report-store.js";
|
|
26
|
+
|
|
27
|
+
const CSP_REPORT_MAX_BYTES = 8 * 1024;
|
|
28
|
+
const BODY_DEADLINE_MS = 5_000;
|
|
29
|
+
const LIMITER_CAPACITY = 20;
|
|
30
|
+
/** Integer bucket arithmetic: one token = 1000 units, refilled 1 unit per ms (exact; no float drift). */
|
|
31
|
+
const TOKEN = 1_000;
|
|
32
|
+
const CAPACITY_UNITS = LIMITER_CAPACITY * TOKEN;
|
|
33
|
+
/** Hard bound on tracked peers; the oldest-inserted entries go first once the idle sweep frees nothing. */
|
|
34
|
+
const MAX_LIMITER_PEERS = 100_000;
|
|
35
|
+
const SWEEP_EVERY_MS = 1_000;
|
|
36
|
+
/** One `[csp] violation` line per policy × directive per window. */
|
|
37
|
+
const LOG_THROTTLE_MS = 60_000;
|
|
38
|
+
const MAX_LOG_KEYS = 128;
|
|
39
|
+
|
|
40
|
+
const REPORT_TYPES = new Set(["application/csp-report", "application/reports+json"]);
|
|
41
|
+
const SINK_METHODS = ["DELETE", "GET", "HEAD", "OPTIONS", "PATCH", "POST", "PUT"] as const;
|
|
42
|
+
|
|
43
|
+
/** Per-peer token bucket: capacity {@link LIMITER_CAPACITY}, refilled 1 token/s; full + idle entries are evicted. */
|
|
44
|
+
class PeerLimiter {
|
|
45
|
+
private readonly peers = new Map<string, { units: number; at: number }>();
|
|
46
|
+
private lastSweep = 0;
|
|
47
|
+
private readonly now: () => number;
|
|
48
|
+
constructor(now: () => number) {
|
|
49
|
+
this.now = now;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
get size(): number {
|
|
53
|
+
return this.peers.size;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
take(peer: string): boolean {
|
|
57
|
+
const t = this.now();
|
|
58
|
+
this.sweep(t);
|
|
59
|
+
const prev = this.peers.get(peer);
|
|
60
|
+
const units = prev ? Math.min(CAPACITY_UNITS, prev.units + (t - prev.at)) : CAPACITY_UNITS;
|
|
61
|
+
const ok = units >= TOKEN;
|
|
62
|
+
this.peers.delete(peer);
|
|
63
|
+
this.peers.set(peer, { units: ok ? units - TOKEN : units, at: t });
|
|
64
|
+
return ok;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** Drop entries whose bucket would be full again; bound the map even under a wide peer flood. */
|
|
68
|
+
private sweep(t: number): void {
|
|
69
|
+
if (t - this.lastSweep < SWEEP_EVERY_MS && this.peers.size < MAX_LIMITER_PEERS) return;
|
|
70
|
+
this.lastSweep = t;
|
|
71
|
+
for (const [peer, s] of this.peers) {
|
|
72
|
+
if (s.units + (t - s.at) >= CAPACITY_UNITS) this.peers.delete(peer);
|
|
73
|
+
}
|
|
74
|
+
while (this.peers.size >= MAX_LIMITER_PEERS) this.peers.delete(this.peers.keys().next().value as string);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* After a 413 the rest of the upload is drained (and discarded) so the refusal reaches the client, but only for a
|
|
80
|
+
* bounded time: an endless chunked body must not pin the connection. Destroyed once `ms` elapses unless it ended.
|
|
81
|
+
*/
|
|
82
|
+
function boundedDrain(raw: IncomingMessage, ms: number): void {
|
|
83
|
+
if (raw.readableEnded || raw.destroyed) return;
|
|
84
|
+
const timer = setTimeout(() => raw.destroy(), ms);
|
|
85
|
+
timer.unref?.();
|
|
86
|
+
const clear = () => clearTimeout(timer);
|
|
87
|
+
raw.once("end", clear);
|
|
88
|
+
raw.once("close", clear);
|
|
89
|
+
raw.resume();
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
type ReadResult = { kind: "ok"; body: Buffer } | { kind: "too-large" } | { kind: "timeout" } | { kind: "aborted" };
|
|
93
|
+
|
|
94
|
+
/** Read at most `cap` bytes of `raw`, counting what arrives; stops listening at the cap or the deadline. */
|
|
95
|
+
function readCapped(
|
|
96
|
+
raw: IncomingMessage,
|
|
97
|
+
cap: number,
|
|
98
|
+
deadlineMs: number,
|
|
99
|
+
onBytes?: (total: number) => void,
|
|
100
|
+
): Promise<ReadResult> {
|
|
101
|
+
return new Promise((resolve) => {
|
|
102
|
+
const chunks: Buffer[] = [];
|
|
103
|
+
let total = 0;
|
|
104
|
+
let settled = false;
|
|
105
|
+
const finish = (r: ReadResult) => {
|
|
106
|
+
if (settled) return;
|
|
107
|
+
settled = true;
|
|
108
|
+
clearTimeout(timer);
|
|
109
|
+
raw.off("data", onData);
|
|
110
|
+
raw.off("end", onEnd);
|
|
111
|
+
raw.off("error", onAbort);
|
|
112
|
+
raw.off("aborted", onAbort);
|
|
113
|
+
raw.off("close", onAbort);
|
|
114
|
+
// Keep draining (and discarding) what the client still sends, so the refusal reaches it and the
|
|
115
|
+
// connection stays usable; nothing is buffered or counted from here on.
|
|
116
|
+
raw.resume();
|
|
117
|
+
onBytes?.(total);
|
|
118
|
+
if (r.kind === "too-large") boundedDrain(raw, deadlineMs);
|
|
119
|
+
resolve(r);
|
|
120
|
+
};
|
|
121
|
+
const onData = (c: Buffer | string) => {
|
|
122
|
+
const b = typeof c === "string" ? Buffer.from(c) : c;
|
|
123
|
+
total += b.length;
|
|
124
|
+
if (total > cap) return finish({ kind: "too-large" });
|
|
125
|
+
chunks.push(b);
|
|
126
|
+
};
|
|
127
|
+
const onEnd = () => finish({ kind: "ok", body: Buffer.concat(chunks) });
|
|
128
|
+
const onAbort = () => finish({ kind: "aborted" });
|
|
129
|
+
const timer = setTimeout(() => finish({ kind: "timeout" }), deadlineMs);
|
|
130
|
+
timer.unref?.();
|
|
131
|
+
if (raw.readableEnded) return finish({ kind: "ok", body: Buffer.alloc(0) });
|
|
132
|
+
raw.on("data", onData);
|
|
133
|
+
raw.on("end", onEnd);
|
|
134
|
+
raw.on("error", onAbort);
|
|
135
|
+
raw.on("aborted", onAbort);
|
|
136
|
+
raw.on("close", onAbort);
|
|
137
|
+
raw.resume();
|
|
138
|
+
});
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
const str = (v: unknown): string | undefined => (typeof v === "string" && v.length > 0 ? v : undefined);
|
|
142
|
+
const isObj = (v: unknown): v is Record<string, unknown> => !!v && typeof v === "object" && !Array.isArray(v);
|
|
143
|
+
|
|
144
|
+
/**
|
|
145
|
+
* The report objects in a parsed body: legacy `{ "csp-report": {…} }`, or a Reporting API
|
|
146
|
+
* array (or single element) of `{ type: "csp-violation", body: {…} }`. `null` = not a CSP report.
|
|
147
|
+
*/
|
|
148
|
+
function extractReports(json: unknown): Record<string, unknown>[] | null {
|
|
149
|
+
const items = Array.isArray(json) ? json : [json];
|
|
150
|
+
const out: Record<string, unknown>[] = [];
|
|
151
|
+
for (const it of items) {
|
|
152
|
+
if (!isObj(it)) continue;
|
|
153
|
+
if (isObj(it["csp-report"])) out.push(it["csp-report"]);
|
|
154
|
+
else if (isObj(it.body) && (it.type === undefined || it.type === "csp-violation")) out.push(it.body);
|
|
155
|
+
}
|
|
156
|
+
return out.length > 0 ? out : null;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** The report objects in a request body, or `null` when it is not JSON or not a CSP report. */
|
|
160
|
+
function parseReports(body: Buffer): Record<string, unknown>[] | null {
|
|
161
|
+
try {
|
|
162
|
+
return extractReports(JSON.parse(body.toString("utf8")));
|
|
163
|
+
} catch {
|
|
164
|
+
return null;
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/** `effective-directive` / `effectiveDirective`, else the first token of `violated-directive`; lowercased. */
|
|
169
|
+
function directiveOf(r: Record<string, unknown>): string {
|
|
170
|
+
const eff = str(r["effective-directive"]) ?? str(r.effectiveDirective);
|
|
171
|
+
if (eff) return eff.trim().toLowerCase();
|
|
172
|
+
const violated = str(r["violated-directive"]) ?? str(r.violatedDirective);
|
|
173
|
+
return violated?.trim().split(/\s+/)[0]?.toLowerCase() ?? "";
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
/** Path (no query/fragment) of the report's document, or undefined. */
|
|
177
|
+
function documentPathOf(r: Record<string, unknown>): string | undefined {
|
|
178
|
+
const uri = str(r["document-uri"]) ?? str(r.documentURL) ?? str(r.documentUri);
|
|
179
|
+
if (!uri) return undefined;
|
|
180
|
+
try {
|
|
181
|
+
return new URL(uri).pathname;
|
|
182
|
+
} catch {
|
|
183
|
+
return undefined;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
export interface CspReportSinkDeps {
|
|
188
|
+
store: CspReportStore;
|
|
189
|
+
/** Guards the operator reset route (the sink itself is unauthenticated by design). */
|
|
190
|
+
networkGuard: NetworkGuard;
|
|
191
|
+
/** Clock for the limiter and the log throttle (default `Date.now`). */
|
|
192
|
+
now?: () => number;
|
|
193
|
+
/** Body read deadline (default {@link BODY_DEADLINE_MS}). */
|
|
194
|
+
bodyDeadlineMs?: number;
|
|
195
|
+
/** Log sink for the throttled violation line (default `console.warn`). */
|
|
196
|
+
log?: (msg: string) => void;
|
|
197
|
+
/** Observer: total bytes the sink read for one request (test/ops hook; never carries content). */
|
|
198
|
+
onBodyRead?: (bytes: number) => void;
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
function refuse(reply: FastifyReply, code: number, error: string, closeConnection = false): FastifyReply {
|
|
202
|
+
// Only a stalled body (408) ends the connection; draining a trickle would hold it for as long as the client likes.
|
|
203
|
+
if (closeConnection) reply.header("connection", "close");
|
|
204
|
+
return reply.code(code).send({ error });
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Register the sink (encapsulated scope) and the operator reset route on `fastify`.
|
|
209
|
+
* The store is flushed when the server closes. The handle exposes the limiter's tracked-peer count (tests/ops).
|
|
210
|
+
*/
|
|
211
|
+
export function registerCspReportSink(fastify: FastifyInstance, deps: CspReportSinkDeps): { trackedPeers(): number } {
|
|
212
|
+
const { store, networkGuard } = deps;
|
|
213
|
+
const now = deps.now ?? Date.now;
|
|
214
|
+
const deadline = deps.bodyDeadlineMs ?? BODY_DEADLINE_MS;
|
|
215
|
+
const log = deps.log ?? ((m: string) => console.warn(m));
|
|
216
|
+
const limiter = new PeerLimiter(now);
|
|
217
|
+
const lastLogged = new Map<string, number>();
|
|
218
|
+
|
|
219
|
+
const logViolation = (policy: CspReportPolicy, directive: string) => {
|
|
220
|
+
const key = `${policy}\u0000${directive}`;
|
|
221
|
+
const t = now();
|
|
222
|
+
const prev = lastLogged.get(key);
|
|
223
|
+
if (prev !== undefined && t - prev < LOG_THROTTLE_MS) return;
|
|
224
|
+
if (lastLogged.size >= MAX_LOG_KEYS) lastLogged.clear();
|
|
225
|
+
lastLogged.set(key, t);
|
|
226
|
+
log(`[csp] violation policy=${policy} directive=${directive}`);
|
|
227
|
+
};
|
|
228
|
+
|
|
229
|
+
fastify.addHook("onClose", async () => store.close());
|
|
230
|
+
|
|
231
|
+
fastify.register(async (scope) => {
|
|
232
|
+
// This scope owns body handling: drop whatever parsers the root (or the live sink) registered
|
|
233
|
+
// and hand the raw stream to the handler, which reads it with its own counting reader.
|
|
234
|
+
scope.removeAllContentTypeParsers();
|
|
235
|
+
scope.addContentTypeParser("*", (_req, payload, done) => done(null, payload));
|
|
236
|
+
|
|
237
|
+
/** Refusals on the request line: 404 (label) → 405 (method) → 429 (limiter). */
|
|
238
|
+
const admit = (request: FastifyRequest, reply: FastifyReply, policy: string): FastifyReply | null => {
|
|
239
|
+
if (!isCspReportPolicy(policy)) return refuse(reply, 404, "not found");
|
|
240
|
+
if (request.method !== "POST") {
|
|
241
|
+
reply.header("allow", "POST");
|
|
242
|
+
return refuse(reply, 405, "method not allowed");
|
|
243
|
+
}
|
|
244
|
+
if (limiter.take(request.socket?.remoteAddress ?? request.ip)) return null;
|
|
245
|
+
store.recordDropped();
|
|
246
|
+
return refuse(reply, 429, "too many reports");
|
|
247
|
+
};
|
|
248
|
+
|
|
249
|
+
/** Refusals from the headers, before the body is read: 415 → compressed 400 → declared-size 413. */
|
|
250
|
+
const screen = (request: FastifyRequest, reply: FastifyReply): FastifyReply | null => {
|
|
251
|
+
const mediaType = String(request.headers["content-type"] ?? "").split(";")[0]?.trim().toLowerCase() ?? "";
|
|
252
|
+
if (!REPORT_TYPES.has(mediaType)) return refuse(reply, 415, "unsupported media type");
|
|
253
|
+
const encoding = String(request.headers["content-encoding"] ?? "").trim().toLowerCase();
|
|
254
|
+
if (encoding && encoding !== "identity") return refuse(reply, 400, "invalid report");
|
|
255
|
+
const declared = Number(request.headers["content-length"]);
|
|
256
|
+
if (!Number.isFinite(declared) || declared <= CSP_REPORT_MAX_BYTES) return null;
|
|
257
|
+
deps.onBodyRead?.(0);
|
|
258
|
+
store.recordDropped();
|
|
259
|
+
boundedDrain(request.raw, deadline);
|
|
260
|
+
return refuse(reply, 413, "report too large");
|
|
261
|
+
};
|
|
262
|
+
|
|
263
|
+
/** The reply for a body read that did not complete. */
|
|
264
|
+
const refuseUnfinished = (reply: FastifyReply, kind: "too-large" | "timeout" | "aborted"): FastifyReply => {
|
|
265
|
+
// Client went away: nothing counted; the reply goes nowhere.
|
|
266
|
+
if (kind === "aborted") return reply.code(400).send();
|
|
267
|
+
store.recordDropped();
|
|
268
|
+
return kind === "too-large" ? refuse(reply, 413, "report too large") : refuse(reply, 408, "request timeout", true);
|
|
269
|
+
};
|
|
270
|
+
|
|
271
|
+
scope.route({
|
|
272
|
+
method: [...SINK_METHODS],
|
|
273
|
+
url: `${CSP_REPORT_PREFIX}:policy`,
|
|
274
|
+
handler: async (request: FastifyRequest, reply: FastifyReply) => {
|
|
275
|
+
const { policy } = request.params as { policy: string };
|
|
276
|
+
const early = admit(request, reply, policy) ?? screen(request, reply);
|
|
277
|
+
if (early) return early;
|
|
278
|
+
|
|
279
|
+
const read = await readCapped(request.raw, CSP_REPORT_MAX_BYTES, deadline, deps.onBodyRead);
|
|
280
|
+
if (read.kind !== "ok") return refuseUnfinished(reply, read.kind);
|
|
281
|
+
|
|
282
|
+
const reports = parseReports(read.body);
|
|
283
|
+
if (!reports) return refuse(reply, 400, "invalid report");
|
|
284
|
+
for (const r of reports) {
|
|
285
|
+
const directive = directiveOf(r);
|
|
286
|
+
store.record(policy as CspReportPolicy, directive, documentPathOf(r));
|
|
287
|
+
// Log the allow-set form only, never report text.
|
|
288
|
+
logViolation(policy as CspReportPolicy, normalizeDirective(directive));
|
|
289
|
+
}
|
|
290
|
+
return reply.code(204).send();
|
|
291
|
+
},
|
|
292
|
+
});
|
|
293
|
+
});
|
|
294
|
+
|
|
295
|
+
// Operator reset: tier `operate` (route-tiers.ts), behind the network guard like every /api route.
|
|
296
|
+
fastify.post("/api/csp-reports/reset", { preHandler: networkGuard }, async () => ({
|
|
297
|
+
success: true,
|
|
298
|
+
since: store.reset(),
|
|
299
|
+
}));
|
|
300
|
+
|
|
301
|
+
return { trackedPeers: () => limiter.size };
|
|
302
|
+
}
|