import { request } from 'node:http'; import { connect } from 'node:net'; import { gunzipSync } from 'node:zlib'; import { afterAll, beforeAll, describe, expect, it } from 'vitest'; import { securityHeaders } from '../config/securityHeaders.ts'; import { createFixtureSite, type FixtureSite } from './support/fixtureSite.ts'; import { findNginx, startNginx, type MimeVariant, type RunningNginx, } from './support/nginx.ts'; // BR-HST-24: de nginx-regels worden bewezen door een echte nginx, niet door de // tekst te lezen. De site is een kleine fixture (geen build nodig); dezelfde // regels voor de previewserver staan in previewServer.test.ts. const nginxBin = findNginx(); const inCi = Boolean(process.env.CI); // Zonder nginx: in CI een duidelijke fout, lokaal een zichtbare melding if (!nginxBin) { if (inCi) { describe('serverregels (nginx)', () => { it('vindt nginx', () => { throw new Error('nginx ontbreekt in CI (BR-HST-24)'); }); }); } else { describe('serverregels (nginx)', () => { it('nginx niet gevonden: serverregeltests overgeslagen (zie BR-HST-24)', (context) => { console.log(context.task.name); context.skip(); }); }); } } interface Reply { status: number; headers: Record; rawHeaders: string[]; body: Buffer; } // node:http en niet fetch: fetch voegt dubbele headers samen en pakt gzip uit function get( origin: string, path: string, options: { method?: string; headers?: Record } = {}, ): Promise { return new Promise((resolve, reject) => { const req = request( origin + path, { method: options.method ?? 'GET', headers: options.headers }, (res) => { const chunks: Buffer[] = []; res.on('data', (chunk: Buffer) => chunks.push(chunk)); res.on('end', () => resolve({ status: res.statusCode ?? 0, headers: Object.fromEntries( Object.entries(res.headers).map(([k, v]) => [ k, String(v), ]), ), rawHeaders: res.rawHeaders, body: Buffer.concat(chunks), }), ); }, ); req.on('error', reject); req.end(); }); } const countHeader = (reply: Reply, name: string) => reply.rawHeaders.filter( (value, i) => i % 2 === 0 && value.toLowerCase() === name.toLowerCase(), ).length; // Alle productieheaders, X-Robots-Tag en precies één Cache-Control function expectFullHeaders(reply: Reply, cacheControl = 'no-cache') { for (const [name, value] of Object.entries(securityHeaders('production'))) { expect(countHeader(reply, name), name).toBe(1); expect(reply.headers[name.toLowerCase()], name).toBe(value); } expect(countHeader(reply, 'X-Robots-Tag')).toBe(1); expect(reply.headers['x-robots-tag']).toBe('noindex, nofollow'); expect(countHeader(reply, 'Cache-Control')).toBe(1); expect(reply.headers['cache-control']).toBe(cacheControl); } // Een ruw HTTP/1.0-verzoek, zoals de proxy-Pi dat naar de hosting-Pi stuurt function getHttp10(origin: string, path: string, headers: string[]) { const { port } = new URL(origin); return new Promise<{ head: string; body: Buffer }>((resolve, reject) => { const socket = connect(Number(port), '127.0.0.1'); const chunks: Buffer[] = []; socket.on('connect', () => socket.write( [ `GET ${path} HTTP/1.0`, 'Host: test.andreaslop.nl', ...headers, '', '', ].join('\r\n'), ), ); socket.on('data', (chunk: Buffer) => chunks.push(chunk)); socket.on('error', reject); socket.on('close', () => { const all = Buffer.concat(chunks); const split = all.indexOf('\r\n\r\n'); resolve({ head: all.subarray(0, split).toString('latin1'), body: all.subarray(split + 4), }); }); }); } const mimeVariants: MimeVariant[] = ['new', 'old']; const rulesSuite = nginxBin ? describe : describe.skip; rulesSuite.each(mimeVariants)( 'serverregels op een echte nginx (.js als %s mime-type)', (variant) => { let site: FixtureSite; let nginx: RunningNginx; const markerOf = (file: string) => site.markers.get(file) ?? file; beforeAll(async () => { site = await createFixtureSite(); nginx = await startNginx({ siteDir: site.dir, mimeVariant: variant, }); console.log( `[serverRules] nginx -v: ${nginx.version} (${nginx.origin})`, ); }); afterAll(async () => { await nginx?.stop(); await site?.remove(); }); const page = (path: string, init?: Parameters[2]) => get(nginx.origin, path, init); describe("pagina's en bestanden (BR-HST-01, V3)", () => { it.each([ ['/', 'index.html'], ['/over-mij', 'over-mij.html'], ['/soorten-fotoshoots', 'soorten-fotoshoots.html'], [ '/soorten-fotoshoots/newborn', 'soorten-fotoshoots/newborn.html', ], ['/over-mij?x=1', 'over-mij.html'], ['/?x=1', 'index.html'], ])('%s geeft 200 met %s', async (path, file) => { const reply = await page(path); expect(reply.status).toBe(200); expect(reply.body.toString()).toContain(markerOf(file)); expectFullHeaders(reply); }); it.each([ ['/assets/index-AbC123xYz.js', 'assets/index-AbC123xYz.js'], ['/sitemap.xml', 'sitemap.xml'], ])('%s geeft 200 met het bestand', async (path, file) => { const reply = await page(path); expect(reply.status).toBe(200); expect(reply.body.toString()).toContain(markerOf(file)); }); it('de map soorten-fotoshoots/ naast het paginabestand stuurt niet door en toont geen lijst (V3)', async () => { const file = await page('/soorten-fotoshoots'); expect(file.status).toBe(200); expect(file.body.toString()).toContain( markerOf('soorten-fotoshoots.html'), ); const dir = await page('/soorten-fotoshoots/'); expect(dir.status).toBe(301); expect(dir.headers.location).toBe('/soorten-fotoshoots'); }); it('/ werkt zonder index-directive (V2)', async () => { const reply = await page('/'); expect(reply.status).toBe(200); expect(reply.body.toString()).toContain(markerOf('index.html')); }); it('/robots.txt verbiedt alles op de testsite', async () => { const reply = await page('/robots.txt'); expect(reply.status).toBe(200); expect(reply.body.toString()).toContain('Disallow: /'); expect(reply.body.toString()).not.toContain('fixture:'); expectFullHeaders(reply); }); }); describe('doorverwijzingen (BR-HST-03, 04, 06, V2)', () => { it.each([ ['/over-mij/', '/over-mij'], ['/over-mij///', '/over-mij'], ['/soorten-fotoshoots/', '/soorten-fotoshoots'], ['/over-mij/?x=1', '/over-mij?x=1'], ['/soorten-fotoshoots/?x=1', '/soorten-fotoshoots?x=1'], ['/over-mij.html', '/over-mij'], [ '/soorten-fotoshoots/newborn.html', '/soorten-fotoshoots/newborn', ], ['/index', '/'], ['/index.html', '/'], ['/index/', '/'], ['/Over-Mij', '/over-mij'], ['/OVER-MIJ.HTML', '/over-mij'], ['/Over-Mij/', '/over-mij'], ['/Over-Mij?x=1&y=%20z', '/over-mij?x=1&y=%20z'], ['/onbekend/', '/onbekend'], ['/assets/', '/assets'], ])('%s gaat met één 301 naar %s', async (path, target) => { const reply = await page(path); expect(reply.status).toBe(301); // Relatief: absolute_redirect staat uit expect(reply.headers.location).toBe(target); expectFullHeaders(reply); }); }); describe('404 (BR-HST-02, 05, V4)', () => { it.each([ '/404', '/404.html', '/onbekend', '/Onbekend', '/x.html', '/assets/missing.js', '/assets', ])('%s geeft 404 met de 404-pagina', async (path) => { const reply = await page(path); expect(reply.status).toBe(404); expect(reply.body.toString()).toContain(markerOf('404.html')); // Ook de 404 van een ontbrekend asset is niet immutable expectFullHeaders(reply); }); it('HEAD op een pagina en op een onbekende URL', async () => { const ok = await page('/over-mij', { method: 'HEAD' }); expect(ok.status).toBe(200); expect(ok.body).toHaveLength(0); expectFullHeaders(ok); const missing = await page('/onbekend', { method: 'HEAD' }); expect(missing.status).toBe(404); expect(missing.body).toHaveLength(0); expectFullHeaders(missing); }); }); describe('caching (BR-HST-12)', () => { it('/assets/* heeft precies één Cache-Control: immutable', async () => { for (const path of [ '/assets/index-AbC123xYz.js', '/assets/style-Qw9.css', '/assets/font-Ab.woff2', ]) { const reply = await page(path); expect(reply.status, path).toBe(200); expectFullHeaders( reply, 'public, max-age=31536000, immutable', ); } }); it('al het andere revalideert', async () => { for (const path of ['/', '/sitemap.xml', '/favicon.png']) { expectFullHeaders(await page(path)); } }); }); describe('compressie (BR-HST-09, V5)', () => { const compressed = [ '/', '/over-mij', '/assets/index-AbC123xYz.js', '/assets/style-Qw9.css', '/assets/icon-Zz1.svg', '/assets/data.json', '/sitemap.xml', '/assets/readme.txt', ]; const plain = ['/assets/font-Ab.woff2', '/favicon.png']; it.each(compressed)('%s krijgt gzip', async (path) => { const reply = await page(path, { headers: { 'Accept-Encoding': 'gzip' }, }); expect(reply.status).toBe(200); expect(reply.headers['content-encoding']).toBe('gzip'); expect(reply.headers.vary).toContain('Accept-Encoding'); expect(gunzipSync(reply.body).length).toBeGreaterThan(256); }); it.each(plain)('%s krijgt geen gzip', async (path) => { const reply = await page(path, { headers: { 'Accept-Encoding': 'gzip' }, }); expect(reply.status).toBe(200); expect(reply.headers['content-encoding']).toBeUndefined(); }); it.each(compressed)( '%s krijgt gzip over HTTP/1.0 (zoals de proxy het vraagt)', async (path) => { const reply = await getHttp10(nginx.origin, path, [ 'Accept-Encoding: gzip', ]); expect(reply.head).toMatch(/^HTTP\/1\.\d 200/); expect(reply.head).toMatch(/content-encoding: gzip/i); expect(gunzipSync(reply.body).length).toBeGreaterThan(256); }, ); it.each(plain)( '%s krijgt over HTTP/1.0 geen gzip', async (path) => { const reply = await getHttp10(nginx.origin, path, [ 'Accept-Encoding: gzip', ]); expect(reply.head).toMatch(/^HTTP\/1\.\d 200/); expect(reply.head).not.toMatch(/content-encoding/i); }, ); it('zonder Accept-Encoding blijft het antwoord onbewerkt', async () => { const reply = await page('/assets/index-AbC123xYz.js'); expect(reply.headers['content-encoding']).toBeUndefined(); expect(reply.body.toString()).toContain( markerOf('assets/index-AbC123xYz.js'), ); }); }); describe('vijandige paden (BR-HST-06)', () => { it.each([ '//evil.example/', '//evil.example', '/\\evil.example/', '/\\evil.example', '/%5Cevil.example/', '/%2F%2Fevil.example/', '/%0d%0aSet-Cookie:%20x=1/', '/over-mij%0d%0aSet-Cookie:%20x=1/', '/%2e%2e/', ])('%s leidt niet naar een ander domein', async (path) => { const reply = await page(path); const location = reply.headers.location; if (reply.status >= 300 && reply.status < 400) { expect(location).toBeDefined(); expect(location?.startsWith('//')).toBe(false); expect(location?.startsWith('/\\')).toBe(false); expect(location).not.toMatch(/[\r\n]/); } expect(reply.headers['set-cookie']).toBeUndefined(); }); }); }, );