#!/usr/bin/env node /** * Integrità del pacchetto di rilascio (brief §11.7), da eseguire dopo scripts/package.mjs: * * - in release/ ci sono solo zip, tar.gz, SHA256SUMS.txt e BUILD-INFO.txt, con i nomi attesi; * - le impronte di SHA256SUMS.txt sono corrette (anche con `sha256sum -c`, se disponibile); * - zip e tar.gz, estratti in una cartella temporanea, contengono esattamente i file di dist/ * (stessi percorsi, dimensioni e contenuto), alla radice, con .htaccess e tutte le pagine; * - lo zip non supera 5 MB; BUILD-INFO.txt riporta versione, commit e data. */ import { execFileSync, spawnSync } from 'node:child_process'; import { createHash } from 'node:crypto'; import { existsSync, mkdtempSync, readFileSync, readdirSync, rmSync, statSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { crc32, inflateRawSync } from 'node:zlib'; import { readSitemapPaths } from './lib/pages.mjs'; import { archiveNames, distDir, listFiles, releaseDir, resolveVersion } from './lib/release.mjs'; const MAX_ZIP = 5 * 1024 * 1024; const errors = []; const fail = (msg) => errors.push(msg); const sha256 = (buf) => createHash('sha256').update(buf).digest('hex'); /** Lettore ZIP minimale (directory centrale + store/deflate), senza dipendenze esterne. */ function readZip(file) { const buf = readFileSync(file); let eocd = -1; for (let i = buf.length - 22; i >= Math.max(0, buf.length - 22 - 65535); i--) { if (buf.readUInt32LE(i) === 0x06054b50) { eocd = i; break; } } if (eocd < 0) throw new Error('fine della directory centrale non trovata (zip danneggiato)'); const count = buf.readUInt16LE(eocd + 10); let p = buf.readUInt32LE(eocd + 16); const entries = new Map(); for (let i = 0; i < count; i++) { if (buf.readUInt32LE(p) !== 0x02014b50) throw new Error('voce della directory centrale non valida'); const method = buf.readUInt16LE(p + 10); const crc = buf.readUInt32LE(p + 16); const compSize = buf.readUInt32LE(p + 20); const size = buf.readUInt32LE(p + 24); const nameLen = buf.readUInt16LE(p + 28); const extraLen = buf.readUInt16LE(p + 30); const commentLen = buf.readUInt16LE(p + 32); const localOffset = buf.readUInt32LE(p + 42); const name = buf.toString('utf8', p + 46, p + 46 + nameLen); p += 46 + nameLen + extraLen + commentLen; if (name.endsWith('/')) continue; // cartella const lNameLen = buf.readUInt16LE(localOffset + 26); const lExtraLen = buf.readUInt16LE(localOffset + 28); const start = localOffset + 30 + lNameLen + lExtraLen; const raw = buf.subarray(start, start + compSize); const data = method === 0 ? raw : method === 8 ? inflateRawSync(raw) : null; if (!data) throw new Error(`metodo di compressione ${method} non supportato (${name})`); if (data.length !== size) throw new Error(`dimensione errata per ${name}`); if (crc32(data) !== crc) throw new Error(`CRC errato per ${name}`); entries.set(name, data); } return entries; } /** * Estrazione del tar.gz con `tar` di sistema in una cartella temporanea. L'archivio arriva da * stdin: su Windows il GNU tar di Git Bash interpreta «C:\…» come host remoto. */ function readTarGz(file) { const dir = mkdtempSync(join(tmpdir(), 'sito-studio-grasso-')); try { execFileSync('tar', ['-xzf', '-'], { cwd: dir, input: readFileSync(file) }); const entries = new Map(); for (const rel of listAll(dir)) entries.set(rel, readFileSync(join(dir, rel))); return entries; } finally { rmSync(dir, { recursive: true, force: true }); } } function listAll(dir, base = '') { const out = []; for (const e of readdirSync(join(dir, base), { withFileTypes: true })) { const rel = base ? `${base}/${e.name}` : e.name; if (e.isDirectory()) out.push(...listAll(dir, rel)); else out.push(rel); } return out.sort(); } function compareWithDist(label, entries, expected) { const names = [...entries.keys()].sort(); const missing = expected.filter((f) => !entries.has(f)); const extra = names.filter((f) => !expected.includes(f)); if (missing.length) fail(`${label}: file di dist/ mancanti nell'archivio: ${missing.join(', ')}`); if (extra.length) fail(`${label}: file in più rispetto a dist/: ${extra.join(', ')}`); for (const f of expected) { const data = entries.get(f); if (!data) continue; const original = readFileSync(join(distDir, f)); if (data.length !== original.length) fail(`${label}: dimensione diversa per ${f}`); else if (sha256(data) !== sha256(original)) fail(`${label}: contenuto diverso per ${f}`); } if ([...entries.keys()].some((f) => f.startsWith('dist/'))) { fail(`${label}: i file devono stare alla radice dell'archivio, non in una cartella dist/`); } const required = [ 'index.html', '404.html', '.htaccess', 'robots.txt', 'sitemap-index.xml', 'favicon.svg', ]; for (const f of required) if (!entries.has(f)) fail(`${label}: manca ${f} alla radice`); for (const p of readSitemapPaths(distDir)) { const f = p === '/' ? 'index.html' : `${p.replace(/^\//, '')}index.html`; if (!entries.has(f)) fail(`${label}: manca la pagina ${p} (${f})`); } if ([...entries.keys()].some((f) => f.endsWith('.map'))) fail(`${label}: contiene file .map`); } /* ------------------------------------------------------------------ verifica */ let version; try { version = resolveVersion(); } catch (e) { console.error(`✘ ${e.message}`); process.exit(1); } const names = archiveNames(version); const expectedRelease = [names.zip, names.tgz, 'SHA256SUMS.txt', 'BUILD-INFO.txt'].sort(); if (!existsSync(releaseDir)) { console.error('✘ release/ assente: eseguire `npm run package`.'); process.exit(1); } const present = readdirSync(releaseDir).sort(); for (const f of expectedRelease) if (!present.includes(f)) fail(`release/: manca ${f}`); for (const f of present) if (!expectedRelease.includes(f)) fail(`release/: file inatteso ${f} (la cartella deve contenere solo il pacchetto)`); // impronte const sumsFile = join(releaseDir, 'SHA256SUMS.txt'); if (existsSync(sumsFile)) { const lines = readFileSync(sumsFile, 'utf8').trim().split('\n'); const listed = new Set(); for (const line of lines) { const m = line.match(/^([0-9a-f]{64}) {2}(.+)$/); if (!m) { fail(`SHA256SUMS.txt: riga non valida «${line}»`); continue; } listed.add(m[2]); const target = join(releaseDir, m[2]); if (!existsSync(target)) fail(`SHA256SUMS.txt: il file ${m[2]} non esiste`); else if (sha256(readFileSync(target)) !== m[1]) fail(`SHA256SUMS.txt: impronta errata per ${m[2]}`); } for (const f of [names.zip, names.tgz]) if (!listed.has(f)) fail(`SHA256SUMS.txt: manca ${f}`); const tool = spawnSync('sha256sum', ['-c', 'SHA256SUMS.txt'], { cwd: releaseDir, encoding: 'utf8', }); if (tool.error) console.log(' (sha256sum non disponibile: impronte verificate solo con Node.js)'); else if (tool.status !== 0) fail(`sha256sum -c non superato:\n${tool.stdout}${tool.stderr}`); else console.log(` sha256sum -c: ${tool.stdout.trim().split('\n').join(' · ')}`); } // contenuto degli archivi const expected = listFiles(distDir); const zipPath = join(releaseDir, names.zip); const tgzPath = join(releaseDir, names.tgz); if (existsSync(zipPath)) { const size = statSync(zipPath).size; if (size > MAX_ZIP) fail(`${names.zip}: ${(size / 1048576).toFixed(2)} MB oltre il limite di 5 MB`); try { compareWithDist(names.zip, readZip(zipPath), expected); } catch (e) { fail(`${names.zip}: ${e.message}`); } } if (existsSync(tgzPath)) { try { compareWithDist(names.tgz, readTarGz(tgzPath), expected); } catch (e) { fail(`${names.tgz}: ${e.message}`); } } // BUILD-INFO const infoFile = join(releaseDir, 'BUILD-INFO.txt'); if (existsSync(infoFile)) { const info = readFileSync(infoFile, 'utf8'); if (!info.includes(`Versione: ${version}`)) fail('BUILD-INFO.txt: manca «Versione»'); if (!/^Commit: [0-9a-f]{7,40}$/m.test(info)) fail('BUILD-INFO.txt: manca l’hash del commit'); if (!/^Data: \d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/m.test(info)) fail('BUILD-INFO.txt: manca la data ISO'); if (!/^Node\.js: v\d+/m.test(info) || !/^Astro: \d+/m.test(info)) fail('BUILD-INFO.txt: mancano le versioni di Node.js e Astro'); } if (errors.length) { console.error(`✘ Pacchetto v${version}: ${errors.length} errori`); for (const e of errors) console.error(` - ${e}`); process.exit(1); } const zipKb = (statSync(zipPath).size / 1024).toFixed(1); console.log( `✔ Pacchetto v${version} verificato: ${expected.length} file identici a dist/ in zip (${zipKb} KB) e tar.gz, impronte corrette.`, );