import { execFile, spawn, type ChildProcess } from 'node:child_process'; import { existsSync, readFileSync, rmSync } from 'node:fs'; import { mkdtemp, rm, writeFile } from 'node:fs/promises'; import { createServer } from 'node:net'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { promisify } from 'node:util'; import { nginxTestConf } from '../../config/serverConfig.ts'; // Start een echte, onbevoorrechte nginx met het gegenereerde testblok // (BR-HST-24). Alleen voor de serverregeltests: eigen prefixmap, eigen poort, // geen systeemconfiguratie. const execFileAsync = promisify(execFile); // Waar nginx kan staan: NGINX_BIN, het PATH, de twee bekende Windows-plekken const windowsPaths = [ 'C:\\nginx\\nginx.exe', 'C:\\Users\\Bryan\\scoop\\apps\\nginx\\current\\nginx.exe', ]; export function findNginx(): string | undefined { const fromEnv = process.env.NGINX_BIN; if (fromEnv) return existsSync(fromEnv) ? fromEnv : undefined; const names = process.platform === 'win32' ? ['nginx.exe'] : ['nginx']; const separator = process.platform === 'win32' ? ';' : ':'; for (const dir of (process.env.PATH ?? '').split(separator)) { for (const name of names) { if (dir && existsSync(join(dir, name))) return join(dir, name); } } // Op Linux staat nginx soms in sbin, buiten het PATH van een gebruiker for (const path of ['/usr/sbin/nginx', ...windowsPaths]) { if (existsSync(path)) return path; } return undefined; } // nginx 1.24 kent .js als application/javascript, vanaf 1.25.2 als // text/javascript (de Pi draait 1.30.6). Beide tabellen worden getest. export type MimeVariant = 'new' | 'old'; const mimeTable = (variant: MimeVariant) => `types { text/html html; text/css css; ${variant === 'old' ? 'application/javascript' : 'text/javascript'} js; image/svg+xml svg; application/json json; text/xml xml; text/plain txt; image/png png; font/woff2 woff2; }`; // Alle nog lopende instanties, voor het opruimen als het proces stopt const running = new Set<{ child: ChildProcess; tmp: string }>(); process.on('exit', () => { for (const { child, tmp } of running) { child.kill(); try { rmSync(tmp, { recursive: true, force: true }); } catch { // Opruimen bij afsluiten mag falen } } }); // Als root (de CI-container) draait de master als root en laat nginx de workers // onder een andere gebruiker (www-data of nobody) draaien. Die kan de // tijdelijke map (mode 700 van mkdtemp) niet openen en geeft overal 403. De // workers draaien daarom ook als root. Zonder root mag de user-directive niet: // nginx waarschuwt dan dat hij alleen voor het hoofdproces als root zin heeft. export const userDirective = (uid: number | undefined) => uid === 0 ? 'user root;\n' : ''; // nginx onder Windows wil voorwaartse slashes in de configuratie const slashed = (path: string) => path.replace(/\\/g, '/'); async function freePort(): Promise { return new Promise((resolve, reject) => { const probe = createServer(); probe.once('error', reject); probe.listen(0, '127.0.0.1', () => { const address = probe.address(); probe.close(() => typeof address === 'object' && address ? resolve(address.port) : reject(new Error('geen poort gekregen')), ); }); }); } export interface RunningNginx { origin: string; version: string; stop(): Promise; } export async function startNginx(options: { siteDir: string; mimeVariant?: MimeVariant; }): Promise { const bin = findNginx(); if (!bin) throw new Error('nginx niet gevonden'); const { mimeVariant = 'new' } = options; const tmp = await mkdtemp(join(tmpdir(), 'andreaslop-nginx-')); const port = await freePort(); const serverFile = join(tmp, 'andreaslop-test.conf'); const confFile = join(tmp, 'nginx.conf'); const errorLog = join(tmp, 'error.log'); const temp = (name: string) => `"${slashed(join(tmp, name))}"`; await writeFile( serverFile, nginxTestConf({ listen: `127.0.0.1:${port}`, root: slashed(options.siteDir), }), ); await writeFile( confFile, `${userDirective(process.getuid?.())}daemon off; pid "${slashed(join(tmp, 'nginx.pid'))}"; error_log "${slashed(errorLog)}"; events {} http { ${mimeTable(mimeVariant)} client_body_temp_path ${temp('client_body')}; proxy_temp_path ${temp('proxy')}; fastcgi_temp_path ${temp('fastcgi')}; uwsgi_temp_path ${temp('uwsgi')}; scgi_temp_path ${temp('scgi')}; access_log off; include "${slashed(serverFile)}"; } `, ); // nginx -v schrijft naar stderr const { stdout, stderr } = await execFileAsync(bin, ['-v']); const version = (stdout + stderr).trim(); await execFileAsync(bin, [ '-t', '-p', `${slashed(tmp)}/`, '-c', slashed(confFile), '-e', slashed(errorLog), ]).catch((error: { stderr?: string }) => { throw new Error(`nginx -t keurt de configuratie af:\n${error.stderr}`); }); const child = spawn( bin, [ '-p', `${slashed(tmp)}/`, '-c', slashed(confFile), '-e', slashed(errorLog), ], { stdio: 'ignore' }, ); const entry = { child, tmp }; running.add(entry); let exited = false; child.once('exit', () => { exited = true; }); const stop = async () => { if (!exited) { const done = new Promise((resolve) => child.once('exit', () => resolve()), ); child.kill(); // Mocht nginx op SIGTERM niet reageren, dan alsnog hard stoppen const timer = setTimeout(() => child.kill('SIGKILL'), 5000); await done; clearTimeout(timer); } running.delete(entry); await rm(tmp, { recursive: true, force: true }); }; const origin = `http://127.0.0.1:${port}`; const deadline = Date.now() + 5000; for (;;) { if (exited) { const log = existsSync(errorLog) ? readFileSync(errorLog, 'utf8') : '(geen foutlog)'; await stop(); throw new Error(`nginx stopte bij het starten:\n${log}`); } try { await fetch(origin + '/'); break; } catch { if (Date.now() > deadline) { await stop(); throw new Error('nginx antwoordde niet binnen 5 seconden'); } await new Promise((resolve) => setTimeout(resolve, 50)); } } return { origin, version, stop }; }