Files
Studio_Grasso/scripts/check-compliance.mjs
T
Claude 0a718a8f6d fix: correzioni della verifica indipendente
- privacy (modalità php): conservazione dell'impronta HMAC descritta come
  avviene davvero; cron facoltativo in DEPLOY.md
- contitolarità con Google: punto di contatto e verifica dell'accordo
  ex art. 26 in TODO B4; informativa breve con art. 6.1.b o f
- «titolo conseguito in Italia» tolto: dato da confermare (statoTitolo,
  TODO C13); qualifica CAF del Dott. Ezio Grasso con la dicitura ufficiale
- mappe: il consenso carica tutte le mappe della pagina
- Esc sul sottomenu riporta il focus sul pulsante; sidebar «Altri servizi»
- resa: anello CTA ancorato al contenuto, colonna legale allineata alla
  testa, spazi non separabili anche nei testi legali e nel ruolo, «tel.»
  unito al numero, a capo dopo la @ nel pulsante e-mail, breadcrumb
- contact.php: UTF-8 non valido rifiutato, nessun avviso con open_basedir,
  apostrofi tipografici; CSP con direttive ripetute segnalate;
  --shell-safe neutralizza ogni $
- DEPLOY: ordine dei passi della modalità endpoint; TODO B2/C13 e righe
- date di aggiornamento dei testi legali

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016zJ9ZWGKvoKoxYwbmnRKdJ
2026-10-16 00:49:49 +00:00

774 lines
26 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env node
/**
* Controlli di conformità sul sito compilato (brief §11.5). Ogni errore indica COSA non va e
* DOVE (file di dist/). Richiede `npm run build`. Uscita con codice 1 se c'è almeno un errore.
*
* I dati attesi (abilitazioni, servizi, P.IVA, professionisti) sono letti dalle stesse fonti
* del sito: src/data/studio.ts e src/content/servizi/*.md.
*/
import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
import { join, resolve } from 'node:path';
import { pathToFileURL } from 'node:url';
import { DomUtils, parseDocument } from 'htmlparser2';
import { fileToPath, listHtmlFiles, readSitemapPaths } from './lib/pages.mjs';
import { root } from './lib/preview-server.mjs';
const dist = resolve(root, 'dist');
// I moduli TypeScript del sito sono importati direttamente (type stripping di Node), con URL
// file:// perché su Windows un percorso assoluto non è un URL valido per import().
const importSrc = (path) => import(pathToFileURL(resolve(root, path)).href);
const { abilitazioni, professionisti, studio, contactForm } = await importSrc('src/data/studio.ts');
// stesso anno del footer: SOURCE_DATE_EPOCH, se impostata, altrimenti l'anno corrente
const { buildYear } = await importSrc('src/lib/build.ts');
const SITE = (process.env.SITE_URL || 'https://www.grassoezio.it').replace(/\/+$/, '');
const PIVA = `P.IVA ${studio.partitaIva}`;
const LEGAL_PAGES = ['/privacy-policy/', '/cookie-policy/', '/note-legali/', '/accessibilita/'];
const NOINDEX_PAGES = ['/404.html', '/contatti/grazie/'];
const BUDGET_HTML_CSS = 120 * 1024;
const BUDGET_JS = 15 * 1024;
const BUDGET_FONTS = 110 * 1024;
const errors = [];
const fail = (where, what) => errors.push(`${where}: ${what}`);
let checks = 0;
const check = (ok, where, what) => {
checks++;
if (!ok) fail(where, what);
return ok;
};
/* ------------------------------------------------------------------ utilità DOM */
const { findAll, findOne, getAttributeValue: attr, textContent, getParent } = DomUtils;
const isTag = (n) => n.type === 'tag' || n.type === 'script' || n.type === 'style';
const all = (doc, pred) => findAll((n) => isTag(n) && pred(n), doc.children);
const byTag = (doc, name) => all(doc, (n) => n.name === name);
const normalize = (s) => s.replace(/\s+/g, ' ').replace(/[’‘]/g, "'").trim();
/** Testo visibile (esclusi script, style, noscript, template). */
function visibleText(node) {
if (node.type === 'text') return node.data;
if (!isTag(node) && node.type !== 'root') return '';
if (['script', 'style', 'noscript', 'template'].includes(node.name)) return '';
return (node.children ?? []).map(visibleText).join(' ');
}
const BLOCKS = new Set([
'p',
'li',
'dd',
'dt',
'h1',
'h2',
'h3',
'h4',
'h5',
'h6',
'td',
'th',
'address',
'figcaption',
'blockquote',
'label',
'button',
'a',
'title',
]);
/** Tutti i nodi di testo del documento (DomUtils.findAll restituisce solo elementi). */
function textNodes(node, out = []) {
for (const child of node.children ?? []) {
if (child.type === 'text') out.push(child);
else textNodes(child, out);
}
return out;
}
/** Divide in frasi senza spezzare abbreviazioni come «Dott.», «Dott.ssa», «n.», «sez.». */
function sentences(text) {
const protectedText = text.replace(
/\b(Dott|Dott\.ssa|Avv|Rag|Sig|n|nn|sez|art|artt|co|lett|par|D\.Lgs|D\.L|L|Reg|ecc|es|tel|p)\./gi,
(m) => m.replace(/\./g, '\u2024'),
);
return protectedText.split(/(?<=[.!?;])\s+/).map((s) => s.replace(/\u2024/g, '.'));
}
function closestBlock(node) {
let n = getParent(node);
while (n && !(isTag(n) && BLOCKS.has(n.name))) n = getParent(n);
return n;
}
function ancestorWithAttr(node, name, value) {
for (let n = getParent(node); n; n = getParent(n)) {
if (isTag(n) && attr(n, name) === value) return n;
}
return null;
}
/* ------------------------------------------------------------------ pagine */
check(existsSync(dist), 'dist/', 'cartella assente: esegui prima `npm run build`');
const htmlFiles = listHtmlFiles(dist);
const pages = htmlFiles.map((file) => {
const html = readFileSync(join(dist, file), 'utf8');
return { file: `dist/${file}`, path: fileToPath(file), html, doc: parseDocument(html) };
});
const byPath = new Map(pages.map((p) => [p.path, p]));
check(pages.length >= 18, 'dist/', `attese almeno 18 pagine HTML, trovate ${pages.length}`);
/* ------------------------------------------------------------------ file obbligatori */
for (const f of [
'.htaccess',
'404.html',
'robots.txt',
'sitemap-index.xml',
'favicon.svg',
'favicon.ico',
]) {
check(existsSync(join(dist, f)), `dist/${f}`, 'file obbligatorio mancante');
}
for (const p of LEGAL_PAGES) {
const page = byPath.get(p);
if (check(Boolean(page), `pagina ${p}`, 'pagina legale mancante')) {
check(byTag(page.doc, 'h1').length === 1, page.file, 'la pagina legale deve avere un <h1>');
}
}
/* ------------------------------------------------------------------ robots e sitemap */
const robots = existsSync(join(dist, 'robots.txt'))
? readFileSync(join(dist, 'robots.txt'), 'utf8')
: '';
check(
robots.includes(`Sitemap: ${SITE}/sitemap-index.xml`),
'dist/robots.txt',
`manca la riga «Sitemap: ${SITE}/sitemap-index.xml»`,
);
check(
/User-agent:\s*\*/i.test(robots) && /Allow:\s*\//i.test(robots),
'dist/robots.txt',
'mancano User-agent/Allow',
);
const sitemapPaths = readSitemapPaths(dist);
const expectedInSitemap = pages
.map((p) => p.path)
.filter((p) => !NOINDEX_PAGES.includes(p))
.sort();
for (const p of expectedInSitemap)
check(sitemapPaths.includes(p), 'sitemap', `manca la pagina ${p}`);
for (const p of sitemapPaths) {
check(expectedInSitemap.includes(p), 'sitemap', `contiene ${p}, che non esiste o è noindex`);
}
for (const p of NOINDEX_PAGES) {
const page = byPath.get(p);
if (check(Boolean(page), `pagina ${p}`, 'pagina mancante')) {
const robotsMeta = findOne(
(n) => n.name === 'meta' && attr(n, 'name') === 'robots',
page.doc.children,
);
check(
/noindex/.test(attr(robotsMeta ?? {}, 'content') ?? ''),
page.file,
'manca <meta name="robots" content="noindex">',
);
}
}
/* ------------------------------------------------------------------ controlli per pagina */
const PLACEHOLDERS = [
/\bTODO\b/,
/lorem/i,
/XXX/,
/\[da\b/i,
/\{\{|\}\}/,
/\bundefined\b/,
/\bnull\b/,
/NaN/,
];
const FORBIDDEN_REFS = [
/fonts\.googleapis\.com/i,
/gstatic/i,
/analytics/i,
/gtag/i,
/\bcdn\./i,
/googletagmanager/i,
];
const COMMERCIALISTA_OK =
/giulia|odcec|(ordine|consiglio nazionale) dei dottori commercialisti|\bocc\b|organismo di composizione della crisi/i;
const titles = new Map();
const descriptions = new Map();
const year = String(buildYear);
for (const page of pages) {
const { doc, file, path, html } = page;
const where = `${file} (${path})`;
// lingua, viewport, titolo, descrizione, canonical
const htmlEl = byTag(doc, 'html')[0];
check(attr(htmlEl ?? {}, 'lang') === 'it', where, 'manca lang="it" su <html>');
const viewport = findOne(
(n) => n.name === 'meta' && attr(n, 'name') === 'viewport',
doc.children,
);
const vp = attr(viewport ?? {}, 'content') ?? '';
check(Boolean(viewport), where, 'manca il meta viewport');
check(
!/user-scalable\s*=\s*(no|0)|maximum-scale/i.test(vp),
where,
`meta viewport che blocca lo zoom: «${vp}»`,
);
const title = normalize(textContent(byTag(doc, 'title')[0] ?? { children: [] }));
check(
title.length > 0 && title.length <= 65,
where,
`titolo vuoto o oltre 65 caratteri: «${title}»`,
);
if (titles.has(title)) fail(where, `titolo duplicato di ${titles.get(title)}: «${title}»`);
titles.set(title, path);
const descEl = findOne(
(n) => n.name === 'meta' && attr(n, 'name') === 'description',
doc.children,
);
const desc = normalize(attr(descEl ?? {}, 'content') ?? '');
check(
desc.length >= 120 && desc.length <= 155,
where,
`descrizione di ${desc.length} caratteri (attesi 120–155)`,
);
if (descriptions.has(desc)) fail(where, `descrizione duplicata di ${descriptions.get(desc)}`);
descriptions.set(desc, path);
// canonical e og:url solo per le pagine indicizzabili (404 e conferma del modulo: nessuno)
const canonical = findOne(
(n) => n.name === 'link' && attr(n, 'rel') === 'canonical',
doc.children,
);
const ogUrl = findOne((n) => n.name === 'meta' && attr(n, 'property') === 'og:url', doc.children);
if (NOINDEX_PAGES.includes(path)) {
check(!canonical && !ogUrl, where, 'pagina noindex con canonical o og:url');
} else {
check(
attr(canonical ?? {}, 'href') === `${SITE}${path}`,
where,
`canonical atteso ${SITE}${path}, trovato ${attr(canonical ?? {}, 'href')}`,
);
check(attr(ogUrl ?? {}, 'content') === `${SITE}${path}`, where, 'og:url diverso dal canonical');
}
// un solo h1
check(
byTag(doc, 'h1').length === 1,
where,
`attesa una sola intestazione <h1>, trovate ${byTag(doc, 'h1').length}`,
);
// footer: P.IVA, anno, link legali
const footer = byTag(doc, 'footer')[0];
const footerText = footer ? normalize(visibleText(footer)) : '';
check(footerText.includes(PIVA), where, `il footer non contiene «${PIVA}»`);
check(
footerText.includes(`© ${year}`),
where,
`il footer non contiene «© ${year}» (anno di build)`,
);
for (const legal of ['/privacy-policy/', '/cookie-policy/', '/note-legali/', '/accessibilita/']) {
const found = all(doc, (n) => n.name === 'a' && attr(n, 'href') === legal).length > 0;
check(found, where, `manca il link a ${legal}`);
}
// risorse: niente http://, niente domini vietati, niente iframe statici
for (const el of all(doc, () => true)) {
for (const name of ['src', 'href', 'srcset', 'action', 'data-map-src', 'poster']) {
const v = attr(el, name);
if (v && /^\s*http:\/\//i.test(v))
fail(where, `risorsa o link non sicuro (http://) in <${el.name} ${name}="${v}">`);
}
for (const [name, value] of Object.entries(el.attribs ?? {})) {
if (/^on[a-z]+$/i.test(name))
fail(where, `gestore di evento inline vietato dalla CSP: <${el.name} ${name}="${value}">`);
}
}
for (const re of FORBIDDEN_REFS)
check(!re.test(html), where, `riferimento vietato a ${re.source.replace(/\\/g, '')}`);
check(
byTag(doc, 'iframe').length === 0,
where,
"<iframe> presente nell'HTML statico (la mappa va caricata solo su richiesta)",
);
// script: solo esterni dallo stesso sito o dati JSON-LD
for (const s of byTag(doc, 'script')) {
const type = attr(s, 'type') ?? '';
const src = attr(s, 'src');
if (type === 'application/ld+json') continue;
check(
Boolean(src) && src.startsWith('/'),
where,
`script inline o esterno non ammesso dalla CSP (type="${type}" src="${src ?? ''}")`,
);
}
// immagini con alt e dimensioni
for (const img of byTag(doc, 'img')) {
check(
attr(img, 'alt') !== undefined,
where,
`<img src="${attr(img, 'src')}"> senza attributo alt`,
);
check(
Boolean(attr(img, 'width') && attr(img, 'height')),
where,
`<img src="${attr(img, 'src')}"> senza width/height`,
);
}
// link esterni: rel="noopener", nessun target="_blank" non segnalato
for (const a of byTag(doc, 'a')) {
const href = attr(a, 'href') ?? '';
if (/^https?:\/\//.test(href) && !href.startsWith(SITE)) {
check(
/\bnoopener\b/.test(attr(a, 'rel') ?? ''),
where,
`link esterno senza rel="noopener": ${href}`,
);
}
if (attr(a, 'target') === '_blank') {
check(
/nuova scheda|nuova finestra/i.test(textContent(a)),
where,
`link con target="_blank" senza indicazione per screen reader: ${href}`,
);
}
}
// segnaposto nel testo visibile e negli attributi testuali
const text = visibleText(doc);
const attrText = all(doc, () => true)
.flatMap((el) =>
['alt', 'title', 'aria-label', 'placeholder', 'content', 'value'].map(
(n) => attr(el, n) ?? '',
),
)
.join(' ');
for (const re of PLACEHOLDERS) {
const m = (text + ' ' + attrText).match(re);
check(!m, where, `testo segnaposto «${m?.[0]}» presente nella pagina`);
}
// «commercialista» solo per la Dott.ssa Giulia Grasso, l'ODCEC o l'OCC (controllo per frase)
for (const node of textNodes(doc)) {
if (!/commercialist/i.test(node.data)) continue;
let p = getParent(node);
let skip = false;
for (; p; p = getParent(p))
if (isTag(p) && ['script', 'style', 'noscript'].includes(p.name)) skip = true;
if (skip) continue;
if (ancestorWithAttr(node, 'data-person', 'giulia-grasso')) continue;
const block = closestBlock(node) ?? getParent(node);
const blockText = normalize(visibleText(block));
for (const s of sentences(blockText).filter((x) => /commercialist/i.test(x))) {
check(
COMMERCIALISTA_OK.test(s),
where,
`«commercialista» usato fuori contesto (ammesso solo per la Dott.ssa Giulia Grasso, ODCEC, OCC): «${s}»`,
);
}
}
const lower = normalize(text).toLowerCase();
for (const bad of [
'studio commercialista',
'studio di commercialisti',
'studio di commercialista',
'commercialista ezio',
'ezio grasso, commercialista',
'ezio grasso commercialista',
]) {
check(!lower.includes(bad), where, `dicitura vietata «${bad}»`);
}
// JSON-LD
const ld = byTag(doc, 'script').filter((s) => attr(s, 'type') === 'application/ld+json');
check(ld.length > 0, where, 'nessun dato strutturato JSON-LD');
const nodes = [];
for (const s of ld) {
try {
const data = JSON.parse(textContent(s));
check(
data['@context'] === 'https://schema.org',
where,
'JSON-LD senza @context https://schema.org',
);
for (const item of data['@graph'] ?? [data]) {
check(Boolean(item['@type']), where, 'elemento JSON-LD senza @type');
nodes.push(item);
}
} catch (e) {
fail(where, `JSON-LD non valido: ${e.message}`);
}
}
const org = nodes.find((n) => n['@type'] === 'AccountingService');
if (check(Boolean(org), where, 'JSON-LD: manca AccountingService')) {
for (const k of [
'name',
'url',
'telephone',
'email',
'address',
'location',
'openingHoursSpecification',
'areaServed',
'employee',
'sameAs',
]) {
check(org[k] !== undefined, where, `JSON-LD AccountingService: manca «${k}»`);
}
check(
org.name === `${studio.nome} — ${studio.sottotitolo}`,
where,
`JSON-LD: name atteso «${studio.nome} — ${studio.sottotitolo}»`,
);
check(
org.vatID === `IT${studio.partitaIva}`,
where,
`JSON-LD: vatID atteso IT${studio.partitaIva}`,
);
check(
org.telephone === studio.telefoni[0].display,
where,
'JSON-LD: telefono diverso da studio.ts',
);
check(org.email === studio.email, where, 'JSON-LD: e-mail diversa da studio.ts');
check(
org.address?.['@type'] === 'PostalAddress',
where,
'JSON-LD: address non è un PostalAddress',
);
check(
Array.isArray(org.sameAs) && org.sameAs.length === 0,
where,
'JSON-LD: sameAs deve essere vuoto (nessun social)',
);
const hours = (org.openingHoursSpecification ?? [])
.map((h) => `${h.opens}-${h.closes}`)
.sort()
.join(',');
check(
hours === '09:00-12:30,15:00-18:30',
where,
`JSON-LD: orari attesi 09:00-12:30 e 15:00-18:30, trovati ${hours}`,
);
const people = (org.employee ?? org.founder ?? []).filter((p) => p['@type'] === 'Person');
check(people.length === professionisti.length, where, 'JSON-LD: professionisti mancanti');
for (const p of professionisti) {
const ldp = people.find((x) => x.name === p.nomeSenzaTitolo);
check(
ldp?.jobTitle === p.qualificaPrincipale,
where,
`JSON-LD: jobTitle di ${p.nome} diverso da studio.ts`,
);
}
}
const internal = path !== '/' && path !== '/404.html';
if (internal)
check(
nodes.some((n) => n['@type'] === 'BreadcrumbList'),
where,
'JSON-LD: manca BreadcrumbList',
);
if (/^\/servizi\/[^/]+\/$/.test(path)) {
const service = nodes.find((n) => n['@type'] === 'Service');
if (check(Boolean(service), where, 'JSON-LD: manca Service')) {
for (const k of ['name', 'description', 'provider', 'areaServed'])
check(Boolean(service[k]), where, `JSON-LD Service: manca «${k}»`);
}
}
// budget HTML + CSS (il CSS è incluso nella pagina)
const size = statSync(join(dist, file.replace(/^dist\//, ''))).size;
check(
size <= BUDGET_HTML_CSS,
where,
`HTML+CSS di ${Math.round(size / 1024)} KB oltre il budget di 120 KB`,
);
}
/* ------------------------------------------------------------------ contenuti attesi */
function servicesFromCollection() {
const dir = resolve(root, 'src/content/servizi');
return readdirSync(dir)
.filter((f) => f.endsWith('.md'))
.map((f) => {
const fm = readFileSync(join(dir, f), 'utf8').split('---')[1];
const get = (k) =>
(fm.match(new RegExp(`^${k}:\\s*(.+)$`, 'm'))?.[1] ?? '')
.trim()
.replace(/^['"]|['"]$/g, '');
return {
titolo: get('titolo'),
slug: get('slug'),
anchor: get('anchorLegacy'),
ordine: Number(get('ordine')),
};
})
.sort((a, b) => a.ordine - b.ordine);
}
const servizi = servicesFromCollection();
check(servizi.length === 6, 'src/content/servizi', `attesi 6 servizi, trovati ${servizi.length}`);
const hub = byPath.get('/servizi/');
const home = byPath.get('/');
for (const s of servizi) {
check(
byPath.has(`/servizi/${s.slug}/`),
`servizio «${s.titolo}»`,
`manca la pagina /servizi/${s.slug}/`,
);
if (hub) {
const card = findOne((n) => attr(n, 'id') === s.anchor, hub.doc.children);
check(
Boolean(card),
'dist/servizi/index.html',
`manca la card con id="${s.anchor}" (ancora del vecchio sito)`,
);
check(
attr(card ?? {}, 'data-legacy-href') === `/servizi/${s.slug}/`,
'dist/servizi/index.html',
`la card #${s.anchor} non punta a /servizi/${s.slug}/`,
);
}
if (home) {
const link = all(home.doc, (n) => n.name === 'a' && attr(n, 'href') === `/servizi/${s.slug}/`);
check(link.length > 0, 'dist/index.html', `la home non collega il servizio «${s.titolo}»`);
}
}
for (const [p, label] of [
['/', 'home'],
['/studio/', 'Lo studio'],
]) {
const page = byPath.get(p);
if (!page) continue;
const badges = all(page.doc, (n) => n.name === 'li' && /\bbadge\b/.test(attr(n, 'class') ?? ''));
check(
badges.length === abilitazioni.length,
page.file,
`${label}: attesi ${abilitazioni.length} badge di abilitazione, trovati ${badges.length}`,
);
abilitazioni.forEach((a, i) => {
const t = normalize(visibleText(badges[i] ?? { children: [] }));
check(
t.includes(normalize(a.testo)),
page.file,
`${label}: il badge n. ${i + 1} non corrisponde a studio.ts («${a.testo.slice(0, 60)}…»)`,
);
});
// riferimento L. 4/2013 nella scheda del Dott. Ezio Grasso
const ezio = findOne(
(n) => attr(n, 'data-person') === 'ezio-grasso' && n.name === 'article',
page.doc.children,
);
const et = normalize(visibleText(ezio ?? { children: [] }));
check(
/Legge 14 gennaio 2013, n\. 4/.test(et) && et.includes('1535'),
page.file,
`${label}: la scheda del Dott. Ezio Grasso non riporta il riferimento alla L. 4/2013 e l'iscrizione I.N.T. n. 1535`,
);
}
const note = byPath.get('/note-legali/');
if (note) {
const t = normalize(visibleText(note.doc));
check(
/Legge 14 gennaio 2013, n\. 4/.test(t),
note.file,
'le Note legali non riportano il riferimento alla L. 4/2013',
);
check(t.includes(PIVA.replace('P.IVA ', '')), note.file, 'le Note legali non riportano la P.IVA');
}
// modulo: con mode = off nessun <form>, ma card e-mail con oggetto precompilato
const contatti = byPath.get('/contatti/');
if (contatti) {
const forms = byTag(contatti.doc, 'form');
if (contactForm.mode === 'off') {
check(
forms.length === 0,
contatti.file,
'contactForm.mode = "off" ma la pagina contiene un <form>',
);
const mail = all(
contatti.doc,
(n) =>
n.name === 'a' && (attr(n, 'href') ?? '').startsWith(`mailto:${studio.email}?subject=`),
);
check(mail.length > 0, contatti.file, 'manca il pulsante e-mail con oggetto precompilato');
} else {
check(forms.length === 1, contatti.file, 'modulo di contatto assente');
const trap = all(contatti.doc, (n) => n.name === 'input' && attr(n, 'name') === 'sito_web');
check(
trap.length === 1 && attr(trap[0], 'tabindex') === '-1',
contatti.file,
'campo honeypot assente o raggiungibile da tastiera',
);
check(
all(contatti.doc, (n) => n.name === 'input' && attr(n, 'name') === 'ts').length === 1,
contatti.file,
'campo ts assente',
);
const privacy = all(
contatti.doc,
(n) =>
n.name === 'input' && attr(n, 'name') === 'privacy' && attr(n, 'required') !== undefined,
);
check(privacy.length === 1, contatti.file, 'checkbox privacy obbligatoria assente');
}
}
/* ------------------------------------------------------------------ asset */
const astroDir = join(dist, '_astro');
const assets = existsSync(astroDir) ? readdirSync(astroDir) : [];
const jsBytes = assets
.filter((f) => f.endsWith('.js'))
.reduce((n, f) => n + statSync(join(astroDir, f)).size, 0);
check(
jsBytes <= BUDGET_JS,
'dist/_astro',
`JavaScript totale ${(jsBytes / 1024).toFixed(1)} KB oltre il budget di 15 KB`,
);
for (const f of assets.filter((x) => /\.(js|css)$/.test(x))) {
const src = readFileSync(join(astroDir, f), 'utf8');
for (const re of FORBIDDEN_REFS)
check(
!re.test(src),
`dist/_astro/${f}`,
`riferimento vietato a ${re.source.replace(/\\/g, '')}`,
);
check(!/document\.cookie/.test(src), `dist/_astro/${f}`, 'uso di document.cookie');
check(
!/localStorage/.test(src),
`dist/_astro/${f}`,
'uso di localStorage (solo sessionStorage ammesso)',
);
}
const mapFiles = [];
(function walk(dir) {
for (const e of readdirSync(dir, { withFileTypes: true })) {
if (e.isDirectory()) walk(join(dir, e.name));
else if (e.name.endsWith('.map')) mapFiles.push(join(dir, e.name));
}
})(dist);
check(mapFiles.length === 0, 'dist/', `file .map presenti: ${mapFiles.join(', ')}`);
const preload = home
? all(
home.doc,
(n) => n.name === 'link' && attr(n, 'rel') === 'preload' && attr(n, 'as') === 'font',
)
: [];
check(
preload.length === 2,
'dist/index.html',
`attesi 2 font precaricati, trovati ${preload.length}`,
);
const fontBytes = preload.reduce((n, l) => n + statSync(join(dist, attr(l, 'href'))).size, 0);
check(
fontBytes <= BUDGET_FONTS,
'dist/index.html',
`font principali ${Math.round(fontBytes / 1024)} KB oltre il budget`,
);
/* ------------------------------------------------------------------ .htaccess */
const htaccess = existsSync(join(dist, '.htaccess'))
? readFileSync(join(dist, '.htaccess'), 'utf8')
: '';
for (const [re, what] of [
[/ErrorDocument 404 \/404\.html/, 'ErrorDocument 404 /404.html'],
[
/RedirectMatch 301 \^\/privacy\/\?\$ \/privacy-policy\//,
'redirect /privacy → /privacy-policy/',
],
[/X-Content-Type-Options "nosniff"/, 'X-Content-Type-Options'],
[/Referrer-Policy "strict-origin-when-cross-origin"/, 'Referrer-Policy'],
[/Permissions-Policy/, 'Permissions-Policy'],
[/X-Frame-Options "SAMEORIGIN"/, 'X-Frame-Options'],
[/#\s*Header always set Strict-Transport-Security/, 'HSTS presente ma commentato'],
[/\\\.map\$/, 'blocco dei file .map'],
]) {
check(re.test(htaccess), 'dist/.htaccess', `manca: ${what}`);
}
// Content-Security-Policy di §9.4, confrontata per direttive. Con il modulo esterno
// (`contactForm.mode = 'endpoint'`) form-action deve ammettere anche l'origine del fornitore.
const EXPECTED_CSP = {
'default-src': ["'self'"],
'img-src': ["'self'", 'data:'],
'style-src': ["'self'", "'unsafe-inline'"],
'script-src': ["'self'"],
'font-src': ["'self'"],
'frame-src': ['https://www.google.com'],
'form-action': ["'self'"],
'base-uri': ["'self'"],
'frame-ancestors': ["'self'"],
};
if (contactForm.mode === 'endpoint' && /^https:\/\//.test(contactForm.endpoint)) {
EXPECTED_CSP['form-action'].push(new URL(contactForm.endpoint).origin);
}
/** Direttive della CSP in forma canonica (direttive e sorgenti in ordine alfabetico). */
const canonicalCsp = (directives) =>
JSON.stringify(
Object.entries(directives)
.map(([name, sources]) => [name, [...sources].sort()])
.sort(([a], [b]) => a.localeCompare(b)),
);
/** Direttive della CSP; una direttiva ripetuta è un errore (il browser applica solo la prima). */
const parseCsp = (value) => {
const out = {};
for (const [name, ...sources] of value
.split(';')
.map((d) => d.trim().split(/\s+/))
.filter((d) => d[0])) {
if (name in out) fail('dist/.htaccess', `direttiva CSP ripetuta: ${name}`);
else out[name] = sources;
}
return out;
};
const cspLines = [
...htaccess.matchAll(/^\s*Header always set Content-Security-Policy "([^"]+)"/gm),
];
check(
cspLines.length === 1,
'dist/.htaccess',
`attesa una sola Content-Security-Policy attiva, trovate ${cspLines.length}`,
);
if (cspLines.length === 1) {
check(
canonicalCsp(parseCsp(cspLines[0][1])) === canonicalCsp(EXPECTED_CSP),
'dist/.htaccess',
`Content-Security-Policy diversa da quella attesa (§9.4${
contactForm.mode === 'endpoint' ? ' + origine del modulo esterno in form-action' : ''
}): «${cspLines[0][1]}»`,
);
}
/* ------------------------------------------------------------------ esito */
if (errors.length > 0) {
console.error(
`✘ Conformità: ${errors.length} errori su ${checks} controlli (${pages.length} pagine)\n`,
);
for (const e of errors) console.error(` - ${e}`);
process.exit(1);
}
console.log(`✔ Conformità: ${checks} controlli superati su ${pages.length} pagine.`);