Monitoring settings (Sentry, Umami) and the CSP origins come from the build environment

One build per environment: PROD_* variables for the production artifact,
TEST_* for the test build and the CSP check. The build fails when a variable
is empty. Tests use the production values from config/monitoringTestEnv.ts.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-18 19:29:51 +01:00
co-authored by Claude Sonnet 5.5
parent 6475696709
commit 49b1d5f0ba
14 changed files with 286 additions and 85 deletions
@@ -1,5 +1,5 @@
import { render } from '@testing-library/react';
import { afterEach, describe, expect, it } from 'vitest';
import { afterEach, describe, expect, it, vi } from 'vitest';
import UmamiAnalytics from './UmamiAnalytics';
const umamiScripts = () =>
@@ -8,6 +8,7 @@ const umamiScripts = () =>
);
afterEach(() => {
vi.unstubAllEnvs();
umamiScripts().forEach((script) => script.remove());
});
@@ -18,18 +19,28 @@ describe('UmamiAnalytics', () => {
});
it.each([
['andreaslop.nl', '3edbb7d1-4388-4f2d-9cef-11ade88ace96'],
['test.andreaslop.nl', '7fb301ab-6ecc-4aea-beee-71bcb6009bfe'],
])('telt op %s met de juiste website', (hostname, websiteId) => {
render(<UmamiAnalytics hostname={hostname} />);
['production', 'andreaslop.nl', '3edbb7d1-4388-4f2d-9cef-11ade88ace96'],
['test', 'test.andreaslop.nl', 'test-website'],
])(
'telt in de %s-build op %s met de juiste website',
(environment, hostname, websiteId) => {
vi.stubEnv('VITE_APP_ENV', environment);
vi.stubEnv('VITE_UMAMI_WEBSITE_ID', websiteId);
render(<UmamiAnalytics hostname={hostname} />);
const [script] = umamiScripts();
expect(script.defer).toBe(true);
expect(script.dataset).toMatchObject({
websiteId,
domains: hostname,
doNotTrack: 'true',
});
const [script] = umamiScripts();
expect(script.defer).toBe(true);
expect(script.dataset).toMatchObject({
websiteId,
domains: hostname,
doNotTrack: 'true',
});
},
);
it('voegt geen script toe op de host van de andere omgeving', () => {
render(<UmamiAnalytics hostname="test.andreaslop.nl" />);
expect(umamiScripts()).toHaveLength(0);
});
it('voegt het script maar één keer toe', () => {
@@ -1,5 +1,5 @@
import { useEffect } from 'react';
import { monitoringFor, umamiOrigin } from '@/monitoring/config';
import { monitoringFor } from '@/monitoring/config';
const SCRIPT_ELEMENT_ID = 'umami-analytics-script';
@@ -16,7 +16,7 @@ export default function UmamiAnalytics({ hostname }: { hostname?: string }) {
const script = document.createElement('script');
script.id = SCRIPT_ELEMENT_ID;
script.src = `${umamiOrigin}/script.js`;
script.src = monitoring.umamiScriptUrl;
script.defer = true;
script.dataset.websiteId = monitoring.umamiWebsiteId;
script.dataset.domains = host;
+81 -13
View File
@@ -1,11 +1,22 @@
import fc from 'fast-check';
import { describe, expect, it } from 'vitest';
import { afterEach, describe, expect, it, vi } from 'vitest';
import {
monitoredHostnames,
monitoringConfig,
monitoringFor,
sentryIngestOrigin,
monitoringOrigins,
} from './config';
const dsn = 'https://key@o1.ingest.de.sentry.io/2';
const script = 'https://analytics.example.nl/script.js';
const raw = (extra: Record<string, unknown> = {}) => ({
environment: 'production',
sentryDsn: dsn,
umamiScriptUrl: script,
umamiWebsiteId: 'site-1',
...extra,
});
// Alles wat geen test- of productiehost is
const otherHostname = fc
.oneof(
@@ -25,32 +36,89 @@ const otherHostname = fc
)
.filter((host) => !monitoredHostnames.includes(host));
describe('monitoringFor', () => {
it('productiehost meet als production met de productiewebsite', () => {
expect(monitoringFor('andreaslop.nl')).toEqual({
afterEach(() => vi.unstubAllEnvs());
describe('monitoringConfig', () => {
it('leest de waarden uit de omgeving van de build', () => {
// De testomgeving (vite.config.ts) is de productiebuild
expect(monitoringConfig()).toMatchObject({
environment: 'production',
umamiWebsiteId: '3edbb7d1-4388-4f2d-9cef-11ade88ace96',
});
vi.stubEnv('VITE_APP_ENV', 'test');
vi.stubEnv('VITE_UMAMI_WEBSITE_ID', ' abc ');
expect(monitoringConfig()).toMatchObject({
environment: 'test',
umamiWebsiteId: 'abc',
});
});
it('testhost meet als test met de testwebsite', () => {
expect(monitoringFor('test.andreaslop.nl')).toEqual({
environment: 'test',
umamiWebsiteId: '7fb301ab-6ecc-4aea-beee-71bcb6009bfe',
it('geeft null als er iets ontbreekt of ongeldig is', () => {
expect(monitoringConfig(raw())).not.toBeNull();
for (const bad of [
{ environment: 'staging' },
{ environment: undefined },
{ sentryDsn: undefined },
{ sentryDsn: 'http://key@host/1' },
{ sentryDsn: 'geen url' },
{ umamiScriptUrl: '' },
{ umamiScriptUrl: 'http://analytics.example.nl/script.js' },
{ umamiWebsiteId: ' ' },
{ umamiWebsiteId: 5 },
]) {
expect(monitoringConfig(raw(bad))).toBeNull();
}
});
});
describe('monitoringFor', () => {
it('productiebuild meet alleen op de productiehost', () => {
const config = monitoringConfig(raw());
expect(monitoringFor('andreaslop.nl', config)).toEqual({
environment: 'production',
sentryDsn: dsn,
umamiScriptUrl: script,
umamiWebsiteId: 'site-1',
});
expect(monitoringFor('test.andreaslop.nl', config)).toBeNull();
});
it('testbuild meet alleen op de testhost', () => {
const config = monitoringConfig(raw({ environment: 'test' }));
expect(monitoringFor('test.andreaslop.nl', config)?.environment).toBe(
'test',
);
expect(monitoringFor('andreaslop.nl', config)).toBeNull();
});
it('meet niets zonder instellingen', () => {
expect(monitoringFor('andreaslop.nl', null)).toBeNull();
});
it('elke andere host meet niets (M1)', () => {
fc.assert(
fc.property(otherHostname, (host) => {
expect(monitoringFor(host)).toBeNull();
expect(
monitoringFor(
host,
monitoringConfig(raw({ environment: 'test' })),
),
).toBeNull();
}),
);
});
});
it('Sentry-ingest is de EU-host uit de DSN, zonder sleutel', () => {
expect(sentryIngestOrigin).toBe(
'https://o4511795618185216.ingest.de.sentry.io',
);
describe('monitoringOrigins', () => {
it('zijn de herkomst van het Umami-script en van de Sentry-ingest, zonder sleutel', () => {
expect(monitoringOrigins(monitoringConfig(raw()))).toEqual({
umami: ['https://analytics.example.nl'],
sentry: ['https://o1.ingest.de.sentry.io'],
});
});
it('zijn leeg zonder instellingen', () => {
expect(monitoringOrigins(null)).toEqual({ umami: [], sentry: [] });
});
});
+83 -30
View File
@@ -1,43 +1,96 @@
// Instellingen voor Sentry en Umami (monitoring-plan M1/M2). Deze waarden zijn
// openbaar: ze staan hoe dan ook in de browser van elke bezoeker.
// Instellingen voor Sentry en Umami (monitoring-plan M1/M2). De waarden zijn
// openbaar (ze staan in de browser van elke bezoeker) maar komen niet meer uit
// de code: de pipeline geeft ze per omgeving mee aan de build, uit de Gitea-
// variabelen {TEST|PROD}_SENTRY_DSN, _UMAMI_SCRIPT_URL en _UMAMI_WEBSITE_ID,
// als VITE_SENTRY_DSN, VITE_UMAMI_SCRIPT_URL, VITE_UMAMI_WEBSITE_ID en
// VITE_APP_ENV ('test' of 'production'). Eén build hoort dus bij één omgeving.
// Geen imports uit Vite: config/securityHeaders.ts leest dit bestand ook in Node.
export type MonitoringEnvironment = 'test' | 'production';
export interface Monitoring {
export interface MonitoringConfig {
environment: MonitoringEnvironment;
sentryDsn: string;
umamiScriptUrl: string;
umamiWebsiteId: string;
}
export const sentryDsn =
'https://12ec77dcc3216a98b96d3fb3dac13f66@o4511795618185216.ingest.de.sentry.io/4512282287472720';
export type Monitoring = MonitoringConfig;
// Waar de browser fouten naartoe stuurt; nodig voor connect-src in de CSP
export const sentryIngestOrigin = new URL(sentryDsn).origin;
// De host waarop de build van een omgeving meet
const hostnameByEnvironment: Record<MonitoringEnvironment, string> = {
production: 'andreaslop.nl',
test: 'test.andreaslop.nl',
};
export const umamiOrigin = 'https://analytics.slpsoftware.nl';
// In de Vite-build staan de waarden in import.meta.env (statisch vervangen,
// daarom elke naam los); de buildscripts onder Node lezen process.env.
const fromProcess = (name: string): unknown =>
typeof process === 'undefined' ? undefined : process.env[name];
// Eén build voor beide omgevingen: de hostname bepaalt de omgeving
const monitoringByHostname = new Map<string, Monitoring>([
[
'andreaslop.nl',
{
environment: 'production',
umamiWebsiteId: '3edbb7d1-4388-4f2d-9cef-11ade88ace96',
},
],
[
'test.andreaslop.nl',
{
environment: 'test',
umamiWebsiteId: '7fb301ab-6ecc-4aea-beee-71bcb6009bfe',
},
],
]);
// Onbekende host (localhost, Lighthouse CI, previews): niets meten (M1)
export function monitoringFor(hostname: string): Monitoring | null {
return monitoringByHostname.get(hostname) ?? null;
function rawSettings(): Record<keyof MonitoringConfig, unknown> {
const env = import.meta.env;
return {
environment: env?.VITE_APP_ENV ?? fromProcess('VITE_APP_ENV'),
sentryDsn: env?.VITE_SENTRY_DSN ?? fromProcess('VITE_SENTRY_DSN'),
umamiScriptUrl:
env?.VITE_UMAMI_SCRIPT_URL ?? fromProcess('VITE_UMAMI_SCRIPT_URL'),
umamiWebsiteId:
env?.VITE_UMAMI_WEBSITE_ID ?? fromProcess('VITE_UMAMI_WEBSITE_ID'),
};
}
export const monitoredHostnames = [...monitoringByHostname.keys()];
const isHttps = (value: string): boolean => {
try {
return new URL(value).protocol === 'https:';
} catch {
return false;
}
};
// De instellingen van deze build, of null als er iets ontbreekt of ongeldig is
// (dan meet de site niets: liever geen meting dan een kapotte)
export function monitoringConfig(
raw: Record<keyof MonitoringConfig, unknown> = rawSettings(),
): MonitoringConfig | null {
const { environment, sentryDsn, umamiScriptUrl, umamiWebsiteId } = raw;
if (environment !== 'test' && environment !== 'production') return null;
const text = (value: unknown) =>
typeof value === 'string' ? value.trim() : '';
const dsn = text(sentryDsn);
const script = text(umamiScriptUrl);
const website = text(umamiWebsiteId);
if (!isHttps(dsn) || !isHttps(script) || website === '') return null;
return {
environment,
sentryDsn: dsn,
umamiScriptUrl: script,
umamiWebsiteId: website,
};
}
// Onbekende host (localhost, Lighthouse CI, previews, de andere omgeving):
// niets meten (M1)
export function monitoringFor(
hostname: string,
config: MonitoringConfig | null = monitoringConfig(),
): Monitoring | null {
if (!config || hostname !== hostnameByEnvironment[config.environment]) {
return null;
}
return { ...config };
}
// De herkomsten voor de CSP: Umami voor script-src en connect-src, de Sentry-
// ingest voor connect-src. Leeg zonder meting.
export function monitoringOrigins(
config: MonitoringConfig | null = monitoringConfig(),
): { umami: string[]; sentry: string[] } {
if (!config) return { umami: [], sentry: [] };
return {
umami: [new URL(config.umamiScriptUrl).origin],
sentry: [new URL(config.sentryDsn).origin],
};
}
export const monitoredHostnames = Object.values(hostnameByEnvironment);
+2
View File
@@ -11,6 +11,7 @@ async function freshSentry() {
}
beforeEach(() => {
vi.unstubAllEnvs();
init.mockReset();
captureException.mockReset();
});
@@ -27,6 +28,7 @@ describe('Sentry', () => {
});
it('start op test met omgeving test en zonder persoonsgegevens', async () => {
vi.stubEnv('VITE_APP_ENV', 'test');
const { startSentry } = await freshSentry();
startSentry('test.andreaslop.nl');
+2 -2
View File
@@ -1,4 +1,4 @@
import { monitoringFor, sentryDsn } from './config';
import { monitoringFor } from './config';
// Sentry laadt pas na het load-event, buiten de hoofdbundel (M4). Fouten van
// daarvoor wachten in een wachtrij en gaan mee zodra Sentry klaar is.
@@ -33,7 +33,7 @@ export function startSentry(hostname = window.location.hostname): void {
// Alleen fouten: geen tracing, geen replay, geen persoonsgegevens (M5).
// Sinds SDK 11 verzamelt Sentry standaard alles; daarom alles expliciet uit.
Sentry.init({
dsn: sentryDsn,
dsn: monitoring.sentryDsn,
environment: monitoring.environment,
release: import.meta.env.VITE_RELEASE,
dataCollection: {