Adds the URL rules to the preview server, IIS config and deploy
The preview server and web.config now follow the same URLs as nginx, without the SPA fallback. Lighthouse exceptions need a recorded reason and the 404 page is audited through an opt-in route. The deploy checks the build first and the served result afterwards. The IIS rules stay unverified until a host exists. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -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