Files
AndreaSlopFotografie/web/config/serverConfig.test.ts
T
SluijsensandClaude Opus 5.5 e4e7f8c82c Adds the URL rules to the preview server, IIS config and deploy
The preview server and web.config now follow the same URLs as nginx, without
the SPA fallback. Lighthouse exceptions need a recorded reason and the 404 page
is audited through an opt-in route. The deploy checks the build first and the
served result afterwards. The IIS rules stay unverified until a host exists.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-01 18:13:21 +01:00

354 lines
14 KiB
TypeScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
import { readFileSync } from 'node:fs';
import { describe, expect, it } from 'vitest';
import { monitoringFor } from '../src/monitoring/config';
import { redirectNames } from './canonicalUrls';
import { gzipMimeTypes } from './compressibleTypes';
import { securityHeaders } from './securityHeaders';
import {
iisWebConfig,
nginxProxyConf,
nginxTestConf,
productionHost,
serverConfigFiles,
} from './serverConfig';
describe('serverconfiguratie', () => {
it.each(Object.entries(serverConfigFiles))(
'%s is gelijk aan de generator (draai anders pnpm server-config)',
(path, generate) => {
expect(readFileSync(path, 'utf8')).toBe(generate());
},
);
it('IIS en nginx zetten elke productieheader', () => {
const iis = iisWebConfig();
const nginx = nginxTestConf();
for (const [name, value] of Object.entries(
securityHeaders('production'),
)) {
expect(iis).toContain(
`<add name="${name}" value="${value.replace(/&/g, '&amp;')}" />`,
);
expect(nginx).toContain(`add_header ${name} "${value}" always;`);
}
});
it('IIS stuurt www in één stap door naar https://andreaslop.nl', () => {
const iis = iisWebConfig();
expect(iis).toContain(
'<add input="{HTTP_HOST}" pattern="^www\\.andreaslop\\.nl$" />',
);
expect(iis).toContain(
'<action type="Redirect" url="https://andreaslop.nl/{R:1}" redirectType="Permanent" />',
);
// Vóór de HTTPS-regel, anders eerst http://www → https://www
expect(iis.indexOf('name="www naar')).toBeLessThan(
iis.indexOf('name="HTTPS"'),
);
});
it('www-doorverwijzing verwijst naar de productiehost uit de monitoring', () => {
expect(monitoringFor(productionHost)?.environment).toBe('production');
});
it('IIS heeft een HTTPS-redirect en geen SPA-fallback', () => {
const iis = iisWebConfig();
expect(iis).toContain('<add input="{HTTPS}" pattern="^OFF$" />');
expect(iis).not.toContain('SPA fallback');
expect(iis).not.toContain('index.html');
});
it('de testsite wordt nooit geindexeerd', () => {
const nginx = nginxTestConf();
expect(nginx).toContain('X-Robots-Tag "noindex, nofollow"');
expect(nginx).toContain('Disallow: /');
// Geen SPA-fallback (BR-HST-02) en geen mapdoorverwijzing (BR-HST-07)
expect(nginx).toContain('try_files $uri $uri.html =404;');
expect(nginx).not.toMatch(/try_files[^;]*\$uri[^;]*\/index\.html/);
expect(nginx).not.toContain('$uri/');
});
it('het testblok claimt nooit de standaardserver (WordPress op dezelfde Pi)', () => {
expect(nginxTestConf()).not.toMatch(/listen[^;]*default_server/);
});
it('houdt doorverwijzingen relatief achter de reverse proxy', () => {
expect(nginxTestConf()).toContain('absolute_redirect off;');
});
it('de proxy geeft de Host-header door en zet zelf geen security headers', () => {
const proxy = nginxProxyConf();
expect(proxy).toContain('proxy_set_header Host $host;');
expect(proxy).toContain('server_name test.andreaslop.nl;');
expect(proxy).not.toContain('add_header');
});
it('proxy en testblok gebruiken dezelfde hostname', () => {
// Alleen echte config-regels, geen commentaar
const name = /^\s*server_name ([^;]+);/m;
const proxyHost = nginxProxyConf().match(name)?.[1];
expect(proxyHost).toBe('test.andreaslop.nl');
expect(nginxTestConf().match(name)?.[1]).toBe(proxyHost);
});
it('elk nginx location-blok herhaalt de security headers', () => {
// nginx erft add_header niet als een location er zelf een zet
const blocks = nginxTestConf()
.split(/^ *location /m)
.slice(1);
// robots.txt, 404, 404.html, assets, de beginpagina en de rest
expect(blocks).toHaveLength(6);
for (const block of blocks) {
expect(block).toContain('Content-Security-Policy');
}
});
it('de nginx-map kent geen tekstsleutels: die negeren hoofdletters', () => {
// Een sleutel /over-mij zou ook /Over-Mij ongemoeid laten (echte nginx)
const map = nginxTestConf().match(
/map \$uri \$andreaslop_canonical \{([^}]*)\}/,
)?.[1];
const keys = (map ?? '')
.split('\n')
.map((line) => line.trim())
.filter((line) => line && line !== 'default "";')
.map((line) => line.split(' ')[0]);
expect(keys.length).toBeGreaterThan(0);
for (const key of keys) expect(key).toMatch(/^~\*?\^\//);
// De hoofdlettergevoelige canonieke vormen staan vóór de varianten
const lastCanonical = keys.findLastIndex((key) => key.startsWith('~^'));
const firstVariant = keys.findIndex((key) => key.startsWith('~*'));
expect(lastCanonical).toBeLessThan(firstVariant);
});
it('een backslash vooraan in het pad geeft 404 voor de doorverwijzing', () => {
const nginx = nginxTestConf();
const guard = nginx.indexOf('if ($uri ~ "^/\\x5c") {');
expect(guard).toBeGreaterThan(-1);
expect(guard).toBeLessThan(nginx.indexOf('if ($andreaslop_canonical)'));
expect(guard).toBeLessThan(nginx.indexOf('rewrite ^/(.+?)/+$'));
});
it('IIS-regels staan in de ontworpen volgorde, allemaal met stopProcessing', () => {
expect(iisRules().map((rule) => rule.getAttribute('name'))).toEqual([
'www naar andreaslop.nl',
'HTTPS',
'Index naar root',
'Pagina canoniek',
'Slash weg',
'404 direct',
'Pagina bestand',
'Map zonder pagina',
]);
for (const rule of iisRules()) {
expect(rule.getAttribute('stopProcessing')).toBe('true');
}
});
it('IIS heeft geen mapweergave, standaarddocument of eigen compressielijst', () => {
const iis = iisWebConfig();
expect(iis).not.toContain('httpCompression');
expect(iis).not.toContain('directoryBrowse');
expect(iis).not.toContain('defaultDocument');
expect(iis).toContain(
'<urlCompression doStaticCompression="true" doDynamicCompression="false" />',
);
expect(iis).toContain('responseMode="ExecuteURL"');
expect(iis).toContain('path="/404.html"');
});
it('IIS: ToLower alleen in de canonieke regel, een voorste backslash wordt nooit doel', () => {
expect(iisWebConfig().match(/ToLower/g)).toHaveLength(1);
const canonical = iisRule('Pagina canoniek');
expect(canonical.innerHTML).toContain('{ToLower:{R:1}}');
// Hoofdlettergevoelig: alleen de exacte kleine-letterwijze blijft staan
expect(
canonical
.querySelector('conditions add')
?.getAttribute('ignoreCase'),
).toBe('false');
const slashUrl = iisRule('Slash weg')
.querySelector('match')
?.getAttribute('url');
expect(slashUrl).toBe('^([^/\\\\].*?)/+$');
// Een doel begint nooit met een backslash of tweede slash (BR-HST-06)
const slash = new RegExp(slashUrl ?? '');
expect(slash.test('\\evil.example/')).toBe(false);
expect(slash.test('/evil.example/')).toBe(false);
expect(slash.test('over-mij/')).toBe(true);
});
it('IIS: 404 en 404.html raken geen paginaregel maar geven 404', () => {
const matchOf = (name: string) =>
new RegExp(
iisRule(name).querySelector('match')?.getAttribute('url') ?? '',
'i',
);
for (const url of ['404', '404.html']) {
expect(matchOf('Pagina canoniek').test(url)).toBe(false);
expect(matchOf('Index naar root').test(url)).toBe(false);
expect(matchOf('404 direct').test(url)).toBe(true);
}
expect(
iisRule('404 direct')
.querySelector('action')
?.getAttribute('statusCode'),
).toBe('404');
});
it('IIS en nginx kennen dezelfde pagina’s (invariant)', () => {
const pages = redirectNames.map((path) => path.replace(/^\//, ''));
expect(iisAlternation()).toEqual(pages);
expect(nginxCanonicalPaths()).toEqual(redirectNames);
// Per pagina één variantregel, plus de beginpagina onder /index
expect(
nginxMapKeys().filter((key) => key.startsWith('~*')),
).toHaveLength(redirectNames.length + 1);
});
it('IIS zet de MIME-types uit compressibleTypes.ts vast', () => {
const iis = iisWebConfig();
for (const [extension, mimeType] of [
['.js', 'text/javascript'],
['.svg', 'image/svg+xml'],
['.json', 'application/json'],
['.xml', 'text/xml'],
['.woff2', 'font/woff2'],
]) {
expect(iis).toContain(`<remove fileExtension="${extension}" />`);
expect(iis).toContain(
`<mimeMap fileExtension="${extension}" mimeType="${mimeType}" />`,
);
}
});
it('nginx: geen mapregel raakt /404 of /404.html (invariant)', () => {
const rules = nginxMapKeys().map((key) =>
key.startsWith('~*')
? new RegExp(key.slice(2), 'i')
: new RegExp(key.slice(1)),
);
expect(rules.length).toBeGreaterThan(0);
for (const path of ['/404', '/404.html', '/404.HTML', '/404/']) {
for (const rule of rules) expect(rule.test(path)).toBe(false);
}
});
it('nginx: server en elk location-blok met add_header hebben de volledige set (invariant)', () => {
const nginx = nginxTestConf();
const full = [
...Object.entries(securityHeaders('production')).map(
([name, value]) => `add_header ${name} "${value}" always;`,
),
'add_header X-Robots-Tag "noindex, nofollow" always;',
];
const serverLevel = nginx.slice(
nginx.indexOf('server {'),
nginx.search(/^ *location /m),
);
const locations = nginx.split(/^ *location /m).slice(1);
const cacheControls = (block: string) =>
block.match(/add_header Cache-Control/g)?.length ?? 0;
for (const block of [serverLevel, ...locations]) {
if (!block.includes('add_header')) continue;
for (const line of full) expect(block).toContain(line);
expect(cacheControls(block)).toBe(1);
}
const assets = locations.find((block) => block.startsWith('/assets/'));
expect(assets).toContain('immutable');
expect(cacheControls(assets ?? '')).toBe(1);
});
it('nginx: geen mapweergave, geen $uri/ en geen return vanuit het pad (invariant)', () => {
const lines = nginxDirectives();
expect(lines.filter((line) => /^index\s/.test(line))).toEqual([]);
expect(lines).not.toContain('autoindex on;');
for (const line of lines.filter((l) => l.startsWith('try_files'))) {
expect(line).not.toContain('$uri/');
expect(line).not.toContain('/index.html $uri');
}
for (const line of lines.filter((l) => /^return\s+30\d/.test(l))) {
expect(line).not.toContain('$uri');
expect(line).not.toContain('$1');
}
expect(lines.filter((line) => line.startsWith('rewrite '))).toEqual([
'rewrite ^/(.+?)/+$ /$1 permanent;',
]);
});
it('nginx: eigen 404-pagina, interne 404.html en eigen gzip-instellingen', () => {
const nginx = nginxTestConf();
expect(nginx).toContain('error_page 404 /404.html;');
expect(nginx).toMatch(/location = \/404\.html \{\s+internal;/);
expect(nginx).toContain('gzip_http_version 1.0;');
const types = nginx.match(/^ *gzip_types ([^;]+);/m)?.[1].split(' ');
for (const type of gzipMimeTypes()) expect(types).toContain(type);
});
it('nginx: de kop noemt het standaardblok en het bestand is een los server-blok', () => {
const nginx = nginxTestConf();
expect(nginx).toContain('00-default.conf');
expect(nginx).toContain('444');
expect(nginx).not.toMatch(
/(terugval|valt terug|fallback)[^\n]*WordPress/i,
);
const lines = nginxDirectives();
expect(lines.some((line) => line.startsWith('include '))).toBe(false);
expect(lines.some((line) => /^http\s*\{/.test(line))).toBe(false);
expect(lines.some((line) => line.includes('default_server'))).toBe(
false,
);
});
});
function iisRules(): Element[] {
const document = new DOMParser().parseFromString(
iisWebConfig(),
'application/xml',
);
expect(document.querySelector('parsererror')).toBeNull();
return [...document.querySelectorAll('rewrite > rules > rule')];
}
function iisRule(name: string): Element {
const rule = iisRules().find((r) => r.getAttribute('name') === name);
if (!rule) throw new Error(`Regel ${name} ontbreekt`);
return rule;
}
// De paginanamen uit de alternation van de canonieke regel
function iisAlternation(): string[] {
const url =
iisRule('Pagina canoniek')
.querySelector('match')
?.getAttribute('url') ?? '';
const body = url.match(/^\^\((.+)\)\(\?:\\\.html\)\?\/\*\$$/)?.[1];
return (body ?? '').split('|').map((name) => name.replace(/\\(.)/g, '$1'));
}
// Config-regels zonder commentaar en inspringing
function nginxDirectives(): string[] {
return nginxTestConf()
.split('\n')
.map((line) => line.trim())
.filter((line) => line && !line.startsWith('#'));
}
function nginxMapKeys(): string[] {
const map = nginxTestConf().match(
/map \$uri \$andreaslop_canonical \{([^}]*)\}/,
)?.[1];
return (map ?? '')
.split('\n')
.map((line) => line.trim())
.filter((line) => line && line !== 'default "";')
.map((line) => line.split(' ')[0]);
}
// De paden van de hoofdlettergevoelige canonieke sleutels (~^/pad$)
function nginxCanonicalPaths(): string[] {
return nginxMapKeys()
.filter((key) => key.startsWith('~^'))
.map((key) => key.slice(2, -1));
}