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:
2026-11-01 03:00:07 +01:00
co-authored by Claude Opus 5.5
parent 4f32042410
commit 33334b889d
16 changed files with 1389 additions and 36 deletions
@@ -202,10 +202,27 @@ jobs:
echo "CHROME_PATH=$CHROME_PATH" >> "$GITHUB_ENV"
"$CHROME_PATH" --version
# De serverregeltests (e2e/serverRules.e2e.ts) starten een echte nginx met
# het gegenereerde testblok (BR-HST-24). nginx komt uit de distributie:
# het runner-image heeft 1.24, de hosting-Pi draait 1.30.6. Dat verschil
# is bewust geaccepteerd; de gebruikte directives zijn oud en stabiel.
# lftp is nodig voor de uploadtests van de productiedeploy. De service die
# het pakket mogelijk start, wordt gestopt: de test draait zijn eigen
# onbevoorrechte nginx op een vrije poort. nginx -v maakt de versie in de
# log zichtbaar.
- name: Install nginx and lftp (serverregeltests)
run: |
sudo apt-get update && sudo apt-get install -y nginx lftp
sudo service nginx stop || true
nginx -v
# Browsertests tegen de gebouwde site (preview-server op dist/client). Chrome
# komt uit de stap hierboven; dezelfde containerflags als bij Lighthouse.
# CI staat hier expliciet aan: zonder nginx moet de job falen en niet
# stilzwijgend de serverregeltests overslaan.
- name: Browsertests
env:
CI: 'true'
LIGHTHOUSE_CHROME_FLAGS: '--no-sandbox --headless=new --disable-dev-shm-usage'
run: pnpm e2e
@@ -5,7 +5,7 @@
- **Feature Slug**: prerendering
- **Project Type**: Brownfield
- **Start Date**: 2026-10-31T14:15:01Z
- **Current Stage**: CONSTRUCTION - Code Generation (unit 3: hosting-and-targets): plan approved; B0 running
- **Current Stage**: CONSTRUCTION - Code Generation (unit 3: hosting-and-targets): steps 1 to 5 done; CP1 waits for a CI run; runner mode being checked before dispatch
- **Branch**: feature/prerendering (from master c4c2f83); commits and pushes allowed for this feature (owner, 2026-10-31); workflow dispatch without deploy allowed; deploy to test after all units (owner, 2026-11-01), after the nginx config is placed
- **Worktree**: K:\Development\SlpSoftware\Projects\AndreaSlopFotografie-prerendering
@@ -0,0 +1,36 @@
# Baseline checks: hosting and targets (Step 1, CP0)
- Commit: `4f32042410a8163b19c2296f99bd85c9ced79538` (branch `feature/prerendering`)
- Date: 2026-11-01
- Node: v24.16.0; pnpm: 12.11.2
- `git status --short`: empty (clean tree; no untracked files reported)
## Command results
| Command | Result | Counts and details |
|---|---|---|
| `pnpm lint` | pass (exit 0) | ESLint: no issues found |
| `pnpm format:check` | pass (exit 0) | All matched files use Prettier code style |
| `pnpm test` | pass (exit 0) | 130 test files passed (130); 1277 tests passed (1277). Coverage thresholds met: statements 96.12%, branches 94.62%, functions 97.27%, lines 96.59%. fast-check seed: `1618276745` |
| `pnpm build && pnpm e2e` | pass (exit 0) | e2e: 9 test files passed (9); 214 tests passed (214); duration 207.73 s. Build completed before the e2e run started (`&&`) |
Logs: `C:\Users\Bryan\AppData\Local\Temp\claude\k--Development-SlpSoftware-Projects-AndreaSlopFotografie\bb0a550e-5427-462f-b99b-f9db012a172a\scratchpad\b0-test.log` (test run), `C:\Users\Bryan\AppData\Local\Temp\claude\k--Development-SlpSoftware-Projects-AndreaSlopFotografie\bb0a550e-5427-462f-b99b-f9db012a172a\tasks\bbl6g4opx.output` (build and e2e).
## Tool availability
- nginx available locally: **no**. `Get-Command nginx` and `where.exe nginx` found nothing; `C:\nginx\nginx.exe` absent; `C:\Users\Bryan\scoop\apps\nginx\current\nginx.exe` absent; `NGINX_BIN` is empty.
- scoop: present; `scoop list` shows only `php 8.5.9`.
- lftp: **no** (`Get-Command lftp` found nothing).
- bash: **yes** (GNU bash 5.2.37, msys; `C:\Users\Bryan\AppData\Local\Microsoft\WindowsApps\bash.exe`).
- curl: **yes** (curl 8.12.1 from Git Bash; `C:\WINDOWS\system32\curl.exe` 8.21.0 also present).
- podman: machine `podman-machine-default` (wsl) listed, not started (`podman machine list` only, read-only).
## Checksums (SHA-256)
- `web/lighthouserc.cjs`: `717c80a2aee64ba534b01bbffcd90b6dceba6fd666dd24fb13d8d4db182bee43`
- `web/lighthouserc.desktop.cjs`: `f13d993389babd384177a0a1c601547b356d894ae97ac12177b09229a5318e04`
## State at the end of Step 1
- No server or browser left running; port 4173 is free.
- Files written by this step: `aidlc-docs/features/prerendering/construction/hosting-and-targets/code/verification-log.md` (V1 to V14 rows, V6 WITHDRAWN) and this file.
@@ -0,0 +1,22 @@
# Verification log: hosting and targets (unit 3)
Source of the points: `construction/hosting-and-targets/infrastructure-design/infrastructure-design.md` § 12. Settled-in step: § 3.2 of the code generation plan.
Status values: OK, BLOCKED, DEVIATION, WITHDRAWN, OPEN.
| V# | Point | Step | Outcome | Evidence | Status |
|---|---|---|---|---|---|
| V1 | The generated nginx file loads in a real nginx (`nginx -t`) as an `http`-level include without any other directive from the Pi; `map` before `server` works in `conf.d`. Every directive is checked against the nginx 1.30 documentation (the Pi runs 1.30.6; CI has 1.24) | 3 (documentation), 6 (real nginx) | Documentation part OK; real-nginx part OPEN (no nginx locally; waits for the CI run) | Checked against nginx.org docs on 2026-11-01: map (context http only; exact string beats regex, first regex in file order wins; ~* case-insensitive; no default gives empty), if/return/rewrite (server, location; rewrite permanent = 301, original args appended unless replacement ends in ?), try_files (server, location), error_page (http, server, location; without = keeps the status), internal (location), absolute_redirect (http, server, location; since 1.11.8, default on), autoindex (http, server, location; default off), gzip/gzip_vary/gzip_proxied/gzip_http_version/gzip_comp_level/gzip_min_length/gzip_types (http, server, location; text/html always compressed). The generated file puts map at http level (conf.d include) and all others in server or location. NOT documented by nginx.org: escaping of the rewrite replacement (BR-HST-06 relies on it; settled only by the real nginx test on //evil.example/ and /evil.example/); the safety of if with only return comes from the nginx wiki, not the page. | OPEN |
| V2 | Server-level `if ... return 301` and `rewrite ... permanent` responses carry all five headers and `Cache-Control` with real nginx; `absolute_redirect off` gives a relative `Location`; `/` works without an `index` directive | 6, 16 | | | open |
| V3 | `/soorten-fotoshoots` (file) and `/soorten-fotoshoots/` (directory) behave as in section 3.1 on nginx and preview; `/assets` and `/assets/` as well | 6, 8, 16 | | | open |
| V4 | `/404` and `/404.html` give 404 with the page and the five headers on nginx; `error_page` keeps the status; HEAD works | 6, 16 | | | open |
| V5 | A HTTP/1.0 request with `Accept-Encoding: gzip` to the generated block gets `Content-Encoding: gzip` for `.html`, `.js`, `.css`, `.svg`, `.json`, `.xml` (all sizes above 256 bytes) and not for `.woff2`/images | 6, 16 | | | open |
| V6 | Withdrawn for this unit (IIS needs a host). The checks move to the "Before go-live" list, U1 to U6 | WITHDRAWN (no host) | | | WITHDRAWN |
| V7 | `previewServer.ts`: the new `resolveRequest` contract (redirect result, query handling, `--audit-route`); unit 1 tests for BR-SRV-07 are updated (the "interim" rules become final); `pageFiles.ts` stays the single path to file mapping | 7, 8 | | | open |
| V8 | The 301 is followed by Chrome with the query string intact for `?pakket=` and `?shoot=` links, and the hydrated page has 1 title (extend the existing "URL die de server niet kent en de router wel" e2e) | 17 | | | open |
| V9 | One Lighthouse run of the 404 page on the preview audit route, and (as comparison) `/404.html` with `ignoreStatusCode`; record best-practices for both, then keep the simpler passing option (O2) | 23 (measurement-final.md) | | | open |
| V10 | lftp: dry run against a `file:` target proves that pass 1 skips all nested `*.html` and `web.config`, pass 2 uploads them, pass 3 deletes only stale files | 14 | | | open |
| V11 | `verify-deployment.sh` fails against a copy of the old nginx config (home page for `/over-mij`) and passes against the new one | 13 | | | open |
| V12 | CI: the `lighthouse` job (or a new `server-rules` job) installs nginx, `pnpm e2e` includes `serverRules.e2e.ts`, and the job fails if nginx is missing | 5, 16 | CI step added (lighthouse job): apt-get install nginx lftp, service nginx stop, nginx -v; Browsertests step has CI=true; serverRules.e2e.ts fails with "nginx ontbreekt in CI (BR-HST-24)" when nginx is missing. Gate proven locally with CI=true and no nginx (1 failed, as intended) and without CI (skip line, exit 0). The real CI run is still to come. | e2e/serverRules.e2e.ts; .gitea/workflows/continuous_integration.yaml; CI run pending | OPEN |
| V13 | `lighthouserc.cjs`: the exception table is empty on delivery unless an owner decision exists; P-HST-11 passes; `pnpm lighthouse` still starts the preview with `--audit-route` and `Local` appears for `startServerReadyPattern` | 11, 12 | | | open |
| V14 | The generated header comment fits the Pi: install path `/etc/nginx/conf.d/andreaslop-test.conf` (included from `nginx.conf:38`), no `sites-enabled`, no global `nginx.conf` change; the file works for a first install and for an update of an existing file | 3 | Header comment rewritten: install path /etc/nginx/conf.d/andreaslop-test.conf, included in http {} from nginx.conf, no sites-enabled, no global nginx.conf change, own gzip block because the Pi has none, works behind an HTTP/1.0 proxy, 444 from 00-default.conf for an unknown host (old WordPress remark removed), server_name and root adaptable, no default_server. The same file serves a first install and an update (it replaces the existing file in place). | Generated deploy/nginx/andreaslop-test.conf (lines 1-12); equals nginxTestConf() (serverConfig.test.ts sync test green) | OK |
@@ -78,6 +78,8 @@ The proxy Pi handles TLS through certbot and forwards `test.andreaslop.nl` to `1
| `proxy_cache` | An old SPA `index.html` could stay cached for `/over-mij` |
| `proxy_redirect` | Could change the relative 301s |
**Checked by the owner on 2026-11-01, reported through the Pi-Main session: no change needed on the proxy Pi.** The server block has `proxy_pass http://192.168.1.103` with Host, X-Forwarded-Proto, X-Forwarded-For and X-Real-IP, and no `proxy_http_version` (so HTTP/1.0 upstream), no change to `Accept-Encoding`, no `proxy_intercept_errors` and no `add_header`. At http level there is no gzip, `proxy_cache`, `add_header` or `proxy_buffering`. So `gzip_http_version 1.0` must stay in the new block, all headers and the 404 page come from the hosting Pi, and no cache holds old pages. `http2 on;` in the 443 block is an optional, separate improvement, out of scope for this feature.
The proxy passes an already compressed response through unchanged. If the owner wants gzip for all sites, WordPress included, the proxy Pi is the place for that, and this block can keep its own.
## Points for the generated config
@@ -155,7 +155,7 @@ PBT-06 (stateful): none; the redirect function is stateless. PBT-07 (generators)
## Part A: Setup and baseline (batch B0, Haiku, exclusive)
### Step 1: Confirm a green baseline and create the log [ ]
### Step 1: Confirm a green baseline and create the log [x]
- Executor: Haiku.
- Implements: NFR-PR-Q-01 (baseline), setup.
@@ -174,7 +174,7 @@ PBT-06 (stateful): none; the redirect function is stateless. PBT-07 (generators)
The riskiest mechanism is the nginx block (a `map`, a server-level `if` and `rewrite`, `error_page` with an internal location, `try_files` without `$uri/`, a custom gzip setup behind a proxy). It is built in its real form and proven with a real nginx process before the rest. Reading the config is not a proof.
### Step 2: Shared URL and type modules (BR-HST-04, 06, 11) [ ]
### Step 2: Shared URL and type modules (BR-HST-04, 06, 11) [x]
- Executor: Sonnet.
- Implements: BR-HST-03, 04, 06, 11; P-HST-02, 03, 04 (function level).
@@ -186,8 +186,9 @@ The riskiest mechanism is the nginx block (a `map`, a server-level `if` and `rew
4. `canonicalUrls.test.ts`: example-based table (the redirect rows of infrastructure-design.md § 3.1) and properties: P-HST-02 (every `pageVariant` returns the canonical page, `(invariant)`), P-HST-03 (the result is a fixpoint: `canonicalRedirect(result)` is `undefined`, and `stripTrailingSlashes(result)` is `undefined`, `(idempotent)`; the combined function used by the resolver needs at most 2 hops for any `pageVariant` or `unknownPath` plus slashes), P-HST-04 (a target starts with `/`, never `//` or `/\`, has no control characters, and is one of `pagePaths`, `(invariant)`; run it also over `hostilePath`: a non-`undefined` result is still one of `pagePaths`).
- Done when: `pnpm exec vitest run config/canonicalUrls.test.ts` green; `pnpm exec tsc --noEmit`, `pnpm lint` clean; `pnpm exec prettier --check` on the new files clean.
- Record: one line with the exported names.
- Done. `canonicalUrls.ts`: pagePaths, redirectNames, escapeRegex, variantPattern, canonicalRedirect, stripTrailingSlashes. `compressibleTypes.ts`: FileType, compressibleTypes, plainTypes, compressibleExtensions, gzipMimeTypes. `src/test/urlArbitraries.ts`: knownPage, caseVariant, pageVariant, unknownPath, hostilePath, queryString. stripTrailingSlashes returns undefined when the stripped target would start with // or / or hold control characters (BR-HST-06), so the resolver treats such a path as unknown.
### Step 3: The nginx block (BR-HST-01 to 09, 11 to 13; V14) [ ]
### Step 3: The nginx block (BR-HST-01 to 09, 11 to 13; V14) [x]
- Executor: Sonnet.
- Implements: BR-HST-01 to 09, 11 to 13; FR-PR-14, 16, 23; V1 (documentation part), V14.
@@ -200,8 +201,9 @@ The riskiest mechanism is the nginx block (a `map`, a server-level `if` and `rew
5. Run `pnpm server-config`. Update the three `serverConfig.test.ts` tests that § 6 lists for nginx (they assert the old SPA fallback and the location count) with stricter replacements; the rest of the test file is unchanged and must pass.
- Done when: `pnpm exec vitest run config/serverConfig.test.ts` green (the IIS SPA-fallback test is still the old one and still passes because Step 9 has not run); the committed `deploy/nginx/andreaslop-test.conf` equals `nginxTestConf()`; `pnpm exec tsc --noEmit`, `pnpm lint` clean.
- Record: verification log V1 (documentation), V14.
- Done. V1 documentation part and V14 recorded. The three serverConfig tests of section 6 (noindex/try_files, location count) changed and are stricter. The nginx.org rewrite page does not document escaping of the replacement; BR-HST-06 relies on it and the real nginx test must show it.
### Step 4: Fixture site, nginx harness and the first contract test (BR-HST-24) [ ]
### Step 4: Fixture site, nginx harness and the first contract test (BR-HST-24) [x]
- Executor: Sonnet.
- Implements: BR-HST-24; V1 to V5 (tests); P-HST-09 (first version).
@@ -212,8 +214,9 @@ The riskiest mechanism is the nginx block (a `map`, a server-level `if` and `rew
3. `serverRules.e2e.ts`: `describe.skipIf`-style gate: if `findNginx()` is undefined, then when `process.env.CI` is set the suite **fails** with the message "nginx ontbreekt in CI (BR-HST-24)", otherwise it is skipped and prints one visible line `nginx niet gevonden: serverregeltests overgeslagen (zie BR-HST-24)`. First version tests, against real nginx and the fixture: every row of infrastructure-design.md § 3.1 (status, `Location` path+query, which fixture file was served by the marker text, `404.html` body on 404); the five security headers + `Cache-Control` + `X-Robots-Tag` on 200, 301 and 404 responses (V2, V4); `/soorten-fotoshoots` serves the file and `/soorten-fotoshoots/` redirects (V3); `/` works without an `index` directive; HEAD on a page and on an unknown URL; `/robots.txt` returns `Disallow: /`; `Content-Encoding: gzip` for `.html`, `.js`, `.css`, `.svg`, `.json`, `.xml`, `.txt`, none for `.woff2` and `.png`, in both mime variants (V5); a raw HTTP/1.0 request over `node:net` with `Accept-Encoding: gzip` also gets gzip; `Vary: Accept-Encoding` present; `/assets/*` has exactly **one** `Cache-Control` header, `public, max-age=31536000, immutable` (count the raw header lines through `node:http` `rawHeaders`, not through the merged `fetch` Headers object), all else `no-cache`; the full header set is present on a 301, on the 404 page, on `/404` and `/404.html` (the `error_page` path) and on `/assets/*`; hostile paths (`//evil.example/`, `/\evil.example`) never yield a 3xx whose `Location` starts with `//` or `/\`.
- Done when: `pnpm exec tsc --noEmit`, `pnpm lint` clean; `pnpm exec vitest run --config vitest.e2e.config.ts e2e/serverRules.e2e.ts` either passes against a local nginx (if Step 1 found one) or prints the skip line (no nginx locally) and exits 0 outside CI; with `CI=true` and no nginx it fails with the message above (run it once to prove the gate; then unset `CI`).
- Record: which nginx version ran, or "skipped: no local nginx".
- Skipped: no local nginx. Gate proven: without CI one visible skip line, exit 0; with CI=true the suite fails with "nginx ontbreekt in CI (BR-HST-24)". The harness has never started a real nginx (only type-checked), so a first CI run may still show harness defects.
### Step 5: Install nginx and lftp in the CI job (V12) [ ]
### Step 5: Install nginx and lftp in the CI job (V12) [x]
- Executor: Sonnet.
- Implements: BR-HST-24; V12.
@@ -221,6 +224,7 @@ The riskiest mechanism is the nginx block (a `map`, a server-level `if` and `rew
- Do: in job `lighthouse`, before the `Browsertests` step add a step "Install nginx and lftp (serverregeltests)": `sudo apt-get update && sudo apt-get install -y nginx lftp`, then stop a service the package may have started (`sudo service nginx stop || true`), then `nginx -v`. Give the `Browsertests` step `CI: 'true'` in its `env` (so a missing nginx fails the job; do not rely on the runner setting it). Do not touch the deploy jobs yet (Step 15). Keep the file's Dutch comment style and explain why the packages are installed (the Ubuntu runner image carries nginx 1.24; the Pi runs 1.30.6; accepted gap, BR-HST-24).
- Done when: the YAML parses (`pnpm exec prettier --check ../.gitea/workflows/continuous_integration.yaml` or, if prettier rejects the path, `node -e` with the `yaml` parser is NOT available: use `pnpm exec prettier --parser yaml --check` on the file contents via stdin); the diff shows only the new step and the env line.
- Record: the exact diff.
- Done: one new step "Install nginx and lftp (serverregeltests)" before Browsertests, plus `CI: 'true'` in the env of Browsertests, with Dutch comments. See `git diff .gitea`.
### Step 6: Checkpoint CP1: the nginx proof [ ] STOP-AND-ASK if no local nginx
+175
View File
@@ -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\\]\\\\',
);
});
});
+63
View File
@@ -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;
}
+91
View File
@@ -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');
}
+9 -3
View File
@@ -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
View File
@@ -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;
}
}
`;
+106 -8
View File
@@ -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;
}
}
+376
View File
@@ -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();
});
});
},
);
+88
View File
@@ -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 }),
};
}
+206
View File
@@ -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 };
}
+80
View File
@@ -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}$/),
);