Files
SluijsensandClaude Sonnet 5.5 41a6e7be5a Prepares the test site for the CMS host
The test route on the proxy Pi now points at the CMS host on port 5200.
verify-deployment.sh gets a --cms mode that checks the exact security
headers, caching, gzip only, a percent-encoded redirect, the 405 for
POST, and the CMS routes. The deploy-test job uses it once the Gitea
variable ASF_TEST_SERVED_BY_CMS is true.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
2026-11-08 02:05:59 +01:00

331 lines
14 KiB
TypeScript

// Genereert de webserverconfiguratie voor test (nginx op de Raspberry Pi) en
// productie (IIS bij de webhoster) uit dezelfde securityheaders als de Vite
// 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 { compressibleTypes, gzipMimeTypes } from './compressibleTypes.ts';
import { escapeRegex, redirectNames, variantPattern } from './canonicalUrls.ts';
import { securityHeaders } from './securityHeaders.ts';
const generatedNotice =
'Gegenereerd door web/config/serverConfig.ts (pnpm server-config). Niet handmatig aanpassen.';
const xmlAttribute = (value: string) =>
value
.replace(/&/g, '&amp;')
.replace(/"/g, '&quot;')
.replace(/</g, '&lt;')
.replace(/>/g, '&gt;');
// De enige productiehost: www stuurt hierheen door, zodat monitoring (alleen
// op deze hostname) en zoekmachines één adres zien
export const productionHost = 'andreaslop.nl';
// IIS (productie): www-doorverwijzing, security headers, HTTPS-redirect, de
// URL-regels uit de paginalijst (BR-HST-01 tot 08), compressie en caching.
// De www-regel staat vóór HTTPS, zodat http://www. in één stap op
// https://andreaslop.nl uitkomt. Deze regels zijn nog op geen echte IIS-host
// geprobeerd: de open punten U1 tot U6 staan in infrastructure-design.md.
// Bestanden in /assets hebben een hash in de naam en mogen lang gecachet
// worden; de pagina's nooit, zodat een nieuwe release direct zichtbaar is.
// MIME-types die IIS standaard anders of niet kent, worden vastgezet op de
// waarden uit compressibleTypes.ts, zodat statische compressie ze oppakt.
const iisPinnedExtensions = ['.js', '.svg', '.json', '.xml'];
export function iisWebConfig(): string {
const headers = Object.entries(securityHeaders('production'))
.map(
([name, value]) =>
` <add name="${name}" value="${xmlAttribute(value)}" />`,
)
.join('\n');
const mimePins = compressibleTypes
.filter((type) => iisPinnedExtensions.includes(type.extension))
.map(
(type) =>
` <remove fileExtension="${type.extension}" />\n` +
` <mimeMap fileExtension="${type.extension}" mimeType="${xmlAttribute(type.mimeTypes[0])}" />`,
)
.join('\n');
// Paginanamen zonder voorste slash. De canonieke vorm is kleine letters;
// alleen een afwijkende schrijfwijze (hoofdletters, .html, slashes) wordt
// doorverwezen, ToLower raakt dus nooit de hash-namen in /assets.
const pageNames = redirectNames
.map((path) => escapeRegex(path.replace(/^\//, '')))
.join('|');
return `<?xml version="1.0" encoding="utf-8"?>
<!-- ${generatedNotice} -->
<configuration>
<system.webServer>
<rewrite>
<rules>
<rule name="www naar ${productionHost}" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTP_HOST}" pattern="^www\\.${productionHost.replace(/\./g, '\\.')}$" />
</conditions>
<action type="Redirect" url="https://${productionHost}/{R:1}" redirectType="Permanent" />
</rule>
<rule name="HTTPS" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{HTTPS}" pattern="^OFF$" />
</conditions>
<action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" />
</rule>
<rule name="Index naar root" stopProcessing="true">
<match url="^${variantPattern('/')}$" />
<action type="Redirect" url="/" redirectType="Permanent" />
</rule>
<rule name="Pagina canoniek" stopProcessing="true">
<match url="^(${xmlAttribute(pageNames)})(?:\\.html)?/*$" />
<conditions>
<add input="{R:0}" pattern="^(?:${xmlAttribute(pageNames)})$" ignoreCase="false" negate="true" />
</conditions>
<action type="Redirect" url="/{ToLower:{R:1}}" redirectType="Permanent" />
</rule>
<rule name="Slash weg" stopProcessing="true">
<match url="^([^/\\\\].*?)/+$" />
<action type="Redirect" url="/{R:1}" redirectType="Permanent" />
</rule>
<rule name="404 direct" stopProcessing="true">
<match url="^404(?:\\.html)?$" />
<action type="CustomResponse" statusCode="404" statusReason="Not Found" statusDescription="Not Found" />
</rule>
<rule name="Pagina bestand" stopProcessing="true">
<match url="^(.+)$" />
<conditions>
<add input="{REQUEST_FILENAME}.html" matchType="IsFile" />
</conditions>
<action type="Rewrite" url="{R:1}.html" />
</rule>
<rule name="Map zonder pagina" stopProcessing="true">
<match url="^(.+)$" />
<conditions>
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" />
</conditions>
<action type="CustomResponse" statusCode="404" statusReason="Not Found" statusDescription="Not Found" />
</rule>
</rules>
</rewrite>
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="404" subStatusCode="-1" />
<error statusCode="404" subStatusCode="-1" path="/404.html" responseMode="ExecuteURL" />
</httpErrors>
<urlCompression doStaticCompression="true" doDynamicCompression="false" />
<httpProtocol>
<customHeaders>
<remove name="X-Powered-By" />
${headers}
</customHeaders>
</httpProtocol>
<staticContent>
<remove fileExtension=".woff2" />
<mimeMap fileExtension=".woff2" mimeType="font/woff2" />
${mimePins}
<clientCache cacheControlMode="DisableCache" />
</staticContent>
</system.webServer>
<location path="assets">
<system.webServer>
<staticContent>
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="365.00:00:00" />
</staticContent>
</system.webServer>
</location>
</configuration>
`;
}
// 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, 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 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');
// De canonieke vormen komen eerst, als hoofdlettergevoelige regex: nginx
// vergelijkt gewone tekstsleutels in een map zonder onderscheid tussen
// hoofd- en kleine letters, dus een exacte sleutel /over-mij zou ook
// /Over-Mij ongemoeid laten. De eerste regex die past wint. 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 (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 ${listen};
server_name test.andreaslop.nl;
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;
# 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(' ')};
# Een backslash vooraan zou na het weghalen van de slashes een Location
# /\\host geven, en browsers lezen dat als //host. Dat pad bestaat niet
# (BR-HST-06). \\x5c is de backslash; $uri is hier al gedecodeerd.
if ($uri ~ "^/\\x5c") {
return 404;
}
# 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(' ', 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(' ', immutable)}
try_files $uri =404;
}
# 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(' ', noCache)}
try_files $uri $uri.html =404;
}
}
`;
}
// nginx op de reverse-proxy-Pi (test): alleen HTTP. certbot voegt daarna
// HTTPS en de redirect toe (certbot --nginx -d test.andreaslop.nl). Geen
// security headers hier: de CMS-host zet ze al, dubbel geeft dubbele headers.
// Intern adres van de hosting-Pi (waar de CMS-host en WordPress draaien)
const hostingPiAddress = '192.168.1.103';
// Poort van de CMS-host Api.AndreaSlopFotografie (test) op de hosting-Pi. De
// host serveert /admin, /api/v1 en de voorgerenderde site zelf; nginx op de
// hosting-Pi (poort 80, andreaslop-test.conf) blijft als terugvaloptie staan.
const cmsHostPort = 5200;
export function nginxProxyConf(): string {
return `# ${generatedNotice}
# Reverse proxy voor de testsite naar de CMS-host op de hosting-Pi. certbot
# past dit bestand aan voor HTTPS; kopieer het daarna dus niet opnieuw zonder
# certbot opnieuw te draaien. Terugvallen op nginx van de hosting-Pi: haal
# :${cmsHostPort} weg achter proxy_pass.
server {
listen 80;
server_name test.andreaslop.nl;
location / {
proxy_pass http://${hostingPiAddress}:${cmsHostPort};
# De CMS-host gebruikt Host niet om een site te kiezen, maar de
# terugvaloptie (nginx op de hosting-Pi) wel: daarom blijft hij staan
proxy_set_header Host $host;
proxy_set_header X-Forwarded-Proto $scheme;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header X-Real-IP $remote_addr;
}
}
`;
}
export const serverConfigFiles = {
'deploy/iis/web.config': iisWebConfig,
'deploy/nginx/andreaslop-test.conf': nginxTestConf,
'deploy/nginx/test.andreaslop.nl.proxy.conf': nginxProxyConf,
} as const;