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,66 @@
// @vitest-environment jsdom
import { cleanup, render } from "@testing-library/react";
import { renderToStaticMarkup } from "react-dom/server";
import { afterEach, describe, expect, it, vi } from "vitest";
import { buildDocumentContentSecurityPolicy } from "~/utils/security/contentSecurityPolicy";
import ScriptAnalytics from "./ScriptAnalytics";
const { hasConsent } = vi.hoisted(() => ({ hasConsent: vi.fn(() => true) }));
vi.mock("react-router", () => ({
useLocation: () => ({ pathname: "/" }),
}));
vi.mock("~/utils/data/useRootData", () => ({
useRootData: () => ({
domainName: "example.test",
userSession: { cookies: [] },
appConfiguration: {
analytics: {
enabled: true,
simpleAnalytics: true,
plausibleAnalytics: true,
},
},
}),
}));
vi.mock("~/utils/app/HostAwareSurface", () => ({
isAppOrAdminSurface: () => false,
}));
vi.mock("~/utils/helpers/CookieHelper", () => ({
default: { hasConsent },
}));
afterEach(() => cleanup());
describe("analytics script CSP nonces", () => {
it("does not contact analytics providers before browser consent", () => {
hasConsent.mockReturnValueOnce(false);
render(<ScriptAnalytics nonce="aBcDeFgHiJkLmNoPqRsTuVwX" />);
expect(document.querySelector("script[src*='simpleanalyticscdn.com'],script[src*='plausible.io']")).toBeNull();
});
it("renders every executable analytics tag with the nonce used by the response policy", () => {
const nonce = "aBcDeFgHiJkLmNoPqRsTuVwX";
const policy = buildDocumentContentSecurityPolicy(nonce);
render(<ScriptAnalytics nonce={nonce} />);
const scripts = [
document.querySelector<HTMLScriptElement>('script[src="https://scripts.simpleanalyticscdn.com/latest.js"]'),
document.querySelector<HTMLScriptElement>('script[src="https://plausible.io/js/script.js"]'),
];
expect(scripts.every((script) => script?.nonce === nonce)).toBe(true);
expect(policy).toContain(`'nonce-${nonce}'`);
});
it("keeps the tracking pixel decorative for assistive technology", () => {
const markup = renderToStaticMarkup(
<ScriptAnalytics nonce="aBcDeFgHiJkLmNoPqRsTuVwX" />,
);
expect(markup).toContain(
'<img src="https://queue.simpleanalyticscdn.com/noscript.gif" alt=""',
);
});
});
@@ -1,10 +1,12 @@
import { useLocation } from "react-router";
import { useRootData } from "~/utils/data/useRootData";
import { isAppOrAdminSurface } from "~/utils/app/HostAwareSurface";
import CookieHelper from "~/utils/helpers/CookieHelper";
import { CookieCategory } from "~/application/cookies/CookieCategory";
// EU-Sterilisation (R-P1a): Google-Analytics-Einbindung (gtag.js) entfernt. Es bleiben nur die
// datenschutzfreundlichen EU-Tracker SimpleAnalytics + Plausible, die der Admin opt-in aktiviert.
export default function ScriptAnalytics() {
export default function ScriptAnalytics({ nonce }: { nonce?: string }) {
const rootData = useRootData();
const location = useLocation();
if (!rootData.appConfiguration?.analytics.enabled) {
@@ -13,20 +15,23 @@ export default function ScriptAnalytics() {
if (isAppOrAdminSurface(rootData, location.pathname)) {
return null;
}
if (!CookieHelper.hasConsent(rootData.userSession ?? null, CookieCategory.ANALYTICS)) {
return null;
}
return (
<>
{rootData.appConfiguration?.analytics.simpleAnalytics && (
<>
<script async defer src="https://scripts.simpleanalyticscdn.com/latest.js"></script>
<script nonce={nonce} async defer src="https://scripts.simpleanalyticscdn.com/latest.js"></script>
<noscript>
<img src="https://queue.simpleanalyticscdn.com/noscript.gif" alt="privacy-friendly-simpleanalytics" referrerPolicy="no-referrer-when-downgrade" />
<img src="https://queue.simpleanalyticscdn.com/noscript.gif" alt="" referrerPolicy="no-referrer-when-downgrade" />
</noscript>
</>
)}
{rootData.appConfiguration?.analytics.plausibleAnalytics && (
<>
<script defer data-domain={rootData.domainName} src="https://plausible.io/js/script.js"></script>
<script nonce={nonce} defer data-domain={rootData.domainName} src="https://plausible.io/js/script.js"></script>
</>
)}
</>
@@ -0,0 +1,60 @@
// @vitest-environment jsdom
import { cleanup, render, waitFor } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import ScriptCrisp from "./ScriptCrisp";
const { hasConsent, isAppOrAdminSurface } = vi.hoisted(() => ({
hasConsent: vi.fn(() => false),
isAppOrAdminSurface: vi.fn(() => false),
}));
vi.mock("react-router", () => ({
useLocation: () => ({ pathname: "/" }),
}));
vi.mock("~/utils/data/useRootData", () => ({
useRootData: () => ({ chatWebsiteId: "site-id", userSession: { cookies: [] } }),
}));
vi.mock("~/utils/helpers/CookieHelper", () => ({
default: { hasConsent },
}));
vi.mock("~/utils/app/HostAwareSurface", () => ({
isAppOrAdminSurface,
}));
afterEach(() => {
cleanup();
document.querySelectorAll('script[src="https://client.crisp.chat/l.js"]').forEach((node) => node.remove());
delete window.$crisp;
delete window.CRISP_WEBSITE_ID;
hasConsent.mockReset();
hasConsent.mockReturnValue(false);
isAppOrAdminSurface.mockReset();
isAppOrAdminSurface.mockReturnValue(false);
});
describe("ScriptCrisp privacy gate", () => {
it("does not contact Crisp without functional-cookie consent", () => {
render(<ScriptCrisp nonce="aBcDeFgHiJkLmNoPqRsTuVwX" />);
expect(document.querySelector('script[src="https://client.crisp.chat/l.js"]')).toBeNull();
});
it("loads Crisp on a public surface after consent and carries the CSP nonce", async () => {
hasConsent.mockReturnValue(true);
render(<ScriptCrisp nonce="aBcDeFgHiJkLmNoPqRsTuVwX" />);
await waitFor(() => {
const script = document.querySelector<HTMLScriptElement>('script[src="https://client.crisp.chat/l.js"]');
expect(script?.nonce).toBe("aBcDeFgHiJkLmNoPqRsTuVwX");
});
});
it("never loads the public chat script on app or admin surfaces", () => {
hasConsent.mockReturnValue(true);
isAppOrAdminSurface.mockReturnValue(true);
render(<ScriptCrisp nonce="aBcDeFgHiJkLmNoPqRsTuVwX" />);
expect(document.querySelector('script[src="https://client.crisp.chat/l.js"]')).toBeNull();
});
});
@@ -5,40 +5,31 @@ import CookieHelper from "~/utils/helpers/CookieHelper";
import { CookieCategory } from "~/application/cookies/CookieCategory";
import { isAppOrAdminSurface } from "~/utils/app/HostAwareSurface";
const FORCE_IN_ROUTES = ["/crisp"];
export default function ScriptCrisp() {
export default function ScriptCrisp({ nonce }: { nonce?: string }) {
const rootData = useRootData();
const location = useLocation();
useEffect(() => {
const isAppOrAdminArea = isAppOrAdminSurface(rootData, location.pathname);
let hasConsent = CookieHelper.hasConsent(rootData.userSession ?? null, CookieCategory.FUNCTIONAL) || isAppOrAdminArea || FORCE_IN_ROUTES.some((p) => location.pathname.startsWith(p));
if (rootData.chatWebsiteId && hasConsent && !window.$crisp) {
const hasConsent = CookieHelper.hasConsent(rootData.userSession ?? null, CookieCategory.FUNCTIONAL);
if (!isAppOrAdminArea && rootData.chatWebsiteId && hasConsent && !window.$crisp) {
window.$crisp = [];
window.CRISP_WEBSITE_ID = rootData.chatWebsiteId;
const d = document;
const s = d.createElement("script");
s.src = "https://client.crisp.chat/l.js";
s.async = true;
if (nonce) s.nonce = nonce;
d.getElementsByTagName("head")[0].appendChild(s);
}
if (window.$crisp && isAppOrAdminArea) {
try {
// @ts-ignore
window.$crisp.push(["do", "chat:hide"]);
} catch {
// ignore
}
}
}, [rootData, rootData.userSession?.cookies, rootData.chatWebsiteId, location.pathname]);
}, [rootData, rootData.userSession?.cookies, rootData.chatWebsiteId, location.pathname, nonce]);
return null;
}
declare global {
interface Window {
$crisp: any;
CRISP_WEBSITE_ID: string;
$crisp?: any;
CRISP_WEBSITE_ID?: string;
}
}
@@ -0,0 +1,54 @@
// @vitest-environment jsdom
import { cleanup, render } from "@testing-library/react";
import { afterEach, describe, expect, it } from "vitest";
import ScriptInjector from "./ScriptInjector";
afterEach(() => {
cleanup();
document.head.querySelectorAll("script[data-hivegrid-custom-script]").forEach((node) => node.remove());
document.body.querySelectorAll("script[data-hivegrid-custom-script]").forEach((node) => node.remove());
});
describe("ScriptInjector", () => {
it("injects only explicit script elements and preserves their attributes", () => {
render(
<ScriptInjector
nonce="aBcDeFgHiJkLmNoPqRsTuVwX"
scripts={{
head: '<meta name="not-a-script"><script nonce="administrator-value" src="https://cdn.example.test/tracker.js" async></script>',
body: '<img src="missing" onerror="window.__unexpected = true"><script>window.__expected = true</script>',
}}
/>,
);
const headScripts = document.head.querySelectorAll("script[data-hivegrid-custom-script]");
const bodyScripts = document.body.querySelectorAll("script[data-hivegrid-custom-script]");
expect(headScripts).toHaveLength(1);
expect(headScripts[0]?.getAttribute("src")).toBe("https://cdn.example.test/tracker.js");
expect(headScripts[0]?.nonce).toBe("aBcDeFgHiJkLmNoPqRsTuVwX");
expect(headScripts[0]?.hasAttribute("async")).toBe(true);
expect(bodyScripts).toHaveLength(1);
expect(bodyScripts[0]?.textContent).toBe("window.__expected = true");
expect(bodyScripts[0]?.nonce).toBe("aBcDeFgHiJkLmNoPqRsTuVwX");
expect(document.querySelector('[onerror="window.__unexpected = true"]')).toBeNull();
});
it("does not duplicate unchanged snippets across rerenders and removes owned nodes on cleanup", () => {
const scripts = { head: "<script>window.__head = true</script>", body: "<script>window.__body = true</script>" };
const view = render(<ScriptInjector scripts={scripts} />);
expect(document.querySelectorAll("script[data-hivegrid-custom-script]")).toHaveLength(2);
view.rerender(<ScriptInjector scripts={{ ...scripts }} />);
expect(document.querySelectorAll("script[data-hivegrid-custom-script]")).toHaveLength(2);
view.unmount();
expect(document.querySelectorAll("script[data-hivegrid-custom-script]")).toHaveLength(0);
});
it("never trusts a nonce persisted in administrator-authored markup", () => {
render(<ScriptInjector scripts={{ head: '<script nonce="persisted-spoof">window.__head = true</script>', body: null }} />);
expect(document.head.querySelector<HTMLScriptElement>("script[data-hivegrid-custom-script]")?.nonce).toBe("");
});
});
@@ -5,42 +5,56 @@ interface ScriptInjectorProps {
head: string | null;
body: string | null;
};
nonce?: string;
}
const ScriptInjector = ({ scripts }: ScriptInjectorProps) => {
const ScriptInjector = ({ scripts, nonce }: ScriptInjectorProps) => {
useEffect(() => {
if (scripts?.head) {
const headDiv = document.createElement("div");
headDiv.innerHTML = scripts.head;
Array.from(headDiv.childNodes).forEach((node) => {
if (node.nodeType === Node.ELEMENT_NODE) {
const script = document.createElement("script");
Array.from((node as Element).attributes).forEach((attr) => {
script.setAttribute(attr.name, attr.value);
});
script.innerHTML = (node as Element).innerHTML;
document.head.appendChild(script);
}
});
}
const injectedNodes = [
...injectScriptElements(scripts?.head, document.head, nonce),
...injectScriptElements(scripts?.body, document.body, nonce),
];
if (scripts?.body) {
const bodyDiv = document.createElement("div");
bodyDiv.innerHTML = scripts.body;
Array.from(bodyDiv.childNodes).forEach((node) => {
if (node.nodeType === Node.ELEMENT_NODE) {
const script = document.createElement("script");
Array.from((node as Element).attributes).forEach((attr) => {
script.setAttribute(attr.name, attr.value);
});
script.innerHTML = (node as Element).innerHTML;
document.body.appendChild(script);
}
});
}
}, [scripts]);
return () => {
for (const node of injectedNodes) {
node.remove();
}
};
}, [scripts?.head, scripts?.body, nonce]);
return null;
};
function injectScriptElements(markup: string | null | undefined, target: HTMLElement, nonce?: string): HTMLScriptElement[] {
if (!markup) {
return [];
}
const template = document.createElement("template");
template.innerHTML = markup;
const injected: HTMLScriptElement[] = [];
// This feature intentionally accepts administrator-authored scripts. Only
// actual <script> elements are executable, though: treating arbitrary HTML
// elements as scripts made malformed snippets unexpectedly executable (for
// example an <img onerror> payload became a script with an error handler).
for (const source of template.content.querySelectorAll("script")) {
const script = document.createElement("script");
for (const attribute of source.attributes) {
if (attribute.name.toLowerCase() === "nonce") continue;
script.setAttribute(attribute.name, attribute.value);
}
// The server nonce always wins over an administrator-supplied nonce
// attribute. This keeps custom scripts functional under strict-dynamic
// without turning stored configuration into a CSP bypass primitive.
if (nonce) script.nonce = nonce;
script.textContent = source.textContent;
script.dataset.hivegridCustomScript = "true";
target.appendChild(script);
injected.push(script);
}
return injected;
}
export default ScriptInjector;
@@ -0,0 +1,63 @@
// @vitest-environment jsdom
import { cleanup, render, waitFor } from "@testing-library/react";
import { afterEach, describe, expect, it, vi } from "vitest";
import ScriptSentryReplay from "./ScriptSentryReplay";
const mocks = vi.hoisted(() => ({
disableSentryReplay: vi.fn(async () => true),
enableSentryReplay: vi.fn(() => true),
hasConsent: vi.fn(() => false),
readClientSentryConfig: vi.fn(() => ({
dsn: "https://public@example.test/1",
replaysOnErrorSampleRate: 1,
replaysSessionSampleRate: 0.1,
})),
}));
vi.mock("~/utils/data/useRootData", () => ({
useRootData: () => ({ userSession: { cookies: [] } }),
}));
vi.mock("~/utils/helpers/CookieHelper", () => ({
default: { hasConsent: mocks.hasConsent },
}));
vi.mock("~/sentry.client", () => ({
readClientSentryConfig: mocks.readClientSentryConfig,
}));
vi.mock("~/sentry-replay.client", () => ({
disableSentryReplay: mocks.disableSentryReplay,
enableSentryReplay: mocks.enableSentryReplay,
}));
afterEach(() => {
cleanup();
vi.clearAllMocks();
mocks.hasConsent.mockReturnValue(false);
});
describe("ScriptSentryReplay consent gate", () => {
it("starts Replay only after analytics consent and stops it on revocation", async () => {
const view = render(<ScriptSentryReplay />);
expect(mocks.readClientSentryConfig).not.toHaveBeenCalled();
expect(mocks.enableSentryReplay).not.toHaveBeenCalled();
mocks.hasConsent.mockReturnValue(true);
view.rerender(<ScriptSentryReplay />);
await waitFor(() => {
expect(mocks.enableSentryReplay).toHaveBeenCalledWith({
dsn: "https://public@example.test/1",
replaysOnErrorSampleRate: 1,
replaysSessionSampleRate: 0.1,
});
});
mocks.hasConsent.mockReturnValue(false);
view.rerender(<ScriptSentryReplay />);
await waitFor(() => {
expect(mocks.disableSentryReplay).toHaveBeenCalled();
});
});
});
@@ -0,0 +1,48 @@
import { useEffect } from "react";
import { CookieCategory } from "~/application/cookies/CookieCategory";
import { useRootData } from "~/utils/data/useRootData";
import CookieHelper from "~/utils/helpers/CookieHelper";
type ReplayModule = typeof import("~/sentry-replay.client");
let loadedReplayModule: Promise<ReplayModule> | undefined;
export default function ScriptSentryReplay() {
const rootData = useRootData();
const hasAnalyticsConsent = CookieHelper.hasConsent(rootData.userSession ?? null, CookieCategory.ANALYTICS);
useEffect(() => {
let cancelled = false;
if (!hasAnalyticsConsent) {
if (loadedReplayModule) {
void loadedReplayModule.then(({ disableSentryReplay }) => disableSentryReplay());
}
return () => {
cancelled = true;
};
}
void import("~/sentry.client").then(({ readClientSentryConfig }) => {
const config = readClientSentryConfig();
if (cancelled || !config.dsn || (config.replaysSessionSampleRate <= 0 && config.replaysOnErrorSampleRate <= 0)) {
return;
}
loadedReplayModule ??= import("~/sentry-replay.client");
void loadedReplayModule.then(({ enableSentryReplay }) => {
if (!cancelled) {
enableSentryReplay(config);
}
});
});
return () => {
cancelled = true;
if (loadedReplayModule) {
void loadedReplayModule.then(({ disableSentryReplay }) => disableSentryReplay());
}
};
}, [hasAnalyticsConsent]);
return null;
}