Refresh HiveGrid Cloud reference snapshot

This commit is contained in:
david committed 2026-08-03 15:31:14 +02:00
1 parent 5e99e14772
commit 7f88026f79
5955 files changed
+1177325 -188362

No files matched your search

@@ -0,0 +1,125 @@
import { describe, expect, it } from "vitest";
import {
CSP_NONCE_REQUEST_HEADER,
SERVICE_WORKER_CONTENT_SECURITY_POLICY,
STATIC_ASSET_CONTENT_SECURITY_POLICY,
buildDocumentContentSecurityPolicy,
contentSecurityPolicyAllowsExternalFraming,
getRequestCspNonce,
isValidCspNonce,
} from "./contentSecurityPolicy";
const NONCE = "aBcDeFgHiJkLmNoPqRsTuVwX";
describe("document Content-Security-Policy", () => {
it("binds executable scripts to the request nonce and supplies every resource directive", () => {
const policy = buildDocumentContentSecurityPolicy(NONCE);
expect(policy).toContain(`script-src 'self' 'nonce-${NONCE}' 'strict-dynamic' 'wasm-unsafe-eval'`);
expect(policy).toContain("script-src-attr 'none'");
expect(policy).toContain("worker-src 'self' blob:");
expect(policy).not.toContain("worker-src 'self' blob: https:");
expect(policy).toContain("style-src 'self' 'unsafe-inline'");
for (const directive of [
"default-src",
"connect-src",
"img-src",
"font-src",
"frame-src",
"worker-src",
"media-src",
"manifest-src",
"base-uri",
"object-src",
"form-action",
"frame-ancestors",
]) {
expect(policy).toMatch(new RegExp(`(?:^|; )${directive} `, "u"));
}
expect(policy).not.toContain("'unsafe-eval'");
expect(policy).not.toContain("script-src 'unsafe-inline'");
});
it("keeps the booking embed exception while retaining the complete policy", () => {
const policy = buildDocumentContentSecurityPolicy(
NONCE,
"base-uri 'self'; object-src 'none'; form-action 'self'; script-src-attr 'none'; frame-ancestors *"
);
expect(policy).toContain("frame-ancestors *");
expect(policy).toContain(`script-src 'self' 'nonce-${NONCE}' 'strict-dynamic' 'wasm-unsafe-eval'`);
expect(contentSecurityPolicyAllowsExternalFraming(policy)).toBe(true);
});
it("restricts authenticated browser connections to exact validated origins", () => {
const policy = buildDocumentContentSecurityPolicy(NONCE, undefined, {
surface: "authenticated",
authenticatedConnectSources: [
"https://api.example.test",
"https://public@sentry.example.test/1",
"wss://collab.example.test",
"https://otel.example.test/path",
"https://api.example.test",
],
});
const connectSource = policy.match(/(?:^|; )connect-src ([^;]+)/u)?.[1];
expect(connectSource).toBe("'self' https://api.example.test wss://collab.example.test");
expect(connectSource?.split(" ")).not.toContain("https:");
expect(connectSource?.split(" ")).not.toContain("wss:");
expect(policy).toContain("font-src 'self' data:");
// Tenant-configured images, media and onboarding embeds remain compatible
// until those persisted URLs have their own origin registry/proxy.
expect(policy).toContain("img-src 'self' data: blob: https:");
expect(policy).toContain("frame-src 'self' https:");
expect(policy).toContain("media-src 'self' data: blob: https:");
});
it("does not let route policies broaden authenticated destination lists", () => {
const policy = buildDocumentContentSecurityPolicy(NONCE, "connect-src 'self' https: wss:; font-src 'self' data: https:; worker-src 'none'", {
surface: "authenticated",
authenticatedConnectSources: ["https://api.example.test"],
});
expect(policy).toContain("connect-src 'self' https://api.example.test");
expect(policy).toContain("font-src 'self' data:");
expect(policy).toContain("worker-src 'none'");
});
it("retains plugin route restrictions without accepting a weaker script policy", () => {
const policy = buildDocumentContentSecurityPolicy(
NONCE,
"default-src 'self'; script-src 'self' 'unsafe-inline'; connect-src 'self'; img-src 'self' data: blob:; worker-src 'none'; media-src 'none'; manifest-src 'none'; navigate-to 'self'"
);
expect(policy).toContain(`script-src 'self' 'nonce-${NONCE}' 'strict-dynamic' 'wasm-unsafe-eval'`);
expect(policy.match(/(?:^|; )script-src ([^;]+)/u)?.[1]).not.toContain("'unsafe-inline'");
expect(policy).toContain("connect-src 'self'");
expect(policy).toContain("worker-src 'none'");
expect(policy).toContain("media-src 'none'");
expect(policy).toContain("manifest-src 'none'");
expect(policy).toContain("navigate-to 'self'");
});
it("rejects malformed nonces instead of interpolating attacker-controlled policy text", () => {
expect(isValidCspNonce("attacker'; script-src *")).toBe(false);
expect(() => buildDocumentContentSecurityPolicy("attacker'; script-src *")).toThrow(/invalid format/u);
expect(getRequestCspNonce(new Request("https://example.test", { headers: { [CSP_NONCE_REQUEST_HEADER]: "spoofed" } }))).toBeUndefined();
});
it("uses a nonce-free deny-by-default policy for static assets", () => {
expect(STATIC_ASSET_CONTENT_SECURITY_POLICY).toContain("default-src 'none'");
expect(STATIC_ASSET_CONTENT_SECURITY_POLICY).toContain("script-src 'none'");
expect(STATIC_ASSET_CONTENT_SECURITY_POLICY).toContain("connect-src 'none'");
expect(STATIC_ASSET_CONTENT_SECURITY_POLICY).not.toContain("nonce-");
});
it("allows only same-origin connections from the service worker", () => {
expect(SERVICE_WORKER_CONTENT_SECURITY_POLICY).toBe(
STATIC_ASSET_CONTENT_SECURITY_POLICY.replace("connect-src 'none'", "connect-src 'self'")
);
expect(SERVICE_WORKER_CONTENT_SECURITY_POLICY).toContain("connect-src 'self'");
expect(SERVICE_WORKER_CONTENT_SECURITY_POLICY).not.toContain("connect-src 'none'");
});
});
@@ -0,0 +1,184 @@
export const CSP_NONCE_REQUEST_HEADER = "x-hivegrid-csp-nonce";
const CSP_NONCE_PATTERN = /^[A-Za-z0-9_-]{24}$/u;
export type DocumentContentSecurityPolicyOptions = {
surface?: "public" | "authenticated";
authenticatedConnectSources?: readonly string[];
};
const DOCUMENT_DIRECTIVES: ReadonlyArray<readonly [string, string]> = [
["default-src", "'self'"],
["script-src", "'self'"],
["script-src-attr", "'none'"],
["style-src", "'self' 'unsafe-inline'"],
["connect-src", "'self' https: wss:"],
["img-src", "'self' data: blob: https:"],
["font-src", "'self' data: https:"],
["frame-src", "'self' https:"],
["worker-src", "'self' blob:"],
["media-src", "'self' data: blob: https:"],
["manifest-src", "'self'"],
["base-uri", "'self'"],
["object-src", "'none'"],
["form-action", "'self'"],
["frame-ancestors", "'self'"],
];
const ROUTE_OVERRIDE_DIRECTIVES = new Set([
"default-src",
"style-src",
"connect-src",
"img-src",
"font-src",
"frame-src",
"child-src",
"worker-src",
"media-src",
"manifest-src",
"frame-ancestors",
"navigate-to",
]);
export const STATIC_ASSET_CONTENT_SECURITY_POLICY = [
"default-src 'none'",
"script-src 'none'",
"script-src-attr 'none'",
"style-src 'none'",
"connect-src 'none'",
"img-src 'self' data:",
"font-src 'self' data:",
"frame-src 'none'",
"worker-src 'none'",
"media-src 'none'",
"manifest-src 'none'",
"base-uri 'none'",
"object-src 'none'",
"form-action 'none'",
"frame-ancestors 'none'",
].join("; ");
export const SERVICE_WORKER_CONTENT_SECURITY_POLICY = STATIC_ASSET_CONTENT_SECURITY_POLICY.replace(
"connect-src 'none'",
"connect-src 'self'"
);
export function isValidCspNonce(value: string | null | undefined): value is string {
return typeof value === "string" && CSP_NONCE_PATTERN.test(value);
}
export function getRequestCspNonce(request: Request): string | undefined {
const nonce = request.headers.get(CSP_NONCE_REQUEST_HEADER);
return isValidCspNonce(nonce) ? nonce : undefined;
}
export function getCspNonceFromHeaders(...headers: Headers[]): string | undefined {
for (const candidate of headers) {
const nonce = candidate.get(CSP_NONCE_REQUEST_HEADER);
if (isValidCspNonce(nonce)) {
return nonce;
}
}
return undefined;
}
/**
* Builds the document policy from a server-generated nonce. Route policies may
* tighten resource destinations and frame ancestry, but they can never replace
* the nonce-bearing script policy or weaken base/object/form protections.
*/
export function buildDocumentContentSecurityPolicy(nonce: string, routePolicy?: string | null, options: DocumentContentSecurityPolicyOptions = {}): string {
if (!isValidCspNonce(nonce)) {
throw new Error("Document CSP nonce has an invalid format.");
}
const directives = new Map<string, string>(DOCUMENT_DIRECTIVES);
if (options.surface === "authenticated") {
directives.set("connect-src", ["'self'", ...normalizeCspSourceExpressions(options.authenticatedConnectSources)].join(" "));
directives.set("font-src", "'self' data:");
}
for (const [name, value] of parseRoutePolicy(routePolicy)) {
if (ROUTE_OVERRIDE_DIRECTIVES.has(name) && routeOverrideDoesNotBroadenAuthenticatedPolicy(name, value, directives, options.surface)) {
directives.set(name, value);
}
}
// The self-hosted Cap challenge compiles its proof-of-work engine as
// WebAssembly. `wasm-unsafe-eval` permits only Wasm compilation (not
// JavaScript eval) and keeps the nonce + strict-dynamic script boundary.
directives.set("script-src", `'self' 'nonce-${nonce}' 'strict-dynamic' 'wasm-unsafe-eval'`);
directives.set("script-src-attr", "'none'");
directives.set("base-uri", "'self'");
directives.set("object-src", "'none'");
directives.set("form-action", "'self'");
return [...directives].map(([name, value]) => `${name} ${value}`).join("; ");
}
/**
* Turns validated URL origins into CSP source expressions. Callers still own
* URL/protocol validation; this final boundary rejects policy syntax instead
* of interpolating an environment value into the response header.
*/
export function normalizeCspSourceExpressions(values: readonly string[] | null | undefined): string[] {
const sources = new Set<string>();
for (const value of values ?? []) {
const candidate = value.trim();
if (/^(?:https?|wss?):\/\/[A-Za-z0-9.[\]:_-]+$/u.test(candidate)) {
sources.add(candidate);
}
}
return [...sources].sort();
}
export function contentSecurityPolicyAllowsExternalFraming(policy: string): boolean {
const frameAncestors = parseRoutePolicy(policy).find(([name]) => name === "frame-ancestors")?.[1];
return frameAncestors !== undefined && frameAncestors !== "'self'" && frameAncestors !== "'none'";
}
function parseRoutePolicy(policy: string | null | undefined): Array<readonly [string, string]> {
if (!policy) {
return [];
}
const directives: Array<readonly [string, string]> = [];
for (const rawDirective of policy.split(";")) {
const directive = rawDirective.trim();
if (!directive) continue;
const separatorIndex = directive.search(/\s/u);
if (separatorIndex <= 0) continue;
const name = directive.slice(0, separatorIndex).toLowerCase();
const value = directive.slice(separatorIndex).trim().replace(/\s+/gu, " ");
if (!value || !/^[a-z][a-z0-9-]*$/u.test(name)) continue;
directives.push([name, value]);
}
return directives;
}
function routeOverrideDoesNotBroadenAuthenticatedPolicy(
name: string,
value: string,
directives: ReadonlyMap<string, string>,
surface: DocumentContentSecurityPolicyOptions["surface"]
): boolean {
if (surface !== "authenticated") return true;
const baseValue = directives.get(name);
if (!baseValue) return true;
return isCspSourceListSubset(value, baseValue);
}
function isCspSourceListSubset(candidateValue: string, baseValue: string): boolean {
const candidateSources = candidateValue.split(/\s+/u);
const baseSources = new Set(baseValue.split(/\s+/u));
if (candidateSources.length === 1 && candidateSources[0] === "'none'") return true;
if (candidateSources.includes("'none'")) return false;
return candidateSources.every((candidate) => {
if (baseSources.has(candidate) || baseSources.has("*")) return true;
if (candidate.startsWith("https://") && baseSources.has("https:")) return true;
if (candidate.startsWith("http://") && baseSources.has("http:")) return true;
if (candidate.startsWith("wss://") && baseSources.has("wss:")) return true;
if (candidate.startsWith("ws://") && baseSources.has("ws:")) return true;
return false;
});
}
@@ -0,0 +1,24 @@
// @vitest-environment jsdom
import { describe, expect, it } from "vitest";
import { getCurrentDocumentCspNonce } from "./documentCspNonce";
describe("document CSP nonce", () => {
it("reads the browser nonce property from a trusted document script", () => {
const script = document.createElement("script");
script.nonce = "aBcDeFgHiJkLmNoPqRsTuVwX";
document.head.appendChild(script);
expect(getCurrentDocumentCspNonce(document)).toBe(script.nonce);
script.remove();
});
it("ignores malformed nonce attributes", () => {
const script = document.createElement("script");
script.nonce = "spoofed";
document.head.appendChild(script);
expect(getCurrentDocumentCspNonce(document)).toBeUndefined();
script.remove();
});
});
@@ -0,0 +1,7 @@
import { isValidCspNonce } from "./contentSecurityPolicy";
/** Reads the browser-normalized nonce property from an already trusted script. */
export function getCurrentDocumentCspNonce(documentRef: Document): string | undefined {
const nonce = documentRef.querySelector<HTMLScriptElement>("script[nonce]")?.nonce;
return isValidCspNonce(nonce) ? nonce : undefined;
}
@@ -0,0 +1,141 @@
import { describe, expect, it } from "vitest";
import { getRequestDocumentContentSecurityPolicyOptions, isAuthenticatedDocumentRequest } from "./requestContentSecurityPolicy.server";
const webConfig = {
routing: {
protocol: "https" as const,
apiHost: "api.example.test",
appBaseDomain: "example.test",
webAppHost: "app.example.test",
adminAppHost: "admin.example.test",
},
storage: {
endpoint: "https://s3.example.test/path",
publicBaseUrl: "https://cdn.example.test/files",
localPublicBaseUrl: "http://localhost:3000/storage",
},
};
describe("request-scoped document CSP", () => {
it("uses the canonical host context for tenant and admin documents", () => {
expect(isAuthenticatedDocumentRequest(new Request("https://app.example.test/acme/dashboard"), webConfig.routing)).toBe(true);
expect(isAuthenticatedDocumentRequest(new Request("https://app.example.test/app/acme/dashboard"), webConfig.routing)).toBe(true);
expect(isAuthenticatedDocumentRequest(new Request("https://admin.example.test/dashboard"), webConfig.routing)).toBe(true);
expect(isAuthenticatedDocumentRequest(new Request("https://admin.example.test/admin/dashboard"), webConfig.routing)).toBe(true);
expect(isAuthenticatedDocumentRequest(new Request("https://example.test/acme/dashboard"), webConfig.routing)).toBe(false);
expect(isAuthenticatedDocumentRequest(new Request("https://api.example.test/acme/dashboard"), webConfig.routing)).toBe(false);
});
it("uses the trusted forwarded routing host behind the web proxy", () => {
const request = new Request("https://example.test/acme/dashboard", {
headers: {
host: "example.test",
"x-forwarded-host": "app.example.test",
},
});
expect(isAuthenticatedDocumentRequest(request, webConfig.routing)).toBe(true);
});
it("keeps public, auth, marketing and embed documents on the compatibility policy", () => {
const publicUrls = [
"https://app.example.test/",
"https://app.example.test/login",
"https://app.example.test/auth/magic-link",
"https://admin.example.test/login",
"https://admin.example.test/auth/admin/callback",
"https://app.example.test/docs/de/start",
"https://app.example.test/help",
"https://app.example.test/optin/token_1",
"https://app.example.test/unsubscribe/token_1",
"https://app.example.test/sign/token_1",
"https://app.example.test/b/acme/consulting",
"https://app.example.test/b/acme/consulting/embed",
"https://app.example.test/f/acme/contact",
"https://app.example.test/embed/forms/form_1",
];
for (const url of publicUrls) {
expect(isAuthenticatedDocumentRequest(new Request(url), webConfig.routing), url).toBe(false);
}
expect(isAuthenticatedDocumentRequest(new Request("https://app.example.test/optin-customer/dashboard"), webConfig.routing)).toBe(true);
expect(isAuthenticatedDocumentRequest(new Request("https://app.example.test/integrations/dashboard"), webConfig.routing)).toBe(true);
expect(isAuthenticatedDocumentRequest(new Request("https://app.example.test/b/dashboard"), webConfig.routing)).toBe(true);
});
it("allows only exact API, Sentry, OTel, storage and collaboration origins", () => {
const options = getRequestDocumentContentSecurityPolicyOptions(
new Request("https://app.example.test/acme/dashboard"),
webConfig,
{
SENTRY_DSN_WEB: "https://server@sentry-fallback.example.test/2",
},
{
VITE_SENTRY_DSN_WEB: "https://browser@sentry.example.test/1",
VITE_OTEL_EXPORTER_OTLP_ENDPOINT: "https://otel.example.test/v1/traces",
VITE_HOCUSPOCUS_URL: "wss://collab.example.test/socket",
}
);
expect(options).toEqual({
surface: "authenticated",
authenticatedConnectSources: [
"https://api.example.test",
"https://sentry.example.test",
"https://otel.example.test",
"https://s3.example.test",
"https://cdn.example.test",
"http://localhost:3000",
"wss://api.example.test",
"wss://collab.example.test",
],
});
});
it("fails closed for malformed, non-network and insecure remote endpoints", () => {
const options = getRequestDocumentContentSecurityPolicyOptions(
new Request("https://admin.example.test/admin/dashboard"),
{
...webConfig,
storage: {
endpoint: "javascript:alert(1)",
publicBaseUrl: "https://safe.example.test; img-src *",
localPublicBaseUrl: "http://remote.example.test/files",
},
},
{},
{
VITE_SENTRY_DSN_WEB: "not a url",
VITE_OTEL_EXPORTER_OTLP_ENDPOINT: "file:///tmp/traces",
VITE_HOCUSPOCUS_URL: "ws://remote.example.test/socket",
}
);
expect(options).toEqual({
surface: "authenticated",
authenticatedConnectSources: ["https://api.example.test", "wss://api.example.test"],
});
});
it("allows the exact local API WebSocket origin without opening remote insecure sockets", () => {
const options = getRequestDocumentContentSecurityPolicyOptions(new Request("http://app.localhost:3000/acme/chat"), {
...webConfig,
routing: {
...webConfig.routing,
protocol: "http",
apiHost: "api.localhost:3001",
webAppHost: "app.localhost:3000",
adminAppHost: "admin.localhost:3000",
},
});
expect(options.authenticatedConnectSources).toContain("ws://api.localhost:3001");
expect(options.authenticatedConnectSources).not.toContain("ws:");
});
it("keeps public surfaces on their compatibility policy", () => {
expect(getRequestDocumentContentSecurityPolicyOptions(new Request("https://app.example.test/login"), webConfig)).toEqual({ surface: "public" });
});
});
@@ -0,0 +1,83 @@
import type { DomainRoutingConfig, WebConfig } from "@hivegrid/config";
import { getHostRoutingContext, getRequestRoutingHost } from "../app/HostRouting.server";
import { isWebRoutePath, normalizeRoutePath } from "../app/PublicRouteSegments";
import type { DocumentContentSecurityPolicyOptions } from "./contentSecurityPolicy";
type CspEnvironment = Record<string, string | undefined>;
const PUBLIC_DOCUMENT_COMPATIBILITY_ROUTES = [
/^\/b\/[^/]+\/[^/]+(?:\/embed)?\/?$/u,
/^\/e\/(?:c|o)\/[^/]+\/?$/u,
/^\/email\/track-(?:click|open)\/[^/]+\/?$/u,
/^\/embed\/forms\/[^/]+\/?$/u,
/^\/f\/[^/]+\/[^/]+\/?$/u,
/^\/help(?:\/|$)/u,
/^\/integrations\/(?:google\/oauth\/callback|email\/(?:google|microsoft)\/oauth\/callback)\/?$/u,
/^\/(?:optin|sign|unsubscribe)\/[^/]+\/?$/u,
] as const;
export function getRequestDocumentContentSecurityPolicyOptions(
request: Request,
webConfig: Pick<WebConfig, "routing" | "storage">,
runtimeEnv: CspEnvironment = process.env,
buildEnv: CspEnvironment = {}
): DocumentContentSecurityPolicyOptions {
if (!isAuthenticatedDocumentRequest(request, webConfig.routing)) {
return { surface: "public" };
}
const readPublicEnv = (name: string) => buildEnv[name]?.trim() || runtimeEnv[name]?.trim();
const httpUrls = [
`${webConfig.routing.protocol}://${webConfig.routing.apiHost}`,
readPublicEnv("VITE_SENTRY_DSN_WEB") ?? readPublicEnv("SENTRY_DSN_WEB"),
readPublicEnv("VITE_OTEL_EXPORTER_OTLP_ENDPOINT"),
webConfig.storage.endpoint,
webConfig.storage.publicBaseUrl,
webConfig.storage.localPublicBaseUrl,
];
const apiWebSocketUrl = `${webConfig.routing.protocol === "https" ? "wss" : "ws"}://${webConfig.routing.apiHost}`;
const webSocketUrls = [apiWebSocketUrl, readPublicEnv("VITE_HOCUSPOCUS_URL")];
return {
surface: "authenticated",
authenticatedConnectSources: [
...httpUrls.map((value) => toCspOrigin(value, "http")).filter((value): value is string => Boolean(value)),
...webSocketUrls.map((value) => toCspOrigin(value, "websocket")).filter((value): value is string => Boolean(value)),
],
};
}
export function isAuthenticatedDocumentRequest(request: Request, routing: DomainRoutingConfig): boolean {
const url = new URL(request.url);
const context = getHostRoutingContext(getRequestRoutingHost(request, url, routing), routing);
if (context !== "app" && context !== "admin") {
return false;
}
const pathname = normalizeRoutePath(url.pathname);
if (pathname === "/" || isWebRoutePath(pathname)) {
return false;
}
return !PUBLIC_DOCUMENT_COMPATIBILITY_ROUTES.some((routePattern) => routePattern.test(pathname));
}
function toCspOrigin(value: string | undefined, kind: "http" | "websocket"): string | undefined {
if (!value) return undefined;
try {
const url = new URL(value);
const secureProtocol = kind === "http" ? "https:" : "wss:";
const insecureProtocol = kind === "http" ? "http:" : "ws:";
if (url.protocol !== secureProtocol && !(url.protocol === insecureProtocol && isLoopbackHostname(url.hostname))) {
return undefined;
}
return url.origin === "null" ? undefined : url.origin;
} catch {
return undefined;
}
}
function isLoopbackHostname(hostname: string): boolean {
const normalized = hostname.toLowerCase().replace(/^\[|\]$/gu, "");
return normalized === "localhost" || normalized.endsWith(".localhost") || normalized === "::1" || /^127(?:\.\d{1,3}){3}$/u.test(normalized);
}