Generates the nginx rules for prerendered pages
Pages now map to their html file, other forms get one redirect, unknown URLs get a real 404 and responses are compressed. A browser-free test suite runs the rules against a real nginx, in CI only so far. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,175 @@
|
||||
import fc from 'fast-check';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import {
|
||||
hostilePath,
|
||||
pageVariant,
|
||||
unknownPath,
|
||||
} from '../src/test/urlArbitraries';
|
||||
import {
|
||||
canonicalRedirect,
|
||||
escapeRegex,
|
||||
pagePaths,
|
||||
redirectNames,
|
||||
stripTrailingSlashes,
|
||||
variantPattern,
|
||||
} from './canonicalUrls';
|
||||
|
||||
// Wat de resolver per stap doet: eerst de paginavariant, anders de slashes
|
||||
const hop = (path: string) =>
|
||||
canonicalRedirect(path) ?? stripTrailingSlashes(path);
|
||||
|
||||
describe('pagePaths', () => {
|
||||
it('begint met de beginpagina en bevat elke andere pagina eenmaal', () => {
|
||||
expect(pagePaths[0]).toBe('/');
|
||||
expect(new Set(pagePaths).size).toBe(pagePaths.length);
|
||||
expect(redirectNames).toEqual(pagePaths.slice(1));
|
||||
});
|
||||
});
|
||||
|
||||
describe('canonicalRedirect', () => {
|
||||
it.each([
|
||||
['/over-mij/', '/over-mij'],
|
||||
['/over-mij///', '/over-mij'],
|
||||
['/over-mij.html', '/over-mij'],
|
||||
['/soorten-fotoshoots/', '/soorten-fotoshoots'],
|
||||
['/soorten-fotoshoots/newborn.html', '/soorten-fotoshoots/newborn'],
|
||||
['/index', '/'],
|
||||
['/index.html', '/'],
|
||||
['/index/', '/'],
|
||||
['/Over-Mij', '/over-mij'],
|
||||
['/OVER-MIJ.HTML', '/over-mij'],
|
||||
['/Over-Mij/', '/over-mij'],
|
||||
['/Index.HTML//', '/'],
|
||||
])('%s gaat naar %s', (path, target) => {
|
||||
expect(canonicalRedirect(path)).toBe(target);
|
||||
});
|
||||
|
||||
it.each([
|
||||
'/',
|
||||
'/over-mij',
|
||||
'/soorten-fotoshoots/newborn',
|
||||
'/onbekend',
|
||||
'/Onbekend',
|
||||
'/onbekend/',
|
||||
'/x.html',
|
||||
'/404',
|
||||
'/404.html',
|
||||
'/assets',
|
||||
'/assets/',
|
||||
'/over-mij/extra',
|
||||
'',
|
||||
])('laat %s met rust', (path) => {
|
||||
expect(canonicalRedirect(path)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('P-HST-02: elke variant van een bekende pagina gaat naar het canonieke pad (invariant)', () => {
|
||||
fc.assert(
|
||||
fc.property(pageVariant, (variant) => {
|
||||
const name = variant
|
||||
.toLowerCase()
|
||||
.replace(/\/+$/, '')
|
||||
.replace(/\.html$/, '');
|
||||
const canonical = name === '/index' ? '/' : name;
|
||||
const target = canonicalRedirect(variant);
|
||||
// De canonieke vorm zelf blijft staan
|
||||
expect(target).toBe(
|
||||
variant === canonical ? undefined : canonical,
|
||||
);
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('P-HST-03: het doel is een dekpunt en een variant heeft hooguit twee stappen nodig (idempotent)', () => {
|
||||
fc.assert(
|
||||
fc.property(pageVariant, (variant) => {
|
||||
const target = canonicalRedirect(variant) ?? variant;
|
||||
expect(canonicalRedirect(target)).toBeUndefined();
|
||||
expect(stripTrailingSlashes(target)).toBeUndefined();
|
||||
}),
|
||||
);
|
||||
fc.assert(
|
||||
fc.property(
|
||||
unknownPath,
|
||||
fc.integer({ min: 0, max: 3 }),
|
||||
(path, slashes) => {
|
||||
const first = hop(path + '/'.repeat(slashes));
|
||||
// Na de eerste stap is er niets meer te doen
|
||||
expect(first === undefined ? undefined : hop(first)).toBe(
|
||||
undefined,
|
||||
);
|
||||
},
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it('P-HST-04: een doel begint met een slash, nooit met // of /\\, en is een bekende pagina (invariant)', () => {
|
||||
const check = (path: string) => {
|
||||
const target = canonicalRedirect(path);
|
||||
if (target === undefined) return;
|
||||
expect(pagePaths).toContain(target);
|
||||
expect(target.startsWith('/')).toBe(true);
|
||||
expect(target.startsWith('//')).toBe(false);
|
||||
expect(target.startsWith('/\\')).toBe(false);
|
||||
// eslint-disable-next-line no-control-regex
|
||||
expect(target).not.toMatch(/[\u0000-\u001f\u007f]/);
|
||||
};
|
||||
fc.assert(fc.property(pageVariant, check));
|
||||
fc.assert(fc.property(hostilePath, check));
|
||||
});
|
||||
});
|
||||
|
||||
describe('stripTrailingSlashes', () => {
|
||||
it.each([
|
||||
['/onbekend/', '/onbekend'],
|
||||
['/onbekend///', '/onbekend'],
|
||||
['/assets/', '/assets'],
|
||||
['/a/b/', '/a/b'],
|
||||
['//', '/'],
|
||||
])('%s wordt %s', (path, stripped) => {
|
||||
expect(stripTrailingSlashes(path)).toBe(stripped);
|
||||
});
|
||||
|
||||
it.each(['/', '', '/onbekend', '/a/b'])('laat %s met rust', (path) => {
|
||||
expect(stripTrailingSlashes(path)).toBeUndefined();
|
||||
});
|
||||
|
||||
it.each([
|
||||
'//evil.example/',
|
||||
'/\\evil.example/',
|
||||
'/over-mij\r\nSet-Cookie: x=1/',
|
||||
'/over-mij\0/',
|
||||
])('geeft geen doel voor het gevaarlijke pad %j (BR-HST-06)', (path) => {
|
||||
expect(stripTrailingSlashes(path)).toBeUndefined();
|
||||
});
|
||||
|
||||
it('P-HST-04: een doel is veilig, ook voor vijandige paden (invariant)', () => {
|
||||
fc.assert(
|
||||
fc.property(hostilePath, (path) => {
|
||||
const target = stripTrailingSlashes(path);
|
||||
if (target === undefined) return;
|
||||
expect(target.startsWith('/')).toBe(true);
|
||||
expect(target.startsWith('//')).toBe(false);
|
||||
expect(target.startsWith('/\\')).toBe(false);
|
||||
expect(target.endsWith('/') && target !== '/').toBe(false);
|
||||
// eslint-disable-next-line no-control-regex
|
||||
expect(target).not.toMatch(/[\u0000-\u001f\u007f]/);
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('variantPattern en escapeRegex', () => {
|
||||
it('zet de naam, een optionele .html en slashes in het patroon', () => {
|
||||
expect(variantPattern('/over-mij')).toBe('over-mij(?:\\.html)?/*');
|
||||
expect(variantPattern('/')).toBe('index(?:\\.html)?/*');
|
||||
expect(variantPattern('/soorten-fotoshoots/newborn')).toBe(
|
||||
'soorten-fotoshoots/newborn(?:\\.html)?/*',
|
||||
);
|
||||
});
|
||||
|
||||
it('escapet tekens met een betekenis in een reguliere expressie', () => {
|
||||
expect(escapeRegex('a.b*c(d)|e[f]\\')).toBe(
|
||||
'a\\.b\\*c\\(d\\)\\|e\\[f\\]\\\\',
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,63 @@
|
||||
// De URL-regels voor bekende pagina's (BR-HST-03, 04, 06) op één plek: de
|
||||
// previewserver gebruikt de functies, de generatoren voor nginx en IIS halen
|
||||
// er de patronen en de paginalijst uit. Zo kennen alle drie dezelfde pagina's
|
||||
// en dezelfde varianten. Puur: geen DOM en geen I/O.
|
||||
import sitePages from '../src/sitePages.ts';
|
||||
|
||||
// '/' staat vooraan; de rest in de volgorde van het register
|
||||
export const pagePaths: readonly string[] = Object.keys(sitePages);
|
||||
|
||||
// Alle pagina's behalve '/': die krijgen een eigen regel in nginx en IIS
|
||||
export const redirectNames: readonly string[] = pagePaths.filter(
|
||||
(path) => path !== '/',
|
||||
);
|
||||
|
||||
// Naam van de beginpagina onder een andere naam (BR-HST-04)
|
||||
const INDEX_NAME = 'index';
|
||||
|
||||
export const escapeRegex = (text: string): string =>
|
||||
text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
||||
|
||||
// Bron van het hoofdletterongevoelige patroon voor alle varianten van één
|
||||
// pagina, zonder voorste slash of ankers: de naam, eventueel .html, eventueel
|
||||
// slashes aan het eind. Voor '/' is de naam 'index'. nginx zet er '^/' voor,
|
||||
// IIS '^'. De canonieke vorm zelf valt er ook onder; de generatoren sluiten
|
||||
// die uit.
|
||||
export function variantPattern(path: string): string {
|
||||
const name = path === '/' ? INDEX_NAME : path.replace(/^\//, '');
|
||||
return `${escapeRegex(name)}(?:\\.html)?/*`;
|
||||
}
|
||||
|
||||
const variantMatchers = pagePaths.map(
|
||||
(path) => [new RegExp(`^/${variantPattern(path)}$`, 'i'), path] as const,
|
||||
);
|
||||
|
||||
// Het canonieke doel als het (gedecodeerde) pad een afwijkende vorm van een
|
||||
// bekende pagina is, anders undefined. Onbekende paden en /404 blijven
|
||||
// onaangeroerd. Het doel komt altijd uit de constante paginalijst.
|
||||
export function canonicalRedirect(decodedPath: string): string | undefined {
|
||||
for (const [matcher, canonical] of variantMatchers) {
|
||||
if (matcher.test(decodedPath)) {
|
||||
return decodedPath === canonical ? undefined : canonical;
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// Stuurcodes en DEL in een doel zouden een header kunnen splitsen
|
||||
// eslint-disable-next-line no-control-regex
|
||||
const CONTROL_CHARACTERS = /[\u0000-\u001f\u007f]/;
|
||||
|
||||
// Het pad zonder slashes aan het eind (BR-HST-03), voor elk pad langer dan één
|
||||
// teken dat op een slash eindigt. Een doel dat met '//' of '/\' begint (een
|
||||
// ander domein voor de browser) of stuurcodes bevat wordt niet teruggegeven
|
||||
// (BR-HST-06): de aanroeper behandelt zo'n pad als onbekend.
|
||||
export function stripTrailingSlashes(decodedPath: string): string | undefined {
|
||||
if (decodedPath.length < 2 || !decodedPath.endsWith('/')) return undefined;
|
||||
const stripped = decodedPath.replace(/\/+$/, '') || '/';
|
||||
if (stripped.startsWith('//') || stripped.startsWith('/\\')) {
|
||||
return undefined;
|
||||
}
|
||||
if (CONTROL_CHARACTERS.test(stripped)) return undefined;
|
||||
return stripped;
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
// Eén lijst met bestandstypen voor de previewserver (Content-Type en welke
|
||||
// bestanden gzip krijgen), de gzip_types van nginx en de MIME-pins van IIS
|
||||
// (BR-HST-11). Een test controleert dat ze overeenkomen.
|
||||
|
||||
export interface FileType {
|
||||
extension: string;
|
||||
// MIME-types zonder parameters, zoals nginx en IIS ze kennen
|
||||
mimeTypes: string[];
|
||||
// Exacte Content-Type van de previewserver
|
||||
previewContentType: string;
|
||||
}
|
||||
|
||||
// Tekst: wordt gecomprimeerd. nginx 1.24 kent .js als application/javascript,
|
||||
// vanaf 1.25.2 als text/javascript (de Pi draait 1.30.6): gzip_types moet
|
||||
// beide bevatten. Zo ook .xml.
|
||||
export const compressibleTypes: readonly FileType[] = [
|
||||
{
|
||||
extension: '.html',
|
||||
mimeTypes: ['text/html'],
|
||||
previewContentType: 'text/html; charset=utf-8',
|
||||
},
|
||||
{
|
||||
extension: '.js',
|
||||
mimeTypes: ['text/javascript', 'application/javascript'],
|
||||
previewContentType: 'text/javascript; charset=utf-8',
|
||||
},
|
||||
{
|
||||
extension: '.css',
|
||||
mimeTypes: ['text/css'],
|
||||
previewContentType: 'text/css; charset=utf-8',
|
||||
},
|
||||
{
|
||||
extension: '.svg',
|
||||
mimeTypes: ['image/svg+xml'],
|
||||
previewContentType: 'image/svg+xml',
|
||||
},
|
||||
{
|
||||
extension: '.json',
|
||||
mimeTypes: ['application/json'],
|
||||
previewContentType: 'application/json; charset=utf-8',
|
||||
},
|
||||
{
|
||||
extension: '.xml',
|
||||
mimeTypes: ['text/xml', 'application/xml'],
|
||||
previewContentType: 'application/xml; charset=utf-8',
|
||||
},
|
||||
{
|
||||
extension: '.txt',
|
||||
mimeTypes: ['text/plain'],
|
||||
previewContentType: 'text/plain; charset=utf-8',
|
||||
},
|
||||
];
|
||||
|
||||
// Al gecomprimeerd: niet nog eens comprimeren
|
||||
export const plainTypes: readonly FileType[] = [
|
||||
{
|
||||
extension: '.png',
|
||||
mimeTypes: ['image/png'],
|
||||
previewContentType: 'image/png',
|
||||
},
|
||||
{
|
||||
extension: '.jpg',
|
||||
mimeTypes: ['image/jpeg'],
|
||||
previewContentType: 'image/jpeg',
|
||||
},
|
||||
{
|
||||
extension: '.webp',
|
||||
mimeTypes: ['image/webp'],
|
||||
previewContentType: 'image/webp',
|
||||
},
|
||||
{
|
||||
extension: '.woff2',
|
||||
mimeTypes: ['font/woff2'],
|
||||
previewContentType: 'font/woff2',
|
||||
},
|
||||
{
|
||||
extension: '.ico',
|
||||
mimeTypes: ['image/x-icon'],
|
||||
previewContentType: 'image/x-icon',
|
||||
},
|
||||
];
|
||||
|
||||
export const compressibleExtensions: ReadonlySet<string> = new Set(
|
||||
compressibleTypes.map((type) => type.extension),
|
||||
);
|
||||
|
||||
// Voor gzip_types: uniek, zonder text/html (nginx comprimeert dat altijd)
|
||||
export function gzipMimeTypes(): string[] {
|
||||
const types = compressibleTypes.flatMap((type) => type.mimeTypes);
|
||||
return [...new Set(types)].filter((type) => type !== 'text/html');
|
||||
}
|
||||
@@ -59,7 +59,10 @@ describe('serverconfiguratie', () => {
|
||||
const nginx = nginxTestConf();
|
||||
expect(nginx).toContain('X-Robots-Tag "noindex, nofollow"');
|
||||
expect(nginx).toContain('Disallow: /');
|
||||
expect(nginx).toContain('try_files $uri $uri/ /index.html =404;');
|
||||
// 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)', () => {
|
||||
@@ -87,8 +90,11 @@ describe('serverconfiguratie', () => {
|
||||
|
||||
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 ').slice(1);
|
||||
expect(blocks).toHaveLength(3);
|
||||
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');
|
||||
}
|
||||
|
||||
+108
-19
@@ -3,6 +3,8 @@
|
||||
// dev- en preview-server. Zo bestaat de headerset maar op één plek.
|
||||
// Schrijven: `pnpm server-config`. Een test controleert dat de bestanden in
|
||||
// deploy/ gelijk zijn aan wat deze functies opleveren.
|
||||
import { gzipMimeTypes } from './compressibleTypes.ts';
|
||||
import { redirectNames, variantPattern } from './canonicalUrls.ts';
|
||||
import { securityHeaders } from './securityHeaders.ts';
|
||||
|
||||
const generatedNotice =
|
||||
@@ -87,55 +89,142 @@ ${headers}
|
||||
|
||||
// nginx (test): dezelfde headers, plus noindex zodat de testsite nooit in
|
||||
// zoekmachines komt. nginx erft add_header niet als een location er zelf een
|
||||
// zet, daarom staan de headers in elk location-blok.
|
||||
export function nginxTestConf(): string {
|
||||
const headers = [
|
||||
// zet, daarom staan de headers in elk location-blok, elk met de volledige set
|
||||
// en zijn eigen Cache-Control. De URL-regels (BR-HST-01 tot 08) komen uit de
|
||||
// paginalijst, zodat nginx, IIS en de previewserver dezelfde pagina's kennen.
|
||||
//
|
||||
// listen en root zijn instelbaar voor de serverregeltests (e2e/serverRules),
|
||||
// die een echte nginx op een vrije poort met een tijdelijke map starten.
|
||||
export function nginxTestConf(
|
||||
options: { listen?: string; root?: string } = {},
|
||||
): string {
|
||||
const { listen = '80', root = '/var/www/html/andreaslop-test' } = options;
|
||||
const securityLines = [
|
||||
...Object.entries(securityHeaders('production')).map(
|
||||
([name, value]) => `add_header ${name} "${value}" always;`,
|
||||
),
|
||||
'add_header X-Robots-Tag "noindex, nofollow" always;',
|
||||
];
|
||||
const block = (indent: string, extra: string[] = []) =>
|
||||
[...headers, ...extra].map((line) => indent + line).join('\n');
|
||||
const noCache = 'add_header Cache-Control "no-cache" always;';
|
||||
const immutable =
|
||||
'add_header Cache-Control "public, max-age=31536000, immutable" always;';
|
||||
// Eén bron voor alle blokken met headers: de volledige set plus precies
|
||||
// één Cache-Control, zodat geen enkel blok een header kwijtraakt
|
||||
const block = (indent: string, cacheControl: string | undefined) =>
|
||||
[...securityLines, ...(cacheControl ? [cacheControl] : [])]
|
||||
.map((line) => indent + line)
|
||||
.join('\n');
|
||||
|
||||
// Exacte canonieke vormen winnen van de reguliere expressies eronder, dus
|
||||
// het canonieke pad zelf wordt nooit doorverwezen. Geen regel mag /404 of
|
||||
// /404.html raken: error_page draait de server-regels opnieuw met
|
||||
// $uri=/404.html en zou van de 404-pagina een redirect maken.
|
||||
const canonicalEntries = redirectNames.map((path) => ` ${path} "";`);
|
||||
const variantEntries = [
|
||||
` ~*^/${variantPattern('/')}$ /;`,
|
||||
...redirectNames.map(
|
||||
(path) => ` ~*^/${variantPattern(path)}$ ${path};`,
|
||||
),
|
||||
];
|
||||
|
||||
return `# ${generatedNotice}
|
||||
# Test-omgeving op de Raspberry Pi, achter de reverse-proxy-Pi (die TLS afhandelt
|
||||
# met certbot). De proxy moet de Host-header doorgeven (proxy_set_header Host
|
||||
# $host), anders kiest nginx hier het standaardblok (WordPress).
|
||||
# Test-omgeving op de Raspberry Pi (hosting-Pi), achter de reverse-proxy-Pi
|
||||
# (die TLS afhandelt met certbot). Installatie: als
|
||||
# /etc/nginx/conf.d/andreaslop-test.conf; nginx.conf laadt conf.d binnen
|
||||
# http {}, er is geen sites-enabled. De globale nginx.conf hoeft niet te
|
||||
# veranderen: dit bestand brengt zijn eigen gzip-instellingen mee, want op de
|
||||
# Pi staat gzip nergens aan. Ze werken ook als de proxy HTTP/1.0 praat.
|
||||
# De proxy moet de Host-header doorgeven (proxy_set_header Host $host); het
|
||||
# blok wordt gekozen op server_name. Een onbekende host krijgt een 444 van
|
||||
# het standaardblok /etc/nginx/conf.d/00-default.conf.
|
||||
# Eigen server-blok naast de WordPress-site: bewust geen default_server, zodat
|
||||
# dit blok alleen de testhostname beantwoordt.
|
||||
# Pas server_name en root aan aan de server; de rest komt uit de generator.
|
||||
|
||||
# Bekende pagina's in een afwijkende vorm (hoofdletters, .html, /index,
|
||||
# slashes aan het eind) gaan met één 301 naar het canonieke pad. De waarden
|
||||
# zijn constanten uit de paginalijst, nooit afgeleid van het verzoek.
|
||||
map $uri $andreaslop_canonical {
|
||||
default "";
|
||||
${canonicalEntries.join('\n')}
|
||||
${variantEntries.join('\n')}
|
||||
}
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
listen ${listen};
|
||||
server_name test.andreaslop.nl;
|
||||
root /var/www/html/andreaslop-test;
|
||||
index index.html;
|
||||
root ${root};
|
||||
|
||||
# Achter de reverse proxy: doorverwijzingen relatief houden, anders stuurt
|
||||
# nginx naar zijn eigen http://-adres in plaats van de https-hostname
|
||||
absolute_redirect off;
|
||||
|
||||
${block(' ', ['add_header Cache-Control "no-cache" always;'])}
|
||||
# Geen index-directive en geen mappen tonen: index zou intern naar
|
||||
# /index.html gaan, dat hierboven naar / doorverwijst (lus)
|
||||
autoindex off;
|
||||
|
||||
${block(' ', noCache)}
|
||||
|
||||
# Eigen compressie (de Pi heeft geen gzip aan). text/html is altijd aan.
|
||||
gzip on;
|
||||
gzip_vary on;
|
||||
gzip_proxied any;
|
||||
gzip_http_version 1.0;
|
||||
gzip_comp_level 5;
|
||||
gzip_min_length 256;
|
||||
gzip_types ${gzipMimeTypes().join(' ')};
|
||||
|
||||
# Alleen return in een if is veilig. Het doel komt uit de map hierboven.
|
||||
if ($andreaslop_canonical) {
|
||||
return 301 $andreaslop_canonical$is_args$args;
|
||||
}
|
||||
|
||||
# Slashes aan het eind van elk ander pad weg. Bewust rewrite en geen
|
||||
# return met $uri: de serverregeltests controleren dat een regeleinde of
|
||||
# backslash in het pad nooit in een Location terechtkomt.
|
||||
rewrite ^/(.+?)/+$ /$1 permanent;
|
||||
|
||||
# Onbekend: de 404-pagina met status 404 (geen = achter de code)
|
||||
error_page 404 /404.html;
|
||||
|
||||
# Testsite nooit indexeren
|
||||
location = /robots.txt {
|
||||
${block(' ')}
|
||||
${block(' ', noCache)}
|
||||
default_type text/plain;
|
||||
return 200 "User-agent: *\\nDisallow: /\\n";
|
||||
}
|
||||
|
||||
# Zonder dit zou $uri.html de pagina met 200 tonen
|
||||
location = /404 {
|
||||
${block(' ', noCache)}
|
||||
return 404;
|
||||
}
|
||||
|
||||
# Alleen bereikbaar via error_page; een direct verzoek geeft 404
|
||||
location = /404.html {
|
||||
internal;
|
||||
${block(' ', noCache)}
|
||||
}
|
||||
|
||||
# Bestanden met een hash in de naam: lang cachen
|
||||
location /assets/ {
|
||||
${block(' ', ['add_header Cache-Control "public, max-age=31536000, immutable" always;'])}
|
||||
${block(' ', immutable)}
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
# SPA-fallback: onbekende paden krijgen index.html (de router toont de 404).
|
||||
# =404 aan het eind: zonder index.html (lege map) een 404 in plaats van een
|
||||
# doorverwijzingslus die nginx als 500 afbreekt
|
||||
# Geen index-directive: de beginpagina staat hier uitdrukkelijk
|
||||
location = / {
|
||||
${block(' ', noCache)}
|
||||
try_files /index.html =404;
|
||||
}
|
||||
|
||||
# Paginabestand zonder .html. $uri zonder slash is alleen een bestand, dus
|
||||
# een map naast soorten-fotoshoots.html wordt overgeslagen (BR-HST-07).
|
||||
# Nooit een slash achter de variabele zetten: dat geeft nginx' eigen
|
||||
# mapdoorverwijzing.
|
||||
location / {
|
||||
${block(' ', ['add_header Cache-Control "no-cache" always;'])}
|
||||
try_files $uri $uri/ /index.html =404;
|
||||
${block(' ', noCache)}
|
||||
try_files $uri $uri.html =404;
|
||||
}
|
||||
}
|
||||
`;
|
||||
|
||||
@@ -1,20 +1,58 @@
|
||||
# Gegenereerd door web/config/serverConfig.ts (pnpm server-config). Niet handmatig aanpassen.
|
||||
# Test-omgeving op de Raspberry Pi, achter de reverse-proxy-Pi (die TLS afhandelt
|
||||
# met certbot). De proxy moet de Host-header doorgeven (proxy_set_header Host
|
||||
# $host), anders kiest nginx hier het standaardblok (WordPress).
|
||||
# Test-omgeving op de Raspberry Pi (hosting-Pi), achter de reverse-proxy-Pi
|
||||
# (die TLS afhandelt met certbot). Installatie: als
|
||||
# /etc/nginx/conf.d/andreaslop-test.conf; nginx.conf laadt conf.d binnen
|
||||
# http {}, er is geen sites-enabled. De globale nginx.conf hoeft niet te
|
||||
# veranderen: dit bestand brengt zijn eigen gzip-instellingen mee, want op de
|
||||
# Pi staat gzip nergens aan. Ze werken ook als de proxy HTTP/1.0 praat.
|
||||
# De proxy moet de Host-header doorgeven (proxy_set_header Host $host); het
|
||||
# blok wordt gekozen op server_name. Een onbekende host krijgt een 444 van
|
||||
# het standaardblok /etc/nginx/conf.d/00-default.conf.
|
||||
# Eigen server-blok naast de WordPress-site: bewust geen default_server, zodat
|
||||
# dit blok alleen de testhostname beantwoordt.
|
||||
# Pas server_name en root aan aan de server; de rest komt uit de generator.
|
||||
|
||||
# Bekende pagina's in een afwijkende vorm (hoofdletters, .html, /index,
|
||||
# slashes aan het eind) gaan met één 301 naar het canonieke pad. De waarden
|
||||
# zijn constanten uit de paginalijst, nooit afgeleid van het verzoek.
|
||||
map $uri $andreaslop_canonical {
|
||||
default "";
|
||||
/over-mij "";
|
||||
/portfolio "";
|
||||
/soorten-fotoshoots "";
|
||||
/soorten-fotoshoots/newborn "";
|
||||
/soorten-fotoshoots/zwangerschap "";
|
||||
/soorten-fotoshoots/gezin "";
|
||||
/soorten-fotoshoots/loveshoot "";
|
||||
/soorten-fotoshoots/portret "";
|
||||
/contact "";
|
||||
/privacyverklaring "";
|
||||
~*^/index(?:\.html)?/*$ /;
|
||||
~*^/over-mij(?:\.html)?/*$ /over-mij;
|
||||
~*^/portfolio(?:\.html)?/*$ /portfolio;
|
||||
~*^/soorten-fotoshoots(?:\.html)?/*$ /soorten-fotoshoots;
|
||||
~*^/soorten-fotoshoots/newborn(?:\.html)?/*$ /soorten-fotoshoots/newborn;
|
||||
~*^/soorten-fotoshoots/zwangerschap(?:\.html)?/*$ /soorten-fotoshoots/zwangerschap;
|
||||
~*^/soorten-fotoshoots/gezin(?:\.html)?/*$ /soorten-fotoshoots/gezin;
|
||||
~*^/soorten-fotoshoots/loveshoot(?:\.html)?/*$ /soorten-fotoshoots/loveshoot;
|
||||
~*^/soorten-fotoshoots/portret(?:\.html)?/*$ /soorten-fotoshoots/portret;
|
||||
~*^/contact(?:\.html)?/*$ /contact;
|
||||
~*^/privacyverklaring(?:\.html)?/*$ /privacyverklaring;
|
||||
}
|
||||
|
||||
server {
|
||||
listen 80;
|
||||
server_name test.andreaslop.nl;
|
||||
root /var/www/html/andreaslop-test;
|
||||
index index.html;
|
||||
|
||||
# Achter de reverse proxy: doorverwijzingen relatief houden, anders stuurt
|
||||
# nginx naar zijn eigen http://-adres in plaats van de https-hostname
|
||||
absolute_redirect off;
|
||||
|
||||
# Geen index-directive en geen mappen tonen: index zou intern naar
|
||||
# /index.html gaan, dat hierboven naar / doorverwijst (lus)
|
||||
autoindex off;
|
||||
|
||||
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://analytics.slpsoftware.nl; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' https://analytics.slpsoftware.nl https://o4511795618185216.ingest.de.sentry.io; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'" always;
|
||||
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
|
||||
add_header X-Content-Type-Options "nosniff" always;
|
||||
@@ -23,6 +61,28 @@ server {
|
||||
add_header X-Robots-Tag "noindex, nofollow" always;
|
||||
add_header Cache-Control "no-cache" always;
|
||||
|
||||
# Eigen compressie (de Pi heeft geen gzip aan). text/html is altijd aan.
|
||||
gzip on;
|
||||
gzip_vary on;
|
||||
gzip_proxied any;
|
||||
gzip_http_version 1.0;
|
||||
gzip_comp_level 5;
|
||||
gzip_min_length 256;
|
||||
gzip_types text/javascript application/javascript text/css image/svg+xml application/json text/xml application/xml text/plain;
|
||||
|
||||
# Alleen return in een if is veilig. Het doel komt uit de map hierboven.
|
||||
if ($andreaslop_canonical) {
|
||||
return 301 $andreaslop_canonical$is_args$args;
|
||||
}
|
||||
|
||||
# Slashes aan het eind van elk ander pad weg. Bewust rewrite en geen
|
||||
# return met $uri: de serverregeltests controleren dat een regeleinde of
|
||||
# backslash in het pad nooit in een Location terechtkomt.
|
||||
rewrite ^/(.+?)/+$ /$1 permanent;
|
||||
|
||||
# Onbekend: de 404-pagina met status 404 (geen = achter de code)
|
||||
error_page 404 /404.html;
|
||||
|
||||
# Testsite nooit indexeren
|
||||
location = /robots.txt {
|
||||
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://analytics.slpsoftware.nl; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' https://analytics.slpsoftware.nl https://o4511795618185216.ingest.de.sentry.io; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'" always;
|
||||
@@ -31,10 +91,35 @@ server {
|
||||
add_header X-Frame-Options "DENY" always;
|
||||
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
|
||||
add_header X-Robots-Tag "noindex, nofollow" always;
|
||||
add_header Cache-Control "no-cache" always;
|
||||
default_type text/plain;
|
||||
return 200 "User-agent: *\nDisallow: /\n";
|
||||
}
|
||||
|
||||
# Zonder dit zou $uri.html de pagina met 200 tonen
|
||||
location = /404 {
|
||||
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://analytics.slpsoftware.nl; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' https://analytics.slpsoftware.nl https://o4511795618185216.ingest.de.sentry.io; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'" always;
|
||||
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
|
||||
add_header X-Content-Type-Options "nosniff" always;
|
||||
add_header X-Frame-Options "DENY" always;
|
||||
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
|
||||
add_header X-Robots-Tag "noindex, nofollow" always;
|
||||
add_header Cache-Control "no-cache" always;
|
||||
return 404;
|
||||
}
|
||||
|
||||
# Alleen bereikbaar via error_page; een direct verzoek geeft 404
|
||||
location = /404.html {
|
||||
internal;
|
||||
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://analytics.slpsoftware.nl; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' https://analytics.slpsoftware.nl https://o4511795618185216.ingest.de.sentry.io; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'" always;
|
||||
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
|
||||
add_header X-Content-Type-Options "nosniff" always;
|
||||
add_header X-Frame-Options "DENY" always;
|
||||
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
|
||||
add_header X-Robots-Tag "noindex, nofollow" always;
|
||||
add_header Cache-Control "no-cache" always;
|
||||
}
|
||||
|
||||
# Bestanden met een hash in de naam: lang cachen
|
||||
location /assets/ {
|
||||
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://analytics.slpsoftware.nl; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' https://analytics.slpsoftware.nl https://o4511795618185216.ingest.de.sentry.io; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'" always;
|
||||
@@ -47,9 +132,22 @@ server {
|
||||
try_files $uri =404;
|
||||
}
|
||||
|
||||
# SPA-fallback: onbekende paden krijgen index.html (de router toont de 404).
|
||||
# =404 aan het eind: zonder index.html (lege map) een 404 in plaats van een
|
||||
# doorverwijzingslus die nginx als 500 afbreekt
|
||||
# Geen index-directive: de beginpagina staat hier uitdrukkelijk
|
||||
location = / {
|
||||
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://analytics.slpsoftware.nl; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' https://analytics.slpsoftware.nl https://o4511795618185216.ingest.de.sentry.io; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'" always;
|
||||
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
|
||||
add_header X-Content-Type-Options "nosniff" always;
|
||||
add_header X-Frame-Options "DENY" always;
|
||||
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
|
||||
add_header X-Robots-Tag "noindex, nofollow" always;
|
||||
add_header Cache-Control "no-cache" always;
|
||||
try_files /index.html =404;
|
||||
}
|
||||
|
||||
# Paginabestand zonder .html. $uri zonder slash is alleen een bestand, dus
|
||||
# een map naast soorten-fotoshoots.html wordt overgeslagen (BR-HST-07).
|
||||
# Nooit een slash achter de variabele zetten: dat geeft nginx' eigen
|
||||
# mapdoorverwijzing.
|
||||
location / {
|
||||
add_header Content-Security-Policy "default-src 'self'; script-src 'self' https://analytics.slpsoftware.nl; style-src 'self' 'unsafe-inline'; img-src 'self' data:; font-src 'self'; connect-src 'self' https://analytics.slpsoftware.nl https://o4511795618185216.ingest.de.sentry.io; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'none'" always;
|
||||
add_header Strict-Transport-Security "max-age=31536000; includeSubDomains" always;
|
||||
@@ -58,6 +156,6 @@ server {
|
||||
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
|
||||
add_header X-Robots-Tag "noindex, nofollow" always;
|
||||
add_header Cache-Control "no-cache" always;
|
||||
try_files $uri $uri/ /index.html =404;
|
||||
try_files $uri $uri.html =404;
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,376 @@
|
||||
import { request } from 'node:http';
|
||||
import { connect } from 'node:net';
|
||||
import { gunzipSync } from 'node:zlib';
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
import { securityHeaders } from '../config/securityHeaders.ts';
|
||||
import { createFixtureSite, type FixtureSite } from './support/fixtureSite.ts';
|
||||
import {
|
||||
findNginx,
|
||||
startNginx,
|
||||
type MimeVariant,
|
||||
type RunningNginx,
|
||||
} from './support/nginx.ts';
|
||||
|
||||
// BR-HST-24: de nginx-regels worden bewezen door een echte nginx, niet door de
|
||||
// tekst te lezen. De site is een kleine fixture (geen build nodig); dezelfde
|
||||
// regels voor de previewserver staan in previewServer.test.ts.
|
||||
|
||||
const nginxBin = findNginx();
|
||||
const inCi = Boolean(process.env.CI);
|
||||
|
||||
// Zonder nginx: in CI een duidelijke fout, lokaal een zichtbare melding
|
||||
if (!nginxBin) {
|
||||
if (inCi) {
|
||||
describe('serverregels (nginx)', () => {
|
||||
it('vindt nginx', () => {
|
||||
throw new Error('nginx ontbreekt in CI (BR-HST-24)');
|
||||
});
|
||||
});
|
||||
} else {
|
||||
describe('serverregels (nginx)', () => {
|
||||
it('nginx niet gevonden: serverregeltests overgeslagen (zie BR-HST-24)', (context) => {
|
||||
console.log(context.task.name);
|
||||
context.skip();
|
||||
});
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
interface Reply {
|
||||
status: number;
|
||||
headers: Record<string, string>;
|
||||
rawHeaders: string[];
|
||||
body: Buffer;
|
||||
}
|
||||
|
||||
// node:http en niet fetch: fetch voegt dubbele headers samen en pakt gzip uit
|
||||
function get(
|
||||
origin: string,
|
||||
path: string,
|
||||
options: { method?: string; headers?: Record<string, string> } = {},
|
||||
): Promise<Reply> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const req = request(
|
||||
origin + path,
|
||||
{ method: options.method ?? 'GET', headers: options.headers },
|
||||
(res) => {
|
||||
const chunks: Buffer[] = [];
|
||||
res.on('data', (chunk: Buffer) => chunks.push(chunk));
|
||||
res.on('end', () =>
|
||||
resolve({
|
||||
status: res.statusCode ?? 0,
|
||||
headers: Object.fromEntries(
|
||||
Object.entries(res.headers).map(([k, v]) => [
|
||||
k,
|
||||
String(v),
|
||||
]),
|
||||
),
|
||||
rawHeaders: res.rawHeaders,
|
||||
body: Buffer.concat(chunks),
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
req.on('error', reject);
|
||||
req.end();
|
||||
});
|
||||
}
|
||||
|
||||
const countHeader = (reply: Reply, name: string) =>
|
||||
reply.rawHeaders.filter(
|
||||
(value, i) => i % 2 === 0 && value.toLowerCase() === name.toLowerCase(),
|
||||
).length;
|
||||
|
||||
// Alle productieheaders, X-Robots-Tag en precies één Cache-Control
|
||||
function expectFullHeaders(reply: Reply, cacheControl = 'no-cache') {
|
||||
for (const [name, value] of Object.entries(securityHeaders('production'))) {
|
||||
expect(countHeader(reply, name), name).toBe(1);
|
||||
expect(reply.headers[name.toLowerCase()], name).toBe(value);
|
||||
}
|
||||
expect(countHeader(reply, 'X-Robots-Tag')).toBe(1);
|
||||
expect(reply.headers['x-robots-tag']).toBe('noindex, nofollow');
|
||||
expect(countHeader(reply, 'Cache-Control')).toBe(1);
|
||||
expect(reply.headers['cache-control']).toBe(cacheControl);
|
||||
}
|
||||
|
||||
// Een ruw HTTP/1.0-verzoek, zoals de proxy-Pi dat naar de hosting-Pi stuurt
|
||||
function getHttp10(origin: string, path: string, headers: string[]) {
|
||||
const { port } = new URL(origin);
|
||||
return new Promise<{ head: string; body: Buffer }>((resolve, reject) => {
|
||||
const socket = connect(Number(port), '127.0.0.1');
|
||||
const chunks: Buffer[] = [];
|
||||
socket.on('connect', () =>
|
||||
socket.write(
|
||||
[
|
||||
`GET ${path} HTTP/1.0`,
|
||||
'Host: test.andreaslop.nl',
|
||||
...headers,
|
||||
'',
|
||||
'',
|
||||
].join('\r\n'),
|
||||
),
|
||||
);
|
||||
socket.on('data', (chunk: Buffer) => chunks.push(chunk));
|
||||
socket.on('error', reject);
|
||||
socket.on('close', () => {
|
||||
const all = Buffer.concat(chunks);
|
||||
const split = all.indexOf('\r\n\r\n');
|
||||
resolve({
|
||||
head: all.subarray(0, split).toString('latin1'),
|
||||
body: all.subarray(split + 4),
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
const mimeVariants: MimeVariant[] = ['new', 'old'];
|
||||
|
||||
const rulesSuite = nginxBin ? describe : describe.skip;
|
||||
rulesSuite.each(mimeVariants)(
|
||||
'serverregels op een echte nginx (.js als %s mime-type)',
|
||||
(variant) => {
|
||||
let site: FixtureSite;
|
||||
let nginx: RunningNginx;
|
||||
const markerOf = (file: string) => site.markers.get(file) ?? file;
|
||||
|
||||
beforeAll(async () => {
|
||||
site = await createFixtureSite();
|
||||
nginx = await startNginx({
|
||||
siteDir: site.dir,
|
||||
mimeVariant: variant,
|
||||
});
|
||||
console.log(
|
||||
`[serverRules] nginx -v: ${nginx.version} (${nginx.origin})`,
|
||||
);
|
||||
});
|
||||
afterAll(async () => {
|
||||
await nginx?.stop();
|
||||
await site?.remove();
|
||||
});
|
||||
|
||||
const page = (path: string, init?: Parameters<typeof get>[2]) =>
|
||||
get(nginx.origin, path, init);
|
||||
|
||||
describe("pagina's en bestanden (BR-HST-01, V3)", () => {
|
||||
it.each([
|
||||
['/', 'index.html'],
|
||||
['/over-mij', 'over-mij.html'],
|
||||
['/soorten-fotoshoots', 'soorten-fotoshoots.html'],
|
||||
[
|
||||
'/soorten-fotoshoots/newborn',
|
||||
'soorten-fotoshoots/newborn.html',
|
||||
],
|
||||
['/over-mij?x=1', 'over-mij.html'],
|
||||
['/?x=1', 'index.html'],
|
||||
])('%s geeft 200 met %s', async (path, file) => {
|
||||
const reply = await page(path);
|
||||
expect(reply.status).toBe(200);
|
||||
expect(reply.body.toString()).toContain(markerOf(file));
|
||||
expectFullHeaders(reply);
|
||||
});
|
||||
|
||||
it.each([
|
||||
['/assets/index-AbC123xYz.js', 'assets/index-AbC123xYz.js'],
|
||||
['/sitemap.xml', 'sitemap.xml'],
|
||||
])('%s geeft 200 met het bestand', async (path, file) => {
|
||||
const reply = await page(path);
|
||||
expect(reply.status).toBe(200);
|
||||
expect(reply.body.toString()).toContain(markerOf(file));
|
||||
});
|
||||
|
||||
it('de map soorten-fotoshoots/ naast het paginabestand stuurt niet door en toont geen lijst (V3)', async () => {
|
||||
const file = await page('/soorten-fotoshoots');
|
||||
expect(file.status).toBe(200);
|
||||
expect(file.body.toString()).toContain(
|
||||
markerOf('soorten-fotoshoots.html'),
|
||||
);
|
||||
const dir = await page('/soorten-fotoshoots/');
|
||||
expect(dir.status).toBe(301);
|
||||
expect(dir.headers.location).toBe('/soorten-fotoshoots');
|
||||
});
|
||||
|
||||
it('/ werkt zonder index-directive (V2)', async () => {
|
||||
const reply = await page('/');
|
||||
expect(reply.status).toBe(200);
|
||||
expect(reply.body.toString()).toContain(markerOf('index.html'));
|
||||
});
|
||||
|
||||
it('/robots.txt verbiedt alles op de testsite', async () => {
|
||||
const reply = await page('/robots.txt');
|
||||
expect(reply.status).toBe(200);
|
||||
expect(reply.body.toString()).toContain('Disallow: /');
|
||||
expect(reply.body.toString()).not.toContain('fixture:');
|
||||
expectFullHeaders(reply);
|
||||
});
|
||||
});
|
||||
|
||||
describe('doorverwijzingen (BR-HST-03, 04, 06, V2)', () => {
|
||||
it.each([
|
||||
['/over-mij/', '/over-mij'],
|
||||
['/over-mij///', '/over-mij'],
|
||||
['/soorten-fotoshoots/', '/soorten-fotoshoots'],
|
||||
['/over-mij/?x=1', '/over-mij?x=1'],
|
||||
['/soorten-fotoshoots/?x=1', '/soorten-fotoshoots?x=1'],
|
||||
['/over-mij.html', '/over-mij'],
|
||||
[
|
||||
'/soorten-fotoshoots/newborn.html',
|
||||
'/soorten-fotoshoots/newborn',
|
||||
],
|
||||
['/index', '/'],
|
||||
['/index.html', '/'],
|
||||
['/index/', '/'],
|
||||
['/Over-Mij', '/over-mij'],
|
||||
['/OVER-MIJ.HTML', '/over-mij'],
|
||||
['/Over-Mij/', '/over-mij'],
|
||||
['/Over-Mij?x=1&y=%20z', '/over-mij?x=1&y=%20z'],
|
||||
['/onbekend/', '/onbekend'],
|
||||
['/assets/', '/assets'],
|
||||
])('%s gaat met één 301 naar %s', async (path, target) => {
|
||||
const reply = await page(path);
|
||||
expect(reply.status).toBe(301);
|
||||
// Relatief: absolute_redirect staat uit
|
||||
expect(reply.headers.location).toBe(target);
|
||||
expectFullHeaders(reply);
|
||||
});
|
||||
});
|
||||
|
||||
describe('404 (BR-HST-02, 05, V4)', () => {
|
||||
it.each([
|
||||
'/404',
|
||||
'/404.html',
|
||||
'/onbekend',
|
||||
'/Onbekend',
|
||||
'/x.html',
|
||||
'/assets/missing.js',
|
||||
'/assets',
|
||||
])('%s geeft 404 met de 404-pagina', async (path) => {
|
||||
const reply = await page(path);
|
||||
expect(reply.status).toBe(404);
|
||||
expect(reply.body.toString()).toContain(markerOf('404.html'));
|
||||
// Ook de 404 van een ontbrekend asset is niet immutable
|
||||
expectFullHeaders(reply);
|
||||
});
|
||||
|
||||
it('HEAD op een pagina en op een onbekende URL', async () => {
|
||||
const ok = await page('/over-mij', { method: 'HEAD' });
|
||||
expect(ok.status).toBe(200);
|
||||
expect(ok.body).toHaveLength(0);
|
||||
expectFullHeaders(ok);
|
||||
const missing = await page('/onbekend', { method: 'HEAD' });
|
||||
expect(missing.status).toBe(404);
|
||||
expect(missing.body).toHaveLength(0);
|
||||
expectFullHeaders(missing);
|
||||
});
|
||||
});
|
||||
|
||||
describe('caching (BR-HST-12)', () => {
|
||||
it('/assets/* heeft precies één Cache-Control: immutable', async () => {
|
||||
for (const path of [
|
||||
'/assets/index-AbC123xYz.js',
|
||||
'/assets/style-Qw9.css',
|
||||
'/assets/font-Ab.woff2',
|
||||
]) {
|
||||
const reply = await page(path);
|
||||
expect(reply.status, path).toBe(200);
|
||||
expectFullHeaders(
|
||||
reply,
|
||||
'public, max-age=31536000, immutable',
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it('al het andere revalideert', async () => {
|
||||
for (const path of ['/', '/sitemap.xml', '/favicon.png']) {
|
||||
expectFullHeaders(await page(path));
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe('compressie (BR-HST-09, V5)', () => {
|
||||
const compressed = [
|
||||
'/',
|
||||
'/over-mij',
|
||||
'/assets/index-AbC123xYz.js',
|
||||
'/assets/style-Qw9.css',
|
||||
'/assets/icon-Zz1.svg',
|
||||
'/assets/data.json',
|
||||
'/sitemap.xml',
|
||||
'/assets/readme.txt',
|
||||
];
|
||||
const plain = ['/assets/font-Ab.woff2', '/favicon.png'];
|
||||
|
||||
it.each(compressed)('%s krijgt gzip', async (path) => {
|
||||
const reply = await page(path, {
|
||||
headers: { 'Accept-Encoding': 'gzip' },
|
||||
});
|
||||
expect(reply.status).toBe(200);
|
||||
expect(reply.headers['content-encoding']).toBe('gzip');
|
||||
expect(reply.headers.vary).toContain('Accept-Encoding');
|
||||
expect(gunzipSync(reply.body).length).toBeGreaterThan(256);
|
||||
});
|
||||
|
||||
it.each(plain)('%s krijgt geen gzip', async (path) => {
|
||||
const reply = await page(path, {
|
||||
headers: { 'Accept-Encoding': 'gzip' },
|
||||
});
|
||||
expect(reply.status).toBe(200);
|
||||
expect(reply.headers['content-encoding']).toBeUndefined();
|
||||
});
|
||||
|
||||
it.each(compressed)(
|
||||
'%s krijgt gzip over HTTP/1.0 (zoals de proxy het vraagt)',
|
||||
async (path) => {
|
||||
const reply = await getHttp10(nginx.origin, path, [
|
||||
'Accept-Encoding: gzip',
|
||||
]);
|
||||
expect(reply.head).toMatch(/^HTTP\/1\.\d 200/);
|
||||
expect(reply.head).toMatch(/content-encoding: gzip/i);
|
||||
expect(gunzipSync(reply.body).length).toBeGreaterThan(256);
|
||||
},
|
||||
);
|
||||
|
||||
it.each(plain)(
|
||||
'%s krijgt over HTTP/1.0 geen gzip',
|
||||
async (path) => {
|
||||
const reply = await getHttp10(nginx.origin, path, [
|
||||
'Accept-Encoding: gzip',
|
||||
]);
|
||||
expect(reply.head).toMatch(/^HTTP\/1\.\d 200/);
|
||||
expect(reply.head).not.toMatch(/content-encoding/i);
|
||||
},
|
||||
);
|
||||
|
||||
it('zonder Accept-Encoding blijft het antwoord onbewerkt', async () => {
|
||||
const reply = await page('/assets/index-AbC123xYz.js');
|
||||
expect(reply.headers['content-encoding']).toBeUndefined();
|
||||
expect(reply.body.toString()).toContain(
|
||||
markerOf('assets/index-AbC123xYz.js'),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('vijandige paden (BR-HST-06)', () => {
|
||||
it.each([
|
||||
'//evil.example/',
|
||||
'//evil.example',
|
||||
'/\\evil.example/',
|
||||
'/\\evil.example',
|
||||
'/%5Cevil.example/',
|
||||
'/%2F%2Fevil.example/',
|
||||
'/%0d%0aSet-Cookie:%20x=1/',
|
||||
'/over-mij%0d%0aSet-Cookie:%20x=1/',
|
||||
'/%2e%2e/',
|
||||
])('%s leidt niet naar een ander domein', async (path) => {
|
||||
const reply = await page(path);
|
||||
const location = reply.headers.location;
|
||||
if (reply.status >= 300 && reply.status < 400) {
|
||||
expect(location).toBeDefined();
|
||||
expect(location?.startsWith('//')).toBe(false);
|
||||
expect(location?.startsWith('/\\')).toBe(false);
|
||||
expect(location).not.toMatch(/[\r\n]/);
|
||||
}
|
||||
expect(reply.headers['set-cookie']).toBeUndefined();
|
||||
});
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,88 @@
|
||||
import { randomBytes } from 'node:crypto';
|
||||
import { mkdir, mkdtemp, rm, writeFile } from 'node:fs/promises';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { dirname, join } from 'node:path';
|
||||
import { pagePaths } from '../../config/canonicalUrls.ts';
|
||||
import { NOT_FOUND_FILE, pageFile } from '../../config/pageFiles.ts';
|
||||
|
||||
// Een kleine site in de tijdelijke map met dezelfde vorm als dist/client, voor
|
||||
// de serverregeltests: elk paginabestand, de map soorten-fotoshoots/ naast
|
||||
// soorten-fotoshoots.html (BR-HST-07) en assets met hoofdletters in de naam.
|
||||
// Zo hangen die tests niet af van een build.
|
||||
|
||||
export interface FixtureSite {
|
||||
dir: string;
|
||||
// Bestand (relatief aan dir) naar de tekst die erin staat, zodat een test
|
||||
// aan het antwoord kan zien welk bestand geserveerd is
|
||||
markers: ReadonlyMap<string, string>;
|
||||
remove(): Promise<void>;
|
||||
}
|
||||
|
||||
// Alles boven de 256 bytes van gzip_min_length, anders blijft het onbewerkt
|
||||
const padding = ' vulling'.repeat(80);
|
||||
|
||||
export const markerOf = (file: string) => `fixture:${file}`;
|
||||
|
||||
export async function createFixtureSite(): Promise<FixtureSite> {
|
||||
const dir = await mkdtemp(join(tmpdir(), 'andreaslop-fixture-'));
|
||||
const markers = new Map<string, string>();
|
||||
|
||||
const write = async (file: string, content: string | Buffer) => {
|
||||
const target = join(dir, file);
|
||||
await mkdir(dirname(target), { recursive: true });
|
||||
await writeFile(target, content);
|
||||
};
|
||||
const writeMarked = async (
|
||||
file: string,
|
||||
wrap: (text: string) => string,
|
||||
) => {
|
||||
markers.set(file, markerOf(file));
|
||||
await write(file, wrap(markerOf(file)));
|
||||
};
|
||||
|
||||
for (const path of [...pagePaths, null]) {
|
||||
const file = path === null ? NOT_FOUND_FILE : pageFile(path);
|
||||
await writeMarked(
|
||||
file,
|
||||
(marker) =>
|
||||
`<!doctype html><html><body><p>${marker}</p><!--${padding}--></body></html>`,
|
||||
);
|
||||
}
|
||||
await writeMarked(
|
||||
'robots.txt',
|
||||
(marker) => `${marker}\nUser-agent: *\nAllow: /\n`,
|
||||
);
|
||||
await writeMarked(
|
||||
'sitemap.xml',
|
||||
(marker) =>
|
||||
`<?xml version="1.0"?><urlset><!--${marker}${padding}--></urlset>`,
|
||||
);
|
||||
await write('favicon.png', randomBytes(64));
|
||||
await writeMarked(
|
||||
'assets/index-AbC123xYz.js',
|
||||
(marker) => `// ${marker}\n${'console.log("regel");\n'.repeat(200)}`,
|
||||
);
|
||||
await writeMarked(
|
||||
'assets/style-Qw9.css',
|
||||
(marker) => `/* ${marker} */\n${'.a{color:red}\n'.repeat(200)}`,
|
||||
);
|
||||
await writeMarked(
|
||||
'assets/icon-Zz1.svg',
|
||||
(marker) =>
|
||||
`<svg xmlns="http://www.w3.org/2000/svg"><!--${marker}${padding}--></svg>`,
|
||||
);
|
||||
await writeMarked('assets/data.json', (marker) =>
|
||||
JSON.stringify({ marker, vulling: padding }),
|
||||
);
|
||||
await writeMarked(
|
||||
'assets/readme.txt',
|
||||
(marker) => `${marker}\n${'tekst\n'.repeat(200)}`,
|
||||
);
|
||||
await write('assets/font-Ab.woff2', randomBytes(2048));
|
||||
|
||||
return {
|
||||
dir,
|
||||
markers,
|
||||
remove: () => rm(dir, { recursive: true, force: true }),
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,206 @@
|
||||
import { execFile, spawn, type ChildProcess } from 'node:child_process';
|
||||
import { existsSync, readFileSync, rmSync } from 'node:fs';
|
||||
import { mkdtemp, rm, writeFile } from 'node:fs/promises';
|
||||
import { createServer } from 'node:net';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { join } from 'node:path';
|
||||
import { promisify } from 'node:util';
|
||||
import { nginxTestConf } from '../../config/serverConfig.ts';
|
||||
|
||||
// Start een echte, onbevoorrechte nginx met het gegenereerde testblok
|
||||
// (BR-HST-24). Alleen voor de serverregeltests: eigen prefixmap, eigen poort,
|
||||
// geen systeemconfiguratie.
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
// Waar nginx kan staan: NGINX_BIN, het PATH, de twee bekende Windows-plekken
|
||||
const windowsPaths = [
|
||||
'C:\\nginx\\nginx.exe',
|
||||
'C:\\Users\\Bryan\\scoop\\apps\\nginx\\current\\nginx.exe',
|
||||
];
|
||||
|
||||
export function findNginx(): string | undefined {
|
||||
const fromEnv = process.env.NGINX_BIN;
|
||||
if (fromEnv) return existsSync(fromEnv) ? fromEnv : undefined;
|
||||
const names = process.platform === 'win32' ? ['nginx.exe'] : ['nginx'];
|
||||
const separator = process.platform === 'win32' ? ';' : ':';
|
||||
for (const dir of (process.env.PATH ?? '').split(separator)) {
|
||||
for (const name of names) {
|
||||
if (dir && existsSync(join(dir, name))) return join(dir, name);
|
||||
}
|
||||
}
|
||||
// Op Linux staat nginx soms in sbin, buiten het PATH van een gebruiker
|
||||
for (const path of ['/usr/sbin/nginx', ...windowsPaths]) {
|
||||
if (existsSync(path)) return path;
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
// nginx 1.24 kent .js als application/javascript, vanaf 1.25.2 als
|
||||
// text/javascript (de Pi draait 1.30.6). Beide tabellen worden getest.
|
||||
export type MimeVariant = 'new' | 'old';
|
||||
|
||||
const mimeTable = (variant: MimeVariant) => `types {
|
||||
text/html html;
|
||||
text/css css;
|
||||
${variant === 'old' ? 'application/javascript' : 'text/javascript'} js;
|
||||
image/svg+xml svg;
|
||||
application/json json;
|
||||
text/xml xml;
|
||||
text/plain txt;
|
||||
image/png png;
|
||||
font/woff2 woff2;
|
||||
}`;
|
||||
|
||||
// Alle nog lopende instanties, voor het opruimen als het proces stopt
|
||||
const running = new Set<{ child: ChildProcess; tmp: string }>();
|
||||
process.on('exit', () => {
|
||||
for (const { child, tmp } of running) {
|
||||
child.kill();
|
||||
try {
|
||||
rmSync(tmp, { recursive: true, force: true });
|
||||
} catch {
|
||||
// Opruimen bij afsluiten mag falen
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
// nginx onder Windows wil voorwaartse slashes in de configuratie
|
||||
const slashed = (path: string) => path.replace(/\\/g, '/');
|
||||
|
||||
async function freePort(): Promise<number> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const probe = createServer();
|
||||
probe.once('error', reject);
|
||||
probe.listen(0, '127.0.0.1', () => {
|
||||
const address = probe.address();
|
||||
probe.close(() =>
|
||||
typeof address === 'object' && address
|
||||
? resolve(address.port)
|
||||
: reject(new Error('geen poort gekregen')),
|
||||
);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
export interface RunningNginx {
|
||||
origin: string;
|
||||
version: string;
|
||||
stop(): Promise<void>;
|
||||
}
|
||||
|
||||
export async function startNginx(options: {
|
||||
siteDir: string;
|
||||
mimeVariant?: MimeVariant;
|
||||
}): Promise<RunningNginx> {
|
||||
const bin = findNginx();
|
||||
if (!bin) throw new Error('nginx niet gevonden');
|
||||
const { mimeVariant = 'new' } = options;
|
||||
|
||||
const tmp = await mkdtemp(join(tmpdir(), 'andreaslop-nginx-'));
|
||||
const port = await freePort();
|
||||
const serverFile = join(tmp, 'andreaslop-test.conf');
|
||||
const confFile = join(tmp, 'nginx.conf');
|
||||
const errorLog = join(tmp, 'error.log');
|
||||
const temp = (name: string) => `"${slashed(join(tmp, name))}"`;
|
||||
|
||||
await writeFile(
|
||||
serverFile,
|
||||
nginxTestConf({
|
||||
listen: `127.0.0.1:${port}`,
|
||||
root: slashed(options.siteDir),
|
||||
}),
|
||||
);
|
||||
await writeFile(
|
||||
confFile,
|
||||
`daemon off;
|
||||
pid "${slashed(join(tmp, 'nginx.pid'))}";
|
||||
error_log "${slashed(errorLog)}";
|
||||
events {}
|
||||
http {
|
||||
${mimeTable(mimeVariant)}
|
||||
client_body_temp_path ${temp('client_body')};
|
||||
proxy_temp_path ${temp('proxy')};
|
||||
fastcgi_temp_path ${temp('fastcgi')};
|
||||
uwsgi_temp_path ${temp('uwsgi')};
|
||||
scgi_temp_path ${temp('scgi')};
|
||||
access_log off;
|
||||
include "${slashed(serverFile)}";
|
||||
}
|
||||
`,
|
||||
);
|
||||
|
||||
// nginx -v schrijft naar stderr
|
||||
const { stdout, stderr } = await execFileAsync(bin, ['-v']);
|
||||
const version = (stdout + stderr).trim();
|
||||
|
||||
await execFileAsync(bin, [
|
||||
'-t',
|
||||
'-p',
|
||||
`${slashed(tmp)}/`,
|
||||
'-c',
|
||||
slashed(confFile),
|
||||
'-e',
|
||||
slashed(errorLog),
|
||||
]).catch((error: { stderr?: string }) => {
|
||||
throw new Error(`nginx -t keurt de configuratie af:\n${error.stderr}`);
|
||||
});
|
||||
|
||||
const child = spawn(
|
||||
bin,
|
||||
[
|
||||
'-p',
|
||||
`${slashed(tmp)}/`,
|
||||
'-c',
|
||||
slashed(confFile),
|
||||
'-e',
|
||||
slashed(errorLog),
|
||||
],
|
||||
{ stdio: 'ignore' },
|
||||
);
|
||||
const entry = { child, tmp };
|
||||
running.add(entry);
|
||||
let exited = false;
|
||||
child.once('exit', () => {
|
||||
exited = true;
|
||||
});
|
||||
|
||||
const stop = async () => {
|
||||
if (!exited) {
|
||||
const done = new Promise<void>((resolve) =>
|
||||
child.once('exit', () => resolve()),
|
||||
);
|
||||
child.kill();
|
||||
// Mocht nginx op SIGTERM niet reageren, dan alsnog hard stoppen
|
||||
const timer = setTimeout(() => child.kill('SIGKILL'), 5000);
|
||||
await done;
|
||||
clearTimeout(timer);
|
||||
}
|
||||
running.delete(entry);
|
||||
await rm(tmp, { recursive: true, force: true });
|
||||
};
|
||||
|
||||
const origin = `http://127.0.0.1:${port}`;
|
||||
const deadline = Date.now() + 5000;
|
||||
for (;;) {
|
||||
if (exited) {
|
||||
const log = existsSync(errorLog)
|
||||
? readFileSync(errorLog, 'utf8')
|
||||
: '(geen foutlog)';
|
||||
await stop();
|
||||
throw new Error(`nginx stopte bij het starten:\n${log}`);
|
||||
}
|
||||
try {
|
||||
await fetch(origin + '/');
|
||||
break;
|
||||
} catch {
|
||||
if (Date.now() > deadline) {
|
||||
await stop();
|
||||
throw new Error('nginx antwoordde niet binnen 5 seconden');
|
||||
}
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
}
|
||||
}
|
||||
|
||||
return { origin, version, stop };
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
import fc from 'fast-check';
|
||||
import { pagePaths } from '../../config/canonicalUrls.ts';
|
||||
import { pathSegment } from './arbitraries';
|
||||
|
||||
// Generatoren voor de URL-regels van bekende en onbekende pagina's (BR-HST).
|
||||
// Los van arbitraries.ts en requestArbitraries.ts, zodat die klein blijven
|
||||
// (PBT-07).
|
||||
|
||||
// Een pad uit het paginaregister, '/' inbegrepen
|
||||
export const knownPage = fc.constantFrom(...pagePaths);
|
||||
|
||||
// Hetzelfde pad met willekeurig hoofd- of kleine letters per teken; gelijk aan
|
||||
// het origineel als je het weer kleine letters maakt
|
||||
export const caseVariant = (path: string) =>
|
||||
fc
|
||||
.array(fc.boolean(), { minLength: path.length, maxLength: path.length })
|
||||
.map((flags) =>
|
||||
[...path]
|
||||
.map((char, i) => (flags[i] ? char.toUpperCase() : char))
|
||||
.join(''),
|
||||
);
|
||||
|
||||
// De naam zonder voorste slash; voor '/' de naam 'index' (BR-HST-04)
|
||||
const nameOf = (path: string) =>
|
||||
path === '/' ? 'index' : path.replace(/^\//, '');
|
||||
|
||||
// Een variant van een bekende pagina: hoofdletters, optioneel .html en 0 tot 3
|
||||
// slashes aan het eind. Voor '/' is dat de index-familie (/Index.html//). Kan
|
||||
// ook de canonieke vorm zelf zijn.
|
||||
export const pageVariant = knownPage.chain((page) =>
|
||||
fc
|
||||
.tuple(
|
||||
caseVariant(nameOf(page)),
|
||||
fc.boolean(),
|
||||
fc.integer({ min: 0, max: 3 }),
|
||||
)
|
||||
.map(
|
||||
([name, html, slashes]) =>
|
||||
`/${name}${html ? '.html' : ''}${'/'.repeat(slashes)}`,
|
||||
),
|
||||
);
|
||||
|
||||
// Pad met 1 tot 3 veilige segmenten dat in geen enkele variant (hoofdletters,
|
||||
// .html, slashes, index-familie) een bekende pagina is en niet 404 heet
|
||||
const reserved = new Set([
|
||||
...pagePaths.map((path) => `/${nameOf(path)}`),
|
||||
'/404',
|
||||
]);
|
||||
export const unknownPath = fc
|
||||
.array(pathSegment, { minLength: 1, maxLength: 3 })
|
||||
.map((segments) => '/' + segments.join('/'))
|
||||
.filter((path) => !reserved.has(path));
|
||||
|
||||
// Wat een aanvaller zou proberen: dubbele slash en backslash voor een ander
|
||||
// domein, puntsegmenten (ook gecodeerd), NUL, regeleinden, stuurcodes en heel
|
||||
// lange paden. Begint altijd met een slash.
|
||||
export const hostilePath = fc
|
||||
.oneof(
|
||||
fc.constantFrom(
|
||||
'//evil.example/',
|
||||
'//evil.example',
|
||||
'/\\evil.example/',
|
||||
'/\\evil.example',
|
||||
'/%2e%2e/',
|
||||
'/%2e%2e/etc/passwd/',
|
||||
'/over-mij\0/',
|
||||
'/over-mij\r\nSet-Cookie: x=1/',
|
||||
'/over-mij\n/',
|
||||
'/\u0007bel/',
|
||||
),
|
||||
fc.string({ maxLength: 40 }),
|
||||
fc.string({ minLength: 2000, maxLength: 3000 }),
|
||||
)
|
||||
.map((text) => (text.startsWith('/') ? text : `/${text}`));
|
||||
|
||||
// Query zoals een browser hem stuurt, zonder het vraagteken; kan leeg zijn
|
||||
export const queryString = fc.oneof(
|
||||
fc.constant(''),
|
||||
fc.stringMatching(/^[a-z0-9=&%_.-]{1,30}$/),
|
||||
);
|
||||
Reference in New Issue
Block a user