Adds a preview server that follows the real server rules
Lighthouse and the browser tests need a real 404 status, the .html mapping and the production headers, which vite preview does not give. It is not wired into the scripts yet. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
+20
-17
@@ -224,21 +224,21 @@ The unknowns that can invalidate the design come first. Steps 3 to 6 prove Start
|
||||
|
||||
Files are new `config/*` files and `src/test/htmlArbitraries.ts`. Config files are Dutch-commented like their neighbours. They run under Node type stripping: relative imports with `.ts`, no aliases.
|
||||
|
||||
### Step 7: `config/pageFiles.ts` [ ]
|
||||
### Step 7: `config/pageFiles.ts` [x]
|
||||
|
||||
- Executor: Sonnet.
|
||||
- Implements: BR-BLD-02, 03; domain-entities `config/pageFiles.ts`.
|
||||
- Do: create the pure module with `NOT_FOUND_PATH = '/404'`, `NOT_FOUND_FILE = '404.html'`, `pageFile(path: string): string` (`/` gives `index.html`; otherwise the path without its leading slash plus `.html`) and `pagePath(file: string): string | undefined` (inverse; `undefined` for `404.html` and anything that is not a `.html` page file). Comment on why one mapping serves `vite.config.ts`, the runner and the preview server.
|
||||
- Done when: `pnpm exec tsc --noEmit` clean. (Switching `vite.config.ts` to import it happens in Step 24, to keep B2 off B1's files.)
|
||||
|
||||
### Step 8: `config/inlineScripts.ts` [ ]
|
||||
### Step 8: `config/inlineScripts.ts` [x]
|
||||
|
||||
- Executor: Sonnet.
|
||||
- Implements: BR-SCR-01 to 11, 22 (nothing to build for 22); FR-PR-19, 20; D2, D3.
|
||||
- Do: create the module with the exports of component-methods.md (`MovedScript`, `ExternalizeResult`, `externalizeInlineScripts`, `findExecutableInlineScripts`) and no dependency except `node:crypto` for SHA-256. Implement one internal scanner (BR-SCR-02) that yields script elements with their range, verbatim attribute text and body; the classification of flowchart 1.1 (BR-SCR-04: `src` attribute in any form, empty body, type list, `module`); the unsupported-form checks that throw (BR-SCR-05: `async`/`defer` on a classic script, `<!--` in the body, relative specifier in a module body; error type or message with the codes `UNSUPPORTED_SCRIPT` and `UNTERMINATED_SCRIPT` so the runner can map them); naming (BR-SCR-07, 08; first 12 hex of SHA-256 of the UTF-8 body); the replacement `<script` + attribute text + ` src="/assets/inline-<hash>.js"` + `></script>` (BR-SCR-06). Parse attributes with quote awareness; compare tag and attribute names case-insensitively. A header comment explains why this step exists (NFR-PR-Q-05, BR-BLD-12): the strict `script-src 'self'` blocks Start's inline scripts.
|
||||
- Done when: `pnpm exec tsc --noEmit` clean; a quick manual call on the worked-example table of business-logic-model.md § 3.1 gives the listed outputs (the real tests come in Step 9).
|
||||
|
||||
### Step 9: Tests for `inlineScripts` (P1 to P9) [ ]
|
||||
### Step 9: Tests for `inlineScripts` (P1 to P9) [x]
|
||||
|
||||
- Executor: Sonnet.
|
||||
- Implements: NFR-PR-Q-02; PBT-02 to 05, 07, 08, 10; P1 to P9.
|
||||
@@ -248,7 +248,7 @@ Files are new `config/*` files and `src/test/htmlArbitraries.ts`. Config files a
|
||||
2. `inlineScripts.test.ts`: example-based tests for every row of business-logic-model.md § 3.1 and for each branch of BR-SCR-04 (type list incl. `type=""`, uppercase, `module`; `src` present without value), BR-SCR-05 (a, b, c), BR-SCR-03 (unterminated), attribute retention, trailing `/` in the tag, `>` inside a quoted attribute, uppercase tag names, duplicate bodies. Property tests with titles carrying the category: P1 (invariant), P2 (invariant), P3 (round-trip), P4 (idempotent), P5 (invariant), P6 (invariant), P7 (oracle, `findExecutableInlineScripts` against the model), P8 (invariant), P9 (split and join).
|
||||
- Done when: `pnpm exec vitest run config/inlineScripts.test.ts` passes; the shrunk counterexample and seed would be printed on failure (do not catch or disable).
|
||||
|
||||
### Step 10: Tests for `pageFiles` (P10) [ ]
|
||||
### Step 10: Tests for `pageFiles` (P10) [x]
|
||||
|
||||
- Executor: Sonnet.
|
||||
- Implements: PBT-02, 10; P10.
|
||||
@@ -256,7 +256,7 @@ Files are new `config/*` files and `src/test/htmlArbitraries.ts`. Config files a
|
||||
- Do: examples for `/`, `/over-mij`, `/soorten-fotoshoots/newborn`, `404.html`, a non-page file; property (round-trip): `pagePath(pageFile(p)) === p` for every key of `sitePages` and for generated route-like paths (`routePath` from `arbitraries.ts`); invariant: the file never starts with `/` and ends with `.html`.
|
||||
- Done when: `pnpm exec vitest run config/pageFiles.test.ts` passes.
|
||||
|
||||
### Step 11: Runner `config/externalizeInlineScripts.ts` [ ]
|
||||
### Step 11: Runner `config/externalizeInlineScripts.ts` [x]
|
||||
|
||||
- Executor: Sonnet.
|
||||
- Implements: BR-SCR-12 to 21, BR-MAIL-10, BR-SEC-02, 03, BR-BLD-04, 09 (check part); FR-PR-03, 19, 20, 22; NFR-PR-SEC-03, 04.
|
||||
@@ -267,7 +267,7 @@ Files are new `config/*` files and `src/test/htmlArbitraries.ts`. Config files a
|
||||
Import `sitePages`, `siteContent`, `emailAddress`, `sitemapXml`, `seo` constants with relative `.ts` paths. A header comment explains why the step exists (BR-BLD-12).
|
||||
- Done when: `pnpm exec tsc --noEmit` clean; running `node config/externalizeInlineScripts.ts` on the Step 4 output prints violations (expected at this point: EMAIL_IN_OUTPUT until Step 17) and writes nothing.
|
||||
|
||||
### Step 12: Tests for the runner core (P11 to P13) [ ]
|
||||
### Step 12: Tests for the runner core (P11 to P13) [x]
|
||||
|
||||
- Executor: Sonnet.
|
||||
- Implements: NFR-PR-Q-02; PBT-04, 05, 07, 08, 10; P11 to P13.
|
||||
@@ -275,7 +275,7 @@ Files are new `config/*` files and `src/test/htmlArbitraries.ts`. Config files a
|
||||
- Do: example-based test for each violation code and for the success path (including a second run being a no-op and a `404.html` present); use `anySiteContent`/`validEmail` from `arbitraries.ts` for addresses; a temp-directory test for `externalizeOutput` (writes script files first, writes nothing on violation, exit code via a returned or thrown result you can assert). Properties: P11 (idempotent: apply the plan's writes to the file map, plan again: no writes, no violations), P12 (oracle: violations equal a simple model), P13 (oracle for `containsAddress` with all encodings and random insertion; clean text never flagged).
|
||||
- Done when: `pnpm exec vitest run config/externalizeInlineScripts.test.ts` passes.
|
||||
|
||||
### Step 13: Run the script step on the real output (V3, V4, V13, V17) [ ]
|
||||
### Step 13: Run the script step on the real output (V3, V4, V13, V17) [x]
|
||||
|
||||
- Executor: Sonnet.
|
||||
- Implements: FR-PR-19, 20; BR-SCR-17; V3, V4, V13, V17.
|
||||
@@ -289,7 +289,7 @@ Files are new `config/*` files and `src/test/htmlArbitraries.ts`. Config files a
|
||||
|
||||
Disjoint from B2 and B4. Runs only targeted `vitest run` commands. The editing order inside the batch is the step order.
|
||||
|
||||
### Step 14: `lib` changes for the e-mail address [ ]
|
||||
### Step 14: `lib` changes for the e-mail address [x]
|
||||
|
||||
- Executor: Sonnet.
|
||||
- Implements: BR-MAIL-07, 08; FR-PR-22.
|
||||
@@ -297,7 +297,7 @@ Disjoint from B2 and B4. Runs only targeted `vitest run` commands. The editing o
|
||||
- Do: add `isEmailAddressValid(parts: EmailAddress): boolean`; `emailAddress` reuses it (same results as today). `contactChannels(email, socials, assemble)` with the third parameter: `assemble` false and valid parts give `{ kind: 'email-pending' }` first (no `href`, no `label`); `assemble` true gives the existing email channel; invalid parts none. Extend the `ContactChannel` union (and `external: false` stays on the email kind only). Existing callers are updated in Step 17. Comments in English like the file.
|
||||
- Done when: `pnpm exec tsc --noEmit` reports only the call sites to be fixed in Step 17 (note them), nothing else.
|
||||
|
||||
### Step 15: Tests for the `lib` changes (P14, P15) [ ]
|
||||
### Step 15: Tests for the `lib` changes (P14, P15) [x]
|
||||
|
||||
- Executor: Sonnet.
|
||||
- Implements: NFR-PR-Q-01, Q-02; PBT-03, 05, 10; P14, P15; 100% coverage of `src/lib`.
|
||||
@@ -305,7 +305,7 @@ Disjoint from B2 and B4. Runs only targeted `vitest run` commands. The editing o
|
||||
- Do: examples for each branch of the new parameter and the new function. P15 (oracle): `isEmailAddressValid(p) === (emailAddress(p) !== null)` over `anyEmail`. P14 (invariant): with `assemble` false, `JSON.stringify(contactChannels(...))` never contains the assembled address, and the channel count equals the count with `assemble` true, over `anySiteContent`/`validEmail` and `socialLink` lists.
|
||||
- Done when: `pnpm exec vitest run src/lib/emailAddress.test.ts src/lib/contactChannels.test.ts` passes.
|
||||
|
||||
### Step 16: Search gating, navigation, not found [ ]
|
||||
### Step 16: Search gating, navigation, not found [x]
|
||||
|
||||
- Executor: Sonnet.
|
||||
- Implements: BR-HYD-10, 11, 12, 13; BR-404-04, 05; FR-PR-06, 07, 15.
|
||||
@@ -315,8 +315,9 @@ Disjoint from B2 and B4. Runs only targeted `vitest run` commands. The editing o
|
||||
- Navigation: all top-level `NavLink`s in `NavigationBar` and the plain `RouterLink`s in `MobileNav` get `activeOptions={{ exact: true, includeSearch: false }}` (a shared constant per file like `NavSubmenu` has).
|
||||
- `NotFound`: use `hydrated && isShootSectionPath(pathname)`. Keep the in-body `<title>` and `noindex` meta.
|
||||
- Done when: `pnpm exec tsc --noEmit` clean; the old tests of these files pass (`pnpm exec vitest run src/app.test.tsx src/navSubmenu.test.tsx src/components/NavigationBar src/components/StatusPage`); tests that fail because they assumed the first-render search are adapted per BR-TST-02 and listed in the Record line.
|
||||
- Record (2026-10-31): no old test needed a change; new test cases in `NavigationBar.test.tsx`, `NotFound.test.tsx`, `src/routes/hydration.test.tsx`.
|
||||
|
||||
### Step 17: Footer and e-mail components [ ]
|
||||
### Step 17: Footer and e-mail components [x]
|
||||
|
||||
- Executor: Sonnet.
|
||||
- Implements: BR-HYD-14; BR-MAIL-01 to 06, 09 (placeholders only); FR-PR-22; V10 (first sizing).
|
||||
@@ -329,8 +330,9 @@ Disjoint from B2 and B4. Runs only targeted `vitest run` commands. The editing o
|
||||
- `ContactForm`: use `useEmailAddress` instead of `emailAddress(email)`; the failed-state link unchanged otherwise. `shownAt` unchanged (BR-HYD-16).
|
||||
- Update the call sites that Step 14 broke.
|
||||
- Done when: `pnpm exec tsc --noEmit` clean; `pnpm lint` clean; `renderToString` of `Footer`, `ContactDetails`, `ContactFormGate` with the real `siteContent` contains no `@andreaslop.nl`/`info@` (quick manual check; the tests come in Step 21). Placeholder sizes are first estimates; they are measured in Steps 27 and 34 (V10).
|
||||
- Record (2026-10-31): placeholder sizes are estimates, see V10 in the verification log. `src/test/hydrate.tsx` (new) is the shared hydration test helper. `useInView.ts` got a guard in the effect (see Step 19).
|
||||
|
||||
### Step 18: Testimonials in the HTML [ ]
|
||||
### Step 18: Testimonials in the HTML [x]
|
||||
|
||||
- Executor: Sonnet.
|
||||
- Implements: BR-LZY-02; FR-PR-01; NFR-PR-S-02; V9 (code part).
|
||||
@@ -338,15 +340,16 @@ Disjoint from B2 and B4. Runs only targeted `vitest run` commands. The editing o
|
||||
- Do: `CarouselPlaceholder` renders every visible testimonial as a `TestimonialSlide`: the longest in normal flow as today (it sets the height), the others in a wrapper that is visually hidden (use Chakra's visually hidden recipe/`srOnly`-style props used elsewhere in the repo), `aria-hidden="true"` and `inert`. Do not change the carousel itself, the single-review path, or `inView` logic. Update the comment.
|
||||
- Done when: `pnpm exec tsc --noEmit` clean; `renderToString` of `Testimonials` with the real testimonials contains every quote text (manual check; test in Step 21).
|
||||
|
||||
### Step 19: Tests for hooks (hydration phases) [ ]
|
||||
### Step 19: Tests for hooks (hydration phases) [x]
|
||||
|
||||
- Executor: Sonnet.
|
||||
- Implements: BR-HYD-02 to 05, 09; BR-TST-02; NFR-PR-Q-01; PBT: "No PBT properties identified" for hooks (business-logic-model.md § 9), example-based only.
|
||||
- Files: new or extended `web/src/hooks/useHydrated.test.tsx`, `usePageLoaded.test.tsx`, `useInView.test.tsx` (new), `useReveal.test.tsx`, `web/src/components/Hero/useHeroSlider.test.tsx`.
|
||||
- Do: for each hook test (a) `renderToString` (server snapshot value), (b) hydrating a server-rendered markup with `hydrateRoot` shows the server value in the hydrating render and the real value afterwards, (c) a plain `render` (client mount) shows the real value at once. Cases: `useHydrated` false/true; `usePageLoaded` false then `load` event; `useInView` without `IntersectionObserver` (true after hydration, `skip` respected) and with a fake observer (`src/test/fakeIntersectionObserver.ts`); `useReveal` first-render `reducedMotion` false; `useHeroSlider` `hidden` from `visibilitychange`. Keep all existing tests of these files.
|
||||
- Done when: `pnpm exec vitest run src/hooks src/components/Hero` passes.
|
||||
- Record (2026-10-31): found while testing: the effect of the hydrating render still sees `unsupported` false and threw `ReferenceError` without `IntersectionObserver`; `useInView.ts` now checks `typeof IntersectionObserver` in the effect too. No old test changed.
|
||||
|
||||
### Step 20: Tests for routes, navigation and not found [ ]
|
||||
### Step 20: Tests for routes, navigation and not found [x]
|
||||
|
||||
- Executor: Sonnet.
|
||||
- Implements: BR-HYD-10 to 13; BR-404-04, 05; FR-PR-06, 07, 15; NFR-PR-Q-01.
|
||||
@@ -354,7 +357,7 @@ Disjoint from B2 and B4. Runs only targeted `vitest run` commands. The editing o
|
||||
- Do: direct load simulation (`renderApp('/contact?pakket=...')`) still preselects the package and tidies the address bar; `/?pakket=` still scrolls/focuses via the `ContactSection` effect; `/portfolio?shoot=gezin` filters and filter clicks still navigate with `replace`; `NotFound` shows one button while hydrating and the two extra buttons under `/soorten-fotoshoots/` after (use `hydrateRoot`), and on a plain mount at once; no navigation link is current on an unknown sub-path such as `/over-mij/x`, current on real pages and with a search.
|
||||
- Done when: the touched test files pass with targeted `vitest run`.
|
||||
|
||||
### Step 21: Tests for Footer, e-mail components and Testimonials [ ]
|
||||
### Step 21: Tests for Footer, e-mail components and Testimonials [x]
|
||||
|
||||
- Executor: Sonnet.
|
||||
- Implements: BR-HYD-14; BR-MAIL-01 to 07; BR-LZY-02; FR-PR-22; V9 (test part); NFR-PR-Q-01.
|
||||
@@ -366,14 +369,14 @@ Disjoint from B2 and B4. Runs only targeted `vitest run` commands. The editing o
|
||||
|
||||
## Part E: Preview server (batch B4, Sonnet; parallel with B2 and B3)
|
||||
|
||||
### Step 22: `config/previewServer.ts` [ ]
|
||||
### Step 22: `config/previewServer.ts` [x]
|
||||
|
||||
- Executor: Sonnet.
|
||||
- Implements: BR-SRV-01 to 08; D10; NFR-PR-SEC-01; FR-PR-14 (preview part).
|
||||
- Do: create `resolveRequest(path, fileExists)` per BR-SRV-01 to 07 (decode once; reject NUL, backslash, `..` segments; `/` to `index.html`; no-dot last segment through `pageFile` when the file exists; dot last segment is a file request; else `404.html` with status 404; trailing slash and `/404` interim behaviour exactly as BR-SRV-07 says, with a comment "final rule in unit 3 Infrastructure Design"; never returns `{ redirect }`). `startPreviewServer(clientDir, port)` with Node `http`: `GET`/`HEAD` only (405 otherwise), `securityHeaders('production')` on every response, `Cache-Control: no-cache` for HTML, content types from the extension, bind `127.0.0.1`, prints a line containing `Local` with the URL (matches `startServerReadyPattern` in `lighthouserc.cjs`), CLI entry parses `--port` (default 4173), `--strictPort` (fail if taken), and an optional `--dir` (default `dist/client`). Import `pageFile` from `./pageFiles.ts` (Step 7; if B2 has not finished, wait for it) and `securityHeaders` from `./securityHeaders.ts`. Dutch header comment explaining why a own server (D10: real 404 and `.html` mapping, no Node server in production).
|
||||
- Done when: `pnpm exec tsc --noEmit` clean; starting it manually on the Step 4 output answers `curl -I http://127.0.0.1:4173/over-mij` with 200 and the CSP header, and `/nope` with 404 (stop the server afterwards; skip this check while Lighthouse is running anywhere).
|
||||
|
||||
### Step 23: Tests for the preview server (P16, P17) [ ]
|
||||
### Step 23: Tests for the preview server (P16, P17) [x]
|
||||
|
||||
- Executor: Sonnet.
|
||||
- Implements: PBT-03, 05, 07, 08, 10; P16, P17; SECURITY-11 misuse case.
|
||||
|
||||
+2
-2
@@ -33,8 +33,8 @@ Notes:
|
||||
| V6 | Code splitting; router plugin unused | 4 (30 later) | Start's plugin includes `tanstackRouterGenerator` and `tanStackRouterCodeSplitter` itself (client and server environments), so route code splitting is on without an option and `@tanstack/router-plugin` is not needed as a direct dependency. Removed with `pnpm remove @tanstack/router-plugin`; only Start's own copy (1.168.48) remains. | Client build has one chunk per route (`over-mij-*.js`, `contact-*.js`, `portfolio-*.js`, `newborn-*.js`, ..., `_-*.js` for the catch-all), plus `ContactForm`, `Lightbox`, `TestimonialCarousel` chunks. Step 30 re-checks. | OK |
|
||||
| V7 | Sitemap in the client environment only | 4 | `this.environment.name === 'client'` identifies the client build in `generateBundle` (Vite 8.3.1, Start environments `client` and `ssr`). | `dist/client/sitemap.xml` exists once (10 `<loc>`, no `/privacyverklaring`, no `/404`); `find dist -name sitemap.xml` gives only that file; `public/` has no `sitemap.xml`. | OK |
|
||||
| V8 | Lazy `ContactForm` in HTML and hydration | 27 | open (first look: `contact.html` contains `data-testid="contact-form"` and its fields; `/contact` hydrates in Chrome without console output) | | open |
|
||||
| V9 | Testimonials in HTML, hidden slides | 21, 27 | open | | open |
|
||||
| V10 | Placeholder sizes, CLS below 0.01 | 17, 34 | open | | open |
|
||||
| V9 | Testimonials in HTML, hidden slides | 21, 27 | Code part (step 18, 21): `renderToString` of `Testimonials` holds the quote of every visible review; the copies besides the longest sit in a `VisuallyHidden` wrapper with `aria-hidden` and `inert`; axe has no violations in jsdom with the placeholder showing. Layout and reading order in a browser: step 27. | `Testimonials.test.tsx` (4 new tests) | open |
|
||||
| V10 | Placeholder sizes, CLS below 0.01 | 17, 34 | First estimates (step 17), not measured: footer item `minH` 44px below `lg`, `1lh` from `lg` (one line of the list item); contact card item `minH` 44px; gate notice inline block `38ch` (lead " Mail me voor nu op " 20 + address 18 characters, from the parts without assembling) plus a hidden button with the recipe and label. To be measured in 27 and 34. | `Footer.tsx`, `ContactDetails.tsx`, `ContactFormGate.tsx` | open |
|
||||
| V11 | One title, one noindex meta | 4 (normal pages), 27 (`404.html`) | Normal pages in the prerendered HTML: one `<title>`, one `description`, one `canonical`, no `data-fallback`, a robots meta only on `/privacyverklaring`. `404.html`: one `<title>` ("Pagina niet gevonden \| Andrea Slop Fotografie") and one `<meta name="robots" content="noindex">`, no description or canonical. React writes `<meta charSet="utf-8">` with a capital S (valid, attribute names are case-insensitive). | `scripts.mjs` counts per file. After hydration in Chrome: `/`, `/over-mij`, `/contact` still 1 title. Caution for Step 27: `/soorten-fotoshoots/onbekend` showed 2 titles and 2 robots metas after React error #418 (the two extra 404 buttons render before hydration; Step 16 fixes that); `/onbekend` is clean. | OK (normal pages); `404.html` source OK, final check in 27 |
|
||||
| V12 | 404 hydration with real shell | 27 | open (first look, before Step 16: `/onbekend` hydrates clean; `/soorten-fotoshoots/onbekend` gives #418, which Step 16 `hydrated && isShootSectionPath` should remove) | | open |
|
||||
| V13 | Timestamps and build paths | 4, 13 | Repeated on the final output of the runner (HTML plus the 16 moved script files plus all JS/CSS/XML/TXT/JSON): no build timestamp (`YYYY-MM-DDTHH:MM`) in any text file, no `.map` file, no repository root path (forward slashes, backslashes or doubled backslashes) in any text file. File names are content hashes, so they cannot carry a timestamp. | Scan in the scratch run (`repoPathFiles: 0`, `timestampFiles: 0`, `maps: 0`); the runner's own BUILD_PATH_LEAK check reported nothing. | OK |
|
||||
|
||||
@@ -0,0 +1,522 @@
|
||||
import { spawn } from 'node:child_process';
|
||||
import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
||||
import { request, type Server } from 'node:http';
|
||||
import { createServer } from 'node:net';
|
||||
import { tmpdir } from 'node:os';
|
||||
import { dirname, join, posix, win32 } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import fc from 'fast-check';
|
||||
import { afterEach, describe, expect, it } from 'vitest';
|
||||
import {
|
||||
anyRequestPath,
|
||||
dottedFileName,
|
||||
existingFiles,
|
||||
existsIn,
|
||||
pageName,
|
||||
} from '../src/test/requestArbitraries';
|
||||
import { securityHeaders } from './securityHeaders';
|
||||
import {
|
||||
contentTypeOf,
|
||||
resolveRequest,
|
||||
startPreviewServer,
|
||||
} from './previewServer';
|
||||
|
||||
const NOT_FOUND = { file: '404.html', status: 404 };
|
||||
const FILES = new Set([
|
||||
'index.html',
|
||||
'404.html',
|
||||
'over-mij.html',
|
||||
'soorten-fotoshoots.html',
|
||||
'soorten-fotoshoots/newborn.html',
|
||||
'assets/app.js',
|
||||
'favicon.png',
|
||||
]);
|
||||
const resolveIn = (path: string) => resolveRequest(path, existsIn(FILES));
|
||||
|
||||
describe('resolveRequest', () => {
|
||||
it('geeft index.html voor /', () => {
|
||||
expect(resolveIn('/')).toEqual({ file: 'index.html', status: 200 });
|
||||
});
|
||||
|
||||
it('geeft het paginabestand voor een pad zonder punt als dat bestaat', () => {
|
||||
expect(resolveIn('/over-mij')).toEqual({
|
||||
file: 'over-mij.html',
|
||||
status: 200,
|
||||
});
|
||||
expect(resolveIn('/soorten-fotoshoots/newborn')).toEqual({
|
||||
file: 'soorten-fotoshoots/newborn.html',
|
||||
status: 200,
|
||||
});
|
||||
});
|
||||
|
||||
it('geeft 404.html met 404 voor een pad zonder bestaande pagina', () => {
|
||||
expect(resolveIn('/nope')).toEqual(NOT_FOUND);
|
||||
expect(resolveIn('/soorten-fotoshoots/nope')).toEqual(NOT_FOUND);
|
||||
});
|
||||
|
||||
it('behandelt een laatste segment met een punt als bestandsverzoek', () => {
|
||||
expect(resolveIn('/assets/app.js')).toEqual({
|
||||
file: 'assets/app.js',
|
||||
status: 200,
|
||||
});
|
||||
expect(resolveIn('/favicon.png')).toEqual({
|
||||
file: 'favicon.png',
|
||||
status: 200,
|
||||
});
|
||||
expect(resolveIn('/over-mij.html')).toEqual({
|
||||
file: 'over-mij.html',
|
||||
status: 200,
|
||||
});
|
||||
expect(resolveIn('/assets/weg.js')).toEqual(NOT_FOUND);
|
||||
});
|
||||
|
||||
it('zoekt geen paginabestand achter een bestandsverzoek', () => {
|
||||
// /over-mij.x is een bestand, geen pagina
|
||||
expect(resolveIn('/over-mij.x')).toEqual(NOT_FOUND);
|
||||
});
|
||||
|
||||
it('decodeert één keer', () => {
|
||||
expect(resolveIn('/over%2Dmij')).toEqual({
|
||||
file: 'over-mij.html',
|
||||
status: 200,
|
||||
});
|
||||
// Dubbel gecodeerd wordt na één keer een gewone (onbekende) naam
|
||||
expect(resolveIn('/over%252Dmij')).toEqual(NOT_FOUND);
|
||||
});
|
||||
|
||||
it('weigert een pad dat niet decodeert', () => {
|
||||
expect(resolveIn('/%')).toEqual(NOT_FOUND);
|
||||
expect(resolveIn('/%zz')).toEqual(NOT_FOUND);
|
||||
expect(resolveIn('/%c0%af')).toEqual(NOT_FOUND);
|
||||
});
|
||||
|
||||
it('weigert NUL en backslash, ook gecodeerd', () => {
|
||||
expect(resolveIn('/over-mij%00')).toEqual(NOT_FOUND);
|
||||
expect(resolveIn('/over-mij\0.html')).toEqual(NOT_FOUND);
|
||||
expect(resolveIn('/assets\\app.js')).toEqual(NOT_FOUND);
|
||||
expect(resolveIn('/assets%5Capp.js')).toEqual(NOT_FOUND);
|
||||
});
|
||||
|
||||
it('weigert .. in elke codering', () => {
|
||||
for (const path of [
|
||||
'/../index.html',
|
||||
'/assets/../index.html',
|
||||
'/%2e%2e/index.html',
|
||||
'/%2E%2E/index.html',
|
||||
'/assets/%2e%2e/index.html',
|
||||
'/..%2findex.html',
|
||||
'/assets%2f..%2findex.html',
|
||||
'/..',
|
||||
'/assets/..',
|
||||
]) {
|
||||
expect(resolveIn(path), path).toEqual(NOT_FOUND);
|
||||
}
|
||||
});
|
||||
|
||||
it('weigert . en segmenten van alleen punten en spaties', () => {
|
||||
for (const path of [
|
||||
'/./index.html',
|
||||
'/assets/./app.js',
|
||||
'/...',
|
||||
'/.. ',
|
||||
]) {
|
||||
expect(resolveIn(path), path).toEqual(NOT_FOUND);
|
||||
}
|
||||
});
|
||||
|
||||
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);
|
||||
});
|
||||
|
||||
it('geeft 404 voor een dubbele slash', () => {
|
||||
expect(resolveIn('//over-mij')).toEqual(NOT_FOUND);
|
||||
expect(resolveIn('/assets//app.js')).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('antwoordt op /404 met 404.html en status 404, niet 200', () => {
|
||||
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(resolveRequest('/404.html', () => false)).toEqual(NOT_FOUND);
|
||||
});
|
||||
|
||||
it('geeft /index en /index.html het bestand van /', () => {
|
||||
expect(resolveIn('/index')).toEqual({
|
||||
file: 'index.html',
|
||||
status: 200,
|
||||
});
|
||||
expect(resolveIn('/index.html')).toEqual({
|
||||
file: 'index.html',
|
||||
status: 200,
|
||||
});
|
||||
});
|
||||
|
||||
it('geeft nooit een redirect terug', () => {
|
||||
for (const path of ['/over-mij/', '/404', '/index', '/']) {
|
||||
expect(resolveIn(path)).not.toHaveProperty('redirect');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
it('geeft index.html voor / ook als de bestandslijst leeg is', () => {
|
||||
expect(resolveRequest('/', () => false)).toEqual({
|
||||
file: 'index.html',
|
||||
status: 200,
|
||||
});
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveRequest (eigenschappen)', () => {
|
||||
it('blijft binnen clientDir, voor elk pad (invariant, P16)', () => {
|
||||
fc.assert(
|
||||
fc.property(
|
||||
anyRequestPath,
|
||||
existingFiles,
|
||||
fc.boolean(),
|
||||
(path, files, everythingExists) => {
|
||||
const { file, status } = resolveRequest(
|
||||
path,
|
||||
everythingExists ? () => true : existsIn(files),
|
||||
);
|
||||
expect(file.split('/')).not.toContain('..');
|
||||
expect(file.startsWith('/')).toBe(false);
|
||||
expect(posix.isAbsolute(file)).toBe(false);
|
||||
expect(win32.isAbsolute(file)).toBe(false);
|
||||
expect(file).not.toContain('\\');
|
||||
expect(file).not.toContain('\0');
|
||||
// 404 hoort alleen bij de 404-pagina
|
||||
if (status === 404) expect(file).toBe('404.html');
|
||||
},
|
||||
),
|
||||
);
|
||||
});
|
||||
|
||||
it('kent / en /x en /bestand.ext zoals het model (oracle, P17)', () => {
|
||||
fc.assert(
|
||||
fc.property(
|
||||
existingFiles,
|
||||
pageName,
|
||||
fc.array(pageName, { maxLength: 2 }),
|
||||
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')
|
||||
? { file, status: 200 }
|
||||
: NOT_FOUND;
|
||||
|
||||
expect(resolveRequest('/', exists)).toEqual({
|
||||
file: 'index.html',
|
||||
status: 200,
|
||||
});
|
||||
|
||||
const page = [...dirs, name].join('/');
|
||||
expect(resolveRequest(`/${page}`, exists)).toEqual(
|
||||
expected(`${page}.html`, true),
|
||||
);
|
||||
|
||||
const asset = [...dirs, dotted].join('/');
|
||||
expect(resolveRequest(`/${asset}`, exists)).toEqual(
|
||||
expected(asset),
|
||||
);
|
||||
// Een bestand dat echt bestaat wordt altijd gevonden
|
||||
for (const file of files) {
|
||||
expect(resolveRequest(`/${file}`, exists)).toEqual({
|
||||
file,
|
||||
status: 200,
|
||||
});
|
||||
}
|
||||
},
|
||||
),
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('contentTypeOf', () => {
|
||||
it('kiest het type op de extensie, hoofdletterongevoelig', () => {
|
||||
expect(contentTypeOf('a.html')).toBe('text/html; charset=utf-8');
|
||||
expect(contentTypeOf('a.JS')).toBe('text/javascript; charset=utf-8');
|
||||
expect(contentTypeOf('a.woff2')).toBe('font/woff2');
|
||||
expect(contentTypeOf('a.png')).toBe('image/png');
|
||||
expect(contentTypeOf('a.onbekend')).toBe('application/octet-stream');
|
||||
expect(contentTypeOf('geen-extensie')).toBe('application/octet-stream');
|
||||
});
|
||||
});
|
||||
|
||||
interface Answer {
|
||||
status: number;
|
||||
headers: Record<string, string | string[] | undefined>;
|
||||
body: string;
|
||||
}
|
||||
|
||||
// node:http in plaats van fetch: die laat het pad ongemoeid, ook '..'
|
||||
const ask = (port: number, path: string, method = 'GET'): Promise<Answer> =>
|
||||
new Promise((resolve, reject) => {
|
||||
const req = request(
|
||||
{ host: '127.0.0.1', port, path, method },
|
||||
(response) => {
|
||||
const chunks: Buffer[] = [];
|
||||
response.on('data', (chunk: Buffer) => chunks.push(chunk));
|
||||
response.on('end', () =>
|
||||
resolve({
|
||||
status: response.statusCode ?? 0,
|
||||
headers: response.headers,
|
||||
body: Buffer.concat(chunks).toString('utf8'),
|
||||
}),
|
||||
);
|
||||
},
|
||||
);
|
||||
req.on('error', reject);
|
||||
req.end();
|
||||
});
|
||||
|
||||
const tempDirs: string[] = [];
|
||||
const servers: Server[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
servers
|
||||
.splice(0)
|
||||
.map((server) => new Promise((done) => server.close(done))),
|
||||
);
|
||||
for (const dir of tempDirs.splice(0)) {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
});
|
||||
|
||||
function siteDir(): string {
|
||||
const root = mkdtempSync(join(tmpdir(), 'preview-'));
|
||||
tempDirs.push(root);
|
||||
const clientDir = join(root, 'dist', 'client');
|
||||
mkdirSync(join(clientDir, 'assets'), { recursive: true });
|
||||
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, 'assets', 'app.js'), 'boot()');
|
||||
// Buiten clientDir: mag nooit bereikbaar zijn
|
||||
writeFileSync(join(root, 'dist', 'geheim.txt'), 'geheim');
|
||||
return clientDir;
|
||||
}
|
||||
|
||||
async function serve(clientDir: string): Promise<number> {
|
||||
const server = await startPreviewServer(clientDir, 0);
|
||||
servers.push(server);
|
||||
const address = server.address();
|
||||
if (typeof address !== 'object' || !address) throw new Error('geen poort');
|
||||
return address.port;
|
||||
}
|
||||
|
||||
describe('startPreviewServer', () => {
|
||||
it('stuurt een pagina met 200, het type en no-cache', async () => {
|
||||
const port = await serve(siteDir());
|
||||
const answer = await ask(port, '/over-mij');
|
||||
expect(answer.status).toBe(200);
|
||||
expect(answer.body).toBe('<p>over mij</p>');
|
||||
expect(answer.headers['content-type']).toBe('text/html; charset=utf-8');
|
||||
expect(answer.headers['cache-control']).toBe('no-cache');
|
||||
});
|
||||
|
||||
it('stuurt een asset met het type van de extensie, zonder no-cache', async () => {
|
||||
const port = await serve(siteDir());
|
||||
const answer = await ask(port, '/assets/app.js?v=1#x');
|
||||
expect(answer.status).toBe(200);
|
||||
expect(answer.body).toBe('boot()');
|
||||
expect(answer.headers['content-type']).toBe(
|
||||
'text/javascript; charset=utf-8',
|
||||
);
|
||||
expect(answer.headers['cache-control']).toBeUndefined();
|
||||
});
|
||||
|
||||
it('zet de securityheaders op 200 en op 404', async () => {
|
||||
const port = await serve(siteDir());
|
||||
const expected = securityHeaders('production');
|
||||
for (const path of ['/', '/nope']) {
|
||||
const { headers } = await ask(port, path);
|
||||
for (const [name, value] of Object.entries(expected)) {
|
||||
expect(headers[name.toLowerCase()], `${path} ${name}`).toBe(
|
||||
value,
|
||||
);
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
it('antwoordt op een onbekend pad met de 404-pagina en status 404', async () => {
|
||||
const port = await serve(siteDir());
|
||||
const answer = await ask(port, '/nope');
|
||||
expect(answer.status).toBe(404);
|
||||
expect(answer.body).toBe('<p>niet gevonden</p>');
|
||||
expect(answer.headers['content-type']).toBe('text/html; charset=utf-8');
|
||||
});
|
||||
|
||||
it('antwoordt op /404 met status 404', async () => {
|
||||
const port = await serve(siteDir());
|
||||
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>');
|
||||
});
|
||||
|
||||
it('geeft 405 op POST, PUT en DELETE, met securityheaders', async () => {
|
||||
const port = await serve(siteDir());
|
||||
for (const method of ['POST', 'PUT', 'DELETE']) {
|
||||
const answer = await ask(port, '/', method);
|
||||
expect(answer.status, method).toBe(405);
|
||||
expect(answer.headers.allow).toBe('GET, HEAD');
|
||||
expect(answer.headers['content-security-policy']).toBeDefined();
|
||||
}
|
||||
});
|
||||
|
||||
it('stuurt bij HEAD de headers en lengte maar geen inhoud', async () => {
|
||||
const port = await serve(siteDir());
|
||||
const answer = await ask(port, '/over-mij', 'HEAD');
|
||||
expect(answer.status).toBe(200);
|
||||
expect(answer.body).toBe('');
|
||||
expect(answer.headers['content-length']).toBe(
|
||||
String('<p>over mij</p>'.length),
|
||||
);
|
||||
expect(answer.headers['content-type']).toBe('text/html; charset=utf-8');
|
||||
expect((await ask(port, '/nope', 'HEAD')).status).toBe(404);
|
||||
});
|
||||
|
||||
it('komt met geen enkele traversal buiten clientDir (misbruikgeval)', async () => {
|
||||
const port = await serve(siteDir());
|
||||
for (const path of [
|
||||
'/../geheim.txt',
|
||||
'/%2e%2e/geheim.txt',
|
||||
'/..%2fgeheim.txt',
|
||||
'/assets/../../geheim.txt',
|
||||
'/..%5cgeheim.txt',
|
||||
'/%2e%2e%5cgeheim.txt',
|
||||
'/geheim.txt%00.html',
|
||||
]) {
|
||||
const answer = await ask(port, path);
|
||||
expect(answer.status, path).toBe(404);
|
||||
expect(answer.body, path).not.toContain('geheim');
|
||||
}
|
||||
});
|
||||
|
||||
it('geeft een gewone 404 als clientDir geen 404.html heeft', async () => {
|
||||
const clientDir = siteDir();
|
||||
rmSync(join(clientDir, '404.html'));
|
||||
const port = await serve(clientDir);
|
||||
const answer = await ask(port, '/nope');
|
||||
expect(answer.status).toBe(404);
|
||||
expect(answer.body).toBe('Not Found');
|
||||
const head = await ask(port, '/nope', 'HEAD');
|
||||
expect(head.status).toBe(404);
|
||||
expect(head.body).toBe('');
|
||||
});
|
||||
|
||||
it('weigert te starten op een bezette poort', async () => {
|
||||
const port = await serve(siteDir());
|
||||
await expect(startPreviewServer(siteDir(), port)).rejects.toThrow(
|
||||
/EADDRINUSE/,
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
describe('previewServer als opdrachtregel', () => {
|
||||
const script = join(
|
||||
dirname(fileURLToPath(import.meta.url)),
|
||||
'previewServer.ts',
|
||||
);
|
||||
const children: ReturnType<typeof spawn>[] = [];
|
||||
|
||||
afterEach(() => {
|
||||
for (const child of children.splice(0)) child.kill();
|
||||
});
|
||||
|
||||
const start = (...args: string[]) => {
|
||||
const child = spawn(process.execPath, [script, ...args], {
|
||||
stdio: ['ignore', 'pipe', 'pipe'],
|
||||
});
|
||||
children.push(child);
|
||||
let stdout = '';
|
||||
let stderr = '';
|
||||
child.stdout.on('data', (chunk) => (stdout += chunk));
|
||||
child.stderr.on('data', (chunk) => (stderr += chunk));
|
||||
const exited = new Promise<number | null>((done) =>
|
||||
child.on('exit', done),
|
||||
);
|
||||
const ready = new Promise<string>((done) => {
|
||||
const check = () => {
|
||||
if (stdout.includes('Local')) done(stdout);
|
||||
};
|
||||
child.stdout.on('data', check);
|
||||
exited.then(() => done(stdout));
|
||||
});
|
||||
return { ready, exited, stderr: () => stderr };
|
||||
};
|
||||
|
||||
it('meldt een Local-regel met de url en bedient de map', async () => {
|
||||
const clientDir = siteDir();
|
||||
const run = start('--port', '0', '--strictPort', '--dir', clientDir);
|
||||
const line = await run.ready;
|
||||
const match = /Local:\s+http:\/\/127\.0\.0\.1:(\d+)\//.exec(line);
|
||||
expect(match).not.toBeNull();
|
||||
const answer = await ask(Number(match![1]), '/over-mij');
|
||||
expect(answer.status).toBe(200);
|
||||
});
|
||||
|
||||
it('stopt met exitcode 1 op een bezette poort met --strictPort', async () => {
|
||||
const blocker = createServer();
|
||||
await new Promise<void>((done) =>
|
||||
blocker.listen(0, '127.0.0.1', () => done()),
|
||||
);
|
||||
try {
|
||||
const taken = (blocker.address() as { port: number }).port;
|
||||
const run = start(
|
||||
`--port=${taken}`,
|
||||
'--strictPort',
|
||||
'--dir',
|
||||
siteDir(),
|
||||
);
|
||||
expect(await run.exited).toBe(1);
|
||||
expect(run.stderr()).toContain(String(taken));
|
||||
} finally {
|
||||
await new Promise((done) => blocker.close(done));
|
||||
}
|
||||
});
|
||||
|
||||
it('schuift naar een volgende poort zonder --strictPort', async () => {
|
||||
const blocker = createServer();
|
||||
await new Promise<void>((done) =>
|
||||
blocker.listen(0, '127.0.0.1', () => done()),
|
||||
);
|
||||
try {
|
||||
const taken = (blocker.address() as { port: number }).port;
|
||||
const run = start('--port', String(taken), '--dir', siteDir());
|
||||
const line = await run.ready;
|
||||
const port = Number(/:(\d+)\//.exec(line)![1]);
|
||||
expect(port).toBeGreaterThan(taken);
|
||||
} finally {
|
||||
await new Promise((done) => blocker.close(done));
|
||||
}
|
||||
});
|
||||
|
||||
it('stopt met exitcode 1 bij een ongeldige poort', async () => {
|
||||
const run = start('--port', 'abc');
|
||||
expect(await run.exited).toBe(1);
|
||||
expect(run.stderr()).toContain('Ongeldige poort');
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,233 @@
|
||||
// Kleine preview-server voor dist/client, voor Lighthouse en de browsertests.
|
||||
//
|
||||
// Waarom een eigen server (D10): `vite preview` kent geen echte 404 en geen
|
||||
// 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).
|
||||
import { createReadStream, statSync } from 'node:fs';
|
||||
import {
|
||||
createServer,
|
||||
type IncomingMessage,
|
||||
type Server,
|
||||
type ServerResponse,
|
||||
} from 'node:http';
|
||||
import { extname, join, resolve, sep, win32 } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { NOT_FOUND_FILE, pageFile } from './pageFiles.ts';
|
||||
import { securityHeaders } from './securityHeaders.ts';
|
||||
|
||||
export interface ResolvedRequest {
|
||||
// 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 };
|
||||
|
||||
// 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.
|
||||
export function resolveRequest(
|
||||
path: string,
|
||||
fileExists: (file: string) => boolean,
|
||||
): ResolvedRequest {
|
||||
let decoded: string;
|
||||
try {
|
||||
decoded = decodeURIComponent(path);
|
||||
} catch {
|
||||
return NOT_FOUND;
|
||||
}
|
||||
if (
|
||||
!decoded.startsWith('/') ||
|
||||
decoded.includes('\0') ||
|
||||
decoded.includes('\\')
|
||||
) {
|
||||
return NOT_FOUND;
|
||||
}
|
||||
if (decoded === '/') return { file: pageFile('/'), status: 200 };
|
||||
|
||||
// Lege segmenten (dubbele slash, slash aan het eind) en puntsegmenten:
|
||||
// geen redirect in unit 1, die regel is definitief in unit 3
|
||||
// Infrastructure Design (BR-SRV-07)
|
||||
const segments = decoded.slice(1).split('/');
|
||||
if (
|
||||
segments.some((segment) => segment === '' || DOT_SEGMENT.test(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;
|
||||
// Tussenregel, definitief in unit 3 Infrastructure Design: 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',
|
||||
};
|
||||
|
||||
export const contentTypeOf = (file: string): string =>
|
||||
CONTENT_TYPES[extname(file).toLowerCase()] ?? 'application/octet-stream';
|
||||
|
||||
// Alleen het pad: query en hash horen niet bij het bestand. Bewust niet via
|
||||
// `new URL`, want die haalt '..' al weg en dan ziet resolveRequest het niet.
|
||||
const pathOf = (target: string) => target.split(/[?#]/, 1)[0];
|
||||
|
||||
function send(
|
||||
response: ServerResponse,
|
||||
status: number,
|
||||
headers: Record<string, string | number>,
|
||||
body: NodeJS.ReadableStream | string | null,
|
||||
) {
|
||||
response.writeHead(status, {
|
||||
...securityHeaders('production'),
|
||||
...headers,
|
||||
});
|
||||
if (body === null) response.end();
|
||||
else if (typeof body === 'string') response.end(body);
|
||||
else body.pipe(response);
|
||||
}
|
||||
|
||||
export function startPreviewServer(
|
||||
clientDir: string,
|
||||
port: number,
|
||||
): Promise<Server> {
|
||||
const root = resolve(clientDir);
|
||||
const isFile = (file: string) => {
|
||||
try {
|
||||
return statSync(join(root, file)).isFile();
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
const handle = (request: IncomingMessage, response: ServerResponse) => {
|
||||
if (request.method !== 'GET' && request.method !== 'HEAD') {
|
||||
send(
|
||||
response,
|
||||
405,
|
||||
{ Allow: 'GET, HEAD', 'Content-Type': 'text/plain' },
|
||||
'Method Not Allowed',
|
||||
);
|
||||
return;
|
||||
}
|
||||
const { file, status } = resolveRequest(
|
||||
pathOf(request.url ?? '/'),
|
||||
isFile,
|
||||
);
|
||||
const target = join(root, file);
|
||||
// Tweede slot naast resolveRequest: nooit buiten clientDir lezen
|
||||
if (!target.startsWith(root + sep) || !isFile(file)) {
|
||||
send(
|
||||
response,
|
||||
404,
|
||||
{ 'Content-Type': 'text/plain' },
|
||||
request.method === 'HEAD' ? null : 'Not Found',
|
||||
);
|
||||
return;
|
||||
}
|
||||
const headers: Record<string, string | number> = {
|
||||
'Content-Type': contentTypeOf(file),
|
||||
'Content-Length': statSync(target).size,
|
||||
};
|
||||
if (file.endsWith('.html')) headers['Cache-Control'] = 'no-cache';
|
||||
send(
|
||||
response,
|
||||
status,
|
||||
headers,
|
||||
request.method === 'HEAD' ? null : createReadStream(target),
|
||||
);
|
||||
};
|
||||
|
||||
return new Promise((resolvePromise, reject) => {
|
||||
const server = createServer(handle);
|
||||
server.once('error', reject);
|
||||
server.listen(port, '127.0.0.1', () => {
|
||||
server.off('error', reject);
|
||||
resolvePromise(server);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// `--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' };
|
||||
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;
|
||||
}
|
||||
return options;
|
||||
}
|
||||
|
||||
const MAX_PORT_TRIES = 10;
|
||||
|
||||
async function main(args: string[]) {
|
||||
const { port, strictPort, dir } = parseArguments(args);
|
||||
if (!Number.isInteger(port) || port < 0 || port > 65535) {
|
||||
console.error(`Ongeldige poort: ${port}`);
|
||||
process.exitCode = 1;
|
||||
return;
|
||||
}
|
||||
// Zonder --strictPort schuift de poort op als hij bezet is, zoals vite
|
||||
// preview; poort 0 (laat het systeem kiezen) schuift niet
|
||||
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 address = server.address();
|
||||
const actual =
|
||||
typeof address === 'object' && address ? address.port : port;
|
||||
// 'Local' moet erin staan: startServerReadyPattern van lighthouserc.cjs
|
||||
console.log(` Local: http://127.0.0.1:${actual}/`);
|
||||
return;
|
||||
} catch (error) {
|
||||
const inUse =
|
||||
(error as NodeJS.ErrnoException).code === 'EADDRINUSE';
|
||||
if (!inUse || attempt === tries - 1) {
|
||||
console.error(
|
||||
inUse
|
||||
? `Poort ${port + attempt} is al in gebruik`
|
||||
: String(error),
|
||||
);
|
||||
process.exitCode = 1;
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Draait alleen als het bestand zelf wordt gestart (pnpm preview), niet als
|
||||
// een test het importeert.
|
||||
if (
|
||||
process.argv[1] &&
|
||||
resolve(process.argv[1]) === fileURLToPath(import.meta.url)
|
||||
) {
|
||||
await main(process.argv.slice(2));
|
||||
}
|
||||
@@ -0,0 +1,86 @@
|
||||
import fc from 'fast-check';
|
||||
import { pathSegment } from './arbitraries';
|
||||
|
||||
// Generatoren voor verzoekpaden van de preview-server (BR-SRV). Los van
|
||||
// arbitraries.ts, zodat die klein blijft (PBT-07).
|
||||
|
||||
// Stukken die een pad onveilig of vreemd maken: puntsegmenten in elke
|
||||
// codering, NUL, backslashes, kapotte en dubbele codering, unicode
|
||||
export const hostileFragment = fc.constantFrom(
|
||||
'..',
|
||||
'.',
|
||||
'...',
|
||||
'.. ',
|
||||
'%2e%2e',
|
||||
'%2E%2E',
|
||||
'%2e',
|
||||
'%252e%252e',
|
||||
'..%2f',
|
||||
'%2f..',
|
||||
'%5c',
|
||||
'\\',
|
||||
'..\\',
|
||||
'%00',
|
||||
'\0',
|
||||
'%',
|
||||
'%zz',
|
||||
'%c0%af',
|
||||
'%ff',
|
||||
'',
|
||||
'c:',
|
||||
'日本語',
|
||||
'é',
|
||||
'\u{1F600}',
|
||||
' ',
|
||||
);
|
||||
|
||||
const anySegment = fc.oneof(
|
||||
{ weight: 3, arbitrary: pathSegment },
|
||||
{ weight: 3, arbitrary: hostileFragment },
|
||||
{ weight: 1, arbitrary: fc.string({ unit: 'binary', maxLength: 6 }) },
|
||||
);
|
||||
|
||||
// Een pad zoals een client het kan sturen: meestal met voorste slash, soms
|
||||
// zonder, soms rauwe tekst
|
||||
export const anyRequestPath = fc.oneof(
|
||||
{
|
||||
weight: 5,
|
||||
arbitrary: fc
|
||||
.tuple(fc.boolean(), fc.array(anySegment, { maxLength: 5 }))
|
||||
.map(
|
||||
([leading, segments]) =>
|
||||
(leading ? '/' : '') + segments.join('/'),
|
||||
),
|
||||
},
|
||||
{ weight: 1, arbitrary: fc.string({ unit: 'binary', maxLength: 20 }) },
|
||||
);
|
||||
|
||||
// Een bestandsnaam met extensie, zoals een verzoek om een asset
|
||||
export const dottedFileName = fc.stringMatching(
|
||||
/^[a-z0-9-]{1,10}\.[a-z0-9]{1,5}$/,
|
||||
);
|
||||
|
||||
// Een naam zonder punt, voor een paginaverzoek als /x
|
||||
export const pageName = fc.stringMatching(/^[a-z0-9-]{1,12}$/);
|
||||
|
||||
const directory = fc.array(pathSegment, { maxLength: 2 });
|
||||
|
||||
// Een bestand in clientDir: een paginabestand of een bestand met punt in een map
|
||||
const existingFile = fc.oneof(
|
||||
fc
|
||||
.tuple(directory, pageName)
|
||||
.map(([dirs, name]) => [...dirs, `${name}.html`].join('/')),
|
||||
fc
|
||||
.tuple(directory, dottedFileName)
|
||||
.map(([dirs, name]) => [...dirs, name].join('/')),
|
||||
);
|
||||
|
||||
// De bestanden die op schijf staan, als verzameling (het model van P17)
|
||||
export const existingFiles = fc
|
||||
.uniqueArray(existingFile, { maxLength: 12 })
|
||||
.map((files) => new Set(files));
|
||||
|
||||
export const existsIn =
|
||||
(files: ReadonlySet<string>) =>
|
||||
(file: string): boolean =>
|
||||
files.has(file);
|
||||
Reference in New Issue
Block a user