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 = {}, ): Promise { 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 { 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 { 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 { 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 }> { const headers: Record = { ...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((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((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'), 'fixture:index.html', ); }); afterAll(() => site.remove()); const withStub = async ( options: StubOptions, action: (origin: string) => Promise, ) => { 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((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'), ); }); });