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,23 @@
import { describe, expect, it } from "vitest";
import { CSP_NONCE_REQUEST_HEADER } from "../apps/web/app/utils/security/contentSecurityPolicy";
import { createRequestCspNonce, overwriteRequestCspNonce } from "./csp";
describe("request CSP nonce", () => {
it("creates a cryptographically random nonce for every request", () => {
const nonces = new Set(Array.from({ length: 64 }, () => createRequestCspNonce()));
expect(nonces.size).toBe(64);
for (const nonce of nonces) {
expect(nonce).toMatch(/^[A-Za-z0-9_-]{24}$/u);
}
});
it("overwrites a spoofed incoming internal header", () => {
const headers = new Headers({ [CSP_NONCE_REQUEST_HEADER]: "attacker-controlled" });
const trustedNonce = "aBcDeFgHiJkLmNoPqRsTuVwX";
expect(overwriteRequestCspNonce(headers, trustedNonce)).toBe(trustedNonce);
expect(headers.get(CSP_NONCE_REQUEST_HEADER)).toBe(trustedNonce);
});
});
@@ -0,0 +1,15 @@
import { randomBytes } from "node:crypto";
import { CSP_NONCE_REQUEST_HEADER, isValidCspNonce } from "../apps/web/app/utils/security/contentSecurityPolicy";
export function createRequestCspNonce(): string {
return randomBytes(18).toString("base64url");
}
export function overwriteRequestCspNonce(headers: Headers, nonce = createRequestCspNonce()): string {
if (!isValidCspNonce(nonce)) {
throw new Error("Request CSP nonce has an invalid format.");
}
headers.set(CSP_NONCE_REQUEST_HEADER, nonce);
return nonce;
}
@@ -1,6 +1,10 @@
// @vitest-environment node
import { describe, expect, test } from "vitest";
import { getHostRoutingRuntimeDecision } from "./host-routing-runtime";
import {
finalizePortalHostRoutingDecision,
finalizePortalTenantRoutingDecision,
getHostRoutingRuntimeDecision,
} from "./host-routing-runtime";
function expectDispatchDecision(request: Request) {
const decision = getHostRoutingRuntimeDecision(request);
@@ -11,7 +15,32 @@ function expectDispatchDecision(request: Request) {
return decision;
}
const adminOptions = { runtimeSurface: "admin" as const };
function expectAdminDispatchDecision(request: Request) {
const decision = getHostRoutingRuntimeDecision(request, adminOptions);
expect(decision.type).toBe("dispatch");
if (decision.type !== "dispatch") {
throw new Error(`Expected admin dispatch decision, received ${decision.type}`);
}
return decision;
}
describe("getHostRoutingRuntimeDecision", () => {
test("rejects unknown hosts instead of serving authenticated web routes on sibling or attacker domains", () => {
expect(getHostRoutingRuntimeDecision(new Request("https://untrusted.example/acme/dashboard"))).toEqual({
type: "reject",
status: 404,
});
expect(
getHostRoutingRuntimeDecision(
new Request("http://untrusted.example/acme/dashboard", {
headers: { host: "untrusted.example", "x-forwarded-host": "app.localhost" },
})
)
).toEqual({ type: "reject", status: 404 });
});
test("dispatches the canonical app host root to the tenant picker route", () => {
const decision = expectDispatchDecision(new Request("http://app.localhost/?from=login#tenants"));
@@ -21,6 +50,27 @@ describe("getHostRoutingRuntimeDecision", () => {
expect(new URL(decision.request.url).hash).toBe("#tenants");
});
test("isolates public sales bookings on the dedicated meeting host", () => {
const page = expectDispatchDecision(
new Request(
"http://meet.localhost/erstgespraech?date=2026-08-03#slots"
)
);
expect(page.target).toBe("web");
expect(new URL(page.request.url).pathname).toBe(
"/meet/erstgespraech"
);
expect(new URL(page.request.url).search).toBe("?date=2026-08-03");
expect(new URL(page.request.url).hash).toBe("#slots");
const asset = expectDispatchDecision(
new Request("http://meet.localhost/assets/entry.client-build.js")
);
expect(new URL(asset.request.url).pathname).toBe(
"/assets/entry.client-build.js"
);
});
test("keeps app host requests on promoted tenant paths for web dispatch", () => {
const decision = expectDispatchDecision(new Request("http://app.localhost/acme/dashboard?tab=activity#events"));
@@ -38,6 +88,24 @@ describe("getHostRoutingRuntimeDecision", () => {
expect(new URL(decision.request.url).search).toBe("?redirectTo=%2Facme%2Fdashboard");
});
test("dispatches registration plan advice through the allowed auth namespace", () => {
const decision = expectDispatchDecision(new Request("http://app.localhost/auth/registration-plan-advice?office=5&field=15"));
expect(decision.target).toBe("web");
expect(new URL(decision.request.url).pathname).toBe("/auth/registration-plan-advice");
expect(new URL(decision.request.url).search).toBe("?office=5&field=15");
});
test("dispatches the password-policy remind endpoint on the app host", () => {
// Regression guard: the banner's snooze endpoint moved from /api/* to
// /auth/* because removed-API rejection below 404s /api/* on this host.
const decision = expectDispatchDecision(new Request("http://app.localhost/auth/password-policy-remind", { method: "POST" }));
expect(decision.target).toBe("web");
expect(new URL(decision.request.url).pathname).toBe("/auth/password-policy-remind");
expect(decision.request.method).toBe("POST");
});
test("rejects removed public API paths instead of redirecting compatibility routes", () => {
const decision = getHostRoutingRuntimeDecision(new Request("http://app.localhost/api/workflows/run/workflow_1?tenantId=tenant_1"));
@@ -77,7 +145,7 @@ describe("getHostRoutingRuntimeDecision", () => {
});
test("dispatches canonical admin host requests for web dispatch", () => {
const decision = expectDispatchDecision(new Request("http://admin.localhost/accounts/users?role=owner#active"));
const decision = expectAdminDispatchDecision(new Request("http://admin.localhost/accounts/users?role=owner#active"));
expect(decision.target).toBe("web");
expect(new URL(decision.request.url).pathname).toBe("/accounts/users");
@@ -85,9 +153,59 @@ describe("getHostRoutingRuntimeDecision", () => {
expect(new URL(decision.request.url).hash).toBe("#active");
});
test.each([
"/assets/entry.client-build.js",
"/assets/root-build.css",
"/fonts/instrument-sans-latin.woff2",
"/images/placeholder.svg",
"/locales/de/translations.json",
"/android-chrome-192x192.png",
"/android-chrome-512x512.png",
"/android-icon-36x36.png",
"/android-icon-48x48.png",
"/android-icon-72x72.png",
"/android-icon-96x96.png",
"/android-icon-192x192.png",
"/apple-touch-icon.png",
"/browserconfig.xml",
"/favicon.ico",
"/favicon-16x16.png",
"/favicon-32x32.png",
"/favicon-96x96.png",
"/manifest.webmanifest",
"/ms-icon-70x70.png",
"/ms-icon-150x150.png",
"/ms-icon-310x310.png",
"/site.webmanifest",
"/sw.js?v=build-sha",
])("keeps the core admin static asset %s on the admin host", (pathname) => {
for (const method of ["GET", "HEAD"]) {
const decision = expectAdminDispatchDecision(new Request(`http://admin.localhost${pathname}`, { method }));
expect(decision.target).toBe("web");
expect(decision.request.url).toBe(`http://admin.localhost${pathname}`);
expect(decision.request.method).toBe(method);
expect(decision.serveStaticAssets).toBe(true);
expect(decision.reactRouterFallback).toBe(false);
}
});
test("fails closed on admin static asset misses and mutations instead of redirecting them to the app host", () => {
const missingAsset = expectAdminDispatchDecision(new Request("http://admin.localhost/assets/missing-build.js"));
const mutation = getHostRoutingRuntimeDecision(
new Request("http://admin.localhost/assets/entry.client-build.js", { method: "POST", body: "not-a-static-read" }),
adminOptions
);
expect(missingAsset).toEqual(expect.objectContaining({ serveStaticAssets: true, reactRouterFallback: false }));
expect(mutation).toEqual({ type: "reject", status: 404 });
});
test("keeps canonical admin host routes stable for web dispatch", () => {
const settingsDecision = expectDispatchDecision(new Request("http://admin.localhost/settings/profile?tab=mfa#codes"));
const metricsDataDecision = expectDispatchDecision(new Request("http://admin.localhost/metrics/summary.data?_routes=routes%2Fadmin%2Fmetrics%2Fsummary.__host"));
const settingsDecision = expectAdminDispatchDecision(new Request("http://admin.localhost/settings/profile?tab=mfa#codes"));
const metricsDataDecision = expectAdminDispatchDecision(
new Request("http://admin.localhost/metrics/summary.data?_routes=routes%2Fadmin%2Fmetrics%2Fsummary.__host")
);
expect(settingsDecision.target).toBe("web");
expect(new URL(settingsDecision.request.url).pathname).toBe("/settings/profile");
@@ -97,7 +215,7 @@ describe("getHostRoutingRuntimeDecision", () => {
});
test("redirects the legacy admin login URL on the canonical admin host", () => {
expect(getHostRoutingRuntimeDecision(new Request("http://admin.localhost/admin/login?error=sso_state_invalid#retry"))).toEqual({
expect(getHostRoutingRuntimeDecision(new Request("http://admin.localhost/admin/login?error=sso_state_invalid#retry"), adminOptions)).toEqual({
type: "redirect",
status: 308,
location: "http://admin.localhost/login?error=sso_state_invalid#retry",
@@ -114,7 +232,7 @@ describe("getHostRoutingRuntimeDecision", () => {
["/api/credits", "/api/credits"],
["/api/keys.data?_routes=routes%2Fadmin%2Fapi%2Fkeys.__host", "/api/keys.data"],
])("dispatches canonical admin API section route %s to the web runtime", (route, expectedPathname) => {
const decision = expectDispatchDecision(new Request(`http://admin.localhost${route}`));
const decision = expectAdminDispatchDecision(new Request(`http://admin.localhost${route}`));
expect(decision.target).toBe("web");
expect(new URL(decision.request.url).pathname).toBe(expectedPathname);
@@ -185,14 +303,12 @@ describe("getHostRoutingRuntimeDecision", () => {
location: "http://admin.localhost/accounts/users?filter=active",
});
expect(getHostRoutingRuntimeDecision(new Request("http://admin.localhost/acme/dashboard?tab=activity#events"))).toEqual({
type: "redirect",
status: 308,
location: "http://app.localhost/acme/dashboard?tab=activity#events",
type: "reject",
status: 404,
});
expect(getHostRoutingRuntimeDecision(new Request("http://admin.localhost/acme"))).toEqual({
type: "redirect",
status: 308,
location: "http://app.localhost/acme",
type: "reject",
status: 404,
});
expect(getHostRoutingRuntimeDecision(new Request("http://api.localhost/acme"))).toEqual({
type: "redirect",
@@ -215,4 +331,350 @@ describe("getHostRoutingRuntimeDecision", () => {
expect(readyDecision.target).toBe("api");
expect(new URL(readyDecision.request.url).pathname).toBe("/readyz");
});
test("dispatches the token-protected web metrics route to the Core runtime", () => {
const decision = expectDispatchDecision(new Request("http://app.localhost/api/metrics"));
expect(decision.target).toBe("web");
expect(decision.serveStaticAssets).toBe(true);
expect(decision.reactRouterFallback).toBe(true);
expect(new URL(decision.request.url).pathname).toBe("/api/metrics");
});
test("keeps Core and Admin hosts on separate fail-closed runtime surfaces", () => {
expect(getHostRoutingRuntimeDecision(new Request("http://admin.localhost/dashboard"))).toEqual({ type: "reject", status: 404 });
for (const host of ["app.localhost", "api.localhost", "localhost", "meet.localhost"]) {
expect(getHostRoutingRuntimeDecision(new Request(`http://${host}/healthz`), adminOptions)).toEqual({ type: "reject", status: 404 });
}
expect(getHostRoutingRuntimeDecision(new Request("http://admin.localhost/healthz"), adminOptions)).toEqual(
expect.objectContaining({ type: "dispatch", target: "web" })
);
});
});
describe("portal runtime surface boundary", () => {
const portalOptions = { runtimeSurface: "portal" as const };
const customPortalOptions = {
runtimeSurface: "portal" as const,
routing: {
appBaseDomain: "hivegrid.de",
webAppHost: "app.hivegrid.de",
adminAppHost: "admin.hivegrid.de",
apiHost: "api.hivegrid.de",
portalAppHost: "portal.hivegrid.de",
protocol: "https" as const,
},
};
function expectPortalDispatch(request: Request) {
const initialDecision = getHostRoutingRuntimeDecision(request, portalOptions);
const decision =
initialDecision.type === "resolve-portal-tenant"
? finalizePortalTenantRoutingDecision(initialDecision, initialDecision.tenantSlug)
: initialDecision;
expect(decision.type).toBe("dispatch");
if (decision.type !== "dispatch") throw new Error(`Expected portal dispatch, received ${decision.type}`);
return decision;
}
test("keeps the portal host and internal namespace off the core surface", () => {
expect(getHostRoutingRuntimeDecision(new Request("http://portal.localhost/acme"))).toEqual({ type: "reject", status: 404 });
expect(getHostRoutingRuntimeDecision(new Request("http://app.localhost/__portal/acme"))).toEqual({ type: "reject", status: 404 });
expect(getHostRoutingRuntimeDecision(new Request("http://app.localhost/portal/acme"))).toEqual({ type: "reject", status: 404 });
});
test.each(["app.localhost", "admin.localhost", "api.localhost", "localhost", "custom.localhost", "attacker.example"])(
"rejects foreign host %s on the portal surface",
(host) => {
expect(getHostRoutingRuntimeDecision(new Request(`http://${host}/acme`), portalOptions)).toEqual({ type: "reject", status: 404 });
}
);
test("does not trust a forwarded portal host behind a foreign direct host", () => {
const request = new Request("http://internal.local/acme", {
headers: { host: "internal.local", "x-forwarded-host": "portal.localhost" },
});
expect(getHostRoutingRuntimeDecision(request, portalOptions)).toEqual({ type: "reject", status: 404 });
});
test("treats an explicit default HTTPS port as the same portal host", () => {
const decision = getHostRoutingRuntimeDecision(new Request("https://portal.example.com/acme"), {
runtimeSurface: "portal",
routing: {
appBaseDomain: "example.com",
webAppHost: "app.example.com",
adminAppHost: "admin.example.com",
apiHost: "api.example.com",
portalAppHost: "portal.example.com:443",
protocol: "https",
},
});
expect(decision).toEqual(expect.objectContaining({ type: "resolve-portal-tenant", tenantSlug: "acme" }));
});
test("rejects malformed direct hosts without throwing", () => {
const request = new Request("http://portal.localhost/acme", { headers: { host: "[malformed-host" } });
expect(getHostRoutingRuntimeDecision(request, portalOptions)).toEqual({ type: "reject", status: 404 });
expect(getHostRoutingRuntimeDecision(request)).toEqual({ type: "reject", status: 404 });
});
test.each(["/", "/a", "/Admin", "/admin", "/api/projects", "/portal/acme", "/__portal/acme", "/acme.data/projects", "//acme"])(
"rejects missing, invalid, reserved, or internal portal route %s",
(pathname) => {
expect(getHostRoutingRuntimeDecision(new Request(`http://portal.localhost${pathname}`), portalOptions)).toEqual({ type: "reject", status: 404 });
}
);
test("rewrites public tenant paths and React Router data requests into the internal namespace", () => {
const page = expectPortalDispatch(new Request("http://portal.localhost/acme/projects?tab=open#list"));
const data = expectPortalDispatch(new Request("http://portal.localhost/acme.data?_routes=routes%2Fportal"));
expect(page.target).toBe("web");
expect(page.serveStaticAssets).toBe(false);
expect(page.request.url).toBe("http://portal.localhost/__portal/acme/projects?tab=open#list");
expect(data.request.url).toBe("http://portal.localhost/__portal/acme.data?_routes=routes%2Fportal");
expect(page.request.headers.get("x-hivegrid-portal-tenant")).toBe("acme");
});
test("dispatches only the exact React Router manifest endpoint on the standard portal host", () => {
const decision = expectPortalDispatch(new Request("http://portal.localhost/__manifest?paths=%2Facme"));
expect(decision).toEqual(
expect.objectContaining({
target: "web",
serveStaticAssets: false,
reactRouterFallback: true,
})
);
expect(new URL(decision.request.url).pathname).toBe("/__manifest");
expect(getHostRoutingRuntimeDecision(new Request("http://portal.localhost/__manifest/extra"), portalOptions)).toEqual({
type: "reject",
status: 404,
});
});
test("dispatches standard-host framework and asset requests without a product rollout gate", () => {
for (const pathname of ["/__manifest?paths=%2Facme", "/assets/app.js", "/site.webmanifest"]) {
expect(getHostRoutingRuntimeDecision(new Request(`http://portal.localhost${pathname}`), portalOptions)).toEqual(
expect.objectContaining({ type: "dispatch", target: "web" })
);
}
});
test("requires tenant resolution before adding trusted context or rewriting the public path", () => {
const initial = getHostRoutingRuntimeDecision(new Request("http://portal.localhost/acme/projects"), portalOptions);
expect(initial.type).toBe("resolve-portal-tenant");
if (initial.type !== "resolve-portal-tenant") throw new Error(`Expected tenant resolution, received ${initial.type}`);
expect(initial.tenantSlug).toBe("acme");
expect(new URL(initial.request.url).pathname).toBe("/acme/projects");
expect(initial.request.headers.has("x-hivegrid-portal-tenant")).toBe(false);
expect(finalizePortalTenantRoutingDecision(initial, null)).toEqual({ type: "reject", status: 404 });
expect(finalizePortalTenantRoutingDecision(initial, "other")).toEqual({ type: "reject", status: 404 });
});
test("resolves an active custom host before routes, auth, or static assets", () => {
const initial = getHostRoutingRuntimeDecision(new Request("https://kunden.geerkens.de/projects?tab=open"), customPortalOptions);
expect(initial.type).toBe("resolve-portal-host");
if (initial.type !== "resolve-portal-host") throw new Error(`Expected host resolution, received ${initial.type}`);
expect(initial.hostname).toBe("kunden.geerkens.de");
expect(initial.request.headers.has("x-hivegrid-portal-tenant")).toBe(false);
expect(finalizePortalHostRoutingDecision(initial, null)).toEqual({ type: "reject", status: 404 });
const decision = finalizePortalHostRoutingDecision(initial, {
hostname: "kunden.geerkens.de",
tenantSlug: "acme",
activeOrigin: "https://kunden.geerkens.de",
});
expect(decision.type).toBe("dispatch");
if (decision.type !== "dispatch") throw new Error(`Expected dispatch, received ${decision.type}`);
expect(decision.request.url).toBe("https://kunden.geerkens.de/__portal/acme/projects?tab=open");
expect(decision.request.headers.get("x-hivegrid-portal-tenant")).toBe("acme");
expect(decision.request.headers.get("x-hivegrid-portal-origin")).toBe("https://kunden.geerkens.de");
expect(decision.request.headers.get("x-hivegrid-portal-custom-host")).toBe("kunden.geerkens.de");
});
test("keeps custom hosts fail-closed when the production runtime gate is disabled", () => {
const disabledOptions = { ...customPortalOptions, customDomainRuntimeEnabled: false };
for (const pathname of ["/", "/projects", "/assets/app.js", "/__manifest?paths=%2F", "/healthz"]) {
expect(getHostRoutingRuntimeDecision(new Request(`https://kunden.geerkens.de${pathname}`), disabledOptions)).toEqual({
type: "reject",
status: 404,
});
}
expect(getHostRoutingRuntimeDecision(new Request("https://portal.hivegrid.de/acme/projects"), disabledOptions)).toEqual(
expect.objectContaining({ type: "resolve-portal-tenant", tenantSlug: "acme" })
);
});
test("fails custom-host resolution closed for mismatches, noncanonical origins, and privileged operational paths", () => {
const initial = getHostRoutingRuntimeDecision(new Request("https://kunden.geerkens.de/"), customPortalOptions);
if (initial.type !== "resolve-portal-host") throw new Error(`Expected host resolution, received ${initial.type}`);
for (const resolved of [
{ hostname: "other.geerkens.de", tenantSlug: "acme", activeOrigin: "https://other.geerkens.de" },
{ hostname: "kunden.geerkens.de", tenantSlug: "acme", activeOrigin: "http://kunden.geerkens.de" },
{ hostname: "kunden.geerkens.de", tenantSlug: "acme", activeOrigin: "https://kunden.geerkens.de/path" },
{ hostname: "kunden.geerkens.de", tenantSlug: "Admin", activeOrigin: "https://kunden.geerkens.de" },
]) {
expect(finalizePortalHostRoutingDecision(initial, resolved)).toEqual({ type: "reject", status: 404 });
}
for (const pathname of ["/readyz", "/healthcheck", "/api/metrics"]) {
expect(getHostRoutingRuntimeDecision(new Request(`https://kunden.geerkens.de${pathname}`), customPortalOptions)).toEqual({
type: "reject",
status: 404,
});
}
});
test("requires a DNS-verified provision command before dependency-free custom-host health", () => {
const initial = getHostRoutingRuntimeDecision(
new Request("https://kunden.geerkens.de/healthz", {
headers: { "x-hivegrid-portal-tenant": "spoofed" },
}),
customPortalOptions
);
expect(initial).toEqual(expect.objectContaining({ type: "resolve-portal-host", hostname: "kunden.geerkens.de" }));
if (initial.type !== "resolve-portal-host") throw new Error(`Expected host resolution, received ${initial.type}`);
expect(finalizePortalHostRoutingDecision(initial, null)).toEqual({ type: "reject", status: 404 });
const decision = finalizePortalHostRoutingDecision(initial, {
hostname: "kunden.geerkens.de",
tenantSlug: "acme",
activeOrigin: "https://kunden.geerkens.de",
});
if (decision.type !== "dispatch") throw new Error(`Expected dispatch, received ${decision.type}`);
expect(decision).toEqual(expect.objectContaining({ target: "web", serveStaticAssets: false, reactRouterFallback: true }));
expect(new URL(decision.request.url).pathname).toBe("/healthz");
expect(decision.request.headers.has("x-hivegrid-portal-tenant")).toBe(false);
expect(decision.request.headers.has("x-hivegrid-portal-origin")).toBe(false);
expect(decision.request.headers.has("x-hivegrid-portal-custom-host")).toBe(false);
expect(getHostRoutingRuntimeDecision(new Request("https://kunden.geerkens.de/assets/app.js"), customPortalOptions).type).toBe("resolve-portal-host");
});
test("maps custom-host root, data, and assets only after resolution", () => {
const resolution = { hostname: "kunden.geerkens.de", tenantSlug: "acme", activeOrigin: "https://kunden.geerkens.de" };
for (const [pathname, expected] of [
["/", "/__portal/acme"],
["/.data?_routes=root", "/__portal/acme.data"],
["/projects.data?_routes=projects", "/__portal/acme/projects.data"],
]) {
const initial = getHostRoutingRuntimeDecision(new Request(`https://kunden.geerkens.de${pathname}`), customPortalOptions);
if (initial.type !== "resolve-portal-host") throw new Error(`Expected host resolution, received ${initial.type}`);
const decision = finalizePortalHostRoutingDecision(initial, resolution);
expect(decision.type).toBe("dispatch");
if (decision.type !== "dispatch") throw new Error(`Expected dispatch, received ${decision.type}`);
expect(new URL(decision.request.url).pathname).toBe(expected);
}
const assetInitial = getHostRoutingRuntimeDecision(new Request("https://kunden.geerkens.de/assets/app.js"), customPortalOptions);
expect(assetInitial.type).toBe("resolve-portal-host");
if (assetInitial.type !== "resolve-portal-host") throw new Error("Expected host resolution");
const asset = finalizePortalHostRoutingDecision(assetInitial, resolution);
expect(asset).toEqual(expect.objectContaining({ type: "dispatch", serveStaticAssets: true, reactRouterFallback: false }));
const manifestInitial = getHostRoutingRuntimeDecision(
new Request("https://kunden.geerkens.de/__manifest?paths=%2F%2C%2Fprojects%2C%2Fprojects%2Fproject-1&version=router-v1"),
customPortalOptions
);
expect(manifestInitial.type).toBe("resolve-portal-host");
if (manifestInitial.type !== "resolve-portal-host") throw new Error("Expected host resolution");
const manifest = finalizePortalHostRoutingDecision(manifestInitial, resolution);
expect(manifest).toEqual(expect.objectContaining({ type: "dispatch", serveStaticAssets: false, reactRouterFallback: true }));
if (manifest.type !== "dispatch") throw new Error("Expected manifest dispatch");
const manifestUrl = new URL(manifest.request.url);
expect(manifestUrl.pathname).toBe("/__manifest");
expect(manifestUrl.searchParams.get("paths")).toBe("/,/projects,/projects/project-1");
expect(manifestUrl.searchParams.get("version")).toBe("router-v1");
expect(manifest.request.headers.get("x-hivegrid-portal-tenant")).toBe("acme");
});
test("keeps custom-host manifest paths slugless when the trusted tenant collides with an alias", () => {
const initial = getHostRoutingRuntimeDecision(
new Request("https://kunden.geerkens.de/__manifest?paths=%2F%2C%2Fprojects%2C%2Fprojects%2Fproject-1"),
customPortalOptions
);
if (initial.type !== "resolve-portal-host") throw new Error("Expected host resolution");
const decision = finalizePortalHostRoutingDecision(initial, {
hostname: "kunden.geerkens.de",
tenantSlug: "projects",
activeOrigin: "https://kunden.geerkens.de",
});
if (decision.type !== "dispatch") throw new Error("Expected manifest dispatch");
expect(new URL(decision.request.url).searchParams.get("paths")).toBe("/,/projects,/projects/project-1");
expect(decision.request.headers.get("x-hivegrid-portal-tenant")).toBe("projects");
});
test.each(["", "projects", "//attacker.example/projects", "/projects,//attacker.example/projects"])(
"rejects malformed custom-host manifest paths %j",
(paths) => {
const requestUrl = new URL("https://kunden.geerkens.de/__manifest");
if (paths) requestUrl.searchParams.set("paths", paths);
const initial = getHostRoutingRuntimeDecision(new Request(requestUrl), customPortalOptions);
expect(initial.type).toBe("resolve-portal-host");
if (initial.type !== "resolve-portal-host") throw new Error("Expected host resolution");
expect(
finalizePortalHostRoutingDecision(initial, {
hostname: "kunden.geerkens.de",
tenantSlug: "acme",
activeOrigin: "https://kunden.geerkens.de",
})
).toEqual({ type: "reject", status: 404 });
}
);
test("preserves method and body while replacing spoofed portal context", async () => {
const decision = expectPortalDispatch(
new Request("http://portal.localhost/acme/projects", {
method: "POST",
body: "action=create",
headers: {
"content-type": "application/x-www-form-urlencoded",
"x-hivegrid-portal-tenant": "victim",
"x-hivegrid-portal-role": "admin",
},
})
);
expect(decision.request.method).toBe("POST");
expect(await decision.request.text()).toBe("action=create");
expect(decision.request.headers.get("x-hivegrid-portal-tenant")).toBe("acme");
expect(decision.request.headers.has("x-hivegrid-portal-role")).toBe(false);
});
test("allows only the explicit portal static namespaces on the exact portal host", () => {
for (const pathname of [
"/assets/app.js",
"/fonts/inter.woff2",
"/images/logo.svg",
"/locales/de/translations.json",
"/favicon.ico",
"/favicon-32x32.png",
]) {
expect(expectPortalDispatch(new Request(`http://portal.localhost${pathname}`)).serveStaticAssets).toBe(true);
expect(expectPortalDispatch(new Request(`http://portal.localhost${pathname}`)).reactRouterFallback).toBe(false);
}
expect(getHostRoutingRuntimeDecision(new Request("http://portal.localhost/sw.js"), portalOptions)).toEqual({ type: "reject", status: 404 });
expect(getHostRoutingRuntimeDecision(new Request("http://portal.localhost/favicon-16x16.png"), portalOptions)).toEqual({ type: "reject", status: 404 });
expect(getHostRoutingRuntimeDecision(new Request("http://app.localhost/assets/app.js"), portalOptions)).toEqual({ type: "reject", status: 404 });
});
test("allows operational routes without exposing static assets", () => {
for (const pathname of ["/healthz", "/readyz", "/healthcheck", "/api/metrics"]) {
const decision = expectPortalDispatch(new Request(`http://portal.localhost${pathname}`));
expect(decision.serveStaticAssets).toBe(false);
expect(new URL(decision.request.url).pathname).toBe(pathname);
}
});
test("strips client portal context headers from core dispatches too", () => {
const decision = expectDispatchDecision(
new Request("http://app.localhost/acme", {
headers: { "x-hivegrid-portal-tenant": "spoofed", "x-hivegrid-portal-role": "admin" },
})
);
expect(decision.request.headers.has("x-hivegrid-portal-tenant")).toBe(false);
expect(decision.request.headers.has("x-hivegrid-portal-role")).toBe(false);
});
});
@@ -1,21 +1,118 @@
import { getCanonicalHostRedirectUrl, getHostAwareInternalUrlPath, getHostRoutingContextFromRequest } from "../apps/web/app/utils/app/HostRouting.server";
import {
getCanonicalHostRedirectUrl,
getHostAwareInternalUrlPath,
getHostRoutingContext,
getRequestRoutingHost,
type HostRoutingContext,
} from "../apps/web/app/utils/app/HostRouting.server";
import { reservedTenantRouteSlugs } from "../apps/web/app/utils/app/PublicRouteSegments";
import { isPortalCustomDomainRuntimeEnabled } from "../apps/web/app/services/customer-portal/portal-custom-domain-runtime.server";
import { getDomainRoutingConfig, normalizeHostForProtocol, type DomainRoutingConfig, type WebRuntimeSurface } from "@hivegrid/config";
export type HostRoutingRuntimeDecision =
| { type: "redirect"; status: 308; location: string }
| { type: "reject"; status: 404 }
| { type: "dispatch"; target: "api" | "web"; request: Request };
| { type: "resolve-portal-tenant"; tenantSlug: string; request: Request }
| { type: "resolve-portal-host"; hostname: string; request: Request }
| { type: "dispatch"; target: "api" | "web"; request: Request; serveStaticAssets: boolean; reactRouterFallback: boolean };
export type PortalTenantRoutingDecision = Extract<HostRoutingRuntimeDecision, { type: "resolve-portal-tenant" }>;
export type PortalHostRoutingDecision = Extract<HostRoutingRuntimeDecision, { type: "resolve-portal-host" }>;
export type PortalHostResolution = {
readonly hostname: string;
readonly tenantSlug: string;
readonly activeOrigin: string;
};
export type FinalHostRoutingRuntimeDecision = Exclude<
HostRoutingRuntimeDecision,
PortalTenantRoutingDecision | PortalHostRoutingDecision
>;
export type HostRoutingRuntimeOptions = {
runtimeSurface?: WebRuntimeSurface;
routing?: DomainRoutingConfig;
customDomainRuntimeEnabled?: boolean;
};
const internalWebApiProxyHeader = "x-hivegrid-internal-web-api-proxy";
const portalContextHeaderPrefix = "x-hivegrid-portal-";
const portalTenantHeader = "x-hivegrid-portal-tenant";
const portalOriginHeader = "x-hivegrid-portal-origin";
const portalCustomHostHeader = "x-hivegrid-portal-custom-host";
const portalTenantSlugPattern = /^[a-z0-9][a-z0-9-]{1,62}$/;
const portalReservedSlugs = new Set<string>([...reservedTenantRouteSlugs, "portal", "__portal"]);
const portalStaticPrefixes = ["/assets/", "/fonts/", "/images/", "/locales/"] as const;
const portalStaticExactPaths = new Set(["/favicon.ico", "/favicon.svg", "/favicon-32x32.png", "/site.webmanifest"]);
const portalFrameworkPaths = new Set(["/__manifest"]);
const adminStaticPrefixes = ["/assets/", "/fonts/", "/images/", "/locales/"] as const;
const adminStaticExactPaths = new Set([
"/android-chrome-192x192.png",
"/android-chrome-512x512.png",
"/android-icon-36x36.png",
"/android-icon-48x48.png",
"/android-icon-72x72.png",
"/android-icon-96x96.png",
"/android-icon-192x192.png",
"/apple-touch-icon.png",
"/browserconfig.xml",
"/favicon.ico",
"/favicon-16x16.png",
"/favicon-32x32.png",
"/favicon-96x96.png",
"/manifest.webmanifest",
"/ms-icon-70x70.png",
"/ms-icon-150x150.png",
"/ms-icon-310x310.png",
"/site.webmanifest",
"/sw.js",
]);
export function getHostRoutingRuntimeDecision(request: Request): HostRoutingRuntimeDecision {
const context = getHostRoutingContextFromRequest(request);
export function getHostRoutingRuntimeDecision(request: Request, options: HostRoutingRuntimeOptions = {}): HostRoutingRuntimeDecision {
const runtimeSurface = options.runtimeSurface ?? "core";
const routing = options.routing ?? getDomainRoutingConfig(process.env);
if (runtimeSurface === "portal") {
return getPortalRuntimeDecision(request, routing, options.customDomainRuntimeEnabled ?? isPortalCustomDomainRuntimeEnabled());
}
const directHost = request.headers.get("host") ?? new URL(request.url).host;
const directContext = getHostRoutingContext(directHost, routing);
if (hostsEqual(directHost, routing.portalAppHost, routing.protocol) || isPortalInternalPath(new URL(request.url).pathname)) {
return { type: "reject", status: 404 };
}
if (directContext === "unknown") {
return { type: "reject", status: 404 };
}
if (runtimeSurface === "admin" ? directContext !== "admin" : directContext === "admin") {
return { type: "reject", status: 404 };
}
const context = getHostRoutingContext(
getRequestRoutingHost(request, new URL(request.url), routing),
routing
);
if (context === "unknown") {
return { type: "reject", status: 404 };
}
if (context === "admin" && isAdminStaticAssetPath(new URL(request.url).pathname)) {
if (request.method !== "GET" && request.method !== "HEAD") {
return { type: "reject", status: 404 };
}
return {
type: "dispatch",
target: "web",
request: sanitizePortalContextHeaders(request),
serveStaticAssets: true,
reactRouterFallback: false,
};
}
if (isInternalWebApiProxyRequest(request, context)) {
const requestUrl = new URL(request.url);
const rewrittenRequest = rewriteRequestUrl(request, `${requestUrl.pathname}${requestUrl.search}${requestUrl.hash}`);
return {
type: "dispatch",
target: "web",
request: rewrittenRequest,
request: sanitizePortalContextHeaders(rewrittenRequest),
serveStaticAssets: true,
reactRouterFallback: true,
};
}
@@ -48,10 +145,248 @@ export function getHostRoutingRuntimeDecision(request: Request): HostRoutingRunt
return {
type: "dispatch",
target: context === "api" ? "api" : "web",
request: rewrittenRequest,
request: sanitizePortalContextHeaders(rewrittenRequest),
serveStaticAssets: context !== "api",
reactRouterFallback: true,
};
}
function getPortalRuntimeDecision(request: Request, routing: DomainRoutingConfig, customDomainRuntimeEnabled: boolean): HostRoutingRuntimeDecision {
const url = new URL(request.url);
const directHost = request.headers.get("host") ?? url.host;
if (!hostsEqual(directHost, routing.portalAppHost, routing.protocol)) {
if (!customDomainRuntimeEnabled) return { type: "reject", status: 404 };
const hostname = getCustomPortalHostname(directHost, routing);
if (!hostname || (isOperationalPath(url.pathname) && url.pathname !== "/healthz") || isPortalInternalPath(url.pathname)) {
return { type: "reject", status: 404 };
}
return { type: "resolve-portal-host", hostname, request: sanitizePortalContextHeaders(request) };
}
if (isOperationalPath(url.pathname)) {
return {
type: "dispatch",
target: "web",
request: sanitizePortalContextHeaders(request),
serveStaticAssets: false,
reactRouterFallback: true,
};
}
if (isPortalFrameworkPath(url.pathname)) {
return {
type: "dispatch",
target: "web",
request: sanitizePortalContextHeaders(request),
serveStaticAssets: false,
reactRouterFallback: true,
};
}
if (isPortalStaticAssetPath(url.pathname)) {
return {
type: "dispatch",
target: "web",
request: sanitizePortalContextHeaders(request),
serveStaticAssets: true,
reactRouterFallback: false,
};
}
if (isPortalInternalPath(url.pathname)) {
return { type: "reject", status: 404 };
}
const tenantSlug = getPortalTenantSlug(url.pathname);
if (!tenantSlug) {
return { type: "reject", status: 404 };
}
return {
type: "resolve-portal-tenant",
tenantSlug,
request: sanitizePortalContextHeaders(request),
};
}
/**
* Completes the internal rewrite only after the caller has resolved the
* standard-host tenant through the portal DB role's pre-auth capability.
*/
export function finalizePortalTenantRoutingDecision(decision: PortalTenantRoutingDecision, resolvedTenantSlug: string | null): FinalHostRoutingRuntimeDecision {
if (resolvedTenantSlug !== decision.tenantSlug) {
return { type: "reject", status: 404 };
}
const url = new URL(decision.request.url);
const rewrittenPath = `/__portal${url.pathname}${url.search}${url.hash}`;
return {
type: "dispatch",
target: "web",
request: rewriteRequestUrl(decision.request, rewrittenPath, {
tenantSlug: resolvedTenantSlug,
origin: new URL(decision.request.url).origin,
}),
serveStaticAssets: false,
reactRouterFallback: true,
};
}
/**
* Completes custom-host dispatch only after the portal DB role has returned an
* active, generation-current domain binding. This gate deliberately runs for
* assets as well as routes so an unknown host can never observe the portal
* build or reach authentication.
*/
export function finalizePortalHostRoutingDecision(decision: PortalHostRoutingDecision, resolved: PortalHostResolution | null): FinalHostRoutingRuntimeDecision {
if (!resolved || resolved.hostname !== decision.hostname || !portalTenantSlugPattern.test(resolved.tenantSlug)) {
return { type: "reject", status: 404 };
}
const activeOrigin = normalizeResolvedPortalOrigin(resolved.activeOrigin, decision.hostname);
if (!activeOrigin) return { type: "reject", status: 404 };
const url = new URL(decision.request.url);
const context = { tenantSlug: resolved.tenantSlug, origin: activeOrigin, customHost: decision.hostname } as const;
if (url.pathname === "/healthz") {
return {
type: "dispatch",
target: "web",
// Host resolution above is the authorization gate. The operational
// manifest boundary intentionally rejects tenant context headers, so a
// health probe must cross it as a context-free operational request.
request: sanitizePortalContextHeaders(decision.request),
serveStaticAssets: false,
reactRouterFallback: true,
};
}
if (isPortalFrameworkPath(url.pathname)) {
const rewrittenManifestRequest = rewriteCustomPortalManifestRequest(decision.request, resolved.tenantSlug, context);
if (!rewrittenManifestRequest) return { type: "reject", status: 404 };
return {
type: "dispatch",
target: "web",
request: rewrittenManifestRequest,
serveStaticAssets: false,
reactRouterFallback: true,
};
}
if (isPortalStaticAssetPath(url.pathname)) {
return {
type: "dispatch",
target: "web",
request: sanitizePortalContextHeaders(decision.request, context),
serveStaticAssets: true,
reactRouterFallback: false,
};
}
const tenantPath = prependPortalTenantToCustomPath(url.pathname, resolved.tenantSlug);
if (!tenantPath) return { type: "reject", status: 404 };
return {
type: "dispatch",
target: "web",
request: rewriteRequestUrl(decision.request, `/__portal${tenantPath}${url.search}${url.hash}`, context),
serveStaticAssets: false,
reactRouterFallback: true,
};
}
function getPortalTenantSlug(pathname: string) {
if (!pathname.startsWith("/") || pathname.startsWith("//")) {
return null;
}
const rawFirstSegment = pathname.slice(1).split("/", 1)[0] ?? "";
if (rawFirstSegment.endsWith(".data") && pathname !== `/${rawFirstSegment}`) {
return null;
}
const firstSegment = rawFirstSegment.replace(/\.data$/, "");
if (!portalTenantSlugPattern.test(firstSegment) || portalReservedSlugs.has(firstSegment)) {
return null;
}
return firstSegment;
}
function isPortalStaticAssetPath(pathname: string) {
return portalStaticExactPaths.has(pathname) || portalStaticPrefixes.some((prefix) => pathname.startsWith(prefix));
}
function isAdminStaticAssetPath(pathname: string) {
return adminStaticExactPaths.has(pathname) || adminStaticPrefixes.some((prefix) => pathname.startsWith(prefix));
}
function isPortalFrameworkPath(pathname: string) {
return portalFrameworkPaths.has(pathname);
}
function isOperationalPath(pathname: string) {
return pathname === "/healthz" || pathname === "/readyz" || pathname === "/healthcheck" || pathname === "/api/metrics";
}
function isPortalInternalPath(pathname: string) {
return pathname === "/__portal" || pathname.startsWith("/__portal/") || pathname === "/portal" || pathname.startsWith("/portal/");
}
function getCustomPortalHostname(directHost: string, routing: DomainRoutingConfig): string | null {
const normalized = normalizeHostForProtocol(directHost, routing.protocol);
if (!normalized || normalized.includes(":")) return null;
if (
[routing.portalAppHost, routing.webAppHost, routing.adminAppHost, routing.apiHost, routing.appBaseDomain].some((host) =>
hostsEqual(normalized, host, routing.protocol)
)
) {
return null;
}
const hostname = new URL(`${routing.protocol}://${normalized}`).hostname.toLowerCase();
if (
!hostname.includes(".") ||
hostname.endsWith(".localhost") ||
hostname.endsWith(".local") ||
hostname.endsWith(".internal") ||
hostname.endsWith(".example") ||
hostname.endsWith(".invalid") ||
hostname.endsWith(".test")
) {
return null;
}
return hostname;
}
function normalizeResolvedPortalOrigin(activeOrigin: string, hostname: string): string | null {
try {
const origin = new URL(activeOrigin);
if (origin.protocol !== "https:" || origin.hostname.toLowerCase() !== hostname || origin.port || origin.pathname !== "/") return null;
if (origin.username || origin.password || origin.search || origin.hash) return null;
return origin.origin;
} catch {
return null;
}
}
function prependPortalTenantToCustomPath(pathname: string, tenantSlug: string): string | null {
if (!pathname.startsWith("/") || pathname.startsWith("//")) return null;
if (pathname === "/") return `/${tenantSlug}`;
if (pathname === "/.data") return `/${tenantSlug}.data`;
return `/${tenantSlug}${pathname}`;
}
function rewriteCustomPortalManifestRequest(request: Request, tenantSlug: string, context: TrustedPortalContext): Request | null {
const url = new URL(request.url);
const rawPaths = url.searchParams.get("paths");
if (!rawPaths) return null;
const publicPaths = rawPaths.split(",");
if (publicPaths.some((pathname) => prependPortalTenantToCustomPath(pathname, tenantSlug) === null)) {
return null;
}
return sanitizePortalContextHeaders(new Request(url, request), context);
}
function hostsEqual(actualHost: string, expectedHost: string, protocol: DomainRoutingConfig["protocol"]) {
const normalizedActualHost = normalizeHostForProtocol(actualHost, protocol);
const normalizedExpectedHost = normalizeHostForProtocol(expectedHost, protocol);
return Boolean(normalizedActualHost && normalizedExpectedHost && normalizedActualHost === normalizedExpectedHost);
}
function isInternalWebApiProxyRequest(request: Request, context: ReturnType<typeof getHostRoutingContextFromRequest>) {
if (context !== "app" || request.headers.get(internalWebApiProxyHeader) !== "1") {
return false;
@@ -79,17 +414,18 @@ function getLegacyAdminLoginRedirect(request: Request, context: ReturnType<typeo
function isRemovedLegacyRoute(request: Request, context: ReturnType<typeof getHostRoutingContextFromRequest>) {
const pathname = new URL(request.url).pathname.replace(/\/+$/g, "") || "/";
const isLegacyApiV1Route = pathname === "/api/v1" || pathname.startsWith("/api/v1/");
const isWebMetricsRoute = pathname === "/api/metrics";
const isAdminApiSectionRoute = context === "admin" && (pathname === "/api" || pathname.startsWith("/api/")) && !isLegacyApiV1Route;
return (
pathname === "/app" ||
pathname.startsWith("/app/") ||
pathname === "/admin" ||
pathname.startsWith("/admin/") ||
(!isAdminApiSectionRoute && (pathname === "/api" || (pathname.startsWith("/api/") && !isLegacyApiV1Route)))
(!isAdminApiSectionRoute && !isWebMetricsRoute && (pathname === "/api" || (pathname.startsWith("/api/") && !isLegacyApiV1Route)))
);
}
function getRuntimeInternalUrlPath(request: Request, context: ReturnType<typeof getHostRoutingContextFromRequest>) {
function getRuntimeInternalUrlPath(request: Request, context: HostRoutingContext) {
if (context === "app") {
const url = new URL(request.url);
return `${url.pathname}${url.search}${url.hash}`;
@@ -98,12 +434,43 @@ function getRuntimeInternalUrlPath(request: Request, context: ReturnType<typeof
return getHostAwareInternalUrlPath(request);
}
function rewriteRequestUrl(request: Request, internalUrlPath: string) {
type TrustedPortalContext = {
readonly tenantSlug: string;
readonly origin: string;
readonly customHost?: string;
};
function rewriteRequestUrl(request: Request, internalUrlPath: string, portalContext?: TrustedPortalContext) {
const url = new URL(request.url);
url.pathname = "/";
url.search = "";
url.hash = "";
const rewrittenUrl = new URL(internalUrlPath, url);
return new Request(rewrittenUrl, request);
const init: RequestInit & { duplex?: "half" } = {
method: request.method,
headers: request.headers,
signal: request.signal,
};
if (request.method !== "GET" && request.method !== "HEAD") {
init.body = request.body;
init.duplex = "half";
}
const rewrittenRequest = new Request(rewrittenUrl, init);
return sanitizePortalContextHeaders(rewrittenRequest, portalContext);
}
function sanitizePortalContextHeaders(request: Request, portalContext?: TrustedPortalContext) {
const headers = new Headers();
for (const [name, value] of request.headers) {
if (!name.toLowerCase().startsWith(portalContextHeaderPrefix)) {
headers.append(name, value);
}
}
if (portalContext) {
headers.set(portalTenantHeader, portalContext.tenantSlug);
headers.set(portalOriginHeader, portalContext.origin);
if (portalContext.customHost) headers.set(portalCustomHostHeader, portalContext.customHost);
}
return new Request(request, { headers });
}
@@ -0,0 +1,22 @@
import { describe, expect, it } from "vitest";
import { getPortalCapabilityResponseSecurityHeaders } from "../apps/web/app/services/customer-portal/portal-response-security";
describe("Customer Portal capability response security", () => {
it.each([
"/acme/login/magic/secret-capability",
"/acme/setup/secret-capability/",
"/acme/verify-email/secret-capability",
"/acme/reset-password/secret-capability.data",
])("forces no-store and no-referrer for the final response to %s", (pathname) => {
expect(getPortalCapabilityResponseSecurityHeaders(new Request(`https://portal.hivegrid.test${pathname}`), "portal")).toEqual({
"Cache-Control": "no-store",
"Referrer-Policy": "no-referrer",
});
});
it("does not alter ordinary Portal pages or any Core response", () => {
expect(getPortalCapabilityResponseSecurityHeaders(new Request("https://portal.hivegrid.test/acme/projects"), "portal")).toBeNull();
expect(getPortalCapabilityResponseSecurityHeaders(new Request("https://app.hivegrid.test/acme/setup/secret"), "core")).toBeNull();
});
});
@@ -0,0 +1,217 @@
import { matchRoutes } from "react-router";
import { describe, expect, it } from "vitest";
import { createPortalRouteConfig } from "../apps/web/app/routes";
import { finalizePortalHostRoutingDecision, finalizePortalTenantRoutingDecision, getHostRoutingRuntimeDecision } from "./host-routing-runtime";
import { prepareReactRouterManifestRequest } from "./react-router-manifest-dispatch";
const routing = {
appHost: "app.hivegrid.test",
adminHost: "admin.hivegrid.test",
apiHost: "api.hivegrid.test",
portalAppHost: "portal.hivegrid.test",
};
describe("React Router manifest dispatch", () => {
it("validates and removes the trusted portal namespace before route matching", () => {
const outerDecision = getHostRoutingRuntimeDecision(
new Request("https://portal.hivegrid.test/acme/projects/project-1?tab=files", {
headers: { host: "portal.hivegrid.test" },
}),
{ runtimeSurface: "portal", routing }
);
expect(outerDecision.type).toBe("resolve-portal-tenant");
if (outerDecision.type !== "resolve-portal-tenant") throw new Error("expected portal tenant resolution");
const resolvedDecision = finalizePortalTenantRoutingDecision(outerDecision, "acme");
expect(resolvedDecision.type).toBe("dispatch");
if (resolvedDecision.type !== "dispatch") throw new Error("expected portal dispatch");
expect(new URL(resolvedDecision.request.url).pathname).toBe("/__portal/acme/projects/project-1");
const manifestDecision = prepareReactRouterManifestRequest(resolvedDecision.request, "portal");
expect(manifestDecision.type).toBe("dispatch");
if (manifestDecision.type !== "dispatch") throw new Error("expected manifest dispatch");
expect(manifestDecision.request.url).toBe("https://portal.hivegrid.test/acme/projects/project-1?tab=files");
expect(manifestDecision.request.headers.get("x-hivegrid-portal-tenant")).toBe("acme");
});
it("normalizes portal data requests to their public path", () => {
const request = new Request("https://portal.hivegrid.test/__portal/acme.data?_routes=routes%2Fcustomer-portal%2Flayout", {
headers: { "x-hivegrid-portal-tenant": "acme" },
});
const decision = prepareReactRouterManifestRequest(request, "portal");
expect(decision.type).toBe("dispatch");
if (decision.type !== "dispatch") throw new Error("expected manifest dispatch");
expect(new URL(decision.request.url).pathname).toBe("/acme.data");
});
it.each([
["public portal path", "https://portal.hivegrid.test/acme/projects", "acme"],
["missing trusted tenant", "https://portal.hivegrid.test/__portal/acme/projects", null],
["mismatched trusted tenant", "https://portal.hivegrid.test/__portal/acme/projects", "other"],
])("rejects %s before the portal manifest", (_label, url, tenant) => {
const headers = tenant ? { "x-hivegrid-portal-tenant": tenant } : undefined;
expect(prepareReactRouterManifestRequest(new Request(url, { headers }), "portal")).toEqual({
type: "reject",
status: 404,
});
});
it.each(["/healthz", "/readyz", "/healthcheck", "/api/metrics"])(
"passes the %s operational route without portal context",
(pathname) => {
const request = new Request(`https://portal.hivegrid.test${pathname}`);
expect(prepareReactRouterManifestRequest(request, "portal")).toEqual({ type: "dispatch", request });
}
);
it("passes an authorized custom-host health probe through both routing boundaries", () => {
const customRouting = {
appBaseDomain: "hivegrid.de",
webAppHost: "app.hivegrid.de",
adminAppHost: "admin.hivegrid.de",
apiHost: "api.hivegrid.de",
portalAppHost: "portal.hivegrid.de",
protocol: "https" as const,
};
const outerDecision = getHostRoutingRuntimeDecision(
new Request("https://kunden.example.org/healthz", {
headers: {
host: "kunden.example.org",
"x-hivegrid-portal-tenant": "spoofed",
"x-hivegrid-portal-origin": "https://attacker.example.org",
},
}),
{ runtimeSurface: "portal", routing: customRouting }
);
expect(outerDecision.type).toBe("resolve-portal-host");
if (outerDecision.type !== "resolve-portal-host") throw new Error("expected custom-host resolution");
const resolvedDecision = finalizePortalHostRoutingDecision(outerDecision, {
hostname: "kunden.example.org",
tenantSlug: "acme",
activeOrigin: "https://kunden.example.org",
});
expect(resolvedDecision.type).toBe("dispatch");
if (resolvedDecision.type !== "dispatch") throw new Error("expected custom-host health dispatch");
expect(resolvedDecision.request.headers.has("x-hivegrid-portal-tenant")).toBe(false);
expect(resolvedDecision.request.headers.has("x-hivegrid-portal-origin")).toBe(false);
const manifestDecision = prepareReactRouterManifestRequest(resolvedDecision.request, "portal");
expect(manifestDecision.type).toBe("dispatch");
if (manifestDecision.type !== "dispatch") throw new Error("expected operational manifest dispatch");
expect(new URL(manifestDecision.request.url).pathname).toBe("/healthz");
});
it("keeps custom-host SSR and browser route ids byte-for-byte aligned", () => {
const customRouting = {
appBaseDomain: "hivegrid.de",
webAppHost: "app.hivegrid.de",
adminAppHost: "admin.hivegrid.de",
apiHost: "api.hivegrid.de",
portalAppHost: "portal.hivegrid.de",
protocol: "https" as const,
};
const outerDecision = getHostRoutingRuntimeDecision(new Request("https://kunden.example.org/login"), {
runtimeSurface: "portal",
routing: customRouting,
});
expect(outerDecision.type).toBe("resolve-portal-host");
if (outerDecision.type !== "resolve-portal-host") throw new Error("expected custom-host resolution");
const resolvedDecision = finalizePortalHostRoutingDecision(outerDecision, {
hostname: "kunden.example.org",
tenantSlug: "acme",
activeOrigin: "https://kunden.example.org",
});
expect(resolvedDecision.type).toBe("dispatch");
if (resolvedDecision.type !== "dispatch") throw new Error("expected custom-host dispatch");
const manifestDecision = prepareReactRouterManifestRequest(resolvedDecision.request, "portal");
expect(manifestDecision.type).toBe("dispatch");
if (manifestDecision.type !== "dispatch") throw new Error("expected manifest dispatch");
const ssrPathname = new URL(manifestDecision.request.url).pathname;
const browserPathname = "/login";
const routes = createPortalRouteConfig();
const ssrRouteIds = matchRoutes(routes, ssrPathname)?.map((match) => match.route.id);
const browserRouteIds = matchRoutes(routes, browserPathname)?.map((match) => match.route.id);
expect(ssrPathname).toBe(browserPathname);
expect(ssrRouteIds).toEqual(["routes/customer-portal/layout.__custom-host", "routes/customer-portal/auth.login.__custom-host"]);
expect(browserRouteIds).toEqual(ssrRouteIds);
});
it("keeps custom-host data and mutation dispatch slugless without dropping trusted context", async () => {
const customRouting = {
appBaseDomain: "hivegrid.de",
webAppHost: "app.hivegrid.de",
adminAppHost: "admin.hivegrid.de",
apiHost: "api.hivegrid.de",
portalAppHost: "portal.hivegrid.de",
protocol: "https" as const,
};
const resolution = { hostname: "kunden.example.org", tenantSlug: "acme", activeOrigin: "https://kunden.example.org" };
const dataOuter = getHostRoutingRuntimeDecision(new Request("https://kunden.example.org/login.data?_routes=custom-auth"), {
runtimeSurface: "portal",
routing: customRouting,
});
if (dataOuter.type !== "resolve-portal-host") throw new Error("expected custom-host data resolution");
const dataResolved = finalizePortalHostRoutingDecision(dataOuter, resolution);
if (dataResolved.type !== "dispatch") throw new Error("expected custom-host data dispatch");
const dataManifest = prepareReactRouterManifestRequest(dataResolved.request, "portal");
expect(dataManifest.type).toBe("dispatch");
if (dataManifest.type !== "dispatch") throw new Error("expected data manifest dispatch");
expect(new URL(dataManifest.request.url).pathname).toBe("/login.data");
const actionOuter = getHostRoutingRuntimeDecision(
new Request("https://kunden.example.org/settings", {
method: "POST",
headers: { "content-type": "application/x-www-form-urlencoded" },
body: "intent=request_export",
}),
{ runtimeSurface: "portal", routing: customRouting }
);
if (actionOuter.type !== "resolve-portal-host") throw new Error("expected custom-host action resolution");
const actionResolved = finalizePortalHostRoutingDecision(actionOuter, resolution);
if (actionResolved.type !== "dispatch") throw new Error("expected custom-host action dispatch");
const actionManifest = prepareReactRouterManifestRequest(actionResolved.request, "portal");
expect(actionManifest.type).toBe("dispatch");
if (actionManifest.type !== "dispatch") throw new Error("expected action manifest dispatch");
expect(new URL(actionManifest.request.url).pathname).toBe("/settings");
expect(actionManifest.request.method).toBe("POST");
expect(actionManifest.request.headers.get("x-hivegrid-portal-tenant")).toBe("acme");
expect(actionManifest.request.headers.get("x-hivegrid-portal-custom-host")).toBe("kunden.example.org");
await expect(actionManifest.request.text()).resolves.toBe("intent=request_export");
});
it("passes the exact React Router manifest endpoint to the selected portal build", () => {
const request = new Request("https://portal.hivegrid.test/__manifest?paths=%2Facme%2Flogin");
expect(prepareReactRouterManifestRequest(request, "portal")).toEqual({ type: "dispatch", request });
expect(prepareReactRouterManifestRequest(new Request("https://portal.hivegrid.test/__manifest/extra"), "portal")).toEqual({
type: "reject",
status: 404,
});
});
it("never dispatches an internal portal request into the Core manifest", () => {
const request = new Request("https://app.hivegrid.test/__portal/acme", {
headers: { "x-hivegrid-portal-tenant": "acme" },
});
expect(prepareReactRouterManifestRequest(request, "core")).toEqual({ type: "reject", status: 404 });
});
it("dispatches Admin routes through the shared Core manifest without weakening the portal boundary", () => {
const adminRequest = new Request("https://admin.hivegrid.test/settings");
expect(prepareReactRouterManifestRequest(adminRequest, "admin")).toEqual({
type: "dispatch",
request: adminRequest,
});
const internalPortalRequest = new Request("https://admin.hivegrid.test/__portal/acme", {
headers: { "x-hivegrid-portal-tenant": "acme" },
});
expect(prepareReactRouterManifestRequest(internalPortalRequest, "admin")).toEqual({
type: "reject",
status: 404,
});
});
});
@@ -0,0 +1,78 @@
import type { WebRuntimeSurface } from "@hivegrid/config";
export type ReactRouterManifestDispatchDecision = { type: "dispatch"; request: Request } | { type: "reject"; status: 404 };
const portalInternalNamespace = "/__portal";
const portalTenantHeader = "x-hivegrid-portal-tenant";
const portalCustomHostHeader = "x-hivegrid-portal-custom-host";
const portalTenantSlugPattern = /^[a-z0-9][a-z0-9-]{1,62}$/;
const operationalPaths = new Set(["/healthz", "/readyz", "/healthcheck", "/api/metrics"]);
const portalFrameworkPaths = new Set(["/__manifest"]);
/**
* Crosses the final trust boundary between host routing and the selected
* React Router manifest. Portal requests must arrive in the reserved internal
* namespace with a matching trusted tenant header. The namespace is removed
* before route matching so SSR and browser hydration both see the public URL.
*/
export function prepareReactRouterManifestRequest(request: Request, runtimeSurface: WebRuntimeSurface): ReactRouterManifestDispatchDecision {
const url = new URL(request.url);
if (runtimeSurface === "core" || runtimeSurface === "admin") {
if (isPortalInternalPath(url.pathname) || request.headers.has(portalTenantHeader)) {
return { type: "reject", status: 404 };
}
return { type: "dispatch", request };
}
if (operationalPaths.has(url.pathname)) {
if (request.headers.has(portalTenantHeader)) {
return { type: "reject", status: 404 };
}
return { type: "dispatch", request };
}
if (portalFrameworkPaths.has(url.pathname)) {
return { type: "dispatch", request };
}
if (!url.pathname.startsWith(`${portalInternalNamespace}/`)) {
return { type: "reject", status: 404 };
}
const publicPathname = url.pathname.slice(portalInternalNamespace.length);
const rawTenantSegment = publicPathname.slice(1).split("/", 1)[0] ?? "";
const tenantSlug = rawTenantSegment.replace(/\.data$/, "");
const trustedTenantSlug = request.headers.get(portalTenantHeader);
if (!trustedTenantSlug || trustedTenantSlug !== tenantSlug || !portalTenantSlugPattern.test(tenantSlug)) {
return { type: "reject", status: 404 };
}
const customHostPathname = request.headers.has(portalCustomHostHeader) ? stripTrustedTenantFromCustomHostPath(publicPathname, tenantSlug) : null;
if (request.headers.has(portalCustomHostHeader) && !customHostPathname) {
return { type: "reject", status: 404 };
}
url.pathname = customHostPathname ?? publicPathname;
const init: RequestInit & { duplex?: "half" } = {
method: request.method,
headers: request.headers,
signal: request.signal,
};
if (request.method !== "GET" && request.method !== "HEAD") {
init.body = request.body;
init.duplex = "half";
}
return { type: "dispatch", request: new Request(url, init) };
}
function stripTrustedTenantFromCustomHostPath(pathname: string, tenantSlug: string): string | null {
const tenantPrefix = `/${tenantSlug}`;
if (pathname === tenantPrefix) return "/";
if (pathname === `${tenantPrefix}.data`) return "/.data";
if (pathname.startsWith(`${tenantPrefix}/`)) return pathname.slice(tenantPrefix.length);
return null;
}
function isPortalInternalPath(pathname: string) {
return pathname === portalInternalNamespace || pathname.startsWith(`${portalInternalNamespace}/`);
}
@@ -0,0 +1,87 @@
import { Readable } from "node:stream";
import { describe, expect, test } from "vitest";
import {
createLimitedRequestBody,
DEFAULT_WEB_REQUEST_BODY_BYTES,
EMAIL_WEBHOOK_REQUEST_BODY_BYTES,
MAX_WEB_REQUEST_BODY_BYTES,
OAUTH_REGISTRATION_REQUEST_BODY_BYTES,
parseRequestContentLength,
PORTAL_UPLOAD_REQUEST_BODY_BYTES,
PORTAL_UPLOAD_MULTIPART_OVERHEAD_BYTES,
PUBLIC_AUTH_FORM_REQUEST_BODY_BYTES,
PUBLIC_BOOKING_REQUEST_BODY_BYTES,
PUBLIC_FORM_REQUEST_BODY_BYTES,
RequestBodyTooLargeError,
resolveWebRequestBodyLimit,
} from "./request-body";
describe("web request body limit", () => {
test("parses only safe decimal content lengths", () => {
expect(parseRequestContentLength("42")).toBe(42);
expect(parseRequestContentLength(" 42 ")).toBe(42);
expect(parseRequestContentLength("-1")).toBeNull();
expect(parseRequestContentLength("invalid")).toBeNull();
});
test("streams a body within the limit without buffering it as one payload", async () => {
const input = Readable.from([Buffer.from("ab"), Buffer.from("cd")]);
const output = createLimitedRequestBody(input as never, 4);
const chunks: Buffer[] = [];
for await (const chunk of output) chunks.push(Buffer.from(chunk));
expect(Buffer.concat(chunks).toString("utf8")).toBe("abcd");
});
test("fails as soon as a chunk crosses the configured limit", async () => {
const input = Readable.from([Buffer.from("abc"), Buffer.from("de")]);
const output = createLimitedRequestBody(input as never, 4);
await expect(async () => {
for await (const chunk of output) {
// Consume the stream so the limiter observes every chunk.
void chunk;
}
}).rejects.toBeInstanceOf(RequestBodyTooLargeError);
});
test("uses a small default and explicit upload-route exceptions", () => {
expect(resolveWebRequestBodyLimit("/acme/settings/members")).toBe(DEFAULT_WEB_REQUEST_BODY_BYTES);
expect(resolveWebRequestBodyLimit("/acme/files/upload/up_1/chunk/0")).toBe(5 * 1024 * 1024);
expect(resolveWebRequestBodyLimit("/acme/projects/project_1/upload", "portal")).toBe(PORTAL_UPLOAD_REQUEST_BODY_BYTES);
expect(resolveWebRequestBodyLimit("/projects/project_1/upload", "portal")).toBe(PORTAL_UPLOAD_REQUEST_BODY_BYTES);
expect(PORTAL_UPLOAD_REQUEST_BODY_BYTES).toBe(101 * 1024 * 1024);
expect(PORTAL_UPLOAD_MULTIPART_OVERHEAD_BYTES).toBe(1024 * 1024);
expect(resolveWebRequestBodyLimit("/acme/projects/project_1/upload", "core")).toBe(DEFAULT_WEB_REQUEST_BODY_BYTES);
expect(resolveWebRequestBodyLimit("/acme/settings/profile")).toBe(8 * 1024 * 1024);
expect(resolveWebRequestBodyLimit("/settings/profile")).toBe(8 * 1024 * 1024);
expect(resolveWebRequestBodyLimit("/acme/hr/my-documents")).toBe(26 * 1024 * 1024);
expect(resolveWebRequestBodyLimit("/acme/emails/new")).toBe(MAX_WEB_REQUEST_BODY_BYTES);
expect(resolveWebRequestBodyLimit("/api/embed/forms/form_1/submit")).toBe(PUBLIC_FORM_REQUEST_BODY_BYTES);
expect(PUBLIC_FORM_REQUEST_BODY_BYTES).toBe(30 * 1024 * 1024);
expect(resolveWebRequestBodyLimit("/oauth/register")).toBe(OAUTH_REGISTRATION_REQUEST_BODY_BYTES);
expect(resolveWebRequestBodyLimit("/oauth/token")).toBe(OAUTH_REGISTRATION_REQUEST_BODY_BYTES);
expect(resolveWebRequestBodyLimit("/oauth/revoke")).toBe(OAUTH_REGISTRATION_REQUEST_BODY_BYTES);
expect(OAUTH_REGISTRATION_REQUEST_BODY_BYTES).toBe(64 * 1024);
expect(resolveWebRequestBodyLimit("/webhooks/email/google")).toBe(EMAIL_WEBHOOK_REQUEST_BODY_BYTES);
expect(resolveWebRequestBodyLimit("/webhooks/email/microsoft")).toBe(EMAIL_WEBHOOK_REQUEST_BODY_BYTES);
expect(EMAIL_WEBHOOK_REQUEST_BODY_BYTES).toBe(256 * 1024);
expect(resolveWebRequestBodyLimit("/register")).toBe(PUBLIC_AUTH_FORM_REQUEST_BODY_BYTES);
expect(resolveWebRequestBodyLimit("/signup")).toBe(PUBLIC_AUTH_FORM_REQUEST_BODY_BYTES);
expect(PUBLIC_AUTH_FORM_REQUEST_BODY_BYTES).toBe(64 * 1024);
expect(resolveWebRequestBodyLimit("/b/acme/consulting")).toBe(PUBLIC_BOOKING_REQUEST_BODY_BYTES);
expect(resolveWebRequestBodyLimit("/b/acme/consulting/embed")).toBe(PUBLIC_BOOKING_REQUEST_BODY_BYTES);
expect(PUBLIC_BOOKING_REQUEST_BODY_BYTES).toBe(64 * 1024);
expect(resolveWebRequestBodyLimit("/settings/general")).toBe(MAX_WEB_REQUEST_BODY_BYTES);
});
test("does not grant upload limits to lookalike paths", () => {
expect(resolveWebRequestBodyLimit("/acme/files/upload/up_1/chunk/not-a-number")).toBe(DEFAULT_WEB_REQUEST_BODY_BYTES);
expect(resolveWebRequestBodyLimit("/acme/projects/project_1/upload/extra", "portal")).toBe(DEFAULT_WEB_REQUEST_BODY_BYTES);
expect(resolveWebRequestBodyLimit("/acme/projects/project%2F1/upload", "portal")).toBe(DEFAULT_WEB_REQUEST_BODY_BYTES);
expect(resolveWebRequestBodyLimit("/evil/api/embed/forms/form_1/submit")).toBe(DEFAULT_WEB_REQUEST_BODY_BYTES);
expect(resolveWebRequestBodyLimit("/oauth/register/extra")).toBe(DEFAULT_WEB_REQUEST_BODY_BYTES);
expect(resolveWebRequestBodyLimit("/evil/webhooks/email/microsoft")).toBe(DEFAULT_WEB_REQUEST_BODY_BYTES);
expect(resolveWebRequestBodyLimit("/evil/b/acme/consulting")).toBe(DEFAULT_WEB_REQUEST_BODY_BYTES);
expect(resolveWebRequestBodyLimit("https://app.example.test/acme/emails/new/extra")).toBe(DEFAULT_WEB_REQUEST_BODY_BYTES);
});
});
@@ -0,0 +1,112 @@
import type { IncomingMessage } from "node:http";
import { Readable } from "node:stream";
export const MAX_WEB_REQUEST_BODY_BYTES = 100 * 1024 * 1024;
export const DEFAULT_WEB_REQUEST_BODY_BYTES = 2 * 1024 * 1024;
const FILE_CHUNK_REQUEST_BODY_BYTES = 5 * 1024 * 1024;
const PROFILE_IMAGE_REQUEST_BODY_BYTES = 8 * 1024 * 1024;
const HR_DOCUMENT_REQUEST_BODY_BYTES = 26 * 1024 * 1024;
export const PUBLIC_FORM_REQUEST_BODY_BYTES = 30 * 1024 * 1024;
export const OAUTH_REGISTRATION_REQUEST_BODY_BYTES = 64 * 1024;
export const EMAIL_WEBHOOK_REQUEST_BODY_BYTES = 256 * 1024;
export const PUBLIC_AUTH_FORM_REQUEST_BODY_BYTES = 64 * 1024;
export const PUBLIC_BOOKING_REQUEST_BODY_BYTES = 64 * 1024;
export const PORTAL_UPLOAD_MULTIPART_OVERHEAD_BYTES = 1024 * 1024;
export const PORTAL_UPLOAD_REQUEST_BODY_BYTES = MAX_WEB_REQUEST_BODY_BYTES + PORTAL_UPLOAD_MULTIPART_OVERHEAD_BYTES;
/**
* Keep ordinary mutations small while granting explicit, narrow exceptions to
* routes that intentionally receive binary data. The 100 MiB value remains an
* absolute ceiling, not the default for every form or JSON action.
*/
export function resolveWebRequestBodyLimit(requestUrl: string | undefined, runtimeSurface: "core" | "portal" = "core"): number {
let pathname: string;
try {
pathname = new URL(requestUrl ?? "/", "http://internal").pathname;
} catch {
return DEFAULT_WEB_REQUEST_BODY_BYTES;
}
if (/^\/[^/]+\/files\/upload\/[^/]+\/chunk\/\d+\/?$/.test(pathname)) {
return FILE_CHUNK_REQUEST_BODY_BYTES;
}
if (
runtimeSurface === "portal" &&
/^(?:\/[^/]+)?\/projects\/[A-Za-z0-9_-]{1,128}\/upload\/?$/u.test(pathname)
) {
// The portal runtime receives the standard-host path with a tenant slug
// and the custom-host path without one. One bounded MiB of multipart
// overhead keeps a legitimate 100 MiB file below the transport ceiling;
// application validation still enforces the exact per-file limit.
return PORTAL_UPLOAD_REQUEST_BODY_BYTES;
}
if (/^\/api\/embed\/forms\/[^/]+\/submit\/?$/.test(pathname)) {
// Keep the transport ceiling aligned with the route's multipart limit.
// A larger server allowance lets chunked requests consume memory in
// request.formData() before the route-level Content-Length check applies.
return PUBLIC_FORM_REQUEST_BODY_BYTES;
}
if (/^\/oauth\/(?:register|token|revoke)\/?$/.test(pathname)) {
return OAUTH_REGISTRATION_REQUEST_BODY_BYTES;
}
if (/^\/webhooks\/email\/(?:google|microsoft)\/?$/.test(pathname)) {
return EMAIL_WEBHOOK_REQUEST_BODY_BYTES;
}
if (/^\/(?:register|signup)\/?$/.test(pathname)) {
return PUBLIC_AUTH_FORM_REQUEST_BODY_BYTES;
}
if (/^\/b\/[^/]+\/[^/]+(?:\/embed)?\/?$/.test(pathname)) {
return PUBLIC_BOOKING_REQUEST_BODY_BYTES;
}
if (/^\/[^/]+\/emails\/new\/?$/.test(pathname)) {
return MAX_WEB_REQUEST_BODY_BYTES;
}
if (/^\/[^/]+\/hr\/my-documents\/?$/.test(pathname)) {
return HR_DOCUMENT_REQUEST_BODY_BYTES;
}
if (/^(?:\/admin)?\/settings\/general\/?$/.test(pathname)) {
return MAX_WEB_REQUEST_BODY_BYTES;
}
if (/^(?:\/admin)?\/settings\/profile\/?$/.test(pathname) || /^\/[^/]+\/settings\/(?:profile|account)\/?$/.test(pathname)) {
return PROFILE_IMAGE_REQUEST_BODY_BYTES;
}
return DEFAULT_WEB_REQUEST_BODY_BYTES;
}
export class RequestBodyTooLargeError extends Error {
readonly code = "WEB_REQUEST_BODY_TOO_LARGE";
constructor(readonly limitBytes: number) {
super(`Web request body exceeds the ${limitBytes}-byte limit.`);
this.name = "RequestBodyTooLargeError";
}
}
export function parseRequestContentLength(value: string | undefined): number | null {
if (value === undefined || !/^\d+$/.test(value.trim())) {
return null;
}
const parsed = Number(value);
return Number.isSafeInteger(parsed) ? parsed : null;
}
export function createLimitedRequestBody(request: IncomingMessage, limitBytes = MAX_WEB_REQUEST_BODY_BYTES): Readable {
return Readable.from(limitRequestBody(request, limitBytes));
}
async function* limitRequestBody(request: IncomingMessage, limitBytes: number): AsyncGenerator<Buffer | string> {
let receivedBytes = 0;
for await (const chunk of request) {
receivedBytes += Buffer.isBuffer(chunk) ? chunk.byteLength : Buffer.byteLength(String(chunk));
if (receivedBytes > limitBytes) {
throw new RequestBodyTooLargeError(limitBytes);
}
yield chunk as Buffer | string;
}
}
export function isRequestBodyTooLargeError(error: unknown): error is RequestBodyTooLargeError {
return error instanceof RequestBodyTooLargeError;
}
@@ -0,0 +1,54 @@
import { describe, expect, it } from "vitest";
import { validateMutationOrigin } from "./request-origin";
describe("web mutation origin gate", () => {
it.each(["GET", "HEAD", "OPTIONS"])("allows safe %s requests", (method) => {
expect(validateMutationOrigin(new Request("https://app.example.test/acme", { method }))).toMatchObject({ allowed: true, reason: "safe-method" });
});
it("allows same-origin browser mutations", () => {
const request = new Request("https://app.example.test/acme/settings", {
method: "POST",
headers: { origin: "https://app.example.test", "sec-fetch-site": "same-origin" },
});
expect(validateMutationOrigin(request)).toEqual({ allowed: true, reason: "same-origin" });
});
it("rejects cross-site browser mutations before route actions", () => {
const request = new Request("https://app.example.test/acme/settings", {
method: "POST",
headers: { origin: "https://evil.example", "sec-fetch-site": "cross-site" },
});
expect(validateMutationOrigin(request)).toEqual({ allowed: false, reason: "cross-site" });
});
it("rejects sibling-subdomain cookie tossing and CSRF", () => {
const request = new Request("https://admin.example.test/settings", {
method: "POST",
headers: { origin: "https://compromised.example.test", "sec-fetch-site": "same-site" },
});
expect(validateMutationOrigin(request)).toEqual({ allowed: false, reason: "origin-mismatch" });
});
it("uses the referer origin when Origin is unavailable", () => {
const request = new Request("https://app.example.test/acme/settings", {
method: "POST",
headers: { referer: "https://app.example.test/acme/profile" },
});
expect(validateMutationOrigin(request)).toEqual({ allowed: true, reason: "same-origin" });
});
it("allows signed non-browser integrations to reach route authentication", () => {
const request = new Request("https://app.example.test/internal/webhook", { method: "POST" });
expect(validateMutationOrigin(request)).toEqual({ allowed: true, reason: "non-browser" });
});
it("fails closed for browser mutations that omit all origin evidence", () => {
const request = new Request("https://app.example.test/acme/settings", {
method: "POST",
headers: { "sec-fetch-site": "same-site" },
});
expect(validateMutationOrigin(request)).toEqual({ allowed: false, reason: "browser-origin-missing" });
});
});
@@ -0,0 +1,52 @@
const SAFE_METHODS = new Set(["GET", "HEAD", "OPTIONS"]);
export type MutationOriginDecision =
| { allowed: true; reason: "safe-method" | "same-origin" | "non-browser" }
| { allowed: false; reason: "cross-site" | "origin-mismatch" | "browser-origin-missing" };
export function validateMutationOrigin(request: Request): MutationOriginDecision {
if (SAFE_METHODS.has(request.method.toUpperCase())) {
return { allowed: true, reason: "safe-method" };
}
const fetchSite = request.headers.get("sec-fetch-site")?.trim().toLowerCase();
if (fetchSite === "cross-site") {
return { allowed: false, reason: "cross-site" };
}
const requestOrigin = new URL(request.url).origin;
const origin = normalizeOrigin(request.headers.get("origin"));
if (origin !== null) {
return origin === requestOrigin
? { allowed: true, reason: "same-origin" }
: { allowed: false, reason: "origin-mismatch" };
}
const referer = normalizeOrigin(request.headers.get("referer"));
if (referer !== null) {
return referer === requestOrigin
? { allowed: true, reason: "same-origin" }
: { allowed: false, reason: "origin-mismatch" };
}
if (fetchSite === "same-origin") {
return { allowed: true, reason: "same-origin" };
}
if (fetchSite !== undefined) {
return { allowed: false, reason: "browser-origin-missing" };
}
// Non-browser integrations authenticate with their own signature/token and
// do not emit Fetch Metadata headers. Their route-level authentication still
// applies; this gate only rejects browser-originated CSRF.
return { allowed: true, reason: "non-browser" };
}
function normalizeOrigin(rawValue: string | null): string | null {
if (!rawValue || rawValue === "null") return null;
try {
return new URL(rawValue).origin;
} catch {
return "invalid";
}
}
@@ -4,14 +4,60 @@ import { fileURLToPath } from "node:url";
import path from "node:path";
const serverSource = readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), "server.ts"), "utf8");
const cspPolicySource = readFileSync(
path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "apps", "web", "app", "utils", "security", "contentSecurityPolicy.ts"),
"utf8"
);
const staticAssetsSource = readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), "static-assets.ts"), "utf8");
const rootPackage = JSON.parse(readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "package.json"), "utf8"));
const webPackage = JSON.parse(readFileSync(path.join(path.dirname(fileURLToPath(import.meta.url)), "..", "apps", "web", "package.json"), "utf8"));
describe("server runtime routing integration", () => {
test("delegates host routing decisions before API or React Router dispatch", () => {
expect(serverSource).toContain("getHostRoutingRuntimeDecision(request)");
test("delegates host routing decisions before React Router dispatch and rejects API-host traffic", () => {
expect(serverSource).toContain("getHostRoutingRuntimeDecision(request, {");
expect(serverSource).toContain("runtimeSurface: webConfig.runtimeSurface");
expect(serverSource).toContain("routing: webConfig.routing");
expect(serverSource).toContain('routingDecision.type === "redirect"');
expect(serverSource).toContain('routingDecision.target === "api"');
expect(serverSource).toContain('new Response("Not Found", { status: 404 })');
expect(serverSource).not.toContain('from "../apps/api/');
expect(serverSource).not.toContain("apiApp.fetch");
});
test("gates hosts and paths before static assets and React Router", () => {
const gateIndex = serverSource.indexOf("getHostRoutingRuntimeDecision(request, {");
const tenantResolutionIndex = serverSource.indexOf("await resolvePortalRuntimeTenant(routingDecision.tenantSlug)", gateIndex);
const tenantRewriteIndex = serverSource.indexOf("finalizePortalTenantRoutingDecision(routingDecision", tenantResolutionIndex);
const hostResolutionIndex = serverSource.indexOf("await resolvePortalRuntimeCustomHost(routingDecision.hostname)", gateIndex);
const healthHostResolutionIndex = serverSource.indexOf("await resolvePortalRuntimeCustomHostHealth(routingDecision.hostname)", gateIndex);
const hostRewriteIndex = serverSource.indexOf("finalizePortalHostRoutingDecision(routingDecision", hostResolutionIndex);
const staticIndex = serverSource.indexOf("await serveStaticAsset(req, res)", gateIndex);
const routerIndex = serverSource.indexOf("handleReactRouterRequest(manifestRequest)", gateIndex);
expect(gateIndex).toBeGreaterThan(0);
expect(tenantResolutionIndex).toBeGreaterThan(gateIndex);
expect(tenantRewriteIndex).toBeGreaterThan(tenantResolutionIndex);
expect(hostResolutionIndex).toBeGreaterThan(gateIndex);
expect(healthHostResolutionIndex).toBeGreaterThan(gateIndex);
expect(hostRewriteIndex).toBeGreaterThan(hostResolutionIndex);
expect(staticIndex).toBeGreaterThan(gateIndex);
expect(staticIndex).toBeGreaterThan(tenantRewriteIndex);
expect(staticIndex).toBeGreaterThan(hostRewriteIndex);
expect(routerIndex).toBeGreaterThan(staticIndex);
expect(serverSource).toContain("routingDecision.serveStaticAssets");
expect(serverSource).toContain("!routingDecision.reactRouterFallback");
expect(serverSource).not.toContain("resolveCustomerPortalFeatureEnabled");
expect(serverSource).not.toContain("finalizePortalFeatureRoutingDecision");
});
test("strips all client-supplied internal portal context headers", () => {
expect(serverSource).toContain('key.toLowerCase().startsWith("x-hivegrid-portal-")');
});
test("derives request protocol from validated config instead of spoofable forwarding headers", () => {
expect(serverSource).toContain("`${webConfig.routing.protocol}://${host}`");
expect(serverSource).toContain("`${webConfig.routing.protocol}://invalid.localhost`");
expect(serverSource).not.toContain('req.headers["x-forwarded-proto"]');
});
test("uses required web config for fail-fast production startup and listen host/port", () => {
@@ -24,6 +70,13 @@ describe("server runtime routing integration", () => {
expect(serverSource).not.toContain("process.env.HOST");
});
test("selects the complete RLS readiness contract for each runtime surface", () => {
expect(serverSource).toContain('import { assertPortalRlsRuntimeReady } from "@hivegrid/db/portal-rls-runtime-readiness.server"');
expect(serverSource).toContain('webConfig.runtimeSurface === "portal"');
expect(serverSource).toContain("await assertPortalRlsRuntimeReady()");
expect(serverSource).toContain("await assertRlsRuntimeReady()");
});
test("delegates root start to the web runtime owner", () => {
expect(rootPackage.scripts.start).toBe("pnpm --filter @hivegrid/web start");
expect(webPackage.scripts.start).toContain("node ../../build/server-runtime/server.js");
@@ -31,57 +84,128 @@ describe("server runtime routing integration", () => {
expect(rootPackage.scripts.start).not.toContain("tsx");
});
test("enters the request i18n scope before React Router runs loaders or actions", () => {
const scopeIndex = serverSource.indexOf("runWithRequestI18nScope(request");
const routerIndex = serverSource.indexOf("reactRouterRequestHandler(request)", scopeIndex);
expect(serverSource).toContain("build.entry.module");
expect(serverSource).toContain("Web server build is missing the request-scoped i18n entry wrapper");
expect(scopeIndex).toBeGreaterThan(0);
expect(routerIndex).toBeGreaterThan(scopeIndex);
});
test("resolves web build artifacts independently from caller cwd", () => {
expect(serverSource).toContain("const RUNTIME_DIRECTORY = path.dirname(fileURLToPath(import.meta.url))");
expect(serverSource).toContain('RUNTIME_DIRECTORY.endsWith(path.join("build", "server-runtime"))');
expect(serverSource).toContain('path.join(REPO_ROOT_DIRECTORY, "apps", "web", "build")');
expect(serverSource).toContain("getWebBuildDirectory(runtimeBuildSurface)");
expect(serverSource).toContain("runtimeBuildSurface !== webConfig.runtimeSurface");
expect(serverSource).not.toContain("process.env.WEB_BUILD_DIRECTORY");
expect(serverSource).toContain('const BUILD_PATH = path.join(WEB_BUILD_DIRECTORY, "server", "index.js")');
expect(serverSource).toContain('const CLIENT_BUILD_DIRECTORY = path.join(WEB_BUILD_DIRECTORY, "client")');
expect(serverSource).not.toContain('path.resolve("build/server/index.js")');
expect(serverSource).not.toContain('path.resolve("build/client")');
});
test("defines idempotent web security headers", () => {
test("validates and strips the reserved namespace before the selected route manifest", () => {
expect(serverSource).toContain("prepareReactRouterManifestRequest(routingDecision.request, runtimeBuildSurface)");
expect(serverSource).toContain("handleReactRouterRequest(manifestRequest)");
});
test("defines nonce-bound web security headers", () => {
expect(serverSource).toContain("function appendWebSecurityHeaders");
expect(serverSource).toContain("\"Content-Security-Policy\": \"base-uri 'self'; object-src 'none'; frame-ancestors 'self'\"");
expect(serverSource).toContain("buildDocumentContentSecurityPolicy(options.documentNonce, routePolicy, options.documentPolicy)");
expect(serverSource).toContain("getRequestDocumentContentSecurityPolicyOptions(request, webConfig, process.env, browserBuildEnv)");
expect(serverSource).toContain("overwriteRequestCspNonce(headers)");
expect(serverSource).toContain("getRequestCspNonce(request)");
expect(serverSource).toContain("STATIC_ASSET_CONTENT_SECURITY_POLICY");
expect(cspPolicySource).toContain("`'self' 'nonce-${nonce}' 'strict-dynamic'`");
expect(cspPolicySource).toContain('["script-src-attr", "\'none\'"]');
expect(cspPolicySource).toContain("[\"style-src\", \"'self' 'unsafe-inline'\"]");
expect(serverSource).toContain('"Strict-Transport-Security"] = "max-age=31536000; includeSubDomains"');
expect(serverSource).toContain('"X-Content-Type-Options": "nosniff"');
expect(serverSource).toContain('"Referrer-Policy": "strict-origin-when-cross-origin"');
expect(serverSource).toContain('"X-Frame-Options": "SAMEORIGIN"');
expect(serverSource).toContain('routeReferrerPolicy ?? "strict-origin-when-cross-origin"');
expect(serverSource).toContain('securityHeaders["X-Frame-Options"] = "SAMEORIGIN"');
expect(serverSource).toContain('removeHeader(headers, "X-Frame-Options")');
expect(serverSource).toContain('"Permissions-Policy": "camera=(), microphone=(), geolocation=(), payment=()"');
expect(serverSource).toContain('"Cross-Origin-Opener-Policy": "same-origin"');
expect(serverSource).toContain('"Cross-Origin-Resource-Policy": "same-origin"');
expect(serverSource).toContain('"Cross-Origin-Opener-Policy": allowsExternalFraming ? "unsafe-none" : "same-origin"');
expect(serverSource).toContain('"Cross-Origin-Resource-Policy": allowsExternalFraming ? "cross-origin" : "same-origin"');
expect(serverSource).toContain('"Cross-Origin-Embedder-Policy": "unsafe-none"');
expect(serverSource).toContain('key === "Content-Security-Policy" && hasHeader(headers, key)');
expect(serverSource).toContain("headers.set(key, value)");
expect(serverSource).toContain("headers.setHeader(key, value)");
expect(serverSource).toContain("key.toLowerCase() === CSP_NONCE_REQUEST_HEADER");
expect(serverSource).toContain('allowsExternalFraming ? "unsafe-none" : "same-origin"');
expect(serverSource).toContain('allowsExternalFraming ? "cross-origin" : "same-origin"');
});
test("applies web security headers to forwarded responses", () => {
expect(serverSource).toMatch(/for \(const \[key, value\] of response\.headers\)[\s\S]*res\.appendHeader\(key, value\);[\s\S]*appendWebSecurityHeaders\(res\);/);
expect(serverSource).toMatch(
/for \(const \[key, value\] of response\.headers\)[\s\S]*res\.appendHeader\(key, value\);[\s\S]*appendWebSecurityHeaders\(res\);/
);
});
test("applies web security headers to static assets without changing cache control", () => {
expect(serverSource).toContain('headers["Cache-Control"] = "public, max-age=31536000, immutable"');
test("overrides every capability response with no-store and no-referrer before final security headers", () => {
expect(serverSource).toContain("getPortalCapabilityResponseSecurityHeaders(request, runtimeBuildSurface)");
expect(serverSource).toMatch(/portalCapabilityHeaders[\s\S]*res\.setHeader\(key, value\)[\s\S]*appendWebSecurityHeaders\(res/);
});
test("applies web security and representation headers to static assets", () => {
expect(serverSource).toContain('"Cache-Control": getStaticCacheControl');
expect(serverSource).toContain('headers["Content-Encoding"] = representation.encoding');
expect(serverSource).toContain('headers.Vary = "Accept-Encoding"');
expect(serverSource).toContain("isStaticAssetNotModified");
expect(serverSource).toMatch(/function getStaticHeaders[\s\S]*return appendWebSecurityHeaders\(headers\);/);
});
test("allows only the service worker to fetch same-origin static assets", () => {
expect(serverSource).toContain('requestUrl.pathname === "/sw.js"');
expect(serverSource).toContain('headers["Content-Security-Policy"] = SERVICE_WORKER_CONTENT_SECURITY_POLICY');
expect(cspPolicySource).toContain("STATIC_ASSET_CONTENT_SECURITY_POLICY.replace(\n \"connect-src 'none'\",\n \"connect-src 'self'\"");
});
test("sets a 1-day cache for /fonts and /images static assets", () => {
// Hash-named bundles get `immutable` because their URL contains the hash,
// but unhashed brand assets need a shorter TTL or stale-content lingers.
// See docs/improvement-plan/03-scaling-infrastructure/asset-cdn.md.
expect(serverSource).toContain('headers["Cache-Control"] = "public, max-age=86400"');
expect(serverSource).toMatch(/pathname === "\/fonts"[\s\S]*pathname\.startsWith\("\/fonts\/"\)/);
expect(serverSource).toMatch(/pathname === "\/images"[\s\S]*pathname\.startsWith\("\/images\/"\)/);
expect(staticAssetsSource).toContain("public, max-age=86400, stale-while-revalidate=604800");
expect(staticAssetsSource).toMatch(/pathname === "\/fonts"[\s\S]*pathname\.startsWith\("\/fonts\/"\)/);
expect(staticAssetsSource).toMatch(/pathname === "\/images"[\s\S]*pathname\.startsWith\("\/images\/"\)/);
});
test("bounds slow requests, headers, keep-alive reuse and request bodies", () => {
expect(serverSource).toContain("server.requestTimeout = 120_000");
expect(serverSource).toContain("server.headersTimeout = 15_000");
expect(serverSource).toContain("server.keepAliveTimeout = 5_000");
expect(serverSource).toContain("server.maxHeadersCount = 100");
expect(serverSource).toContain("server.maxRequestsPerSocket = 1_000");
expect(serverSource).toContain("resolveWebRequestBodyLimit(req.url, webConfig.runtimeSurface)");
expect(serverSource).toContain("createLimitedRequestBody(req, bodyLimitBytes)");
});
test("rejects cross-origin browser mutations before React Router actions", () => {
expect(serverSource).toContain('import { validateMutationOrigin } from "./request-origin"');
expect(serverSource).toContain("validateMutationOrigin(manifestRequest)");
expect(serverSource).toContain('"cross-origin web mutation rejected"');
expect(serverSource).toContain('new Response("Forbidden"');
expect(serverSource.indexOf("validateMutationOrigin(manifestRequest)")).toBeLessThan(serverSource.indexOf("handleReactRouterRequest(manifestRequest)"));
});
test("uses a bounded graceful-shutdown deadline", () => {
expect(serverSource).toContain("server.closeIdleConnections()");
expect(serverSource).toContain("server.closeAllConnections()");
expect(serverSource).toContain("10_000");
});
test("wires server diagnostics through the structured logger", () => {
expect(serverSource).toContain('import { createChildLogger, defaultLogger } from "@hivegrid/logger"');
expect(serverSource).toContain('const serverLogger = createChildLogger(defaultLogger, { component: "server" })');
expect(serverSource).toContain("service: getWebServiceName(webConfig.runtimeSurface)");
expect(serverSource).toContain("surface: webConfig.runtimeSurface");
expect(serverSource).toContain('serverLogger.error({ error }, "server request failed")');
expect(serverSource).toContain('serverLogger.info({ host: address, port: PORT }, "server listening")');
expect(serverSource).toContain('serverLogger.error({ error }, "server shutdown failed")');
expect(serverSource).toContain('serverLogger.error({ error }, "static asset stream failed")');
expect(serverSource).toContain('event: "web.response.client_disconnected"');
expect(serverSource).toContain("if (request.signal.aborted)");
expect(serverSource).not.toContain("request.signal.aborted || res.destroyed");
});
test("does not leave active console diagnostics in the server runtime", () => {
@@ -1,14 +1,49 @@
import { ServerResponse, createServer, type IncomingMessage } from "node:http";
import { createReadStream } from "node:fs";
import { stat } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { fileURLToPath, pathToFileURL } from "node:url";
import type { ServerBuild } from "react-router";
import { loadRequiredWebConfig } from "@hivegrid/config";
import { assertRlsRuntimeReady } from "@hivegrid/db/rls-runtime-readiness.server";
import { assertPortalRlsRuntimeReady } from "@hivegrid/db/portal-rls-runtime-readiness.server";
import {
resolvePortalRuntimeCustomHost,
resolvePortalRuntimeCustomHostHealth,
resolvePortalRuntimeTenant,
} from "@hivegrid/db/portal-runtime-tenant.server";
import { createChildLogger, defaultLogger } from "@hivegrid/logger";
import { app as apiApp } from "../apps/api/src/app";
import { getHostRoutingRuntimeDecision } from "./host-routing-runtime";
import {
finalizePortalHostRoutingDecision,
finalizePortalTenantRoutingDecision,
getHostRoutingRuntimeDecision,
} from "./host-routing-runtime";
import {
createStaticEtag,
getStaticAssetMetadata,
getStaticCacheControl,
hasCompressedRepresentation,
isStaticAssetNotModified,
selectStaticRepresentation,
type StaticAssetMetadata,
type StaticAssetRepresentation,
} from "./static-assets";
import { createLimitedRequestBody, isRequestBodyTooLargeError, parseRequestContentLength, resolveWebRequestBodyLimit } from "./request-body";
import { validateMutationOrigin } from "./request-origin";
import { overwriteRequestCspNonce } from "./csp";
import { prepareReactRouterManifestRequest } from "./react-router-manifest-dispatch";
import { getPortalCapabilityResponseSecurityHeaders } from "../apps/web/app/services/customer-portal/portal-response-security";
import { getWebBuildDirectory, getWebServiceName, requireWebBuildSurface } from "../apps/web/build-surface";
import {
CSP_NONCE_REQUEST_HEADER,
SERVICE_WORKER_CONTENT_SECURITY_POLICY,
STATIC_ASSET_CONTENT_SECURITY_POLICY,
buildDocumentContentSecurityPolicy,
contentSecurityPolicyAllowsExternalFraming,
getRequestCspNonce,
type DocumentContentSecurityPolicyOptions,
} from "../apps/web/app/utils/security/contentSecurityPolicy";
import { getRequestDocumentContentSecurityPolicyOptions } from "../apps/web/app/utils/security/requestContentSecurityPolicy.server";
process.env.NODE_ENV = process.env.NODE_ENV ?? "production";
@@ -16,9 +51,12 @@ const RUNTIME_DIRECTORY = path.dirname(fileURLToPath(import.meta.url));
const REPO_ROOT_DIRECTORY = RUNTIME_DIRECTORY.endsWith(path.join("build", "server-runtime"))
? path.resolve(RUNTIME_DIRECTORY, "..", "..")
: path.resolve(RUNTIME_DIRECTORY, "..");
const WEB_BUILD_DIRECTORY = process.env.WEB_BUILD_DIRECTORY
? path.resolve(process.env.WEB_BUILD_DIRECTORY)
: path.join(REPO_ROOT_DIRECTORY, "apps", "web", "build");
const webConfig = loadRequiredWebConfig();
const runtimeBuildSurface = requireWebBuildSurface();
if (runtimeBuildSurface !== webConfig.runtimeSurface) {
throw new Error("HIVEGRID_RUNTIME_SURFACE must match WEB_RUNTIME_SURFACE");
}
const WEB_BUILD_DIRECTORY = path.join(REPO_ROOT_DIRECTORY, "apps", "web", getWebBuildDirectory(runtimeBuildSurface));
const BUILD_PATH = path.join(WEB_BUILD_DIRECTORY, "server", "index.js");
const CLIENT_BUILD_DIRECTORY = path.join(WEB_BUILD_DIRECTORY, "client");
const ALLOWED_STATIC_ASSET_EXTENSIONS = new Set([
@@ -42,51 +80,136 @@ const ALLOWED_STATIC_ASSET_EXTENSIONS = new Set([
".woff2",
".xml",
]);
const webConfig = loadRequiredWebConfig();
const PORT = webConfig.listen.port;
const HOST = webConfig.listen.host;
const serverLogger = createChildLogger(defaultLogger, { component: "server" });
const serverLogger = createChildLogger(defaultLogger, {
component: "server",
service: getWebServiceName(webConfig.runtimeSurface),
surface: webConfig.runtimeSurface,
});
const browserBuildEnv = {
VITE_SENTRY_DSN_WEB: process.env.VITE_SENTRY_DSN_WEB,
VITE_OTEL_EXPORTER_OTLP_ENDPOINT: process.env.VITE_OTEL_EXPORTER_OTLP_ENDPOINT,
VITE_HOCUSPOCUS_URL: process.env.VITE_HOCUSPOCUS_URL,
};
const rlsReadiness = webConfig.runtimeSurface === "portal" ? await assertPortalRlsRuntimeReady() : await assertRlsRuntimeReady();
if (!rlsReadiness.ready) {
serverLogger.warn({ diagnostics: rlsReadiness.diagnostics, surface: webConfig.runtimeSurface }, "RLS runtime is running in audit mode with failed checks");
}
const [{ createRequestHandler }, { createReadableStreamFromReadable, writeReadableStreamToWritable }] = await Promise.all([
import("react-router"),
import("@react-router/node"),
]);
const build = (await import(pathToFileURL(BUILD_PATH).href)) as ServerBuild;
const handleReactRouterRequest = createRequestHandler(build, process.env.NODE_ENV);
const reactRouterRequestHandler = createRequestHandler(build, process.env.NODE_ENV);
type RequestI18nScopeRunner = (request: Request, callback: () => Promise<Response>) => Promise<Response>;
const runWithRequestI18nScope = (
build.entry.module as ServerBuild["entry"]["module"] & {
runWithRequestI18nScope?: RequestI18nScopeRunner;
}
).runWithRequestI18nScope;
if (typeof runWithRequestI18nScope !== "function") {
throw new Error("Web server build is missing the request-scoped i18n entry wrapper");
}
const handleReactRouterRequest = (request: Request) => runWithRequestI18nScope(request, () => reactRouterRequestHandler(request));
type NodeRequestInit = RequestInit & { duplex?: "half" };
const server = createServer(async (req, res) => {
try {
if (await serveStaticAsset(req, res)) {
const requestBodyLimit = resolveWebRequestBodyLimit(req.url, webConfig.runtimeSurface);
const declaredBodyLength = getDeclaredBodyLength(req);
if (declaredBodyLength !== null && declaredBodyLength > requestBodyLimit) {
sendPayloadTooLarge(res);
return;
}
const request = createWebRequest(req, res);
const routingDecision = getHostRoutingRuntimeDecision(request);
const request = createWebRequest(req, res, requestBodyLimit);
let routingDecision = getHostRoutingRuntimeDecision(request, {
runtimeSurface: webConfig.runtimeSurface,
routing: webConfig.routing,
});
if (routingDecision.type === "resolve-portal-tenant") {
const tenant = await resolvePortalRuntimeTenant(routingDecision.tenantSlug);
routingDecision = finalizePortalTenantRoutingDecision(routingDecision, tenant?.tenantSlug ?? null);
}
if (routingDecision.type === "resolve-portal-host") {
const host =
new URL(routingDecision.request.url).pathname === "/healthz"
? await resolvePortalRuntimeCustomHostHealth(routingDecision.hostname)
: await resolvePortalRuntimeCustomHost(routingDecision.hostname);
routingDecision = finalizePortalHostRoutingDecision(routingDecision, host);
}
if (routingDecision.type === "redirect") {
await sendWebResponse(
res,
new Response(null, {
status: routingDecision.status,
headers: { Location: routingDecision.location },
})
}),
request
);
return;
}
if (routingDecision.type === "reject") {
await sendWebResponse(res, new Response("Not Found", { status: routingDecision.status }));
await sendWebResponse(res, new Response("Not Found", { status: routingDecision.status }), request);
return;
}
if (routingDecision.target === "web" && isWebOperationalRoute(request)) {
await sendWebResponse(res, await handleReactRouterRequest(request));
if (routingDecision.serveStaticAssets) {
if (await serveStaticAsset(req, res)) {
return;
}
if (!routingDecision.reactRouterFallback) {
await sendWebResponse(res, new Response("Not Found", { status: 404 }), routingDecision.request);
return;
}
}
const manifestDispatchDecision = prepareReactRouterManifestRequest(routingDecision.request, runtimeBuildSurface);
if (manifestDispatchDecision.type === "reject") {
await sendWebResponse(res, new Response("Not Found", { status: manifestDispatchDecision.status }), routingDecision.request);
return;
}
const manifestRequest = manifestDispatchDecision.request;
const mutationOriginDecision = validateMutationOrigin(manifestRequest);
if (!mutationOriginDecision.allowed) {
serverLogger.warn({ reason: mutationOriginDecision.reason, method: manifestRequest.method }, "cross-origin web mutation rejected");
await sendWebResponse(
res,
new Response("Forbidden", {
status: 403,
headers: { "Cache-Control": "no-store" },
}),
manifestRequest
);
return;
}
const response = routingDecision.target === "api" ? await apiApp.fetch(routingDecision.request) : await handleReactRouterRequest(routingDecision.request);
await sendWebResponse(res, response);
if (routingDecision.target === "web" && isWebOperationalRoute(manifestRequest)) {
await sendWebResponse(res, await handleReactRouterRequest(manifestRequest), manifestRequest);
return;
}
if (routingDecision.target === "api") {
serverLogger.warn({ host: request.headers.get("host") }, "API host request rejected by web runtime");
await sendWebResponse(res, new Response("Not Found", { status: 404 }), request);
return;
}
await sendWebResponse(res, await handleReactRouterRequest(manifestRequest), manifestRequest);
} catch (error) {
if (isRequestBodyTooLargeError(error)) {
sendPayloadTooLarge(res);
return;
}
serverLogger.error({ error }, "server request failed");
if (!res.headersSent) {
res.statusCode = 500;
@@ -96,20 +219,20 @@ const server = createServer(async (req, res) => {
}
});
server.requestTimeout = 120_000;
server.headersTimeout = 15_000;
server.keepAliveTimeout = 5_000;
server.maxHeadersCount = 100;
server.maxRequestsPerSocket = 1_000;
server.listen(PORT, HOST, () => {
const address = HOST ?? getLocalAddress() ?? "localhost";
serverLogger.info({ host: address, port: PORT }, "server listening");
});
let shuttingDown = false;
for (const signal of ["SIGTERM", "SIGINT"] as const) {
process.once(signal, () => {
server.close((error) => {
if (error) {
serverLogger.error({ error }, "server shutdown failed");
process.exitCode = 1;
}
});
});
process.once(signal, () => beginGracefulShutdown(signal));
}
async function serveStaticAsset(req: IncomingMessage, res: ServerResponse) {
@@ -123,12 +246,29 @@ async function serveStaticAsset(req: IncomingMessage, res: ServerResponse) {
return false;
}
const fileStat = await stat(filePath).catch(() => null);
if (!fileStat?.isFile()) {
const metadata = await getStaticAssetMetadata(filePath);
if (!metadata) {
return false;
}
const headers = getStaticHeaders(filePath, requestUrl.pathname);
const representation = selectStaticRepresentation(metadata, getSingleHeader(req.headers["accept-encoding"]));
const headers = getStaticHeaders(filePath, requestUrl, metadata, representation);
const etag = headers.ETag;
if (
etag &&
isStaticAssetNotModified({
etag,
ifNoneMatch: getSingleHeader(req.headers["if-none-match"]),
ifModifiedSince: getSingleHeader(req.headers["if-modified-since"]),
mtimeMs: metadata.identity.stat.mtimeMs,
})
) {
delete headers["Content-Length"];
res.writeHead(304, headers);
res.end();
return true;
}
res.writeHead(200, headers);
if (req.method === "HEAD") {
@@ -136,7 +276,7 @@ async function serveStaticAsset(req: IncomingMessage, res: ServerResponse) {
return true;
}
createReadStream(filePath)
createReadStream(representation.filePath)
.on("error", (error) => {
serverLogger.error({ error }, "static asset stream failed");
if (!res.headersSent) {
@@ -173,39 +313,53 @@ function getClientFilePath(pathname: string) {
return filePath;
}
function createWebRequest(req: IncomingMessage, res: ServerResponse) {
const protocol = req.headers["x-forwarded-proto"]?.toString().split(",")[0]?.trim() || "http";
function createWebRequest(req: IncomingMessage, res: ServerResponse, bodyLimitBytes: number) {
const host = req.headers.host || "localhost";
const url = new URL(req.url ?? "/", `${protocol}://${host}`);
const url = createWebRequestUrl(req.url, host);
const controller = new AbortController();
res.on("close", () => {
controller.abort();
});
const headers = createWebHeaders(req.headers);
overwriteRequestCspNonce(headers);
const init: NodeRequestInit = {
method: req.method,
headers: createWebHeaders(req.headers),
headers,
signal: controller.signal,
};
if (req.method !== "GET" && req.method !== "HEAD") {
init.body = createReadableStreamFromReadable(req);
init.body = createReadableStreamFromReadable(createLimitedRequestBody(req, bodyLimitBytes));
init.duplex = "half";
}
return new Request(url, init);
}
function createWebRequestUrl(requestUrl: string | undefined, host: string) {
try {
return new URL(requestUrl ?? "/", `${webConfig.routing.protocol}://${host}`);
} catch {
// Preserve the original Host header for the routing gate; this inert URL
// only prevents malformed client input from escaping the fail-closed 404.
return new URL(requestUrl ?? "/", `${webConfig.routing.protocol}://invalid.localhost`);
}
}
function isWebOperationalRoute(request: Request) {
const { pathname } = new URL(request.url);
return pathname === "/healthz" || pathname === "/readyz" || pathname === "/healthcheck";
return pathname === "/healthz" || pathname === "/readyz" || pathname === "/healthcheck" || pathname === "/api/metrics";
}
function createWebHeaders(headers: IncomingMessage["headers"]) {
const webHeaders = new Headers();
for (const [key, value] of Object.entries(headers)) {
if (key.toLowerCase().startsWith("x-hivegrid-portal-")) {
continue;
}
if (Array.isArray(value)) {
for (const item of value) {
webHeaders.append(key, item);
@@ -218,35 +372,65 @@ function createWebHeaders(headers: IncomingMessage["headers"]) {
return webHeaders;
}
async function sendWebResponse(res: ServerResponse, response: Response) {
async function sendWebResponse(res: ServerResponse, response: Response, request: Request) {
res.statusCode = response.status;
res.statusMessage = response.statusText;
for (const [key, value] of response.headers) {
if (key.toLowerCase() === CSP_NONCE_REQUEST_HEADER) continue;
res.appendHeader(key, value);
}
appendWebSecurityHeaders(res);
const portalCapabilityHeaders = getPortalCapabilityResponseSecurityHeaders(request, runtimeBuildSurface);
if (portalCapabilityHeaders) {
for (const [key, value] of Object.entries(portalCapabilityHeaders)) {
res.setHeader(key, value);
}
}
appendWebSecurityHeaders(res, {
documentNonce: getRequestCspNonce(request),
documentPolicy: getRequestDocumentContentSecurityPolicyOptions(request, webConfig, process.env, browserBuildEnv),
});
if (!response.body) {
res.end();
return;
}
await writeReadableStreamToWritable(response.body, res);
try {
await writeReadableStreamToWritable(response.body, res);
} catch (error) {
// A browser can abandon an SSR or SSE response while it is still streaming.
// This is expected transport cancellation, not a server failure.
if (request.signal.aborted) {
serverLogger.debug({ event: "web.response.client_disconnected" }, "web response stream ended after client disconnect");
return;
}
throw error;
}
}
function appendWebSecurityHeaders(headers: Headers): Headers;
function appendWebSecurityHeaders(headers: Record<string, string>): Record<string, string>;
function appendWebSecurityHeaders(headers: ServerResponse): ServerResponse;
function appendWebSecurityHeaders(headers: Headers | Record<string, string> | ServerResponse) {
type WebSecurityHeaderOptions = {
documentNonce?: string;
documentPolicy?: DocumentContentSecurityPolicyOptions;
};
function appendWebSecurityHeaders(headers: Headers, options?: WebSecurityHeaderOptions): Headers;
function appendWebSecurityHeaders(headers: Record<string, string>, options?: WebSecurityHeaderOptions): Record<string, string>;
function appendWebSecurityHeaders(headers: ServerResponse, options?: WebSecurityHeaderOptions): ServerResponse;
function appendWebSecurityHeaders(headers: Headers | Record<string, string> | ServerResponse, options: WebSecurityHeaderOptions = {}) {
const routePolicy = getHeaderValue(headers, "Content-Security-Policy");
const routeReferrerPolicy = getHeaderValue(headers, "Referrer-Policy");
const contentSecurityPolicy = options.documentNonce
? buildDocumentContentSecurityPolicy(options.documentNonce, routePolicy, options.documentPolicy)
: (routePolicy ?? STATIC_ASSET_CONTENT_SECURITY_POLICY);
const allowsExternalFraming = contentSecurityPolicyAllowsExternalFraming(contentSecurityPolicy);
const securityHeaders: Record<string, string> = {
"Content-Security-Policy": "base-uri 'self'; object-src 'none'; frame-ancestors 'self'",
"Content-Security-Policy": contentSecurityPolicy,
"X-Content-Type-Options": "nosniff",
"Referrer-Policy": "strict-origin-when-cross-origin",
"X-Frame-Options": "SAMEORIGIN",
"Referrer-Policy": routeReferrerPolicy ?? "strict-origin-when-cross-origin",
"Permissions-Policy": "camera=(), microphone=(), geolocation=(), payment=()",
"Cross-Origin-Opener-Policy": "same-origin",
"Cross-Origin-Resource-Policy": "same-origin",
"Cross-Origin-Opener-Policy": allowsExternalFraming ? "unsafe-none" : "same-origin",
"Cross-Origin-Resource-Policy": allowsExternalFraming ? "cross-origin" : "same-origin",
"Cross-Origin-Embedder-Policy": "unsafe-none",
};
@@ -254,10 +438,13 @@ function appendWebSecurityHeaders(headers: Headers | Record<string, string> | Se
securityHeaders["Strict-Transport-Security"] = "max-age=31536000; includeSubDomains";
}
if (allowsExternalFraming) {
removeHeader(headers, "X-Frame-Options");
} else {
securityHeaders["X-Frame-Options"] = "SAMEORIGIN";
}
for (const [key, value] of Object.entries(securityHeaders)) {
if (key === "Content-Security-Policy" && hasHeader(headers, key)) {
continue;
}
if (headers instanceof Headers) {
headers.set(key, value);
} else if (headers instanceof ServerResponse) {
@@ -270,37 +457,103 @@ function appendWebSecurityHeaders(headers: Headers | Record<string, string> | Se
return headers;
}
function hasHeader(headers: Headers | Record<string, string> | ServerResponse, key: string) {
function getHeaderValue(headers: Headers | Record<string, string> | ServerResponse, key: string): string | undefined {
if (headers instanceof Headers) {
return headers.has(key);
return headers.get(key) ?? undefined;
}
if (headers instanceof ServerResponse) {
return headers.hasHeader(key);
const value = headers.getHeader(key);
if (Array.isArray(value)) return value.join("; ");
return value === undefined ? undefined : String(value);
}
const normalizedKey = key.toLowerCase();
return Object.keys(headers).some((candidate) => candidate.toLowerCase() === normalizedKey);
const candidate = Object.keys(headers).find((headerName) => headerName.toLowerCase() === normalizedKey);
return candidate ? headers[candidate] : undefined;
}
function getStaticHeaders(filePath: string, pathname: string) {
function removeHeader(headers: Headers | Record<string, string> | ServerResponse, key: string): void {
if (headers instanceof Headers) {
headers.delete(key);
return;
}
if (headers instanceof ServerResponse) {
headers.removeHeader(key);
return;
}
const normalizedKey = key.toLowerCase();
for (const candidate of Object.keys(headers)) {
if (candidate.toLowerCase() === normalizedKey) delete headers[candidate];
}
}
function getStaticHeaders(filePath: string, requestUrl: URL, metadata: StaticAssetMetadata, representation: StaticAssetRepresentation) {
const headers: Record<string, string> = {
"Content-Type": getContentType(filePath),
"Content-Length": String(representation.stat.size),
"Last-Modified": metadata.identity.stat.mtime.toUTCString(),
ETag: createStaticEtag(representation),
"Cache-Control": getStaticCacheControl(requestUrl.pathname, Boolean(requestUrl.searchParams.get("v"))),
};
// Cache-Control strategy aligned with docs/ops/asset-cdn.md:
// * /assets/* → Vite-hashed, safe to cache forever (1 year, immutable)
// * /fonts/* → static brand assets, 1 day
// * /images/* → static brand assets, 1 day
// Anything else (HTML / loader responses / favicons) keeps the default
// (no Cache-Control here — the loader / entry.server is in charge).
if (pathname === "/assets" || pathname.startsWith("/assets/")) {
headers["Cache-Control"] = "public, max-age=31536000, immutable";
} else if (pathname === "/fonts" || pathname.startsWith("/fonts/") || pathname === "/images" || pathname.startsWith("/images/")) {
headers["Cache-Control"] = "public, max-age=86400";
if (requestUrl.pathname === "/sw.js") {
headers["Content-Security-Policy"] = SERVICE_WORKER_CONTENT_SECURITY_POLICY;
}
if (representation.encoding !== "identity") {
headers["Content-Encoding"] = representation.encoding;
}
if (hasCompressedRepresentation(metadata)) {
headers.Vary = "Accept-Encoding";
}
return appendWebSecurityHeaders(headers);
}
function getSingleHeader(value: string | string[] | undefined): string | undefined {
return Array.isArray(value) ? value.at(-1) : value;
}
function getDeclaredBodyLength(req: IncomingMessage): number | null {
if (req.method === "GET" || req.method === "HEAD") {
return null;
}
return parseRequestContentLength(getSingleHeader(req.headers["content-length"]));
}
function sendPayloadTooLarge(res: ServerResponse): void {
if (res.headersSent) {
res.destroy();
return;
}
res.statusCode = 413;
res.shouldKeepAlive = false;
res.setHeader("Connection", "close");
res.setHeader("Content-Type", "text/plain; charset=utf-8");
res.setHeader("Cache-Control", "no-store");
appendWebSecurityHeaders(res);
res.end("Request body too large");
}
function beginGracefulShutdown(signal: "SIGINT" | "SIGTERM"): void {
if (shuttingDown) return;
shuttingDown = true;
serverLogger.info({ signal }, "server shutdown started");
server.closeIdleConnections();
const forceCloseTimer = setTimeout(() => {
serverLogger.error({ signal }, "server shutdown deadline exceeded");
server.closeAllConnections();
process.exitCode = 1;
}, 10_000);
forceCloseTimer.unref();
server.close((error) => {
clearTimeout(forceCloseTimer);
if (error) {
serverLogger.error({ error }, "server shutdown failed");
process.exitCode = 1;
}
});
}
function getContentType(filePath: string) {
switch (path.extname(filePath).toLowerCase()) {
case ".css":
@@ -0,0 +1,60 @@
import { mkdtemp, rm, writeFile } from "node:fs/promises";
import os from "node:os";
import path from "node:path";
import { afterEach, describe, expect, test } from "vitest";
import {
__resetStaticAssetMetadataCacheForTests,
createStaticEtag,
getStaticAssetMetadata,
getStaticCacheControl,
isStaticAssetNotModified,
selectStaticRepresentation,
} from "./static-assets";
const temporaryDirectories: string[] = [];
afterEach(async () => {
__resetStaticAssetMetadataCacheForTests();
await Promise.all(temporaryDirectories.splice(0).map((directory) => rm(directory, { force: true, recursive: true })));
});
async function createAssetFixture() {
const directory = await mkdtemp(path.join(os.tmpdir(), "hivegrid-static-"));
temporaryDirectories.push(directory);
const filePath = path.join(directory, "asset.js");
await Promise.all([writeFile(filePath, "identity"), writeFile(`${filePath}.br`, "br"), writeFile(`${filePath}.gz`, "gzip")]);
return filePath;
}
describe("static asset metadata", () => {
test("selects the highest-quality available precompressed representation", async () => {
const metadata = await getStaticAssetMetadata(await createAssetFixture());
expect(metadata).not.toBeNull();
expect(selectStaticRepresentation(metadata!, "gzip;q=1, br;q=0.5").encoding).toBe("gzip");
expect(selectStaticRepresentation(metadata!, "gzip;q=0, br").encoding).toBe("br");
expect(selectStaticRepresentation(metadata!, undefined).encoding).toBe("identity");
});
test("uses representation-specific validators and honours conditional requests", async () => {
const metadata = await getStaticAssetMetadata(await createAssetFixture());
const representation = selectStaticRepresentation(metadata!, "br");
const etag = createStaticEtag(representation);
expect(etag).toContain("-br");
expect(isStaticAssetNotModified({ etag, ifNoneMatch: etag, mtimeMs: representation.stat.mtimeMs })).toBe(true);
expect(isStaticAssetNotModified({ etag, ifNoneMatch: 'W/"different"', mtimeMs: representation.stat.mtimeMs })).toBe(false);
expect(
isStaticAssetNotModified({
etag,
ifModifiedSince: new Date(representation.stat.mtimeMs + 1_000).toUTCString(),
mtimeMs: representation.stat.mtimeMs,
})
).toBe(true);
});
test("gives revisioned locales immutable caching and unversioned locales a short revalidation window", () => {
expect(getStaticCacheControl("/assets/app-hash.js", false)).toContain("immutable");
expect(getStaticCacheControl("/locales/de/common.json", true)).toContain("immutable");
expect(getStaticCacheControl("/locales/de/common.json", false)).toContain("must-revalidate");
});
});
@@ -0,0 +1,129 @@
import type { Stats } from "node:fs";
import { stat } from "node:fs/promises";
export type StaticContentEncoding = "br" | "gzip" | "identity";
export type StaticAssetRepresentation = {
encoding: StaticContentEncoding;
filePath: string;
stat: Stats;
};
export type StaticAssetMetadata = {
identity: StaticAssetRepresentation;
br?: StaticAssetRepresentation;
gzip?: StaticAssetRepresentation;
};
const metadataCache = new Map<string, Promise<StaticAssetMetadata | null>>();
export async function getStaticAssetMetadata(filePath: string): Promise<StaticAssetMetadata | null> {
const cached = metadataCache.get(filePath);
if (cached) {
return cached;
}
const pending = loadStaticAssetMetadata(filePath);
metadataCache.set(filePath, pending);
const metadata = await pending;
if (metadata === null) {
// Do not let attacker-controlled misses grow a process-lifetime cache.
metadataCache.delete(filePath);
}
return metadata;
}
async function loadStaticAssetMetadata(filePath: string): Promise<StaticAssetMetadata | null> {
const identityStat = await stat(filePath).catch(() => null);
if (!identityStat?.isFile()) {
return null;
}
const [brStat, gzipStat] = await Promise.all([stat(`${filePath}.br`).catch(() => null), stat(`${filePath}.gz`).catch(() => null)]);
return {
identity: { encoding: "identity", filePath, stat: identityStat },
...(brStat?.isFile() ? { br: { encoding: "br" as const, filePath: `${filePath}.br`, stat: brStat } } : {}),
...(gzipStat?.isFile() ? { gzip: { encoding: "gzip" as const, filePath: `${filePath}.gz`, stat: gzipStat } } : {}),
};
}
export function selectStaticRepresentation(metadata: StaticAssetMetadata, acceptEncoding: string | undefined): StaticAssetRepresentation {
const accepted = parseAcceptEncoding(acceptEncoding);
const candidates = [
metadata.br ? { quality: accepted.get("br") ?? accepted.get("*") ?? 0, representation: metadata.br, preference: 2 } : null,
metadata.gzip ? { quality: accepted.get("gzip") ?? accepted.get("*") ?? 0, representation: metadata.gzip, preference: 1 } : null,
]
.filter((candidate): candidate is NonNullable<typeof candidate> => candidate !== null && candidate.quality > 0)
.sort((left, right) => right.quality - left.quality || right.preference - left.preference);
return candidates[0]?.representation ?? metadata.identity;
}
function parseAcceptEncoding(value: string | undefined): Map<string, number> {
const accepted = new Map<string, number>();
for (const item of value?.split(",") ?? []) {
const [rawEncoding, ...parameters] = item.trim().toLowerCase().split(";");
if (!rawEncoding) continue;
let quality = 1;
for (const parameter of parameters) {
const match = /^q\s*=\s*(0(?:\.\d+)?|1(?:\.0+)?)$/.exec(parameter.trim());
if (match) {
quality = Number(match[1]);
}
}
accepted.set(rawEncoding, quality);
}
return accepted;
}
export function createStaticEtag(representation: StaticAssetRepresentation): string {
const size = representation.stat.size.toString(16);
const modified = Math.trunc(representation.stat.mtimeMs).toString(16);
return `W/"${size}-${modified}-${representation.encoding}"`;
}
export function isStaticAssetNotModified(input: { etag: string; ifModifiedSince?: string; ifNoneMatch?: string; mtimeMs: number }): boolean {
if (input.ifNoneMatch !== undefined) {
const expected = normalizeWeakEtag(input.etag);
return input.ifNoneMatch
.split(",")
.map((value) => value.trim())
.some((value) => value === "*" || normalizeWeakEtag(value) === expected);
}
if (input.ifModifiedSince === undefined) {
return false;
}
const since = Date.parse(input.ifModifiedSince);
if (!Number.isFinite(since)) {
return false;
}
return Math.floor(input.mtimeMs / 1000) <= Math.floor(since / 1000);
}
function normalizeWeakEtag(value: string): string {
return value.trim().replace(/^W\//i, "");
}
export function getStaticCacheControl(pathname: string, localeIsRevisioned: boolean): string {
if (pathname === "/assets" || pathname.startsWith("/assets/")) {
return "public, max-age=31536000, immutable";
}
if (pathname === "/locales" || pathname.startsWith("/locales/")) {
return localeIsRevisioned ? "public, max-age=31536000, immutable" : "public, max-age=300, must-revalidate, stale-while-revalidate=86400";
}
if (pathname === "/fonts" || pathname.startsWith("/fonts/") || pathname === "/images" || pathname.startsWith("/images/")) {
return "public, max-age=86400, stale-while-revalidate=604800";
}
return "public, max-age=0, must-revalidate";
}
export function hasCompressedRepresentation(metadata: StaticAssetMetadata): boolean {
return metadata.br !== undefined || metadata.gzip !== undefined;
}
/** Test-only hook for deterministic metadata-cache assertions. */
export function __resetStaticAssetMetadataCacheForTests(): void {
metadataCache.clear();
}
@@ -0,0 +1,100 @@
// @vitest-environment node
import { spawnSync } from "node:child_process";
import path from "node:path";
import { describe, expect, test } from "vitest";
const entrypoint = path.join(process.cwd(), "start.sh");
const commonEnv = {
PATH: process.env.PATH,
RLS_RUNTIME_MODE: "required",
DATABASE_URL: "postgresql://runtime.invalid/hivegrid",
};
function runEntrypoint(env: Record<string, string | undefined>) {
return spawnSync("sh", [entrypoint], {
cwd: process.cwd(),
env: { ...commonEnv, ...env },
encoding: "utf8",
});
}
describe("web runtime entrypoint surface boundary", () => {
test("fails closed when the production surface is missing or invalid", () => {
for (const surface of [undefined, "customer"]) {
const result = runEntrypoint({ WEB_RUNTIME_SURFACE: surface });
expect(result.status).toBe(1);
expect(result.stderr).toContain("WEB_RUNTIME_SURFACE must be explicitly set to core, admin, or portal");
}
});
test("requires the core role and forbids the portal session secret", () => {
const wrongRole = runEntrypoint({
WEB_RUNTIME_SURFACE: "core",
DATABASE_RUNTIME_ROLE: "hivegrid_portal",
SESSION_SECRET: "core-secret",
});
const crossedSecret = runEntrypoint({
WEB_RUNTIME_SURFACE: "core",
DATABASE_RUNTIME_ROLE: "hivegrid_app",
SESSION_SECRET: "core-secret",
PORTAL_SESSION_SECRET: "portal-secret",
});
expect(wrongRole.stderr).toContain("DATABASE_RUNTIME_ROLE=hivegrid_app is mandatory for the web runtime");
expect(crossedSecret.stderr).toContain("PORTAL_SESSION_SECRET is forbidden in the core web runtime");
});
test("requires the dedicated portal role and secret while rejecting core authority", () => {
const wrongRole = runEntrypoint({
WEB_RUNTIME_SURFACE: "portal",
DATABASE_RUNTIME_ROLE: "hivegrid_app",
PORTAL_SESSION_SECRET: "portal-secret",
});
const crossedSecret = runEntrypoint({
WEB_RUNTIME_SURFACE: "portal",
DATABASE_RUNTIME_ROLE: "hivegrid_portal",
PORTAL_SESSION_SECRET: "portal-secret",
SESSION_SECRET: "core-secret",
});
const adminAuthority = runEntrypoint({
WEB_RUNTIME_SURFACE: "portal",
DATABASE_RUNTIME_ROLE: "hivegrid_portal",
PORTAL_SESSION_SECRET: "portal-secret",
AUTHENTIK_ADMIN_JIT_DATABASE_URL: "postgresql://hivegrid_authentik_jit:secret@db.invalid/hivegrid",
});
expect(wrongRole.stderr).toContain("DATABASE_RUNTIME_ROLE=hivegrid_portal is mandatory for the portal web runtime");
expect(crossedSecret.stderr).toContain("SESSION_SECRET is forbidden in the portal web runtime");
expect(adminAuthority.stderr).toContain("AUTHENTIK_ADMIN_JIT_DATABASE_URL is forbidden in the portal web runtime");
});
test("requires a fail-closed Admin runtime with Authentik and no password fallback", () => {
const missingSso = runEntrypoint({
WEB_RUNTIME_SURFACE: "admin",
DATABASE_RUNTIME_ROLE: "hivegrid_app",
SESSION_SECRET: "admin-session-secret",
ADMIN_FALLBACK_LOGIN_ENABLED: "false",
});
const fallbackEnabled = runEntrypoint({
WEB_RUNTIME_SURFACE: "admin",
DATABASE_RUNTIME_ROLE: "hivegrid_app",
SESSION_SECRET: "admin-session-secret",
ADMIN_FALLBACK_LOGIN_ENABLED: "true",
});
expect(missingSso.stderr).toContain("AUTHENTIK_ISSUER_URL is required for the admin web runtime");
expect(fallbackEnabled.stderr).toContain("ADMIN_FALLBACK_LOGIN_ENABLED=false is mandatory for the admin web runtime");
});
test("rejects a pre-set internal build surface that crosses the runtime boundary", () => {
const result = runEntrypoint({
WEB_RUNTIME_SURFACE: "portal",
HIVEGRID_RUNTIME_SURFACE: "core",
DATABASE_RUNTIME_ROLE: "hivegrid_portal",
PORTAL_SESSION_SECRET: "portal-secret",
});
expect(result.status).toBe(1);
expect(result.stderr).toContain("HIVEGRID_RUNTIME_SURFACE must match WEB_RUNTIME_SURFACE");
});
});