Prerenders every page as HTML #14
@@ -119,6 +119,10 @@ jobs:
|
||||
name: dist
|
||||
path: web/dist
|
||||
|
||||
# Alleen de clientmap hoort online: geen servermap, geen source maps
|
||||
- name: Controle van de build
|
||||
run: bash deploy/check-artifact.sh dist
|
||||
|
||||
# Eenvoudig: de testmap leegmaken en de nieuwe build erin zetten. Oude
|
||||
# versies worden niet bewaard. Op de Pi draait ook de huidige
|
||||
# WordPress-site; daarom weigert deze stap een lege variabele, '/', of
|
||||
@@ -151,14 +155,16 @@ jobs:
|
||||
sshpass -e scp -P "$SSH_PORT" -o StrictHostKeyChecking=accept-new -r dist/* "$SSH_USER@$SSH_HOST:$DEPLOY_PATH/"
|
||||
echo "Gedeployd naar test: ${GITHUB_REF_NAME} (${GITHUB_SHA::7})"
|
||||
|
||||
# Vergelijkt wat de server teruggeeft met dist. Met de oude nginx-config
|
||||
# (homepage voor elk pad) wordt deze stap rood: de nieuwe config moet er
|
||||
# dus staan voor de deploy (zie pi-install-instructions.md).
|
||||
- name: Controle na deploy
|
||||
env:
|
||||
HEALTH_URL: ${{ vars.HEALTH_CHECK_URL_TEST }}
|
||||
run: |
|
||||
if [ -z "$HEALTH_URL" ]; then echo "Geen HEALTH_CHECK_URL_TEST ingesteld; overgeslagen"; exit 0; fi
|
||||
curl -fsS -o /dev/null --retry 5 --retry-delay 3 "$HEALTH_URL"
|
||||
curl -fsSI "$HEALTH_URL" | grep -qi '^content-security-policy:'
|
||||
echo "Test bereikbaar met security headers"
|
||||
bash deploy/verify-deployment.sh "$HEALTH_URL" dist --test
|
||||
echo "Test bereikbaar en gelijk aan de build"
|
||||
|
||||
# Lighthouse tegen de gebouwde site (mobiel en desktop)
|
||||
lighthouse:
|
||||
@@ -266,12 +272,11 @@ jobs:
|
||||
name: dist
|
||||
path: web/dist
|
||||
|
||||
- name: IIS-configuratie toevoegen
|
||||
run: cp deploy/iis/web.config dist/web.config
|
||||
|
||||
# FTP met TLS (verplicht) naar de webhoster. Eerst alle bestanden behalve
|
||||
# index.html, dan index.html, en pas daarna oude bestanden opruimen. Zo
|
||||
# FTP met TLS (verplicht) naar de webhoster, in drie rondes (zie
|
||||
# deploy/upload-production.sh): eerst alles behalve HTML en web.config,
|
||||
# dan web.config en alle HTML, en pas daarna oude bestanden opruimen. Zo
|
||||
# verwijst een bezoeker nooit naar een bestand dat er nog niet staat.
|
||||
# Deze job kan pas draaien als er een webhost is.
|
||||
- name: Upload naar productie (FTPS)
|
||||
env:
|
||||
FTP_HOST: ${{ secrets.FTP_HOST }}
|
||||
@@ -280,14 +285,7 @@ jobs:
|
||||
FTP_DIR: ${{ vars.FTP_REMOTE_DIR || 'wwwroot' }}
|
||||
run: |
|
||||
sudo apt-get update && sudo apt-get install -y lftp
|
||||
lftp --env-password -u "$FTP_USER" "$FTP_HOST" -e "
|
||||
set ftp:ssl-force true;
|
||||
set ftp:ssl-protect-data true;
|
||||
set net:max-retries 3;
|
||||
mirror --reverse --verbose --exclude-glob index.html dist/ $FTP_DIR/;
|
||||
put -O $FTP_DIR dist/index.html;
|
||||
mirror --reverse --delete --verbose dist/ $FTP_DIR/;
|
||||
quit"
|
||||
bash deploy/upload-production.sh dist "$FTP_DIR"
|
||||
echo "Gedeployd naar productie: ${GITHUB_REF_NAME} (${GITHUB_SHA::7})"
|
||||
|
||||
- name: Controle na deploy
|
||||
@@ -295,6 +293,5 @@ jobs:
|
||||
HEALTH_URL: ${{ vars.HEALTH_CHECK_URL_PRODUCTION }}
|
||||
run: |
|
||||
if [ -z "$HEALTH_URL" ]; then echo "Geen HEALTH_CHECK_URL_PRODUCTION ingesteld; overgeslagen"; exit 0; fi
|
||||
curl -fsS -o /dev/null --retry 5 --retry-delay 3 "$HEALTH_URL"
|
||||
curl -fsSI "$HEALTH_URL" | grep -qi '^content-security-policy:'
|
||||
echo "Productie bereikbaar met security headers"
|
||||
bash deploy/verify-deployment.sh "$HEALTH_URL" dist
|
||||
echo "Productie bereikbaar en gelijk aan de build"
|
||||
|
||||
@@ -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): CP1 closed (run 593); B2 to B5 running
|
||||
- **Current Stage**: CONSTRUCTION - Code Generation (unit 3: hosting-and-targets): B0 to B5 done; B6 running
|
||||
- **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
|
||||
|
||||
|
||||
+5
-5
@@ -8,15 +8,15 @@ Status values: OK, BLOCKED, DEVIATION, WITHDRAWN, OPEN.
|
||||
|---|---|---|---|---|---|
|
||||
| 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) | OK on nginx 1.24.0: the generated file loads (nginx -t in the harness runs before every start) as an http-level include, map before server works; documentation part checked earlier (see below). Not proven: nginx 1.30.6 on the Pi (CI has 1.24.0); the real check is nginx -t plus the curl matrix during the Pi rollout (H2, H3). | 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. | CI run 593 (commit 8cb9185), job lighthouse, step Browsertests, nginx/1.24.0 (Ubuntu) on the Pi runner (container, root); e2e/serverRules.e2e.ts: 134 tests, all passed, none skipped (2088 ms), 67 per mime variant (.js as text/javascript and as application/javascript); the run totals 348 tests with 341 passed and 7 failed, all 7 in images.e2e.ts and reveal.e2e.ts (timeouts, unrelated); the test prints "[serverRules] nginx -v: nginx version: nginx/1.24.0 (Ubuntu)" once per variant. Earlier cycles found and fixed three defects through this proof: workers as www-data could not read the mkdtemp fixture (harness, run 592: 403), map plain keys ignore case so /Over-Mij was not redirected (generator), and /%5Cevil.example/ produced Location /evil.example (generator, BR-HST-06). | OK |
|
||||
| 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 | OK: 301 from the server-level if and from rewrite carry all five security headers, X-Robots-Tag and exactly one Cache-Control (raw header count); Location is relative (absolute_redirect off); / works without an index directive. Not proven: nginx 1.30.6 on the Pi (CI has 1.24.0); the real check is nginx -t plus the curl matrix during the Pi rollout (H2, H3). | CI run 593 (commit 8cb9185), job lighthouse, step Browsertests, nginx/1.24.0 (Ubuntu) on the Pi runner (container, root); e2e/serverRules.e2e.ts: 134 tests, all passed, none skipped (2088 ms), 67 per mime variant (.js as text/javascript and as application/javascript); the run totals 348 tests with 341 passed and 7 failed, all 7 in images.e2e.ts and reveal.e2e.ts (timeouts, unrelated); the test prints "[serverRules] nginx -v: nginx version: nginx/1.24.0 (Ubuntu)" once per variant. Earlier cycles found and fixed three defects through this proof: workers as www-data could not read the mkdtemp fixture (harness, run 592: 403), map plain keys ignore case so /Over-Mij was not redirected (generator), and /%5Cevil.example/ produced Location /evil.example (generator, BR-HST-06). | OK |
|
||||
| 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 | OK on nginx: /soorten-fotoshoots serves the file with the directory soorten-fotoshoots/ next to it, /soorten-fotoshoots/ gives one 301, /assets gives 404, /assets/ gives 301 to /assets. Preview-server side still open (Step 8/16). Not proven: nginx 1.30.6 on the Pi (CI has 1.24.0); the real check is nginx -t plus the curl matrix during the Pi rollout (H2, H3). | CI run 593 (commit 8cb9185), job lighthouse, step Browsertests, nginx/1.24.0 (Ubuntu) on the Pi runner (container, root); e2e/serverRules.e2e.ts: 134 tests, all passed, none skipped (2088 ms), 67 per mime variant (.js as text/javascript and as application/javascript); the run totals 348 tests with 341 passed and 7 failed, all 7 in images.e2e.ts and reveal.e2e.ts (timeouts, unrelated); the test prints "[serverRules] nginx -v: nginx version: nginx/1.24.0 (Ubuntu)" once per variant. Earlier cycles found and fixed three defects through this proof: workers as www-data could not read the mkdtemp fixture (harness, run 592: 403), map plain keys ignore case so /Over-Mij was not redirected (generator), and /%5Cevil.example/ produced Location /evil.example (generator, BR-HST-06). | OK (nginx part) |
|
||||
| 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 | OK on nginx: /soorten-fotoshoots serves the file with the directory soorten-fotoshoots/ next to it, /soorten-fotoshoots/ gives one 301, /assets gives 404, /assets/ gives 301 to /assets. Preview-server side OK (config/previewServer.test.ts: resolver table and a server-level test with a page next to its directory; /assets 404, /assets/ 301 to /assets); real-nginx parity still open (Step 16). Not proven: nginx 1.30.6 on the Pi (CI has 1.24.0); the real check is nginx -t plus the curl matrix during the Pi rollout (H2, H3). | CI run 593 (commit 8cb9185), job lighthouse, step Browsertests, nginx/1.24.0 (Ubuntu) on the Pi runner (container, root); e2e/serverRules.e2e.ts: 134 tests, all passed, none skipped (2088 ms), 67 per mime variant (.js as text/javascript and as application/javascript); the run totals 348 tests with 341 passed and 7 failed, all 7 in images.e2e.ts and reveal.e2e.ts (timeouts, unrelated); the test prints "[serverRules] nginx -v: nginx version: nginx/1.24.0 (Ubuntu)" once per variant. Earlier cycles found and fixed three defects through this proof: workers as www-data could not read the mkdtemp fixture (harness, run 592: 403), map plain keys ignore case so /Over-Mij was not redirected (generator), and /%5Cevil.example/ produced Location /evil.example (generator, BR-HST-06). | OK (nginx part) |
|
||||
| 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 | OK: /404 and /404.html give 404 with the page and all headers, a missing asset gives the 404 page with no-cache (not immutable), error_page keeps the status, HEAD works. Not proven: nginx 1.30.6 on the Pi (CI has 1.24.0); the real check is nginx -t plus the curl matrix during the Pi rollout (H2, H3). | CI run 593 (commit 8cb9185), job lighthouse, step Browsertests, nginx/1.24.0 (Ubuntu) on the Pi runner (container, root); e2e/serverRules.e2e.ts: 134 tests, all passed, none skipped (2088 ms), 67 per mime variant (.js as text/javascript and as application/javascript); the run totals 348 tests with 341 passed and 7 failed, all 7 in images.e2e.ts and reveal.e2e.ts (timeouts, unrelated); the test prints "[serverRules] nginx -v: nginx version: nginx/1.24.0 (Ubuntu)" once per variant. Earlier cycles found and fixed three defects through this proof: workers as www-data could not read the mkdtemp fixture (harness, run 592: 403), map plain keys ignore case so /Over-Mij was not redirected (generator), and /%5Cevil.example/ produced Location /evil.example (generator, BR-HST-06). | OK |
|
||||
| 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 | OK: HTTP/1.1 and raw HTTP/1.0 requests get gzip for html, js, css, svg, json, xml, txt in both mime variants, none for woff2 and png; Vary: Accept-Encoding present. Not proven: nginx 1.30.6 on the Pi (CI has 1.24.0); the real check is nginx -t plus the curl matrix during the Pi rollout (H2, H3). | CI run 593 (commit 8cb9185), job lighthouse, step Browsertests, nginx/1.24.0 (Ubuntu) on the Pi runner (container, root); e2e/serverRules.e2e.ts: 134 tests, all passed, none skipped (2088 ms), 67 per mime variant (.js as text/javascript and as application/javascript); the run totals 348 tests with 341 passed and 7 failed, all 7 in images.e2e.ts and reveal.e2e.ts (timeouts, unrelated); the test prints "[serverRules] nginx -v: nginx version: nginx/1.24.0 (Ubuntu)" once per variant. Earlier cycles found and fixed three defects through this proof: workers as www-data could not read the mkdtemp fixture (harness, run 592: 403), map plain keys ignore case so /Over-Mij was not redirected (generator), and /%5Cevil.example/ produced Location /evil.example (generator, BR-HST-06). | OK |
|
||||
| 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 |
|
||||
| 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 | OK: `resolveRequest` returns `FileResult` or `RedirectResult` (301) and takes `{ auditRoute }`; `handle()` sends the 301 with a relative `Location` plus the raw query, `Content-Length: 0`, the security headers and no `Cache-Control`, also for HEAD; `/404` and `/404.html` are 404; `/__audit/404` is 200 only with `--audit-route`; `//x` and `/%5Cevil.example/` give the 404 page. The BR-SRV-07 tests are rewritten into the final rules. `pageFiles.ts` is still the only path-to-file mapping. | `pnpm exec vitest run config/previewServer.test.ts`: 89 passed (two runs, seeds 943967193 and 1045251215); `tsc --noEmit` and eslint clean | OK |
|
||||
| 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 |
|
||||
| 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 | Not proven: lftp is not installed on this PC (and may not be installed). Script upload-production.sh uses `--exclude-glob '*.html' --exclude-glob web.config` (pass 1), `put -O` of web.config plus `--include-glob '*.html'` (pass 2) and `mirror --reverse --delete` (pass 3); the generated lftp command was checked with a fake lftp, not with lftp. The test in e2e/deployScripts.e2e.ts (file: target, UPLOAD_PASS=1|2|3, upload order from the verbose output) is written and skipped locally with a visible line; in CI it fails when lftp is missing, and the lighthouse job installs lftp. Unverified until the first CI run: whether `--include-glob` alone includes only HTML and still descends into subdirectories, and the `file:///` target form. | e2e/deployScripts.e2e.ts: 5 skipped locally ("lftp niet gevonden"); deploy/upload-production.sh passes bash -n | 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 | OK against stubs: verify-deployment.sh exits 1 against a stub that imitates the old nginx config (index.html with 200 for every path), with the messages "/over-mij: antwoord is niet gelijk aan over-mij.html", "status 200, verwacht 404" and "/over-mij/: status 200, verwacht 301"; it exits 0 against a stub with the new rules (also with a trailing slash on the URL) and against the preview server on the fixture site. Also fails per missing security header, with --test without X-Robots-Tag or gzip; gzip missing only warns without --test. Not run against the real old or new nginx file on the Pi (nothing is contacted); the first deploy-test run shows it against the new config. | pnpm exec vitest run --config vitest.e2e.config.ts e2e/deployScripts.e2e.ts: 22 passed, 5 skipped (lftp) | OK (stubs) |
|
||||
| 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 | OK: the lighthouse job installs nginx and lftp, Browsertests runs with CI=true, serverRules ran with nginx present. The missing-nginx failure path was proven locally (CI=true without nginx fails with "nginx ontbreekt in CI (BR-HST-24)"). | CI run 593 (commit 8cb9185), job lighthouse, step Browsertests, nginx/1.24.0 (Ubuntu) on the Pi runner (container, root); e2e/serverRules.e2e.ts: 134 tests, all passed, none skipped (2088 ms), 67 per mime variant (.js as text/javascript and as application/javascript); the run totals 348 tests with 341 passed and 7 failed, all 7 in images.e2e.ts and reveal.e2e.ts (timeouts, unrelated); the test prints "[serverRules] nginx -v: nginx version: nginx/1.24.0 (Ubuntu)" once per variant. Earlier cycles found and fixed three defects through this proof: workers as www-data could not read the mkdtemp fixture (harness, run 592: 403), map plain keys ignore case so /Over-Mij was not redirected (generator), and /%5Cevil.example/ produced Location /evil.example (generator, BR-HST-06). The install step in run 593 uses policy-rc.d to keep the package from starting a service. | OK |
|
||||
| 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 |
|
||||
| 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 | Exception table holds the 8 carried-over entries (targets unchanged by plan; decision text "tijdelijk, tot de eindmeting van prerendering" until the owner decides); effective per-URL assertions identical before/after for mobile and desktop, performance level error and warn; `config/lighthouserc.test.ts` + `src/app.test.tsx` 55 tests green; start command has `--audit-route` | Open: `Local` in the `--audit-route` preview output is Step 7 (B2) and not checked here |
|
||||
| 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 |
|
||||
|
||||
+18
-11
@@ -247,7 +247,7 @@ The riskiest mechanism is the nginx block (a `map`, a server-level `if` and `rew
|
||||
|
||||
## Part C: Preview server (batch B2, Sonnet; parallel with B3, B4, B5)
|
||||
|
||||
### Step 7: New `resolveRequest` contract and audit route (BR-HST-01 to 08, 22; V7) [ ]
|
||||
### Step 7: New `resolveRequest` contract and audit route (BR-HST-01 to 08, 22; V7) [x]
|
||||
|
||||
- Executor: Sonnet.
|
||||
- Implements: BR-HST-01 to 08, 11, 13, 22; FR-PR-14, 16, 23.
|
||||
@@ -259,8 +259,9 @@ The riskiest mechanism is the nginx block (a `map`, a server-level `if` and `rew
|
||||
4. `startPreviewServer(clientDir, port, options?: { auditRoute?: boolean })`; `parseArguments` accepts `--audit-route` (boolean) next to `--port`, `--strictPort`, `--dir`; unknown arguments are still ignored. Update the file's header comment: the 404 page is audited through the opt-in route; `/404.html` is a real 404.
|
||||
- Done when: `pnpm exec tsc --noEmit`, `pnpm lint` clean; the tests of § 6 for this file fail as expected and no others (they are rewritten in Step 8).
|
||||
- Record: one line naming the exported types.
|
||||
- Done: exported `FileResult`, `RedirectResult`, `ResolvedRequest` (union), `ResolveOptions`, `PreviewOptions`; `resolveRequest(path, fileExists, options?)` and `startPreviewServer(clientDir, port, options?)`.
|
||||
|
||||
### Step 8: Tests for the preview server (P-HST-01, 05, 06; V3, V7) [ ]
|
||||
### Step 8: Tests for the preview server (P-HST-01, 05, 06; V3, V7) [x]
|
||||
|
||||
- Executor: Sonnet.
|
||||
- Implements: P-HST-01, 02, 03, 04, 05, 06; V3, V7.
|
||||
@@ -272,12 +273,13 @@ The riskiest mechanism is the nginx block (a `map`, a server-level `if` and `rew
|
||||
4. Server level with `startPreviewServer`: a redirect response has status 301, a relative `Location` with the query kept byte for byte (P-HST-05, `(invariant)` over `queryString`), the five security headers, no body, and works for HEAD; `/404.html` and `/404` answer 404 with the page and headers; `/__audit/404` is 404 without the option and 200 with it, and `/404.html` stays 404 with the option; `--audit-route` through the command-line tests (`previewServer als opdrachtregel`): with the flag the route answers 200.
|
||||
- Done when: `pnpm exec vitest run config/previewServer.test.ts` green; `pnpm exec tsc --noEmit`, `pnpm lint` clean.
|
||||
- Record: which existing tests changed (names), and the P17 note.
|
||||
- Done: changed the group `tussenregels uit BR-SRV-07` (now `regels uit BR-HST-03 tot 05`), `behandelt een laatste segment met een punt als bestandsverzoek` (`/over-mij.html` is a 301), the drive-letter assertion (now `toEqual(NOT_FOUND)`, stricter), `antwoordt op /404 met status 404` (now `/404` and `/404.html`, 404 with page and headers), `comprimeert elk teksttype` (requests `/over-mij` instead of `/over-mij.html`, same gzip assertions), P16 (redirect results are skipped, `file` checks unchanged) and P17 (the model returns the redirect for any input that `canonicalRedirect` maps, and `/404.html` is 404). `siteDir` gained `soorten-fotoshoots.html` and its directory.
|
||||
|
||||
---
|
||||
|
||||
## Part D: IIS text and config tests (batch B3, Sonnet; parallel with B2, B4, B5)
|
||||
|
||||
### Step 9: The IIS `web.config` text (BR-HST-04, 07, 10, 19) [ ]
|
||||
### Step 9: The IIS `web.config` text (BR-HST-04, 07, 10, 19) [x]
|
||||
|
||||
- Executor: Sonnet.
|
||||
- Implements: BR-HST-02, 04, 06, 07, 10, 12, 13, 19; FR-PR-14, 16, 23. **These rules are unverified until a host exists; do not build any tooling to verify them.**
|
||||
@@ -285,8 +287,9 @@ The riskiest mechanism is the nginx block (a `map`, a server-level `if` and `rew
|
||||
- Do: rewrite `iisWebConfig` per infrastructure-design.md § 4.3. Rule order inside `<rewrite><rules>`: `www naar andreaslop.nl` and `HTTPS` unchanged; then `Index naar root`, `Pagina canoniek` (alternation of the page names built from `redirectNames` and `variantPattern`, condition `{R:0}` not matching the exact lower-case canonical form with `ignoreCase="false"`, `Redirect` to `/{ToLower:{R:1}}`, permanent), `Slash weg` (`^([^/\\].*?)/+$`, redirect `/{R:1}`), `404 direct` (`^404(?:\.html)?$`, `CustomResponse` 404), `Pagina bestand` (`^(.+)$`, condition `{REQUEST_FILENAME}.html` `IsFile`, rewrite `{R:1}.html`), `Map zonder pagina` (`^(.+)$`, condition `{REQUEST_FILENAME}` `IsDirectory`, `CustomResponse` 404). All with `stopProcessing="true"`. The "SPA fallback" rule is **removed**. After `<rewrite>`: `<httpErrors errorMode="Custom" existingResponse="Replace">` with `<remove statusCode="404" subStatusCode="-1" />` and `<error statusCode="404" subStatusCode="-1" path="/404.html" responseMode="ExecuteURL" />`; `<urlCompression doStaticCompression="true" doDynamicCompression="false" />`; in `staticContent` the existing `woff2` entry plus remove-then-add MIME pins for `.js` (`text/javascript`), `.svg`, `.json`, `.xml` (`text/xml`) taken from `compressibleTypes.ts`; `clientCache` and the `/assets` location block as now; `httpProtocol` headers as now. No `httpCompression`, no `directoryBrowse`, no `defaultDocument`. Escape all attribute values with the existing `xmlAttribute`. Update the header comment: the rules are generated from the page list; unverified until a host exists (open points U1 to U6 in infrastructure-design.md § 7.2).
|
||||
- Done when: the generated file is well-formed XML (parse it in a test, Step 10); `pnpm exec tsc --noEmit`, `pnpm lint` clean.
|
||||
- Record: one line listing the rule names in order.
|
||||
Record (done): www naar andreaslop.nl, HTTPS, Index naar root, Pagina canoniek, Slash weg, 404 direct, Pagina bestand, Map zonder pagina. Unverified until a host exists (V6 withdrawn).
|
||||
|
||||
### Step 10: Complete `serverConfig.test.ts` (P-HST-07, 08, 10) [ ]
|
||||
### Step 10: Complete `serverConfig.test.ts` (P-HST-07, 08, 10) [x]
|
||||
|
||||
- Executor: Sonnet.
|
||||
- Implements: P-HST-07, 08, 10; BR-HST-03, 04, 06, 07, 09 to 13, 19.
|
||||
@@ -297,12 +300,13 @@ The riskiest mechanism is the nginx block (a `map`, a server-level `if` and `rew
|
||||
3. P-HST-10 replacement (example-based text test): `iisWebConfig()` parses as XML (use a small regex-free check with the built-in `DOMParser` via `// @vitest-environment jsdom`, or a string balance check if jsdom is not already used in this file; keep the environment of the file in mind), contains the rule names in the designed order, has no `SPA fallback` and no `index.html` rewrite, contains `ToLower` only inside the canonical rule, `[^/\\]` in the slash rule, `ExecuteURL`, `urlCompression`, and neither `httpCompression` nor `directoryBrowse`; the five headers appear as before.
|
||||
- Done when: `pnpm exec vitest run config/serverConfig.test.ts` green; the number of assertions in the file is higher than before.
|
||||
- Record: the names of replaced tests.
|
||||
Record (done): "IIS heeft een SPA-fallback en een HTTPS-redirect" became "IIS heeft een HTTPS-redirect en geen SPA-fallback" (stricter: also no index.html). The nginx replacements were already in place. 13 tests became 26.
|
||||
|
||||
---
|
||||
|
||||
## Part E: Lighthouse configuration (batch B4, Sonnet; parallel with B2, B3, B5)
|
||||
|
||||
### Step 11: Data-driven `lighthouserc.cjs` and the audit route (BR-HST-21 to 23) [ ]
|
||||
### Step 11: Data-driven `lighthouserc.cjs` and the audit route (BR-HST-21 to 23) [x]
|
||||
|
||||
- Executor: Sonnet.
|
||||
- Implements: BR-HST-21, 22, 23; NFR-PR-P-01, P-02, S-01; V13.
|
||||
@@ -313,9 +317,9 @@ The riskiest mechanism is the nginx block (a `map`, a server-level `if` and `rew
|
||||
3. Update `lighthouserc.d.cts` for the new exports.
|
||||
4. Keep the comment block that explains why performance is `warn` in CI; add one line that `numberOfRuns` is 1 on purpose and that a page exactly at 0.90 can fail `pnpm check` by chance (owner decision O6).
|
||||
- Done when: `node -e "const c=require('./lighthouserc.cjs'); console.log(Object.keys(c.mobileExceptions).length, c.notFoundPath, c.ci.collect.startServerCommand)"` prints 8, `/__audit/404` and the new command; the effective targets per URL are identical to before (compare the output of a small script that prints, per URL, the `minScore` of the matching mobile and desktop entries before (from `git stash`-free means: read the original file with `git show HEAD:web/lighthouserc.cjs` into the scratch folder and load both) and after: all equal); `pnpm exec tsc --noEmit`, `pnpm lint` clean.
|
||||
- Record: the before/after table of targets (must be identical).
|
||||
- Record: targets identical before and after (per URL, mobile and desktop, performance level error and warn): `/` 0.8; `/over-mij`, `/soorten-fotoshoots` and the five shoot pages 0.85; `/portfolio`, `/contact`, `/privacyverklaring` and the 404 page 0.9; desktop 0.9 everywhere. The 404 URL changed to `/__audit/404` as the plan prescribes. `photoPagePaths` is kept as a derived export because `src/app.test.tsx` imports it.
|
||||
|
||||
### Step 12: Tests for the Lighthouse configuration (P-HST-11, V13) [ ]
|
||||
### Step 12: Tests for the Lighthouse configuration (P-HST-11, V13) [x]
|
||||
|
||||
- Executor: Sonnet.
|
||||
- Implements: P-HST-11; BR-HST-22, 23; V13.
|
||||
@@ -324,13 +328,13 @@ The riskiest mechanism is the nginx block (a `map`, a server-level `if` and `rew
|
||||
1. `app.test.tsx`: `expect(lighthouseConfig.notFoundPath).toBe('/__audit/404')` and update the comment (Lighthouse refuses an error status; the preview serves the 404 page with 200 only through the opt-in route; `/404.html` is a real 404).
|
||||
2. `config/lighthouserc.test.ts` (loads the CJS module with `createRequire`): every exception has a non-empty `decision` string, `minScore < 0.9`, and names a path in `indexedPaths`; no URL of the collect list matches two assert-matrix entries and none matches zero (use each entry's `matchingUrlPattern` as a RegExp); `notFoundPath` is not in `indexedPaths` or `noindexPaths`; `startServerCommand` contains `--audit-route`; `numberOfRuns` is 1; the quality categories accessibility, best-practices, SEO have `minScore: 1` in every entry that has them; the desktop config sets every performance assertion to 0.9. Property-style (`(invariant)`) where useful: for any generated subset of exception entries the matrix builder (if exported as a function; otherwise test the produced matrix) covers each indexed page exactly once. Include an example-based test that a deliberately invalid exception (empty decision, `minScore` 0.9) would be rejected by the validation helper you extract (`validateExceptions` in the CJS file, exported and used by the module itself at load time so a bad table fails at import).
|
||||
- Done when: `pnpm exec vitest run config/lighthouserc.test.ts src/app.test.tsx` green; `pnpm exec tsc --noEmit`, `pnpm lint` clean.
|
||||
- Record: one line.
|
||||
- Record: `config/lighthouserc.test.ts` added (invariants, validation helper, desktop); only the `notFoundPath` assertion and its comment changed in `src/app.test.tsx`; 55 tests green across both files.
|
||||
|
||||
---
|
||||
|
||||
## Part F: Deploy scripts and CI (batch B5, Sonnet; parallel with B2, B3, B4)
|
||||
|
||||
### Step 13: Artifact guard and post-deploy script (BR-HST-15, 18; V11) [ ]
|
||||
### Step 13: Artifact guard and post-deploy script (BR-HST-15, 18; V11) [x]
|
||||
|
||||
- Executor: Sonnet.
|
||||
- Implements: BR-HST-15, 18; FR-PR-17; NFR-PR-SEC-03; V11.
|
||||
@@ -341,8 +345,9 @@ The riskiest mechanism is the nginx block (a `map`, a server-level `if` and `rew
|
||||
3. `e2e/deployScripts.e2e.ts`: skipped with a visible line when `bash` or `curl` is missing outside CI (fails in CI). Tests: `check-artifact.sh` passes on a fixture dist and fails for each violation (missing file, `server/`, a `.map`); `verify-deployment.sh` passes against `startPreviewServer` on the fixture site (without `--test`) and **fails against a tiny stub server** that imitates the old behaviour (serves `index.html` with 200 for every path, no 404, no redirects) with a message naming the `/over-mij` byte check (V11); and fails when a security header is missing (stub).
|
||||
- Done when: `pnpm exec vitest run --config vitest.e2e.config.ts e2e/deployScripts.e2e.ts` green (or skipped with the visible line when bash is absent); `pnpm exec tsc --noEmit`, `pnpm lint` clean.
|
||||
- Record: V11 outcome.
|
||||
- Done: check-artifact.sh, verify-deployment.sh and e2e/deployScripts.e2e.ts written. V11: verify-deployment.sh fails against a stub with the old behaviour (homepage with 200 for every path) with "/over-mij: antwoord is niet gelijk aan over-mij.html", and passes against a stub with the new rules and against the preview server on the fixture site. Proven against stubs, not against the real old nginx file. Locally 22 passed, 5 skipped (the lftp tests).
|
||||
|
||||
### Step 14: Production upload script and the lftp passes (BR-HST-14; V10) [ ]
|
||||
### Step 14: Production upload script and the lftp passes (BR-HST-14; V10) [x]
|
||||
|
||||
- Executor: Sonnet.
|
||||
- Implements: BR-HST-14, 15; FR-PR-18; V10.
|
||||
@@ -354,8 +359,9 @@ The riskiest mechanism is the nginx block (a `map`, a server-level `if` and `rew
|
||||
4. If `lftp` is not installed locally, the local test does not run and the syntax is **unverified until the first CI run**: state that plainly in the Record and in the verification log V10 (Status OPEN), and do not install lftp.
|
||||
- Done when: the script exists and passes `bash -n`; the test runs green with lftp, or V10 is recorded OPEN with the reason; `pnpm exec tsc --noEmit`, `pnpm lint` clean.
|
||||
- Record: V10 outcome and the chosen syntax with its source.
|
||||
- Done: upload-production.sh written (passes `bash -n`; command text checked with a fake lftp on the PATH). Chosen syntax: `--exclude-glob '*.html' --exclude-glob web.config` for pass 1 and `--include-glob '*.html'` for pass 2 (the design sketch; lftp manual at https://lftp.yar.ru/ not consulted offline). lftp is not installed locally, so V10 is OPEN: the syntax is unverified until the first CI run (the lighthouse job installs lftp and runs the test). Open question for that run: whether `--include-glob` alone includes only HTML and still descends into directories.
|
||||
|
||||
### Step 15: Workflow edits for the deploy jobs (BR-HST-14 to 18) [ ]
|
||||
### Step 15: Workflow edits for the deploy jobs (BR-HST-14 to 18) [x]
|
||||
|
||||
- Executor: Sonnet.
|
||||
- Implements: BR-HST-14 to 18; FR-PR-17, 18.
|
||||
@@ -366,6 +372,7 @@ The riskiest mechanism is the nginx block (a `map`, a server-level `if` and `rew
|
||||
3. Update the header comment of the workflow only if it states something that is now wrong.
|
||||
- Done when: the YAML is valid (same check as Step 5); the diff touches only the two deploy jobs; the lftp command text exists in exactly one place (`upload-production.sh`).
|
||||
- Record: the diff summary.
|
||||
- Done: deploy-test: new step "Controle van de build" (check-artifact.sh) before the upload; "Controle na deploy" runs verify-deployment.sh with --test. deploy-production: the web.config step and the inline lftp block are replaced by one call of upload-production.sh; the post-deploy step runs verify-deployment.sh; if-condition unchanged. YAML parses (yaml 1.10.3 from the pnpm store); no mirror/lftp command text left in the workflow. See `git diff .gitea`.
|
||||
|
||||
**CP2** (merge point after Steps 7 to 15): run `pnpm exec tsc --noEmit`, `pnpm lint`, `pnpm format:check`, `pnpm test`, `pnpm build`, in that order, alone (no parallel batch running). All green, or STOP.
|
||||
|
||||
|
||||
@@ -0,0 +1,145 @@
|
||||
import fc from 'fast-check';
|
||||
import { createRequire } from 'node:module';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import mobile from '../lighthouserc.cjs';
|
||||
|
||||
const require = createRequire(import.meta.url);
|
||||
|
||||
const desktop: {
|
||||
ci: {
|
||||
assert: { assertMatrix: Entry[] };
|
||||
};
|
||||
} = require('../lighthouserc.desktop.cjs');
|
||||
|
||||
type Entry = {
|
||||
matchingUrlPattern: string;
|
||||
assertions: Record<string, unknown>;
|
||||
};
|
||||
|
||||
const matrix = (mobile.ci as { assert: { assertMatrix: Entry[] } }).assert
|
||||
.assertMatrix;
|
||||
const collect = (
|
||||
mobile.ci as { collect: { url: string[]; numberOfRuns: number } }
|
||||
).collect;
|
||||
const startCommand = (mobile.ci as { collect: { startServerCommand: string } })
|
||||
.collect.startServerCommand;
|
||||
|
||||
const matching = (entries: Entry[], url: string) =>
|
||||
entries.filter((entry) => new RegExp(entry.matchingUrlPattern).test(url));
|
||||
|
||||
const exceptionEntries = Object.entries(mobile.mobileExceptions);
|
||||
|
||||
describe('mobiele uitzonderingen', () => {
|
||||
it('hebben elk een besluit, een doel onder 0,9 en een bestaande pagina', () => {
|
||||
expect(exceptionEntries.length).toBeGreaterThan(0);
|
||||
for (const [path, { minScore, decision }] of exceptionEntries) {
|
||||
expect(decision.trim()).not.toBe('');
|
||||
expect(minScore).toBeLessThan(0.9);
|
||||
expect(mobile.indexedPaths).toContain(path);
|
||||
}
|
||||
});
|
||||
|
||||
it('weigert een ongeldige uitzondering bij het laden', () => {
|
||||
const paths = ['/', '/over-mij'];
|
||||
const valid = { minScore: 0.85, decision: 'besluit' };
|
||||
expect(() =>
|
||||
mobile.validateExceptions({ '/over-mij': valid }, paths),
|
||||
).not.toThrow();
|
||||
expect(() =>
|
||||
mobile.validateExceptions(
|
||||
{ '/over-mij': { ...valid, decision: '' } },
|
||||
paths,
|
||||
),
|
||||
).toThrow(/decision/);
|
||||
expect(() =>
|
||||
mobile.validateExceptions(
|
||||
{ '/over-mij': { ...valid, minScore: 0.9 } },
|
||||
paths,
|
||||
),
|
||||
).toThrow(/0\.9/);
|
||||
expect(() =>
|
||||
mobile.validateExceptions({ '/bestaat-niet': valid }, paths),
|
||||
).toThrow(/unknown/);
|
||||
});
|
||||
});
|
||||
|
||||
describe('Lighthouse-configuratie', () => {
|
||||
it('laat elke URL van de meting precies een matrixregel raken', () => {
|
||||
expect(collect.url.length).toBeGreaterThan(0);
|
||||
for (const url of collect.url) {
|
||||
expect(matching(matrix, url), url).toHaveLength(1);
|
||||
}
|
||||
});
|
||||
|
||||
it('(invariant) dekt elke geindexeerde pagina precies een keer, voor elke deelverzameling uitzonderingen', () => {
|
||||
fc.assert(
|
||||
fc.property(
|
||||
fc.subarray(exceptionEntries, { minLength: 0 }),
|
||||
(subset) => {
|
||||
const entries = mobile.buildIndexedEntries(
|
||||
Object.fromEntries(subset),
|
||||
mobile.indexedPaths,
|
||||
);
|
||||
for (const path of mobile.indexedPaths) {
|
||||
const hits = matching(
|
||||
entries as Entry[],
|
||||
`http://localhost:4173${path}`,
|
||||
);
|
||||
expect(hits).toHaveLength(1);
|
||||
}
|
||||
},
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it('geeft elke uitzondering haar eigen doel en de rest 0,9', () => {
|
||||
for (const path of mobile.indexedPaths) {
|
||||
const [entry] = matching(matrix, `http://localhost:4173${path}`);
|
||||
const performance = entry.assertions['categories:performance'] as [
|
||||
string,
|
||||
{ minScore: number },
|
||||
];
|
||||
expect(performance[1].minScore).toBe(
|
||||
mobile.mobileExceptions[path]?.minScore ?? 0.9,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it('houdt de 404-pagina buiten de pagina-lijsten', () => {
|
||||
expect(mobile.indexedPaths).not.toContain(mobile.notFoundPath);
|
||||
expect(mobile.noindexPaths).not.toContain(mobile.notFoundPath);
|
||||
expect(mobile.notFoundPath).toBe('/__audit/404');
|
||||
});
|
||||
|
||||
it('start de preview met de auditroute en meet een keer', () => {
|
||||
expect(startCommand).toContain('--audit-route');
|
||||
expect(collect.numberOfRuns).toBe(1);
|
||||
});
|
||||
|
||||
it('eist kwaliteitscategorieen van 1 in elke regel die ze heeft', () => {
|
||||
for (const entry of matrix) {
|
||||
for (const key of [
|
||||
'categories:accessibility',
|
||||
'categories:best-practices',
|
||||
'categories:seo',
|
||||
]) {
|
||||
if (key in entry.assertions) {
|
||||
expect(entry.assertions[key]).toEqual([
|
||||
'error',
|
||||
{ minScore: 1 },
|
||||
]);
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('zet op desktop elke prestatie-eis op 0,9', () => {
|
||||
expect(desktop.ci.assert.assertMatrix).toHaveLength(matrix.length);
|
||||
for (const entry of desktop.ci.assert.assertMatrix) {
|
||||
expect(entry.assertions['categories:performance']).toEqual([
|
||||
mobile.performanceLevel,
|
||||
{ minScore: 0.9 },
|
||||
]);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -15,12 +15,22 @@ import {
|
||||
existsIn,
|
||||
pageName,
|
||||
} from '../src/test/requestArbitraries';
|
||||
import {
|
||||
hostilePath,
|
||||
knownPage,
|
||||
pageVariant,
|
||||
queryString,
|
||||
unknownPath,
|
||||
} from '../src/test/urlArbitraries';
|
||||
import { canonicalRedirect, pagePaths } from './canonicalUrls';
|
||||
import { pageFile } from './pageFiles';
|
||||
import { securityHeaders } from './securityHeaders';
|
||||
import {
|
||||
acceptsGzip,
|
||||
contentTypeOf,
|
||||
resolveRequest,
|
||||
startPreviewServer,
|
||||
type ResolvedRequest,
|
||||
} from './previewServer';
|
||||
|
||||
const NOT_FOUND = { file: '404.html', status: 404 };
|
||||
@@ -30,10 +40,30 @@ const FILES = new Set([
|
||||
'over-mij.html',
|
||||
'soorten-fotoshoots.html',
|
||||
'soorten-fotoshoots/newborn.html',
|
||||
'assets/a.js',
|
||||
'assets/app.js',
|
||||
'favicon.png',
|
||||
'robots.txt',
|
||||
'sitemap.xml',
|
||||
]);
|
||||
const resolveIn = (path: string) => resolveRequest(path, existsIn(FILES));
|
||||
const resolveIn = (path: string, options?: { auditRoute?: boolean }) =>
|
||||
resolveRequest(path, existsIn(FILES), options);
|
||||
const PAGE_FILES = new Set(pagePaths.map(pageFile));
|
||||
const redirectTo = (redirect: string): ResolvedRequest => ({
|
||||
redirect,
|
||||
status: 301,
|
||||
});
|
||||
|
||||
// Volgt redirects tot een bestand of een 404 en telt de stappen
|
||||
function follow(path: string, files: ReadonlySet<string> = FILES) {
|
||||
let current = path;
|
||||
for (let hops = 0; hops <= 5; hops++) {
|
||||
const result = resolveRequest(current, existsIn(files));
|
||||
if (!('redirect' in result)) return { result, hops };
|
||||
current = result.redirect;
|
||||
}
|
||||
throw new Error(`geen einde aan de redirects vanaf ${path}`);
|
||||
}
|
||||
|
||||
describe('resolveRequest', () => {
|
||||
it('geeft index.html voor /', () => {
|
||||
@@ -65,10 +95,7 @@ describe('resolveRequest', () => {
|
||||
file: 'favicon.png',
|
||||
status: 200,
|
||||
});
|
||||
expect(resolveIn('/over-mij.html')).toEqual({
|
||||
file: 'over-mij.html',
|
||||
status: 200,
|
||||
});
|
||||
expect(resolveIn('/over-mij.html')).toEqual(redirectTo('/over-mij'));
|
||||
expect(resolveIn('/assets/weg.js')).toEqual(NOT_FOUND);
|
||||
});
|
||||
|
||||
@@ -129,50 +156,156 @@ describe('resolveRequest', () => {
|
||||
it('weigert een pad zonder voorste slash en een Windows-stationsletter', () => {
|
||||
expect(resolveIn('')).toEqual(NOT_FOUND);
|
||||
expect(resolveIn('index.html')).toEqual(NOT_FOUND);
|
||||
const drive = resolveRequest('/c:/windows/x.ini', () => true);
|
||||
expect(win32.isAbsolute(drive.file)).toBe(false);
|
||||
expect(drive).toEqual(NOT_FOUND);
|
||||
expect(resolveRequest('/c:/windows/x.ini', () => true)).toEqual(
|
||||
NOT_FOUND,
|
||||
);
|
||||
});
|
||||
|
||||
it('geeft 404 voor een dubbele slash', () => {
|
||||
expect(resolveIn('//over-mij')).toEqual(NOT_FOUND);
|
||||
expect(resolveIn('/assets//app.js')).toEqual(NOT_FOUND);
|
||||
expect(resolveIn('/over-mij//x')).toEqual(NOT_FOUND);
|
||||
});
|
||||
|
||||
describe('tussenregels uit BR-SRV-07', () => {
|
||||
it('geeft 404 voor een slash aan het eind, zonder redirect', () => {
|
||||
expect(resolveIn('/over-mij/')).toEqual(NOT_FOUND);
|
||||
expect(resolveIn('/soorten-fotoshoots/')).toEqual(NOT_FOUND);
|
||||
expect(resolveIn('/assets/')).toEqual(NOT_FOUND);
|
||||
it('geeft 404 voor een doel dat met // of /\\ zou beginnen (BR-HST-06)', () => {
|
||||
for (const path of [
|
||||
'//evil.example/',
|
||||
'//evil.example//',
|
||||
'/%5Cevil.example/',
|
||||
'/\\evil.example/',
|
||||
'/a//b/',
|
||||
'/over-mij\r\nx/',
|
||||
]) {
|
||||
expect(resolveIn(path), path).toEqual(NOT_FOUND);
|
||||
}
|
||||
});
|
||||
|
||||
describe('regels uit BR-HST-03 tot 05', () => {
|
||||
it('stuurt een slash aan het eind met één 301 naar het pad zonder', () => {
|
||||
expect(resolveIn('/over-mij/')).toEqual(redirectTo('/over-mij'));
|
||||
expect(resolveIn('/over-mij///')).toEqual(redirectTo('/over-mij'));
|
||||
expect(resolveIn('/soorten-fotoshoots/')).toEqual(
|
||||
redirectTo('/soorten-fotoshoots'),
|
||||
);
|
||||
expect(resolveIn('/onbekend/')).toEqual(redirectTo('/onbekend'));
|
||||
expect(resolveIn('/assets/')).toEqual(redirectTo('/assets'));
|
||||
});
|
||||
|
||||
it('antwoordt op /404 met 404.html en status 404, niet 200', () => {
|
||||
it('codeert een doel dat niet uit de paginalijst komt opnieuw', () => {
|
||||
expect(resolveIn('/een%20pad/')).toEqual(redirectTo('/een%20pad'));
|
||||
expect(resolveIn('/a%3Fb/')).toEqual(redirectTo('/a%3Fb'));
|
||||
expect(resolveIn('/caf%C3%A9/')).toEqual(redirectTo('/caf%C3%A9'));
|
||||
});
|
||||
|
||||
it('geeft /404 en /404.html status 404, ook als 404.html bestaat', () => {
|
||||
expect(resolveIn('/404')).toEqual(NOT_FOUND);
|
||||
});
|
||||
|
||||
it('serveert /404.html als bestand met 200 (BR-SRV-04)', () => {
|
||||
// Lighthouse weigert een 404-status en valt hierop terug
|
||||
expect(resolveIn('/404.html')).toEqual({
|
||||
file: '404.html',
|
||||
status: 200,
|
||||
});
|
||||
expect(resolveIn('/404.html')).toEqual(NOT_FOUND);
|
||||
expect(resolveRequest('/404.html', () => false)).toEqual(NOT_FOUND);
|
||||
});
|
||||
|
||||
it('geeft /index en /index.html het bestand van /', () => {
|
||||
expect(resolveIn('/index')).toEqual({
|
||||
file: 'index.html',
|
||||
it('stuurt /index en /index.html met een 301 naar /', () => {
|
||||
expect(resolveIn('/index')).toEqual(redirectTo('/'));
|
||||
expect(resolveIn('/index.html')).toEqual(redirectTo('/'));
|
||||
expect(resolveIn('/index/')).toEqual(redirectTo('/'));
|
||||
});
|
||||
|
||||
it('stuurt hoofdletters en .html van een bekende pagina naar het kanonieke pad', () => {
|
||||
expect(resolveIn('/over-mij.html')).toEqual(
|
||||
redirectTo('/over-mij'),
|
||||
);
|
||||
expect(resolveIn('/Over-Mij')).toEqual(redirectTo('/over-mij'));
|
||||
expect(resolveIn('/OVER-MIJ.HTML')).toEqual(
|
||||
redirectTo('/over-mij'),
|
||||
);
|
||||
expect(resolveIn('/Over-Mij/')).toEqual(redirectTo('/over-mij'));
|
||||
expect(resolveIn('/soorten-fotoshoots/newborn.html')).toEqual(
|
||||
redirectTo('/soorten-fotoshoots/newborn'),
|
||||
);
|
||||
});
|
||||
|
||||
it('stuurt een onbekend pad niet door op hoofdletters', () => {
|
||||
expect(resolveIn('/Onbekend')).toEqual(NOT_FOUND);
|
||||
expect(resolveIn('/x.html')).toEqual(NOT_FOUND);
|
||||
});
|
||||
|
||||
it('laat / en de kanonieke paden zonder redirect', () => {
|
||||
for (const path of ['/', '/over-mij', '/soorten-fotoshoots']) {
|
||||
expect(resolveIn(path)).not.toHaveProperty('redirect');
|
||||
}
|
||||
});
|
||||
|
||||
it('stuurt een map naast een paginabestand nooit door of toont haar (BR-HST-07)', () => {
|
||||
// soorten-fotoshoots.html staat naast de map soorten-fotoshoots/
|
||||
expect(resolveIn('/soorten-fotoshoots')).toEqual({
|
||||
file: 'soorten-fotoshoots.html',
|
||||
status: 200,
|
||||
});
|
||||
expect(resolveIn('/index.html')).toEqual({
|
||||
file: 'index.html',
|
||||
expect(resolveIn('/assets')).toEqual(NOT_FOUND);
|
||||
});
|
||||
});
|
||||
|
||||
describe('tabel uit BR-HST (resultaten per verzoek)', () => {
|
||||
const ok = (file: string): ResolvedRequest => ({ file, status: 200 });
|
||||
const notFound = NOT_FOUND as ResolvedRequest;
|
||||
const rows: [string, ResolvedRequest][] = [
|
||||
['/', ok('index.html')],
|
||||
['/over-mij', ok('over-mij.html')],
|
||||
['/soorten-fotoshoots', ok('soorten-fotoshoots.html')],
|
||||
[
|
||||
'/soorten-fotoshoots/newborn',
|
||||
ok('soorten-fotoshoots/newborn.html'),
|
||||
],
|
||||
['/over-mij/', redirectTo('/over-mij')],
|
||||
['/over-mij///', redirectTo('/over-mij')],
|
||||
['/soorten-fotoshoots/', redirectTo('/soorten-fotoshoots')],
|
||||
['/over-mij.html', redirectTo('/over-mij')],
|
||||
[
|
||||
'/soorten-fotoshoots/newborn.html',
|
||||
redirectTo('/soorten-fotoshoots/newborn'),
|
||||
],
|
||||
['/index', redirectTo('/')],
|
||||
['/index.html', redirectTo('/')],
|
||||
['/index/', redirectTo('/')],
|
||||
['/Over-Mij', redirectTo('/over-mij')],
|
||||
['/OVER-MIJ.HTML', redirectTo('/over-mij')],
|
||||
['/Over-Mij/', redirectTo('/over-mij')],
|
||||
['/404', notFound],
|
||||
['/404.html', notFound],
|
||||
['/onbekend', notFound],
|
||||
['/Onbekend', notFound],
|
||||
['/x.html', notFound],
|
||||
['/assets/missing.js', notFound],
|
||||
['/onbekend/', redirectTo('/onbekend')],
|
||||
['/assets', notFound],
|
||||
['/assets/', redirectTo('/assets')],
|
||||
['/assets/a.js', ok('assets/a.js')],
|
||||
['/robots.txt', ok('robots.txt')],
|
||||
['/sitemap.xml', ok('sitemap.xml')],
|
||||
['/favicon.png', ok('favicon.png')],
|
||||
];
|
||||
|
||||
it.each(rows)('%s', (path, expected) => {
|
||||
expect(resolveIn(path)).toEqual(expected);
|
||||
});
|
||||
});
|
||||
|
||||
describe('opt-in route /__audit/404 (BR-HST-22)', () => {
|
||||
it('geeft zonder de optie 404 en met de optie 200 voor de 404-pagina', () => {
|
||||
expect(resolveIn('/__audit/404')).toEqual(NOT_FOUND);
|
||||
expect(resolveIn('/__audit/404', { auditRoute: false })).toEqual(
|
||||
NOT_FOUND,
|
||||
);
|
||||
expect(resolveIn('/__audit/404', { auditRoute: true })).toEqual({
|
||||
file: '404.html',
|
||||
status: 200,
|
||||
});
|
||||
});
|
||||
|
||||
it('geeft nooit een redirect terug', () => {
|
||||
for (const path of ['/over-mij/', '/404', '/index', '/']) {
|
||||
expect(resolveIn(path)).not.toHaveProperty('redirect');
|
||||
it('laat /404.html en /404 een echte 404 met de optie aan', () => {
|
||||
for (const path of ['/404', '/404.html']) {
|
||||
expect(resolveIn(path, { auditRoute: true }), path).toEqual(
|
||||
NOT_FOUND,
|
||||
);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -193,10 +326,12 @@ describe('resolveRequest (eigenschappen)', () => {
|
||||
existingFiles,
|
||||
fc.boolean(),
|
||||
(path, files, everythingExists) => {
|
||||
const { file, status } = resolveRequest(
|
||||
const result = resolveRequest(
|
||||
path,
|
||||
everythingExists ? () => true : existsIn(files),
|
||||
);
|
||||
if ('redirect' in result) return;
|
||||
const { file, status } = result;
|
||||
expect(file.split('/')).not.toContain('..');
|
||||
expect(file.startsWith('/')).toBe(false);
|
||||
expect(posix.isAbsolute(file)).toBe(false);
|
||||
@@ -219,13 +354,18 @@ describe('resolveRequest (eigenschappen)', () => {
|
||||
dottedFileName,
|
||||
(files, name, dirs, dotted) => {
|
||||
const exists = existsIn(files);
|
||||
// Het model: wat bestaat is 200, de rest 404. Alleen het
|
||||
// pagina-pad /404 is 404 ook al bestaat 404.html; het
|
||||
// bestandsverzoek /404.html is 200.
|
||||
const expected = (file: string, isPage = false) =>
|
||||
files.has(file) && !(isPage && file === '404.html')
|
||||
// Het model: wat bestaat is 200, de rest 404. /404 en
|
||||
// /404.html zijn 404 ook al bestaat 404.html, en een
|
||||
// afwijkende vorm van een bekende pagina krijgt een 301.
|
||||
const expected = (path: string, file: string) => {
|
||||
const canonical = canonicalRedirect(path);
|
||||
if (canonical !== undefined) {
|
||||
return { redirect: canonical, status: 301 };
|
||||
}
|
||||
return files.has(file) && file !== '404.html'
|
||||
? { file, status: 200 }
|
||||
: NOT_FOUND;
|
||||
};
|
||||
|
||||
expect(resolveRequest('/', exists)).toEqual({
|
||||
file: 'index.html',
|
||||
@@ -234,24 +374,108 @@ describe('resolveRequest (eigenschappen)', () => {
|
||||
|
||||
const page = [...dirs, name].join('/');
|
||||
expect(resolveRequest(`/${page}`, exists)).toEqual(
|
||||
expected(`${page}.html`, true),
|
||||
expected(`/${page}`, `${page}.html`),
|
||||
);
|
||||
|
||||
const asset = [...dirs, dotted].join('/');
|
||||
expect(resolveRequest(`/${asset}`, exists)).toEqual(
|
||||
expected(asset),
|
||||
expected(`/${asset}`, asset),
|
||||
);
|
||||
// Een bestand dat echt bestaat wordt altijd gevonden
|
||||
// Een bestand dat echt bestaat wordt gevonden, behalve
|
||||
// 404.html en de paginabestanden die naar hun pad gaan
|
||||
for (const file of files) {
|
||||
expect(resolveRequest(`/${file}`, exists)).toEqual({
|
||||
file,
|
||||
status: 200,
|
||||
});
|
||||
expect(resolveRequest(`/${file}`, exists)).toEqual(
|
||||
expected(`/${file}`, file),
|
||||
);
|
||||
}
|
||||
},
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it('is totaal en veilig voor vijandige paden en paginavarianten (invariant, P-HST-01)', () => {
|
||||
fc.assert(
|
||||
fc.property(
|
||||
fc.oneof(hostilePath, pageVariant, unknownPath, anyRequestPath),
|
||||
fc.boolean(),
|
||||
fc.boolean(),
|
||||
(path, auditRoute, everythingExists) => {
|
||||
const result = resolveRequest(
|
||||
path,
|
||||
everythingExists ? () => true : existsIn(FILES),
|
||||
{ auditRoute },
|
||||
);
|
||||
expect([200, 301, 404]).toContain(result.status);
|
||||
if ('redirect' in result) {
|
||||
expect(result.redirect.startsWith('/')).toBe(true);
|
||||
expect(result.redirect.startsWith('//')).toBe(false);
|
||||
expect(result.redirect.startsWith('/\\')).toBe(false);
|
||||
expect(result.redirect).not.toMatch(
|
||||
// eslint-disable-next-line no-control-regex
|
||||
/[\u0000-\u001f\u007f\\]/,
|
||||
);
|
||||
} else {
|
||||
expect(result.file.split('/')).not.toContain('..');
|
||||
expect(result.file.startsWith('/')).toBe(false);
|
||||
expect(win32.isAbsolute(result.file)).toBe(false);
|
||||
expect(posix.isAbsolute(result.file)).toBe(false);
|
||||
}
|
||||
},
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it('is totaal en veilig voor een vijandig pad, bijvoorbeeld // en /\\ (voorbeeld, P-HST-01)', () => {
|
||||
for (const path of ['//evil.example/', '/%5Cevil.example/', '//']) {
|
||||
const result = resolveIn(path);
|
||||
if ('redirect' in result) {
|
||||
expect(result.redirect.startsWith('//')).toBe(false);
|
||||
}
|
||||
}
|
||||
expect(resolveIn('/%5Cevil.example/')).toEqual(NOT_FOUND);
|
||||
});
|
||||
|
||||
it('brengt elke variant van een bekende pagina in hoogstens 2 stappen bij de pagina (idempotent, P-HST-02, 03)', () => {
|
||||
fc.assert(
|
||||
fc.property(pageVariant, (path) => {
|
||||
const { result, hops } = follow(path, PAGE_FILES);
|
||||
expect(hops).toBeLessThanOrEqual(2);
|
||||
const canonical = canonicalRedirect(path);
|
||||
const target = canonical ?? path;
|
||||
const page = target === '/' ? 'index' : target.slice(1);
|
||||
expect(result).toEqual({ file: `${page}.html`, status: 200 });
|
||||
// Het kanonieke pad is een dekpunt: geen redirect meer
|
||||
expect(
|
||||
resolveRequest(target, existsIn(PAGE_FILES)),
|
||||
).not.toHaveProperty('redirect');
|
||||
}),
|
||||
);
|
||||
});
|
||||
|
||||
it('stuurt elke bekende pagina via een variant naar zichzelf (voorbeeld, P-HST-02)', () => {
|
||||
expect(follow('/Soorten-Fotoshoots/Newborn.html//')).toEqual({
|
||||
result: {
|
||||
file: 'soorten-fotoshoots/newborn.html',
|
||||
status: 200,
|
||||
},
|
||||
hops: 1,
|
||||
});
|
||||
});
|
||||
|
||||
it('geeft 404 voor onbekende paden, 404 voor /404 en /404.html, en nooit een redirect voor / (invariant, P-HST-06)', () => {
|
||||
fc.assert(
|
||||
fc.property(unknownPath, knownPage, (path, page) => {
|
||||
expect(resolveIn(path)).toEqual(NOT_FOUND);
|
||||
expect(resolveIn('/404')).toEqual(NOT_FOUND);
|
||||
expect(resolveIn('/404.html')).toEqual(NOT_FOUND);
|
||||
expect(resolveIn('/')).toEqual({
|
||||
file: 'index.html',
|
||||
status: 200,
|
||||
});
|
||||
expect(resolveIn(page)).not.toHaveProperty('redirect');
|
||||
}),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('contentTypeOf', () => {
|
||||
@@ -329,6 +553,12 @@ function siteDir(): string {
|
||||
writeFileSync(join(clientDir, 'index.html'), '<p>home</p>');
|
||||
writeFileSync(join(clientDir, 'over-mij.html'), '<p>over mij</p>');
|
||||
writeFileSync(join(clientDir, '404.html'), '<p>niet gevonden</p>');
|
||||
writeFileSync(join(clientDir, 'soorten-fotoshoots.html'), '<p>soorten</p>');
|
||||
mkdirSync(join(clientDir, 'soorten-fotoshoots'));
|
||||
writeFileSync(
|
||||
join(clientDir, 'soorten-fotoshoots', 'newborn.html'),
|
||||
'<p>newborn</p>',
|
||||
);
|
||||
writeFileSync(join(clientDir, 'assets', 'app.js'), 'boot()');
|
||||
writeFileSync(join(clientDir, 'assets', 'groot.js'), GROOT_SCRIPT);
|
||||
writeFileSync(join(clientDir, 'logo.png'), BINARY);
|
||||
@@ -338,8 +568,11 @@ function siteDir(): string {
|
||||
return clientDir;
|
||||
}
|
||||
|
||||
async function serve(clientDir: string): Promise<number> {
|
||||
const server = await startPreviewServer(clientDir, 0);
|
||||
async function serve(
|
||||
clientDir: string,
|
||||
options?: { auditRoute?: boolean },
|
||||
): Promise<number> {
|
||||
const server = await startPreviewServer(clientDir, 0, options);
|
||||
servers.push(server);
|
||||
const address = server.address();
|
||||
if (typeof address !== 'object' || !address) throw new Error('geen poort');
|
||||
@@ -388,12 +621,103 @@ describe('startPreviewServer', () => {
|
||||
expect(answer.headers['content-type']).toBe('text/html; charset=utf-8');
|
||||
});
|
||||
|
||||
it('antwoordt op /404 met status 404', async () => {
|
||||
it('antwoordt op /404 en /404.html met de 404-pagina en status 404', async () => {
|
||||
const port = await serve(siteDir());
|
||||
const expected = securityHeaders('production');
|
||||
for (const path of ['/404', '/404.html']) {
|
||||
const answer = await ask(port, path);
|
||||
expect(answer.status, path).toBe(404);
|
||||
expect(answer.body, path).toBe('<p>niet gevonden</p>');
|
||||
expect(answer.headers['content-type'], path).toBe(
|
||||
'text/html; charset=utf-8',
|
||||
);
|
||||
for (const [name, value] of Object.entries(expected)) {
|
||||
expect(answer.headers[name.toLowerCase()], path).toBe(value);
|
||||
}
|
||||
}
|
||||
expect((await ask(port, '/404.html', 'HEAD')).status).toBe(404);
|
||||
});
|
||||
|
||||
it('heeft /__audit/404 alleen met de optie (BR-HST-22)', async () => {
|
||||
const without = await serve(siteDir());
|
||||
expect((await ask(without, '/__audit/404')).status).toBe(404);
|
||||
|
||||
const port = await serve(siteDir(), { auditRoute: true });
|
||||
const audit = await ask(port, '/__audit/404');
|
||||
expect(audit.status).toBe(200);
|
||||
expect(audit.body).toBe('<p>niet gevonden</p>');
|
||||
expect(audit.headers['content-type']).toBe('text/html; charset=utf-8');
|
||||
expect((await ask(port, '/404.html')).status).toBe(404);
|
||||
expect((await ask(port, '/404')).status).toBe(404);
|
||||
const file = await ask(port, '/404.html');
|
||||
expect(file.status).toBe(200);
|
||||
expect(file.body).toBe('<p>niet gevonden</p>');
|
||||
expect((await ask(port, '/andere')).status).toBe(404);
|
||||
});
|
||||
|
||||
it('stuurt een 301 met een relatieve Location, de query en de securityheaders, zonder inhoud', async () => {
|
||||
const port = await serve(siteDir());
|
||||
const expected = securityHeaders('production');
|
||||
for (const method of ['GET', 'HEAD']) {
|
||||
const answer = await ask(port, '/Over-Mij/?x=1&y=%20', method);
|
||||
expect(answer.status, method).toBe(301);
|
||||
expect(answer.headers.location, method).toBe('/over-mij?x=1&y=%20');
|
||||
expect(answer.headers['content-length'], method).toBe('0');
|
||||
expect(answer.headers['cache-control'], method).toBeUndefined();
|
||||
expect(answer.raw.length, method).toBe(0);
|
||||
for (const [name, value] of Object.entries(expected)) {
|
||||
expect(answer.headers[name.toLowerCase()], name).toBe(value);
|
||||
}
|
||||
}
|
||||
const plain = await ask(port, '/onbekend/');
|
||||
expect(plain.status).toBe(301);
|
||||
expect(plain.headers.location).toBe('/onbekend');
|
||||
});
|
||||
|
||||
it('houdt de query byte voor byte in de Location (invariant, P-HST-05)', async () => {
|
||||
const port = await serve(siteDir());
|
||||
await fc.assert(
|
||||
fc.asyncProperty(pageVariant, queryString, async (path, query) => {
|
||||
const canonical = canonicalRedirect(path);
|
||||
fc.pre(canonical !== undefined);
|
||||
const answer = await ask(port, `${path}?${query}`);
|
||||
expect(answer.status).toBe(301);
|
||||
expect(answer.headers.location).toBe(`${canonical}?${query}`);
|
||||
}),
|
||||
{ numRuns: 50 },
|
||||
);
|
||||
});
|
||||
|
||||
it('houdt de query in de Location, voorbeeld (P-HST-05)', async () => {
|
||||
const port = await serve(siteDir());
|
||||
const answer = await ask(port, '/soorten-fotoshoots/?shoot=newborn');
|
||||
expect(answer.headers.location).toBe(
|
||||
'/soorten-fotoshoots?shoot=newborn',
|
||||
);
|
||||
// Zonder query geen vraagteken
|
||||
const bare = await ask(port, '/over-mij/');
|
||||
expect(bare.headers.location).toBe('/over-mij');
|
||||
});
|
||||
|
||||
it('serveert /soorten-fotoshoots als pagina naast zijn map, en /assets niet (V3)', async () => {
|
||||
const port = await serve(siteDir());
|
||||
const page = await ask(port, '/soorten-fotoshoots');
|
||||
expect(page.status).toBe(200);
|
||||
expect(page.body).toBe('<p>soorten</p>');
|
||||
expect((await ask(port, '/soorten-fotoshoots/newborn')).body).toBe(
|
||||
'<p>newborn</p>',
|
||||
);
|
||||
expect((await ask(port, '/assets')).status).toBe(404);
|
||||
const slash = await ask(port, '/assets/');
|
||||
expect(slash.status).toBe(301);
|
||||
expect(slash.headers.location).toBe('/assets');
|
||||
});
|
||||
|
||||
it('geeft /%5Cevil.example/ en //evil.example/ de 404-pagina, geen redirect', async () => {
|
||||
const port = await serve(siteDir());
|
||||
for (const path of ['/%5Cevil.example/', '//evil.example/']) {
|
||||
const answer = await ask(port, path);
|
||||
expect(answer.status, path).toBe(404);
|
||||
expect(answer.headers.location, path).toBeUndefined();
|
||||
expect(answer.body, path).toBe('<p>niet gevonden</p>');
|
||||
}
|
||||
});
|
||||
|
||||
it('geeft 405 op POST, PUT en DELETE, met securityheaders', async () => {
|
||||
@@ -518,17 +842,15 @@ describe('startPreviewServer met compressie (BR-SRV-08)', () => {
|
||||
'a.xml',
|
||||
'a.txt',
|
||||
'a.css',
|
||||
'over-mij.html',
|
||||
'over-mij',
|
||||
]) {
|
||||
const answer = await ask(port, `/${name}`, 'GET', GZIP);
|
||||
expect(answer.headers['content-encoding'], name).toBe('gzip');
|
||||
expect(answer.headers['content-type'], name).toBe(
|
||||
contentTypeOf(name),
|
||||
contentTypeOf(name === 'over-mij' ? 'over-mij.html' : name),
|
||||
);
|
||||
expect(gunzipSync(answer.raw).toString('utf8'), name).toBe(
|
||||
name === 'over-mij.html'
|
||||
? '<p>over mij</p>'
|
||||
: `inhoud van ${name}`,
|
||||
name === 'over-mij' ? '<p>over mij</p>' : `inhoud van ${name}`,
|
||||
);
|
||||
}
|
||||
});
|
||||
@@ -626,6 +948,26 @@ describe('previewServer als opdrachtregel', () => {
|
||||
expect(answer.status).toBe(200);
|
||||
});
|
||||
|
||||
it('opent /__audit/404 alleen met --audit-route', async () => {
|
||||
const clientDir = siteDir();
|
||||
const open = async (...extra: string[]) => {
|
||||
const run = start(
|
||||
'--port',
|
||||
'0',
|
||||
'--strictPort',
|
||||
'--dir',
|
||||
clientDir,
|
||||
...extra,
|
||||
);
|
||||
const line = await run.ready;
|
||||
return Number(/:(\d+)\//.exec(line)![1]);
|
||||
};
|
||||
expect((await ask(await open(), '/__audit/404')).status).toBe(404);
|
||||
const audit = await ask(await open('--audit-route'), '/__audit/404');
|
||||
expect(audit.status).toBe(200);
|
||||
expect(audit.body).toBe('<p>niet gevonden</p>');
|
||||
});
|
||||
|
||||
it('stopt met exitcode 1 op een bezette poort met --strictPort', async () => {
|
||||
const blocker = createServer();
|
||||
await new Promise<void>((done) =>
|
||||
|
||||
+116
-45
@@ -4,7 +4,10 @@
|
||||
// afbeelding van /over-mij naar over-mij.html, en productie draait geen
|
||||
// Node-server. Hier krijgt een onbekend pad 404.html met status 404, en een
|
||||
// pad zonder punt het bijbehorende paginabestand, zoals de host dat straks
|
||||
// ook moet doen (BR-SRV-01 tot 08).
|
||||
// ook moet doen (BR-SRV-01 tot 08). Varianten van een bekende pagina en een
|
||||
// slash aan het eind krijgen één 301 (BR-HST-03, 04). /404.html is een echte
|
||||
// 404; Lighthouse auditeert de 404-pagina via de opt-in route /__audit/404
|
||||
// (--audit-route, BR-HST-22).
|
||||
import { createReadStream, statSync } from 'node:fs';
|
||||
import {
|
||||
createServer,
|
||||
@@ -15,28 +18,59 @@ import {
|
||||
import { extname, join, resolve, sep, win32 } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { createGzip } from 'node:zlib';
|
||||
import { canonicalRedirect, stripTrailingSlashes } from './canonicalUrls.ts';
|
||||
import {
|
||||
compressibleExtensions,
|
||||
compressibleTypes,
|
||||
plainTypes,
|
||||
} from './compressibleTypes.ts';
|
||||
import { NOT_FOUND_FILE, pageFile } from './pageFiles.ts';
|
||||
import { securityHeaders } from './securityHeaders.ts';
|
||||
|
||||
export interface ResolvedRequest {
|
||||
export interface FileResult {
|
||||
// Relatief aan clientDir, met voorwaartse slashes en zonder voorste slash
|
||||
file: string;
|
||||
status: 200 | 404;
|
||||
}
|
||||
|
||||
const NOT_FOUND: ResolvedRequest = { file: NOT_FOUND_FILE, status: 404 };
|
||||
export interface RedirectResult {
|
||||
// Pad zonder query; de server plakt de query van het verzoek erachter
|
||||
redirect: string;
|
||||
status: 301;
|
||||
}
|
||||
|
||||
export type ResolvedRequest = FileResult | RedirectResult;
|
||||
|
||||
export interface ResolveOptions {
|
||||
// Opt-in route /__audit/404: de 404-pagina met status 200, alleen voor
|
||||
// Lighthouse (BR-HST-22)
|
||||
auditRoute?: boolean;
|
||||
}
|
||||
|
||||
const AUDIT_ROUTE = '/__audit/404';
|
||||
|
||||
const NOT_FOUND: FileResult = { file: NOT_FOUND_FILE, status: 404 };
|
||||
|
||||
// Een segment van alleen punten en spaties ('.', '..', '...', '.. ') wordt door
|
||||
// Windows tot een puntsegment teruggebracht, dus het mag nooit door
|
||||
const DOT_SEGMENT = /^[. ]+$/;
|
||||
|
||||
// Het verzoekpad (zonder query of hash) naar het bestand dat erbij hoort.
|
||||
// Eerst één keer decoderen en dán pas op segmenten controleren, zodat
|
||||
// '%2e%2e' en '..%2f' niet langs de controle komen (BR-SRV-06). Een
|
||||
// dubbel gecodeerd pad blijft na één keer decoderen een gewone bestandsnaam.
|
||||
// Het doel van een slash-redirect: de segmenten opnieuw gecodeerd, want het
|
||||
// pad is al gedecodeerd en kan spaties, '?' of niet-ASCII bevatten. Een
|
||||
// '%2F' in het origineel is dan al een segmentscheiding; dat is hier geen
|
||||
// probleem omdat het doel alleen een ander verzoek oplevert.
|
||||
const encodePath = (path: string) =>
|
||||
path.split('/').map(encodeURIComponent).join('/');
|
||||
|
||||
// Het verzoekpad (zonder query of hash) naar het bestand dat erbij hoort, of
|
||||
// naar het pad waar één 301 heen gaat. Eerst één keer decoderen en dán pas
|
||||
// op segmenten controleren, zodat '%2e%2e' en '..%2f' niet langs de controle
|
||||
// komen (BR-SRV-06). Een dubbel gecodeerd pad blijft na één keer decoderen
|
||||
// een gewone bestandsnaam.
|
||||
export function resolveRequest(
|
||||
path: string,
|
||||
fileExists: (file: string) => boolean,
|
||||
options: ResolveOptions = {},
|
||||
): ResolvedRequest {
|
||||
let decoded: string;
|
||||
try {
|
||||
@@ -51,42 +85,54 @@ export function resolveRequest(
|
||||
) {
|
||||
return NOT_FOUND;
|
||||
}
|
||||
if (decoded === '/') return { file: pageFile('/'), status: 200 };
|
||||
|
||||
// Lege segmenten (dubbele slash, slash aan het eind) en puntsegmenten:
|
||||
// geen redirect, maar een 404 (BR-SRV-07)
|
||||
// Puntsegmenten ('.', '..', '...') en een stationsletter horen nergens bij
|
||||
const segments = decoded.slice(1).split('/');
|
||||
if (
|
||||
segments.some((segment) => segment === '' || DOT_SEGMENT.test(segment))
|
||||
) {
|
||||
if (segments.some((segment) => DOT_SEGMENT.test(segment))) {
|
||||
return NOT_FOUND;
|
||||
}
|
||||
|
||||
// Eén 301 voor een afwijkende vorm van een bekende pagina (BR-HST-04) en
|
||||
// voor een slash aan het eind van elk ander pad (BR-HST-03)
|
||||
const canonical = canonicalRedirect(decoded);
|
||||
if (canonical !== undefined) return { redirect: canonical, status: 301 };
|
||||
if (decoded.length > 1 && decoded.endsWith('/')) {
|
||||
const stripped = stripTrailingSlashes(decoded);
|
||||
// Een doel dat niet veilig is (BR-HST-06) of een leeg segment heeft
|
||||
// (//x, BR-SRV-07, buiten de pariteit) is een onbekend pad
|
||||
if (stripped === undefined || stripped.includes('//')) {
|
||||
return NOT_FOUND;
|
||||
}
|
||||
try {
|
||||
return { redirect: encodePath(stripped), status: 301 };
|
||||
} catch {
|
||||
return NOT_FOUND;
|
||||
}
|
||||
}
|
||||
|
||||
// /404 en /404.html zijn echte 404's (BR-HST-05)
|
||||
if (decoded === '/404' || decoded === '/404.html') return NOT_FOUND;
|
||||
if (options.auditRoute && decoded === AUDIT_ROUTE) {
|
||||
return { file: NOT_FOUND_FILE, status: 200 };
|
||||
}
|
||||
if (decoded === '/') return { file: pageFile('/'), status: 200 };
|
||||
|
||||
// Lege segmenten (dubbele slash) blijven een 404 (BR-SRV-07)
|
||||
if (segments.some((segment) => segment === '')) return NOT_FOUND;
|
||||
|
||||
const isFileRequest = segments[segments.length - 1].includes('.');
|
||||
const file = isFileRequest ? segments.join('/') : pageFile(decoded);
|
||||
// Een stationsletter ('c:/x') is op Windows een absoluut pad
|
||||
if (win32.isAbsolute(file)) return NOT_FOUND;
|
||||
// Het pagina-pad /404 antwoordt met 404, niet met 200. Het bestandsverzoek /404.html is
|
||||
// gewoon een bestand (BR-SRV-04) en geeft 200: Lighthouse weigert een
|
||||
// pagina met een 404-status te auditen en gebruikt dit pad als terugval.
|
||||
if (!isFileRequest && file === NOT_FOUND_FILE) return NOT_FOUND;
|
||||
return fileExists(file) ? { file, status: 200 } : NOT_FOUND;
|
||||
}
|
||||
|
||||
const CONTENT_TYPES: Record<string, string> = {
|
||||
'.html': 'text/html; charset=utf-8',
|
||||
'.js': 'text/javascript; charset=utf-8',
|
||||
'.css': 'text/css; charset=utf-8',
|
||||
'.svg': 'image/svg+xml',
|
||||
'.png': 'image/png',
|
||||
'.jpg': 'image/jpeg',
|
||||
'.webp': 'image/webp',
|
||||
'.woff2': 'font/woff2',
|
||||
'.ico': 'image/x-icon',
|
||||
'.xml': 'application/xml; charset=utf-8',
|
||||
'.txt': 'text/plain; charset=utf-8',
|
||||
'.json': 'application/json; charset=utf-8',
|
||||
};
|
||||
const CONTENT_TYPES: Record<string, string> = Object.fromEntries(
|
||||
[...compressibleTypes, ...plainTypes].map((type) => [
|
||||
type.extension,
|
||||
type.previewContentType,
|
||||
]),
|
||||
);
|
||||
|
||||
export const contentTypeOf = (file: string): string =>
|
||||
CONTENT_TYPES[extname(file).toLowerCase()] ?? 'application/octet-stream';
|
||||
@@ -95,18 +141,9 @@ export const contentTypeOf = (file: string): string =>
|
||||
// Waarom: de nulmeting draaide op `vite preview`, dat comprimeert; zonder dit
|
||||
// zijn de Lighthouse-metingen niet te vergelijken (scripts: 667 kB tegen
|
||||
// 202 kB). Productie comprimeert op de host (BR-SRV-08).
|
||||
const COMPRESSIBLE = new Set([
|
||||
'.html',
|
||||
'.js',
|
||||
'.css',
|
||||
'.svg',
|
||||
'.json',
|
||||
'.xml',
|
||||
'.txt',
|
||||
]);
|
||||
|
||||
export const isCompressible = (file: string): boolean =>
|
||||
COMPRESSIBLE.has(extname(file).toLowerCase());
|
||||
compressibleExtensions.has(extname(file).toLowerCase());
|
||||
|
||||
// Staat gzip in Accept-Encoding? 'gzip;q=0' weigert het, '*' staat het toe,
|
||||
// tenzij gzip zelf genoemd is
|
||||
@@ -145,9 +182,20 @@ function send(
|
||||
else body.pipe(response);
|
||||
}
|
||||
|
||||
// De query van het verzoek, byte voor byte vanaf het eerste '?' (zonder hash)
|
||||
const searchOf = (target: string) => {
|
||||
const start = target.indexOf('?');
|
||||
return start === -1 ? '' : target.slice(start).split('#', 1)[0];
|
||||
};
|
||||
|
||||
export interface PreviewOptions {
|
||||
auditRoute?: boolean;
|
||||
}
|
||||
|
||||
export function startPreviewServer(
|
||||
clientDir: string,
|
||||
port: number,
|
||||
options: PreviewOptions = {},
|
||||
): Promise<Server> {
|
||||
const root = resolve(clientDir);
|
||||
const isFile = (file: string) => {
|
||||
@@ -168,10 +216,25 @@ export function startPreviewServer(
|
||||
);
|
||||
return;
|
||||
}
|
||||
const { file, status } = resolveRequest(
|
||||
const resolved = resolveRequest(
|
||||
pathOf(request.url ?? '/'),
|
||||
isFile,
|
||||
options,
|
||||
);
|
||||
if ('redirect' in resolved) {
|
||||
// Geen Cache-Control (BR-HST-12); de query blijft zoals ze kwam
|
||||
send(
|
||||
response,
|
||||
resolved.status,
|
||||
{
|
||||
Location: resolved.redirect + searchOf(request.url ?? ''),
|
||||
'Content-Length': 0,
|
||||
},
|
||||
null,
|
||||
);
|
||||
return;
|
||||
}
|
||||
const { file, status } = resolved;
|
||||
const target = join(root, file);
|
||||
// Tweede slot naast resolveRequest: nooit buiten clientDir lezen
|
||||
if (!target.startsWith(root + sep) || !isFile(file)) {
|
||||
@@ -216,13 +279,19 @@ export function startPreviewServer(
|
||||
// `--port 4173` en `--port=4173`; onbekende argumenten (die `vite preview`
|
||||
// wel kent) worden genegeerd
|
||||
function parseArguments(args: string[]) {
|
||||
const options = { port: 4173, strictPort: false, dir: 'dist/client' };
|
||||
const options = {
|
||||
port: 4173,
|
||||
strictPort: false,
|
||||
dir: 'dist/client',
|
||||
auditRoute: false,
|
||||
};
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
const [name, inline] = args[i].split('=', 2);
|
||||
const value = () => inline ?? args[++i];
|
||||
if (name === '--port') options.port = Number(value());
|
||||
else if (name === '--dir') options.dir = value();
|
||||
else if (name === '--strictPort') options.strictPort = true;
|
||||
else if (name === '--audit-route') options.auditRoute = true;
|
||||
}
|
||||
return options;
|
||||
}
|
||||
@@ -230,7 +299,7 @@ function parseArguments(args: string[]) {
|
||||
const MAX_PORT_TRIES = 10;
|
||||
|
||||
async function main(args: string[]) {
|
||||
const { port, strictPort, dir } = parseArguments(args);
|
||||
const { port, strictPort, dir, auditRoute } = parseArguments(args);
|
||||
if (!Number.isInteger(port) || port < 0 || port > 65535) {
|
||||
console.error(`Ongeldige poort: ${port}`);
|
||||
process.exitCode = 1;
|
||||
@@ -241,7 +310,9 @@ async function main(args: string[]) {
|
||||
const tries = strictPort || port === 0 ? 1 : MAX_PORT_TRIES;
|
||||
for (let attempt = 0; attempt < tries; attempt++) {
|
||||
try {
|
||||
const server = await startPreviewServer(dir, port + attempt);
|
||||
const server = await startPreviewServer(dir, port + attempt, {
|
||||
auditRoute,
|
||||
});
|
||||
const address = server.address();
|
||||
const actual =
|
||||
typeof address === 'object' && address ? address.port : port;
|
||||
|
||||
@@ -1,6 +1,8 @@
|
||||
import { readFileSync } from 'node:fs';
|
||||
import { describe, expect, it } from 'vitest';
|
||||
import { monitoringFor } from '../src/monitoring/config';
|
||||
import { redirectNames } from './canonicalUrls';
|
||||
import { gzipMimeTypes } from './compressibleTypes';
|
||||
import { securityHeaders } from './securityHeaders';
|
||||
import {
|
||||
iisWebConfig,
|
||||
@@ -49,10 +51,11 @@ describe('serverconfiguratie', () => {
|
||||
expect(monitoringFor(productionHost)?.environment).toBe('production');
|
||||
});
|
||||
|
||||
it('IIS heeft een SPA-fallback en een HTTPS-redirect', () => {
|
||||
it('IIS heeft een HTTPS-redirect en geen SPA-fallback', () => {
|
||||
const iis = iisWebConfig();
|
||||
expect(iis).toContain('<action type="Rewrite" url="/index.html" />');
|
||||
expect(iis).toContain('<add input="{HTTPS}" pattern="^OFF$" />');
|
||||
expect(iis).not.toContain('SPA fallback');
|
||||
expect(iis).not.toContain('index.html');
|
||||
});
|
||||
|
||||
it('de testsite wordt nooit geindexeerd', () => {
|
||||
@@ -125,4 +128,226 @@ describe('serverconfiguratie', () => {
|
||||
expect(guard).toBeLessThan(nginx.indexOf('if ($andreaslop_canonical)'));
|
||||
expect(guard).toBeLessThan(nginx.indexOf('rewrite ^/(.+?)/+$'));
|
||||
});
|
||||
|
||||
it('IIS-regels staan in de ontworpen volgorde, allemaal met stopProcessing', () => {
|
||||
expect(iisRules().map((rule) => rule.getAttribute('name'))).toEqual([
|
||||
'www naar andreaslop.nl',
|
||||
'HTTPS',
|
||||
'Index naar root',
|
||||
'Pagina canoniek',
|
||||
'Slash weg',
|
||||
'404 direct',
|
||||
'Pagina bestand',
|
||||
'Map zonder pagina',
|
||||
]);
|
||||
for (const rule of iisRules()) {
|
||||
expect(rule.getAttribute('stopProcessing')).toBe('true');
|
||||
}
|
||||
});
|
||||
|
||||
it('IIS heeft geen mapweergave, standaarddocument of eigen compressielijst', () => {
|
||||
const iis = iisWebConfig();
|
||||
expect(iis).not.toContain('httpCompression');
|
||||
expect(iis).not.toContain('directoryBrowse');
|
||||
expect(iis).not.toContain('defaultDocument');
|
||||
expect(iis).toContain(
|
||||
'<urlCompression doStaticCompression="true" doDynamicCompression="false" />',
|
||||
);
|
||||
expect(iis).toContain('responseMode="ExecuteURL"');
|
||||
expect(iis).toContain('path="/404.html"');
|
||||
});
|
||||
|
||||
it('IIS: ToLower alleen in de canonieke regel, een voorste backslash wordt nooit doel', () => {
|
||||
expect(iisWebConfig().match(/ToLower/g)).toHaveLength(1);
|
||||
const canonical = iisRule('Pagina canoniek');
|
||||
expect(canonical.innerHTML).toContain('{ToLower:{R:1}}');
|
||||
// Hoofdlettergevoelig: alleen de exacte kleine-letterwijze blijft staan
|
||||
expect(
|
||||
canonical
|
||||
.querySelector('conditions add')
|
||||
?.getAttribute('ignoreCase'),
|
||||
).toBe('false');
|
||||
const slashUrl = iisRule('Slash weg')
|
||||
.querySelector('match')
|
||||
?.getAttribute('url');
|
||||
expect(slashUrl).toBe('^([^/\\\\].*?)/+$');
|
||||
// Een doel begint nooit met een backslash of tweede slash (BR-HST-06)
|
||||
const slash = new RegExp(slashUrl ?? '');
|
||||
expect(slash.test('\\evil.example/')).toBe(false);
|
||||
expect(slash.test('/evil.example/')).toBe(false);
|
||||
expect(slash.test('over-mij/')).toBe(true);
|
||||
});
|
||||
|
||||
it('IIS: 404 en 404.html raken geen paginaregel maar geven 404', () => {
|
||||
const matchOf = (name: string) =>
|
||||
new RegExp(
|
||||
iisRule(name).querySelector('match')?.getAttribute('url') ?? '',
|
||||
'i',
|
||||
);
|
||||
for (const url of ['404', '404.html']) {
|
||||
expect(matchOf('Pagina canoniek').test(url)).toBe(false);
|
||||
expect(matchOf('Index naar root').test(url)).toBe(false);
|
||||
expect(matchOf('404 direct').test(url)).toBe(true);
|
||||
}
|
||||
expect(
|
||||
iisRule('404 direct')
|
||||
.querySelector('action')
|
||||
?.getAttribute('statusCode'),
|
||||
).toBe('404');
|
||||
});
|
||||
|
||||
it('IIS en nginx kennen dezelfde pagina’s (invariant)', () => {
|
||||
const pages = redirectNames.map((path) => path.replace(/^\//, ''));
|
||||
expect(iisAlternation()).toEqual(pages);
|
||||
expect(nginxCanonicalPaths()).toEqual(redirectNames);
|
||||
// Per pagina één variantregel, plus de beginpagina onder /index
|
||||
expect(
|
||||
nginxMapKeys().filter((key) => key.startsWith('~*')),
|
||||
).toHaveLength(redirectNames.length + 1);
|
||||
});
|
||||
|
||||
it('IIS zet de MIME-types uit compressibleTypes.ts vast', () => {
|
||||
const iis = iisWebConfig();
|
||||
for (const [extension, mimeType] of [
|
||||
['.js', 'text/javascript'],
|
||||
['.svg', 'image/svg+xml'],
|
||||
['.json', 'application/json'],
|
||||
['.xml', 'text/xml'],
|
||||
['.woff2', 'font/woff2'],
|
||||
]) {
|
||||
expect(iis).toContain(`<remove fileExtension="${extension}" />`);
|
||||
expect(iis).toContain(
|
||||
`<mimeMap fileExtension="${extension}" mimeType="${mimeType}" />`,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
it('nginx: geen mapregel raakt /404 of /404.html (invariant)', () => {
|
||||
const rules = nginxMapKeys().map((key) =>
|
||||
key.startsWith('~*')
|
||||
? new RegExp(key.slice(2), 'i')
|
||||
: new RegExp(key.slice(1)),
|
||||
);
|
||||
expect(rules.length).toBeGreaterThan(0);
|
||||
for (const path of ['/404', '/404.html', '/404.HTML', '/404/']) {
|
||||
for (const rule of rules) expect(rule.test(path)).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
it('nginx: server en elk location-blok met add_header hebben de volledige set (invariant)', () => {
|
||||
const nginx = nginxTestConf();
|
||||
const full = [
|
||||
...Object.entries(securityHeaders('production')).map(
|
||||
([name, value]) => `add_header ${name} "${value}" always;`,
|
||||
),
|
||||
'add_header X-Robots-Tag "noindex, nofollow" always;',
|
||||
];
|
||||
const serverLevel = nginx.slice(
|
||||
nginx.indexOf('server {'),
|
||||
nginx.search(/^ *location /m),
|
||||
);
|
||||
const locations = nginx.split(/^ *location /m).slice(1);
|
||||
const cacheControls = (block: string) =>
|
||||
block.match(/add_header Cache-Control/g)?.length ?? 0;
|
||||
for (const block of [serverLevel, ...locations]) {
|
||||
if (!block.includes('add_header')) continue;
|
||||
for (const line of full) expect(block).toContain(line);
|
||||
expect(cacheControls(block)).toBe(1);
|
||||
}
|
||||
const assets = locations.find((block) => block.startsWith('/assets/'));
|
||||
expect(assets).toContain('immutable');
|
||||
expect(cacheControls(assets ?? '')).toBe(1);
|
||||
});
|
||||
|
||||
it('nginx: geen mapweergave, geen $uri/ en geen return vanuit het pad (invariant)', () => {
|
||||
const lines = nginxDirectives();
|
||||
expect(lines.filter((line) => /^index\s/.test(line))).toEqual([]);
|
||||
expect(lines).not.toContain('autoindex on;');
|
||||
for (const line of lines.filter((l) => l.startsWith('try_files'))) {
|
||||
expect(line).not.toContain('$uri/');
|
||||
expect(line).not.toContain('/index.html $uri');
|
||||
}
|
||||
for (const line of lines.filter((l) => /^return\s+30\d/.test(l))) {
|
||||
expect(line).not.toContain('$uri');
|
||||
expect(line).not.toContain('$1');
|
||||
}
|
||||
expect(lines.filter((line) => line.startsWith('rewrite '))).toEqual([
|
||||
'rewrite ^/(.+?)/+$ /$1 permanent;',
|
||||
]);
|
||||
});
|
||||
|
||||
it('nginx: eigen 404-pagina, interne 404.html en eigen gzip-instellingen', () => {
|
||||
const nginx = nginxTestConf();
|
||||
expect(nginx).toContain('error_page 404 /404.html;');
|
||||
expect(nginx).toMatch(/location = \/404\.html \{\s+internal;/);
|
||||
expect(nginx).toContain('gzip_http_version 1.0;');
|
||||
const types = nginx.match(/^ *gzip_types ([^;]+);/m)?.[1].split(' ');
|
||||
for (const type of gzipMimeTypes()) expect(types).toContain(type);
|
||||
});
|
||||
|
||||
it('nginx: de kop noemt het standaardblok en het bestand is een los server-blok', () => {
|
||||
const nginx = nginxTestConf();
|
||||
expect(nginx).toContain('00-default.conf');
|
||||
expect(nginx).toContain('444');
|
||||
expect(nginx).not.toMatch(
|
||||
/(terugval|valt terug|fallback)[^\n]*WordPress/i,
|
||||
);
|
||||
const lines = nginxDirectives();
|
||||
expect(lines.some((line) => line.startsWith('include '))).toBe(false);
|
||||
expect(lines.some((line) => /^http\s*\{/.test(line))).toBe(false);
|
||||
expect(lines.some((line) => line.includes('default_server'))).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
function iisRules(): Element[] {
|
||||
const document = new DOMParser().parseFromString(
|
||||
iisWebConfig(),
|
||||
'application/xml',
|
||||
);
|
||||
expect(document.querySelector('parsererror')).toBeNull();
|
||||
return [...document.querySelectorAll('rewrite > rules > rule')];
|
||||
}
|
||||
|
||||
function iisRule(name: string): Element {
|
||||
const rule = iisRules().find((r) => r.getAttribute('name') === name);
|
||||
if (!rule) throw new Error(`Regel ${name} ontbreekt`);
|
||||
return rule;
|
||||
}
|
||||
|
||||
// De paginanamen uit de alternation van de canonieke regel
|
||||
function iisAlternation(): string[] {
|
||||
const url =
|
||||
iisRule('Pagina canoniek')
|
||||
.querySelector('match')
|
||||
?.getAttribute('url') ?? '';
|
||||
const body = url.match(/^\^\((.+)\)\(\?:\\\.html\)\?\/\*\$$/)?.[1];
|
||||
return (body ?? '').split('|').map((name) => name.replace(/\\(.)/g, '$1'));
|
||||
}
|
||||
|
||||
// Config-regels zonder commentaar en inspringing
|
||||
function nginxDirectives(): string[] {
|
||||
return nginxTestConf()
|
||||
.split('\n')
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line && !line.startsWith('#'));
|
||||
}
|
||||
|
||||
function nginxMapKeys(): string[] {
|
||||
const map = nginxTestConf().match(
|
||||
/map \$uri \$andreaslop_canonical \{([^}]*)\}/,
|
||||
)?.[1];
|
||||
return (map ?? '')
|
||||
.split('\n')
|
||||
.map((line) => line.trim())
|
||||
.filter((line) => line && line !== 'default "";')
|
||||
.map((line) => line.split(' ')[0]);
|
||||
}
|
||||
|
||||
// De paden van de hoofdlettergevoelige canonieke sleutels (~^/pad$)
|
||||
function nginxCanonicalPaths(): string[] {
|
||||
return nginxMapKeys()
|
||||
.filter((key) => key.startsWith('~^'))
|
||||
.map((key) => key.slice(2, -1));
|
||||
}
|
||||
|
||||
+63
-12
@@ -3,8 +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 { compressibleTypes, gzipMimeTypes } from './compressibleTypes.ts';
|
||||
import { escapeRegex, redirectNames, variantPattern } from './canonicalUrls.ts';
|
||||
import { securityHeaders } from './securityHeaders.ts';
|
||||
|
||||
const generatedNotice =
|
||||
@@ -21,11 +21,17 @@ const xmlAttribute = (value: string) =>
|
||||
// op deze hostname) en zoekmachines één adres zien
|
||||
export const productionHost = 'andreaslop.nl';
|
||||
|
||||
// IIS (productie): www-doorverwijzing, security headers, HTTPS-redirect,
|
||||
// SPA-fallback en caching. De www-regel staat vóór HTTPS, zodat
|
||||
// http://www. in één stap op https://andreaslop.nl uitkomt.
|
||||
// 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; index.html nooit, zodat een nieuwe release direct zichtbaar is.
|
||||
// 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(
|
||||
@@ -33,6 +39,20 @@ export function iisWebConfig(): string {
|
||||
` <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} -->
|
||||
@@ -54,16 +74,46 @@ export function iisWebConfig(): string {
|
||||
</conditions>
|
||||
<action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" />
|
||||
</rule>
|
||||
<rule name="SPA fallback" stopProcessing="true">
|
||||
<match url=".*" />
|
||||
<conditions logicalGrouping="MatchAll">
|
||||
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
|
||||
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
|
||||
<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="Rewrite" url="/index.html" />
|
||||
<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" />
|
||||
@@ -73,6 +123,7 @@ ${headers}
|
||||
<staticContent>
|
||||
<remove fileExtension=".woff2" />
|
||||
<mimeMap fileExtension=".woff2" mimeType="font/woff2" />
|
||||
${mimePins}
|
||||
<clientCache cacheControlMode="DisableCache" />
|
||||
</staticContent>
|
||||
</system.webServer>
|
||||
|
||||
@@ -0,0 +1,47 @@
|
||||
#!/usr/bin/env bash
|
||||
# Controle van de build voordat die wordt geüpload (BR-HST-15, FR-PR-17).
|
||||
# Gebruik: check-artifact.sh <dist-map>
|
||||
# Faalt als een verplicht bestand ontbreekt, als de servermap erin zit, of als
|
||||
# er een source map in staat (die zou de broncode openbaar maken).
|
||||
set -euo pipefail
|
||||
|
||||
if [ "$#" -ne 1 ]; then
|
||||
echo "Gebruik: $0 <dist-map>" >&2
|
||||
exit 2
|
||||
fi
|
||||
dist="$1"
|
||||
|
||||
if [ ! -d "$dist" ]; then
|
||||
echo "Geen map: $dist" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
failures=0
|
||||
fail() {
|
||||
echo "FOUT: $1" >&2
|
||||
failures=$((failures + 1))
|
||||
}
|
||||
|
||||
for file in index.html 404.html over-mij.html; do
|
||||
if [ -f "$dist/$file" ]; then
|
||||
echo "gevonden: $file"
|
||||
else
|
||||
fail "$file ontbreekt in $dist"
|
||||
fi
|
||||
done
|
||||
|
||||
if [ -e "$dist/server" ]; then
|
||||
fail "$dist/server bestaat: alleen de clientmap hoort online"
|
||||
fi
|
||||
|
||||
maps="$(find "$dist" -type f -name '*.map')"
|
||||
if [ -n "$maps" ]; then
|
||||
fail "source maps gevonden:
|
||||
$maps"
|
||||
fi
|
||||
|
||||
if [ "$failures" -gt 0 ]; then
|
||||
echo "Build geweigerd ($failures fout(en))" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "Build in orde: $dist"
|
||||
@@ -18,16 +18,46 @@
|
||||
</conditions>
|
||||
<action type="Redirect" url="https://{HTTP_HOST}/{R:1}" redirectType="Permanent" />
|
||||
</rule>
|
||||
<rule name="SPA fallback" stopProcessing="true">
|
||||
<match url=".*" />
|
||||
<conditions logicalGrouping="MatchAll">
|
||||
<add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />
|
||||
<add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />
|
||||
<rule name="Index naar root" stopProcessing="true">
|
||||
<match url="^index(?:\.html)?/*$" />
|
||||
<action type="Redirect" url="/" redirectType="Permanent" />
|
||||
</rule>
|
||||
<rule name="Pagina canoniek" stopProcessing="true">
|
||||
<match url="^(over-mij|portfolio|soorten-fotoshoots|soorten-fotoshoots/newborn|soorten-fotoshoots/zwangerschap|soorten-fotoshoots/gezin|soorten-fotoshoots/loveshoot|soorten-fotoshoots/portret|contact|privacyverklaring)(?:\.html)?/*$" />
|
||||
<conditions>
|
||||
<add input="{R:0}" pattern="^(?:over-mij|portfolio|soorten-fotoshoots|soorten-fotoshoots/newborn|soorten-fotoshoots/zwangerschap|soorten-fotoshoots/gezin|soorten-fotoshoots/loveshoot|soorten-fotoshoots/portret|contact|privacyverklaring)$" ignoreCase="false" negate="true" />
|
||||
</conditions>
|
||||
<action type="Rewrite" url="/index.html" />
|
||||
<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" />
|
||||
@@ -41,6 +71,14 @@
|
||||
<staticContent>
|
||||
<remove fileExtension=".woff2" />
|
||||
<mimeMap fileExtension=".woff2" mimeType="font/woff2" />
|
||||
<remove fileExtension=".js" />
|
||||
<mimeMap fileExtension=".js" mimeType="text/javascript" />
|
||||
<remove fileExtension=".svg" />
|
||||
<mimeMap fileExtension=".svg" mimeType="image/svg+xml" />
|
||||
<remove fileExtension=".json" />
|
||||
<mimeMap fileExtension=".json" mimeType="application/json" />
|
||||
<remove fileExtension=".xml" />
|
||||
<mimeMap fileExtension=".xml" mimeType="text/xml" />
|
||||
<clientCache cacheControlMode="DisableCache" />
|
||||
</staticContent>
|
||||
</system.webServer>
|
||||
|
||||
@@ -0,0 +1,62 @@
|
||||
#!/usr/bin/env bash
|
||||
# Upload naar productie in drie rondes (BR-HST-14, 15; FR-PR-18).
|
||||
# Gebruik: upload-production.sh <dist-map> <doelmap-op-de-server>
|
||||
# Verbinding: FTP_HOST, FTP_USER en LFTP_PASSWORD uit de omgeving (FTPS).
|
||||
# Alleen voor de test: LFTP_OPEN (bijvoorbeeld file:///) vervangt de
|
||||
# verbinding, en UPLOAD_PASS=1|2|3 voert maar één ronde uit.
|
||||
set -euo pipefail
|
||||
|
||||
if [ "$#" -ne 2 ]; then
|
||||
echo "Gebruik: $0 <dist-map> <doelmap>" >&2
|
||||
exit 2
|
||||
fi
|
||||
dist="${1%/}"
|
||||
remote="${2%/}"
|
||||
|
||||
# De paden komen in een lftp-opdracht; daarom geen spaties of quotes
|
||||
safe='^[A-Za-z0-9._/-]+$'
|
||||
for value in "$dist" "$remote"; do
|
||||
if ! [[ "$value" =~ $safe ]]; then
|
||||
echo "Ongeldig pad: '$value'" >&2
|
||||
exit 2
|
||||
fi
|
||||
done
|
||||
|
||||
here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
bash "$here/check-artifact.sh" "$dist"
|
||||
cp "$here/iis/web.config" "$dist/web.config"
|
||||
|
||||
pass="${UPLOAD_PASS:-all}"
|
||||
case "$pass" in
|
||||
all | 1 | 2 | 3) ;;
|
||||
*) echo "Ongeldige UPLOAD_PASS: '$pass'" >&2; exit 2 ;;
|
||||
esac
|
||||
wants() { [ "$pass" = all ] || [ "$pass" = "$1" ]; }
|
||||
|
||||
commands="set ftp:ssl-force true; set ftp:ssl-protect-data true; set net:max-retries 3;"
|
||||
# Ronde 1: alles behalve HTML en web.config, dus ook /assets. Nieuwe
|
||||
# bestanden met hash in de naam storen de oude release niet.
|
||||
if wants 1; then
|
||||
commands="$commands mirror --reverse --verbose --exclude-glob '*.html' --exclude-glob web.config $dist/ $remote/;"
|
||||
fi
|
||||
# Ronde 2: web.config vlak voor de HTML (de regels passen bij de nieuwe
|
||||
# bestanden), dan alle HTML, ook de geneste pagina's en 404.html. Pas nu
|
||||
# verwijst iets naar de nieuwe assets.
|
||||
if wants 2; then
|
||||
commands="$commands put -O $remote $dist/web.config;"
|
||||
commands="$commands mirror --reverse --verbose --include-glob '*.html' $dist/ $remote/;"
|
||||
fi
|
||||
# Ronde 3: opruimen als laatste, zodat bezoekers met de oude HTML hun oude
|
||||
# assets nog vinden tot de nieuwe HTML helemaal staat.
|
||||
if wants 3; then
|
||||
commands="$commands mirror --reverse --delete --verbose $dist/ $remote/;"
|
||||
fi
|
||||
commands="$commands quit"
|
||||
|
||||
if [ -n "${LFTP_OPEN:-}" ]; then
|
||||
lftp -e "$commands" "$LFTP_OPEN"
|
||||
else
|
||||
: "${FTP_HOST:?FTP_HOST ontbreekt}" "${FTP_USER:?FTP_USER ontbreekt}"
|
||||
: "${LFTP_PASSWORD:?LFTP_PASSWORD ontbreekt}"
|
||||
lftp --env-password -u "$FTP_USER" "$FTP_HOST" -e "$commands"
|
||||
fi
|
||||
@@ -0,0 +1,152 @@
|
||||
#!/usr/bin/env bash
|
||||
# Controle na een deploy (BR-HST-18): wat de server teruggeeft moet gelijk zijn
|
||||
# aan wat in dist staat. Een oude nginx-config die voor elk pad de homepage
|
||||
# geeft (SPA-fallback) valt hier door de mand.
|
||||
# Gebruik: verify-deployment.sh <basis-url> <dist-map> [--test]
|
||||
# --test: ook X-Robots-Tag, en gzip op de JavaScript is verplicht
|
||||
# (zonder --test geeft ontbrekende gzip alleen een waarschuwing)
|
||||
set -euo pipefail
|
||||
|
||||
if [ "$#" -lt 2 ] || [ "$#" -gt 3 ]; then
|
||||
echo "Gebruik: $0 <basis-url> <dist-map> [--test]" >&2
|
||||
exit 2
|
||||
fi
|
||||
base="$1"
|
||||
dist="$2"
|
||||
test_mode=0
|
||||
if [ "$#" -eq 3 ]; then
|
||||
if [ "$3" != "--test" ]; then
|
||||
echo "Onbekende optie: $3" >&2
|
||||
exit 2
|
||||
fi
|
||||
test_mode=1
|
||||
fi
|
||||
|
||||
if ! [[ "$base" =~ ^https?://[^[:space:]]+$ ]]; then
|
||||
echo "Ongeldige URL: '$base'" >&2
|
||||
exit 2
|
||||
fi
|
||||
while [[ "$base" == */ ]]; do base="${base%/}"; done
|
||||
if [ ! -d "$dist" ]; then
|
||||
echo "Geen map: $dist" >&2
|
||||
exit 2
|
||||
fi
|
||||
|
||||
work="$(mktemp -d)"
|
||||
trap 'rm -rf "$work"' EXIT
|
||||
|
||||
failures=0
|
||||
fail() {
|
||||
echo "FOUT: $1" >&2
|
||||
failures=$((failures + 1))
|
||||
}
|
||||
|
||||
# Haalt $base$1 op zonder redirects te volgen en zonder Accept-Encoding
|
||||
# (curl stuurt er zelf geen). Bewaart status, headers en body in $work.
|
||||
# Meer argumenten: extra curl-opties (bijvoorbeeld een header).
|
||||
fetch() {
|
||||
local path="$1"
|
||||
shift
|
||||
: > "$work/headers"
|
||||
: > "$work/body"
|
||||
status="$(curl -sS --max-time 30 -o "$work/body" -D "$work/headers" \
|
||||
-w '%{http_code}' "$@" "$base$path")"
|
||||
}
|
||||
|
||||
# Waarde van een header uit de laatst opgehaalde respons (hoofdletterongevoelig)
|
||||
header() {
|
||||
tr -d '\r' < "$work/headers" | grep -i "^$1:" | head -n 1 | cut -d: -f2- | sed 's/^[[:space:]]*//' || true
|
||||
}
|
||||
|
||||
check_security_headers() {
|
||||
local label="$1" name
|
||||
local names=(Content-Security-Policy Strict-Transport-Security X-Content-Type-Options X-Frame-Options Referrer-Policy)
|
||||
if [ "$test_mode" -eq 1 ]; then names+=(X-Robots-Tag); fi
|
||||
for name in "${names[@]}"; do
|
||||
if [ -z "$(header "$name")" ]; then
|
||||
fail "$label: header $name ontbreekt"
|
||||
fi
|
||||
done
|
||||
}
|
||||
|
||||
# Een 200 met de bytes van het verwachte bestand uit dist
|
||||
expect_file() {
|
||||
local path="$1" file="$2"
|
||||
fetch "$path"
|
||||
if [ "$status" != "200" ]; then
|
||||
fail "$path: status $status, verwacht 200"
|
||||
elif ! cmp -s "$work/body" "$dist/$file"; then
|
||||
fail "$path: antwoord is niet gelijk aan $file uit dist (oude serverconfig of oude build?)"
|
||||
fi
|
||||
check_security_headers "$path"
|
||||
}
|
||||
|
||||
# Een 301 naar een pad (Location mag absoluut of relatief zijn)
|
||||
expect_redirect() {
|
||||
local path="$1" target="$2" location
|
||||
fetch "$path"
|
||||
if [ "$status" != "301" ]; then
|
||||
fail "$path: status $status, verwacht 301"
|
||||
else
|
||||
location="$(header Location)"
|
||||
location="${location#http://*/}"
|
||||
location="${location#https://*/}"
|
||||
if [[ "$location" != /* ]]; then location="/$location"; fi
|
||||
if [ "$location" != "$target" ]; then
|
||||
fail "$path: Location '$(header Location)', verwacht pad $target"
|
||||
fi
|
||||
fi
|
||||
check_security_headers "$path"
|
||||
}
|
||||
|
||||
for file in index.html over-mij.html soorten-fotoshoots/newborn.html 404.html; do
|
||||
if [ ! -f "$dist/$file" ]; then
|
||||
echo "Geen $file in $dist" >&2
|
||||
exit 2
|
||||
fi
|
||||
done
|
||||
|
||||
# De server moet bereikbaar zijn; kort herhalen zoals de oude controle
|
||||
if ! curl -sS --retry 5 --retry-delay 3 --retry-connrefused --max-time 30 \
|
||||
-o /dev/null "$base/"; then
|
||||
echo "Niet bereikbaar: $base/" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
expect_file / index.html
|
||||
expect_file /over-mij over-mij.html
|
||||
expect_file /soorten-fotoshoots/newborn soorten-fotoshoots/newborn.html
|
||||
|
||||
fetch /onbekend-pad-voor-controle
|
||||
if [ "$status" != "404" ]; then
|
||||
fail "/onbekend-pad-voor-controle: status $status, verwacht 404"
|
||||
elif ! cmp -s "$work/body" "$dist/404.html"; then
|
||||
fail "/onbekend-pad-voor-controle: antwoord is niet gelijk aan 404.html uit dist"
|
||||
fi
|
||||
check_security_headers /onbekend-pad-voor-controle
|
||||
|
||||
expect_redirect /over-mij/ /over-mij
|
||||
expect_redirect /Over-Mij /over-mij
|
||||
|
||||
# Compressie van de JavaScript uit index.html
|
||||
script="$(grep -o '/assets/[A-Za-z0-9_./-]*\.js' "$dist/index.html" | head -n 1 || true)"
|
||||
if [ -z "$script" ]; then
|
||||
fail "geen /assets/*.js gevonden in index.html om de compressie te controleren"
|
||||
else
|
||||
fetch "$script" -H 'Accept-Encoding: gzip'
|
||||
if [ "$status" != "200" ]; then
|
||||
fail "$script: status $status, verwacht 200"
|
||||
elif [ "$(header Content-Encoding)" != "gzip" ]; then
|
||||
if [ "$test_mode" -eq 1 ]; then
|
||||
fail "$script: geen Content-Encoding: gzip"
|
||||
else
|
||||
echo "WAARSCHUWING: $script wordt niet gecomprimeerd (de webhost beslist)" >&2
|
||||
fi
|
||||
fi
|
||||
fi
|
||||
|
||||
if [ "$failures" -gt 0 ]; then
|
||||
echo "Controle mislukt ($failures fout(en)) voor $base" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "Controle geslaagd voor $base"
|
||||
@@ -0,0 +1,533 @@
|
||||
import { execFile, spawnSync } from 'node:child_process';
|
||||
import { existsSync } from 'node:fs';
|
||||
import {
|
||||
mkdir,
|
||||
mkdtemp,
|
||||
readdir,
|
||||
readFile,
|
||||
rm,
|
||||
writeFile,
|
||||
} from 'node:fs/promises';
|
||||
import {
|
||||
createServer,
|
||||
type IncomingMessage,
|
||||
type Server,
|
||||
type ServerResponse,
|
||||
} from 'node:http';
|
||||
import type { AddressInfo } from 'node:net';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { dirname, join, resolve } from 'node:path';
|
||||
import { gzipSync } from 'node:zlib';
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest';
|
||||
import { startPreviewServer } from '../config/previewServer.ts';
|
||||
import { securityHeaders } from '../config/securityHeaders.ts';
|
||||
import { createFixtureSite, type FixtureSite } from './support/fixtureSite.ts';
|
||||
|
||||
// De deploy-scripts uit web/deploy: de artefactcontrole, de controle na een
|
||||
// deploy en de upload naar productie (BR-HST-14, 15, 18). Alles draait tegen
|
||||
// een fixture-site, een stub of een lokaal doel; er gaat niets het netwerk op.
|
||||
|
||||
const inCi = Boolean(process.env.CI);
|
||||
const deployDir = resolve('deploy').replaceAll('\\', '/');
|
||||
|
||||
// Op Windows is `bash` in het PATH soms de WSL-launcher in System32; die
|
||||
// start een distributie. Daarom Git Bash zoeken, naast git.exe of in het PATH.
|
||||
function findBash(): string | undefined {
|
||||
if (process.platform !== 'win32') {
|
||||
return spawnSync('bash', ['-c', 'true']).status === 0
|
||||
? 'bash'
|
||||
: undefined;
|
||||
}
|
||||
const candidates = (process.env.PATH ?? '')
|
||||
.split(';')
|
||||
.filter(Boolean)
|
||||
.flatMap((dir) => [
|
||||
join(dir, 'bash.exe'),
|
||||
join(dir, '..', 'bin', 'bash.exe'),
|
||||
join(dir, '..', 'usr', 'bin', 'bash.exe'),
|
||||
])
|
||||
.filter((candidate) => !/system32/i.test(candidate));
|
||||
return candidates.find(
|
||||
(candidate) =>
|
||||
existsSync(candidate) &&
|
||||
spawnSync(candidate, ['-c', 'true']).status === 0,
|
||||
);
|
||||
}
|
||||
|
||||
const hasCommand = (name: string) =>
|
||||
spawnSync(name, ['--version'], { stdio: 'ignore' }).status === 0;
|
||||
|
||||
const bashBin = findBash();
|
||||
const toolsMissing = !bashBin || !hasCommand('curl');
|
||||
|
||||
// Zonder bash of curl: in CI een duidelijke fout, lokaal een zichtbare melding
|
||||
if (toolsMissing) {
|
||||
describe('deploy-scripts', () => {
|
||||
it('bash of curl niet gevonden: deploy-scripttests overgeslagen', (context) => {
|
||||
if (inCi) throw new Error('bash of curl ontbreekt in CI');
|
||||
console.log(context.task.name);
|
||||
context.skip();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
interface Run {
|
||||
code: number;
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
}
|
||||
|
||||
function runScript(
|
||||
script: string,
|
||||
args: string[],
|
||||
env: Record<string, string> = {},
|
||||
): Promise<Run> {
|
||||
return new Promise((done) => {
|
||||
execFile(
|
||||
bashBin ?? 'bash',
|
||||
[`${deployDir}/${script}`, ...args],
|
||||
{ env: { ...process.env, ...env }, maxBuffer: 16 * 1024 * 1024 },
|
||||
(error, stdout, stderr) =>
|
||||
done({
|
||||
code: error ? Number(error.code ?? 1) : 0,
|
||||
stdout,
|
||||
stderr,
|
||||
}),
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
const slash = (path: string) => path.replaceAll('\\', '/');
|
||||
|
||||
const temporaryDirs: string[] = [];
|
||||
async function makeTemp(prefix: string): Promise<string> {
|
||||
const dir = await mkdtemp(join(tmpdir(), prefix));
|
||||
temporaryDirs.push(dir);
|
||||
return dir;
|
||||
}
|
||||
afterAll(async () => {
|
||||
await Promise.all(
|
||||
temporaryDirs.map((dir) => rm(dir, { recursive: true, force: true })),
|
||||
);
|
||||
});
|
||||
|
||||
async function tree(dir: string, base = dir): Promise<string[]> {
|
||||
const result: string[] = [];
|
||||
for (const entry of await readdir(dir, { withFileTypes: true })) {
|
||||
const full = join(dir, entry.name);
|
||||
if (entry.isDirectory()) result.push(...(await tree(full, base)));
|
||||
else result.push(slash(full.slice(base.length + 1)));
|
||||
}
|
||||
return result.sort();
|
||||
}
|
||||
|
||||
async function write(dir: string, file: string, content = file) {
|
||||
const target = join(dir, file);
|
||||
await mkdir(dirname(target), { recursive: true });
|
||||
await writeFile(target, content);
|
||||
}
|
||||
|
||||
// Een minimale, geldige dist voor de artefactcontrole en de upload
|
||||
const validFiles = [
|
||||
'index.html',
|
||||
'404.html',
|
||||
'over-mij.html',
|
||||
'soorten-fotoshoots/newborn.html',
|
||||
'assets/a.js',
|
||||
'robots.txt',
|
||||
];
|
||||
async function makeDist(): Promise<string> {
|
||||
const dir = await makeTemp('andreaslop-dist-');
|
||||
for (const file of validFiles) await write(dir, file);
|
||||
return dir;
|
||||
}
|
||||
|
||||
describe.skipIf(toolsMissing)('check-artifact.sh', () => {
|
||||
it('laat een geldige build door en meldt wat het vond', async () => {
|
||||
const dist = await makeDist();
|
||||
const run = await runScript('check-artifact.sh', [slash(dist)]);
|
||||
expect(run.code).toBe(0);
|
||||
expect(run.stdout).toContain('index.html');
|
||||
expect(run.stdout).toContain('404.html');
|
||||
expect(run.stdout).toContain('over-mij.html');
|
||||
});
|
||||
|
||||
it.each(['index.html', '404.html', 'over-mij.html'])(
|
||||
'weigert een build zonder %s',
|
||||
async (file) => {
|
||||
const dist = await makeDist();
|
||||
await rm(join(dist, file));
|
||||
const run = await runScript('check-artifact.sh', [slash(dist)]);
|
||||
expect(run.code).toBe(1);
|
||||
expect(run.stderr).toContain(`${file} ontbreekt`);
|
||||
},
|
||||
);
|
||||
|
||||
it('weigert een build met een servermap', async () => {
|
||||
const dist = await makeDist();
|
||||
await write(dist, 'server/server.js');
|
||||
const run = await runScript('check-artifact.sh', [slash(dist)]);
|
||||
expect(run.code).toBe(1);
|
||||
expect(run.stderr).toContain('server');
|
||||
});
|
||||
|
||||
it('weigert een source map, ook diep in de map', async () => {
|
||||
const dist = await makeDist();
|
||||
await write(dist, 'assets/deep/a.js.map');
|
||||
const run = await runScript('check-artifact.sh', [slash(dist)]);
|
||||
expect(run.code).toBe(1);
|
||||
expect(run.stderr).toContain('a.js.map');
|
||||
});
|
||||
|
||||
it('weigert een map die niet bestaat', async () => {
|
||||
const run = await runScript('check-artifact.sh', [
|
||||
slash(join(tmpdir(), 'bestaat-niet-andreaslop')),
|
||||
]);
|
||||
expect(run.code).not.toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
// Een kleine server met de bedoelde regels (nieuw) of met het oude gedrag van
|
||||
// de SPA-config (oud: elk pad geeft index.html met 200). Bij 'nieuw' kan een
|
||||
// header of de gzip weggelaten worden.
|
||||
interface StubOptions {
|
||||
behaviour: 'new' | 'old';
|
||||
omitHeader?: string;
|
||||
gzip?: boolean;
|
||||
robots?: boolean;
|
||||
}
|
||||
|
||||
async function startStub(
|
||||
dir: string,
|
||||
options: StubOptions,
|
||||
): Promise<{ origin: string; close: () => Promise<void> }> {
|
||||
const headers: Record<string, string> = {
|
||||
...securityHeaders('production'),
|
||||
};
|
||||
if (options.robots) headers['X-Robots-Tag'] = 'noindex, nofollow';
|
||||
if (options.omitHeader) delete headers[options.omitHeader];
|
||||
|
||||
const files = new Set(await tree(dir));
|
||||
const pages = new Set(
|
||||
[...files]
|
||||
.filter((file) => file.endsWith('.html') && file !== '404.html')
|
||||
.map((file) =>
|
||||
file === 'index.html' ? '/' : '/' + file.slice(0, -5),
|
||||
),
|
||||
);
|
||||
|
||||
const reply = async (
|
||||
request: IncomingMessage,
|
||||
response: ServerResponse,
|
||||
status: number,
|
||||
file: string,
|
||||
) => {
|
||||
const body = await readFile(join(dir, file));
|
||||
const gzipped =
|
||||
options.gzip === true &&
|
||||
file.endsWith('.js') &&
|
||||
/gzip/.test(request.headers['accept-encoding'] ?? '');
|
||||
response.writeHead(status, {
|
||||
...headers,
|
||||
...(gzipped ? { 'Content-Encoding': 'gzip' } : {}),
|
||||
});
|
||||
response.end(gzipped ? gzipSync(body) : body);
|
||||
};
|
||||
const redirect = (response: ServerResponse, location: string) => {
|
||||
response.writeHead(301, { ...headers, Location: location });
|
||||
response.end();
|
||||
};
|
||||
|
||||
const server: Server = createServer((request, response) => {
|
||||
const path = (request.url ?? '/').split('?')[0];
|
||||
void (async () => {
|
||||
if (options.behaviour === 'old') {
|
||||
// Oude nginx: bestaand bestand, anders de homepage met 200
|
||||
const file = path.slice(1);
|
||||
await reply(
|
||||
request,
|
||||
response,
|
||||
200,
|
||||
files.has(file) ? file : 'index.html',
|
||||
);
|
||||
return;
|
||||
}
|
||||
if (files.has(path.slice(1)) && path !== '/') {
|
||||
await reply(request, response, 200, path.slice(1));
|
||||
} else if (pages.has(path)) {
|
||||
await reply(
|
||||
request,
|
||||
response,
|
||||
200,
|
||||
path === '/' ? 'index.html' : `${path.slice(1)}.html`,
|
||||
);
|
||||
} else if (path.length > 1 && path.endsWith('/')) {
|
||||
redirect(response, path.slice(0, -1));
|
||||
} else if (pages.has(path.toLowerCase())) {
|
||||
redirect(response, path.toLowerCase());
|
||||
} else {
|
||||
await reply(request, response, 404, '404.html');
|
||||
}
|
||||
})();
|
||||
});
|
||||
await new Promise<void>((done) => server.listen(0, '127.0.0.1', done));
|
||||
const { port } = server.address() as AddressInfo;
|
||||
return {
|
||||
origin: `http://127.0.0.1:${port}`,
|
||||
close: () =>
|
||||
new Promise<void>((done, fail) => {
|
||||
server.close((error) => (error ? fail(error) : done()));
|
||||
server.closeAllConnections();
|
||||
}),
|
||||
};
|
||||
}
|
||||
|
||||
describe.skipIf(toolsMissing)('verify-deployment.sh', () => {
|
||||
let site: FixtureSite;
|
||||
let dist: string;
|
||||
beforeAll(async () => {
|
||||
site = await createFixtureSite();
|
||||
dist = slash(site.dir);
|
||||
// De homepage verwijst naar de JavaScript, voor de compressiecontrole
|
||||
await writeFile(
|
||||
join(site.dir, 'index.html'),
|
||||
'<!doctype html><html><head><script src="/assets/index-AbC123xYz.js"></script></head><body>fixture:index.html</body></html>',
|
||||
);
|
||||
});
|
||||
afterAll(() => site.remove());
|
||||
|
||||
const withStub = async <T>(
|
||||
options: StubOptions,
|
||||
action: (origin: string) => Promise<T>,
|
||||
) => {
|
||||
const stub = await startStub(site.dir, options);
|
||||
try {
|
||||
return await action(stub.origin);
|
||||
} finally {
|
||||
await stub.close();
|
||||
}
|
||||
};
|
||||
|
||||
it('slaagt tegen de previewserver op de fixture-site', async () => {
|
||||
const server = await startPreviewServer(site.dir, 0);
|
||||
const { port } = server.address() as AddressInfo;
|
||||
try {
|
||||
const run = await runScript('verify-deployment.sh', [
|
||||
`http://127.0.0.1:${port}`,
|
||||
dist,
|
||||
]);
|
||||
expect(run.stderr).not.toContain('FOUT');
|
||||
expect(run.code).toBe(0);
|
||||
expect(run.stdout).toContain('Controle geslaagd');
|
||||
} finally {
|
||||
await new Promise<void>((done) => {
|
||||
server.close(() => done());
|
||||
server.closeAllConnections();
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
it('slaagt tegen een server met de bedoelde regels, ook met een slash aan het eind van de URL', async () => {
|
||||
await withStub({ behaviour: 'new' }, async (origin) => {
|
||||
const run = await runScript('verify-deployment.sh', [
|
||||
`${origin}/`,
|
||||
dist,
|
||||
]);
|
||||
expect(run.stderr).not.toContain('FOUT');
|
||||
expect(run.code).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
it('faalt tegen het oude gedrag (homepage voor elk pad) en noemt de bytes van /over-mij (V11)', async () => {
|
||||
await withStub({ behaviour: 'old' }, async (origin) => {
|
||||
const run = await runScript('verify-deployment.sh', [origin, dist]);
|
||||
expect(run.code).toBe(1);
|
||||
expect(run.stderr).toContain(
|
||||
'/over-mij: antwoord is niet gelijk aan over-mij.html',
|
||||
);
|
||||
expect(run.stderr).toContain('status 200, verwacht 404');
|
||||
expect(run.stderr).toContain(
|
||||
'/over-mij/: status 200, verwacht 301',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
it.each(Object.keys(securityHeaders('production')))(
|
||||
'faalt als %s ontbreekt',
|
||||
async (name) => {
|
||||
await withStub(
|
||||
{ behaviour: 'new', omitHeader: name },
|
||||
async (origin) => {
|
||||
const run = await runScript('verify-deployment.sh', [
|
||||
origin,
|
||||
dist,
|
||||
]);
|
||||
expect(run.code).toBe(1);
|
||||
expect(run.stderr).toContain(`header ${name} ontbreekt`);
|
||||
},
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it('met --test: slaagt met X-Robots-Tag en gzip', async () => {
|
||||
await withStub(
|
||||
{ behaviour: 'new', robots: true, gzip: true },
|
||||
async (origin) => {
|
||||
const run = await runScript('verify-deployment.sh', [
|
||||
origin,
|
||||
dist,
|
||||
'--test',
|
||||
]);
|
||||
expect(run.stderr).not.toContain('FOUT');
|
||||
expect(run.code).toBe(0);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it('met --test: faalt zonder X-Robots-Tag', async () => {
|
||||
await withStub({ behaviour: 'new', gzip: true }, async (origin) => {
|
||||
const run = await runScript('verify-deployment.sh', [
|
||||
origin,
|
||||
dist,
|
||||
'--test',
|
||||
]);
|
||||
expect(run.code).toBe(1);
|
||||
expect(run.stderr).toContain('header X-Robots-Tag ontbreekt');
|
||||
});
|
||||
});
|
||||
|
||||
it('met --test: faalt zonder gzip, zonder --test is dat een waarschuwing', async () => {
|
||||
await withStub(
|
||||
{ behaviour: 'new', robots: true, gzip: false },
|
||||
async (origin) => {
|
||||
const strict = await runScript('verify-deployment.sh', [
|
||||
origin,
|
||||
dist,
|
||||
'--test',
|
||||
]);
|
||||
expect(strict.code).toBe(1);
|
||||
expect(strict.stderr).toContain('geen Content-Encoding: gzip');
|
||||
|
||||
const lenient = await runScript('verify-deployment.sh', [
|
||||
origin,
|
||||
dist,
|
||||
]);
|
||||
expect(lenient.code).toBe(0);
|
||||
expect(lenient.stderr).toContain('WAARSCHUWING');
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it.each(['', 'ftp://example.nl', 'http://a b', 'example.nl'])(
|
||||
'weigert de ongeldige URL %j',
|
||||
async (url) => {
|
||||
const run = await runScript('verify-deployment.sh', [url, dist]);
|
||||
expect(run.code).toBe(2);
|
||||
expect(run.stderr).toContain('Ongeldige URL');
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
// lftp staat niet overal (lokaal vaak niet; CI installeert het): zonder lftp
|
||||
// lokaal een zichtbare melding, in CI een fout
|
||||
const lftpMissing = !hasCommand('lftp') || process.platform === 'win32';
|
||||
if (lftpMissing) {
|
||||
describe('upload-production.sh', () => {
|
||||
it('lftp niet gevonden: uploadtest overgeslagen (de lftp-syntaxis blijft onbewezen)', (context) => {
|
||||
if (inCi) throw new Error('lftp ontbreekt in CI');
|
||||
console.log(context.task.name);
|
||||
context.skip();
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
describe.skipIf(toolsMissing || lftpMissing)('upload-production.sh', () => {
|
||||
const upload = async (
|
||||
dist: string,
|
||||
target: string,
|
||||
pass?: '1' | '2' | '3',
|
||||
) =>
|
||||
runScript('upload-production.sh', [slash(dist), slash(target)], {
|
||||
LFTP_OPEN: 'file:///',
|
||||
...(pass ? { UPLOAD_PASS: pass } : {}),
|
||||
});
|
||||
|
||||
async function setup() {
|
||||
const dist = await makeDist();
|
||||
const target = await makeTemp('andreaslop-target-');
|
||||
await write(target, 'stale.txt');
|
||||
return { dist, target };
|
||||
}
|
||||
|
||||
it('zet de rondes in volgorde: eerst alles behalve HTML, dan HTML, dan opruimen', async () => {
|
||||
const { dist, target } = await setup();
|
||||
|
||||
const first = await upload(dist, target, '1');
|
||||
expect(first.code).toBe(0);
|
||||
expect(await tree(target)).toEqual([
|
||||
'assets/a.js',
|
||||
'robots.txt',
|
||||
'stale.txt',
|
||||
]);
|
||||
|
||||
const second = await upload(dist, target, '2');
|
||||
expect(second.code).toBe(0);
|
||||
expect(await tree(target)).toEqual([
|
||||
'404.html',
|
||||
'assets/a.js',
|
||||
'index.html',
|
||||
'over-mij.html',
|
||||
'robots.txt',
|
||||
'soorten-fotoshoots/newborn.html',
|
||||
'stale.txt',
|
||||
'web.config',
|
||||
]);
|
||||
|
||||
const third = await upload(dist, target, '3');
|
||||
expect(third.code).toBe(0);
|
||||
expect(await tree(target)).toEqual([
|
||||
'404.html',
|
||||
'assets/a.js',
|
||||
'index.html',
|
||||
'over-mij.html',
|
||||
'robots.txt',
|
||||
'soorten-fotoshoots/newborn.html',
|
||||
'web.config',
|
||||
]);
|
||||
});
|
||||
|
||||
it('zet alle assets vóór de eerste HTML (FR-PR-18) en de web.config vóór de HTML', async () => {
|
||||
const { dist, target } = await setup();
|
||||
const run = await upload(dist, target);
|
||||
expect(run.code).toBe(0);
|
||||
|
||||
const lines = run.stdout.split('\n');
|
||||
const at = (needle: string) =>
|
||||
lines.findIndex((line) => line.includes(needle));
|
||||
const firstHtml = lines.findIndex((line) => /\.html/.test(line));
|
||||
expect(at('assets/a.js')).toBeGreaterThanOrEqual(0);
|
||||
expect(at('assets/a.js')).toBeLessThan(firstHtml);
|
||||
expect(at('web.config')).toBeGreaterThanOrEqual(0);
|
||||
expect(at('web.config')).toBeLessThan(firstHtml);
|
||||
|
||||
const expected = [...validFiles, 'web.config'].sort();
|
||||
expect(await tree(target)).toEqual(expected);
|
||||
});
|
||||
|
||||
it('weigert een ongeldige build en uploadt dan niets', async () => {
|
||||
const { dist, target } = await setup();
|
||||
await rm(join(dist, 'index.html'));
|
||||
const run = await upload(dist, target);
|
||||
expect(run.code).not.toBe(0);
|
||||
expect(await tree(target)).toEqual(['stale.txt']);
|
||||
});
|
||||
|
||||
it('neemt de web.config uit deploy/iis over', async () => {
|
||||
const { dist, target } = await setup();
|
||||
const run = await upload(dist, target);
|
||||
expect(run.code).toBe(0);
|
||||
expect(await readFile(join(target, 'web.config'), 'utf8')).toBe(
|
||||
await readFile(join(deployDir, 'iis/web.config'), 'utf8'),
|
||||
);
|
||||
});
|
||||
});
|
||||
+82
-62
@@ -1,5 +1,5 @@
|
||||
// Lighthouse CI tegen de gebouwde site (`pnpm preview`), zodat de echte
|
||||
// securityheaders en de SPA-fallback meetellen. Doelen: NFR-P-01, NFR-A-01,
|
||||
// securityheaders en de 404-afhandeling meetellen. Doelen: NFR-P-01, NFR-A-01,
|
||||
// NFR-S-01/02. Dit is de mobiele meting; lighthouserc.desktop.cjs bouwt hierop
|
||||
// voort voor desktop. `pnpm lighthouse` draait beide.
|
||||
|
||||
@@ -19,35 +19,62 @@ const indexedPaths = [
|
||||
'/contact',
|
||||
];
|
||||
const noindexPaths = ['/privacyverklaring'];
|
||||
const notFoundPath = '/404.html';
|
||||
|
||||
// Homepage mobiel voorlopig 0,8: de foto's zijn nog niet responsive en de
|
||||
// titel verschijnt pas na de JavaScript. Komt terug op 0,9 met responsive
|
||||
// afbeeldingen uit de API/CMS en prerendering (NFR-P-01).
|
||||
const homeMobilePerformance = 0.8;
|
||||
// Lighthouse refuses a main document with an error status, so the preview
|
||||
// serves the 404 page with status 200 on this route only, and only when it is
|
||||
// started with --audit-route (BR-HST-22). /404.html itself is a real 404.
|
||||
const notFoundPath = '/__audit/404';
|
||||
|
||||
// Indexed content pages whose largest paint is a photo, mobile 0.85 for now.
|
||||
// Lighthouse simulates a slow connection: the photo is only requested once
|
||||
// the main bundle and the page's own chunk have run, so these pages land on
|
||||
// LCP ~3.2s and a score of ~0.895, right on 0.9 (measured on /over-mij and
|
||||
// /soorten-fotoshoots; fewer image bytes do not move it). The shoot pages
|
||||
// (largest paint: the first story photo) are in the same position. Back to
|
||||
// 0.9 with prerendering or a smaller main bundle (NFR-P-01).
|
||||
const photoPagePaths = [
|
||||
'/over-mij',
|
||||
'/soorten-fotoshoots',
|
||||
'/soorten-fotoshoots/newborn',
|
||||
'/soorten-fotoshoots/zwangerschap',
|
||||
'/soorten-fotoshoots/gezin',
|
||||
'/soorten-fotoshoots/loveshoot',
|
||||
'/soorten-fotoshoots/portret',
|
||||
];
|
||||
const photoPageMobilePerformance = 0.85;
|
||||
// Mobile performance exceptions, keyed by path. Every entry needs a recorded
|
||||
// decision and a floor below 0.9 (BR-HST-23); a page without an entry must
|
||||
// reach 0.9. These are the temporary exceptions carried over from the
|
||||
// frontend-shell feature, until the final measurement of prerendering:
|
||||
// - the homepage (0.8): the photos are not responsive yet and the title only
|
||||
// appears after the JavaScript (NFR-P-01).
|
||||
// - the indexed content pages whose largest paint is a photo (0.85):
|
||||
// Lighthouse simulates a slow connection and the photo is only requested
|
||||
// once the main bundle and the page's own chunk have run, so they land on
|
||||
// LCP ~3.2s and a score of ~0.895, right on 0.9 (measured on /over-mij and
|
||||
// /soorten-fotoshoots; fewer image bytes do not move it). The shoot pages
|
||||
// (largest paint: the first story photo) are in the same position.
|
||||
const temporary = 'tijdelijk, tot de eindmeting van prerendering';
|
||||
const mobileExceptions = {
|
||||
'/': { minScore: 0.8, decision: temporary },
|
||||
'/over-mij': { minScore: 0.85, decision: temporary },
|
||||
'/soorten-fotoshoots': { minScore: 0.85, decision: temporary },
|
||||
'/soorten-fotoshoots/newborn': { minScore: 0.85, decision: temporary },
|
||||
'/soorten-fotoshoots/zwangerschap': { minScore: 0.85, decision: temporary },
|
||||
'/soorten-fotoshoots/gezin': { minScore: 0.85, decision: temporary },
|
||||
'/soorten-fotoshoots/loveshoot': { minScore: 0.85, decision: temporary },
|
||||
'/soorten-fotoshoots/portret': { minScore: 0.85, decision: temporary },
|
||||
};
|
||||
|
||||
// The exceptions of the content pages with a photo as largest paint
|
||||
const photoPagePaths = Object.keys(mobileExceptions).filter(
|
||||
(path) => path !== '/',
|
||||
);
|
||||
|
||||
const validateExceptions = (exceptions, paths) => {
|
||||
for (const [path, { minScore, decision }] of Object.entries(exceptions)) {
|
||||
if (!paths.includes(path)) {
|
||||
throw new Error(`Exception for unknown page ${path}`);
|
||||
}
|
||||
if (typeof decision !== 'string' || decision.trim() === '') {
|
||||
throw new Error(`Exception for ${path} has no decision`);
|
||||
}
|
||||
if (!(minScore < 0.9)) {
|
||||
throw new Error(`Exception for ${path} is not below 0.9`);
|
||||
}
|
||||
}
|
||||
};
|
||||
validateExceptions(mobileExceptions, indexedPaths);
|
||||
|
||||
// Performance hangt af van de snelheid van de meetmachine: Lighthouse vertraagt
|
||||
// de CPU 4x ten opzichte van een snelle desktop. Op de CI-runner (Raspberry Pi)
|
||||
// valt de score daardoor 30-40 punten lager uit dan op een pc. In CI daarom
|
||||
// alleen melden (LIGHTHOUSE_PERFORMANCE=warn); lokaal in `pnpm check` blokkerend.
|
||||
// numberOfRuns is bewust 1: een pagina die precies op 0,90 zit kan `pnpm check`
|
||||
// toevallig laten falen.
|
||||
const performanceLevel =
|
||||
process.env.LIGHTHOUSE_PERFORMANCE === 'warn' ? 'warn' : 'error';
|
||||
|
||||
@@ -69,10 +96,32 @@ const seoBasics = {
|
||||
const escape = (path) => path.replace(/[.*+?^${}()|[\]\\/]/g, '\\$&');
|
||||
const exact = (paths) => `^${origin}(${paths.map(escape).join('|')})$`;
|
||||
|
||||
// Indexed pages without a mobile exception
|
||||
const otherIndexedPaths = indexedPaths.filter(
|
||||
(path) => path !== '/' && !photoPagePaths.includes(path),
|
||||
);
|
||||
// One entry per page with an exception, one for all other indexed pages
|
||||
const buildIndexedEntries = (exceptions, paths) => {
|
||||
const others = paths.filter((path) => !(path in exceptions));
|
||||
return [
|
||||
...Object.entries(exceptions).map(([path, { minScore }]) => ({
|
||||
matchingUrlPattern: exact([path]),
|
||||
assertions: {
|
||||
...quality,
|
||||
'categories:performance': [performanceLevel, { minScore }],
|
||||
'categories:seo': ['error', { minScore: 1 }],
|
||||
},
|
||||
})),
|
||||
// Empty until another indexed page without an exception exists
|
||||
...(others.length > 0
|
||||
? [
|
||||
{
|
||||
matchingUrlPattern: exact(others),
|
||||
assertions: {
|
||||
...quality,
|
||||
'categories:seo': ['error', { minScore: 1 }],
|
||||
},
|
||||
},
|
||||
]
|
||||
: []),
|
||||
];
|
||||
};
|
||||
|
||||
module.exports = {
|
||||
performanceLevel,
|
||||
@@ -80,9 +129,13 @@ module.exports = {
|
||||
noindexPaths,
|
||||
notFoundPath,
|
||||
photoPagePaths,
|
||||
mobileExceptions,
|
||||
validateExceptions,
|
||||
buildIndexedEntries,
|
||||
ci: {
|
||||
collect: {
|
||||
startServerCommand: 'pnpm preview --port 4173 --strictPort',
|
||||
startServerCommand:
|
||||
'pnpm preview --port 4173 --strictPort --audit-route',
|
||||
startServerReadyPattern: 'Local',
|
||||
url: [...indexedPaths, ...noindexPaths, notFoundPath].map(
|
||||
(path) => origin + path,
|
||||
@@ -101,40 +154,7 @@ module.exports = {
|
||||
// to 0.9. Every URL matching an entry must pass it, so an
|
||||
// exception may only match the pages it names.
|
||||
assertMatrix: [
|
||||
{
|
||||
matchingUrlPattern: exact(['/']),
|
||||
assertions: {
|
||||
...quality,
|
||||
'categories:performance': [
|
||||
performanceLevel,
|
||||
{ minScore: homeMobilePerformance },
|
||||
],
|
||||
'categories:seo': ['error', { minScore: 1 }],
|
||||
},
|
||||
},
|
||||
{
|
||||
matchingUrlPattern: exact(photoPagePaths),
|
||||
assertions: {
|
||||
...quality,
|
||||
'categories:performance': [
|
||||
performanceLevel,
|
||||
{ minScore: photoPageMobilePerformance },
|
||||
],
|
||||
'categories:seo': ['error', { minScore: 1 }],
|
||||
},
|
||||
},
|
||||
// Empty until another indexed page without an exception exists
|
||||
...(otherIndexedPaths.length > 0
|
||||
? [
|
||||
{
|
||||
matchingUrlPattern: exact(otherIndexedPaths),
|
||||
assertions: {
|
||||
...quality,
|
||||
'categories:seo': ['error', { minScore: 1 }],
|
||||
},
|
||||
},
|
||||
]
|
||||
: []),
|
||||
...buildIndexedEntries(mobileExceptions, indexedPaths),
|
||||
{
|
||||
matchingUrlPattern: exact(noindexPaths),
|
||||
assertions: {
|
||||
|
||||
@@ -1,10 +1,19 @@
|
||||
// Types voor lighthouserc.cjs, zodat een test de URL-lijsten kan vergelijken
|
||||
// met het pagina-register
|
||||
type MobileExceptions = Record<string, { minScore: number; decision: string }>;
|
||||
|
||||
declare const config: {
|
||||
performanceLevel: 'warn' | 'error';
|
||||
indexedPaths: string[];
|
||||
noindexPaths: string[];
|
||||
notFoundPath: string;
|
||||
photoPagePaths: string[];
|
||||
mobileExceptions: MobileExceptions;
|
||||
validateExceptions: (exceptions: MobileExceptions, paths: string[]) => void;
|
||||
buildIndexedEntries: (
|
||||
exceptions: MobileExceptions,
|
||||
paths: string[],
|
||||
) => { matchingUrlPattern: string; assertions: Record<string, unknown> }[];
|
||||
ci: unknown;
|
||||
};
|
||||
|
||||
|
||||
@@ -642,8 +642,8 @@ describe('pagina-register', () => {
|
||||
.map(([path]) => path);
|
||||
expect(lighthouseConfig.indexedPaths).toEqual(indexed);
|
||||
expect(lighthouseConfig.noindexPaths).toEqual(noindex);
|
||||
// Lighthouse weigert een 404-pagina; de preview-server geeft het
|
||||
// bestand 404.html als bestandsverzoek met status 200 (BR-SRV-04)
|
||||
expect(lighthouseConfig.notFoundPath).toBe('/404.html');
|
||||
// Lighthouse weigert een foutstatus; de preview-server geeft de 404-pagina
|
||||
// alleen via de opt-in route met status 200. /404.html is een echte 404
|
||||
expect(lighthouseConfig.notFoundPath).toBe('/__audit/404');
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user