Le run della CI restavano «in attesa» perché l'unico runner dell'istanza («Ferrari») non si è mai collegato: il runner resta da configurare. La revisione completa del codice ha trovato anche difetti che avrebbero fatto fallire la CI con il runner online, oltre ad altri problemi del sito, dei controlli e della documentazione. CI e rilascio: - continue-on-error sullo step dei link esterni: Forgejo lo ignora sul job, e un sito esterno irraggiungibile avrebbe reso rossa la CI; - artifact con i file nascosti (report Lighthouse e .htaccess non venivano mai caricati); - token personale RELEASE_TOKEN: FORGEJO_TOKEN è riservato ed è sempre il token automatico; - dominio in un solo punto (site.config.mjs) e variabile del repository SITE_URL; - ripiego REST: release in bozza, file, poi pubblicazione; tag verificato sul server; sostituzione dei file senza mai lasciarli mancanti; - tar.gz identico su Windows, macOS e Linux (byte del sistema operativo nell'header gzip). Sito: CSS compatibile con Safari/iOS 15 (media query classiche, backdrop-filter), anello di focus con contrasto di almeno 3:1, bersagli touch di 44 px dove servono, intestazione desktop senza voci o logo a capo, HTML valido in /servizi/, colore delle chip, stampa senza mappe, giorni di apertura, ricerca e titolo delle mappe e numero breve ricavati dai dati. Modulo di contatto e contact.php: stesse regole nel browser e sul server (spazi, e-mail, a capo, lunghezze), tempo minimo misurato con un solo orologio (ts_invio), corpo in quoted-printable e oggetto RFC 2047, funzionamento con PHP a 32 bit, costante MODALITA_PREDEFINITA per attivarlo. Controlli e test: valori letti dai dati del sito, i sei servizi del brief con le ancore, «commercialista» anche in meta, attributi e dati strutturati, .htaccess su righe attive, HSTS attivabile con una scelta esplicita, contrasto del focus misurato nei test. Esempi di pubblicazione: nginx con gli header di sicurezza in un solo punto (HSTS compreso), deploy automatico che parte alla pubblicazione e sincronizza solo una cartella confermata, procedura nginx che toglie i file delle versioni precedenti. Debug: .vscode/launch.json e tasks.json, F5 avvia il server Astro e apre il browser con il debugger collegato. Documentazione aggiornata (README, DEPLOY, CONTENUTI, CONFORMITA, TODO-STUDIO, CHANGELOG) e decisioni D-045…D-055. Verificato: npm run verify su Windows e nel container della CI (Playwright 1.56.1, root); job dei link esterni in node:24; contact.php con PHP 7.4 e 8.3, a 64 e 32 bit; nginx in Docker; release-upload.sh e deploy di esempio contro API e shell simulate. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
955 lines
33 KiB
JavaScript
955 lines
33 KiB
JavaScript
#!/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, orari e giorni di apertura,
|
||
* dominio) sono letti dalle stesse fonti del sito: src/data/studio.ts,
|
||
* src/content/servizi/*.md e site.config.mjs. Così una modifica dei contenuti fatta come indica
|
||
* docs/CONTENUTI.md non fa fallire i controlli.
|
||
*/
|
||
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 { siteUrl } from '../site.config.mjs';
|
||
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 = siteUrl();
|
||
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;
|
||
}
|
||
|
||
/** Problemi di compatibilità nel CSS generato (pagina HTML o file .css). */
|
||
function cssIssues(css) {
|
||
checks++;
|
||
const issues = [];
|
||
const range = css.match(/@media[^{]*\(\s*(?:width|height)\s*[<>]/);
|
||
if (range) {
|
||
issues.push(
|
||
`media query in sintassi a intervallo «${range[0]}…»: controllare vite.build.cssTarget in astro.config.mjs`,
|
||
);
|
||
}
|
||
for (const block of css.match(/\{[^{}]*-webkit-backdrop-filter:[^{}]*\}/g) ?? []) {
|
||
if (!/[{;]\s*backdrop-filter:/.test(block)) {
|
||
issues.push(`-webkit-backdrop-filter senza backdrop-filter: «${block.slice(0, 80)}…»`);
|
||
}
|
||
}
|
||
return issues;
|
||
}
|
||
|
||
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 DICITURE_VIETATE = [
|
||
'studio commercialista',
|
||
'studio di commercialisti',
|
||
'studio di commercialista',
|
||
'commercialista ezio',
|
||
'ezio grasso, commercialista',
|
||
'ezio grasso commercialista',
|
||
];
|
||
const giulia = professionisti.find((p) => p.id === 'giulia-grasso');
|
||
|
||
/**
|
||
* Testi non visibili che finiscono nei risultati di ricerca, nelle anteprime o agli screen
|
||
* reader: meta (description, Open Graph, Twitter), attributi alt/title/aria-label e stringhe del
|
||
* JSON-LD, esclusa la scheda della Dott.ssa Giulia Grasso. Coppie [provenienza, testo].
|
||
*/
|
||
function hiddenTexts(doc, ldNodes) {
|
||
const out = [];
|
||
for (const el of all(doc, (n) => n.name === 'meta')) {
|
||
const key = attr(el, 'name') ?? attr(el, 'property') ?? '';
|
||
if (/^(description$|og:|twitter:)/.test(key))
|
||
out.push([`meta ${key}`, attr(el, 'content') ?? '']);
|
||
}
|
||
for (const el of all(doc, () => true)) {
|
||
for (const n of ['alt', 'title', 'aria-label', 'data-map-title']) {
|
||
const v = attr(el, n);
|
||
if (v) out.push([`attributo ${n} di <${el.name}>`, v]);
|
||
}
|
||
}
|
||
const walk = (value, path) => {
|
||
if (typeof value === 'string') out.push([`JSON-LD ${path}`, value]);
|
||
else if (Array.isArray(value)) value.forEach((v, i) => walk(v, `${path}[${i}]`));
|
||
else if (value && typeof value === 'object') {
|
||
if (value['@type'] === 'Person' && value.name === giulia?.nomeSenzaTitolo) return;
|
||
for (const [k, v] of Object.entries(value)) walk(v, `${path}.${k}`);
|
||
}
|
||
};
|
||
for (const n of ldNodes) walk(n, String(n['@type'] ?? 'nodo'));
|
||
return out;
|
||
}
|
||
const titles = new Map();
|
||
const descriptions = new Map();
|
||
const year = String(buildYear);
|
||
|
||
// orari e giorni di apertura: formato dei dati in studio.ts e valore atteso nel JSON-LD
|
||
const HHMM = /^([01]\d|2[0-3]):[0-5]\d$/;
|
||
for (const f of studio.orari.fasce) {
|
||
check(
|
||
HHMM.test(f.apertura) && HHMM.test(f.chiusura) && f.apertura < f.chiusura,
|
||
'src/data/studio.ts',
|
||
`fascia oraria non valida «${f.apertura}–${f.chiusura}» (formato HH:MM, apertura prima della chiusura)`,
|
||
);
|
||
}
|
||
check(
|
||
studio.orari.giorniSettimana.length > 0,
|
||
'src/data/studio.ts',
|
||
'orari.giorniSettimana vuoto: indicare i giorni di apertura',
|
||
);
|
||
const EXPECTED_HOURS = studio.orari.fasce
|
||
.map((f) => `${f.apertura}-${f.chiusura}`)
|
||
.sort()
|
||
.join(',');
|
||
|
||
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 DICITURE_VIETATE) {
|
||
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}`);
|
||
}
|
||
}
|
||
|
||
// «commercialista» anche nei testi non visibili (meta, attributi, JSON-LD): ogni stringa è
|
||
// controllata da sola, con le stesse regole del testo visibile
|
||
for (const [origin, value] of hiddenTexts(doc, nodes)) {
|
||
const t = normalize(value);
|
||
if (!/commercialist/i.test(t)) continue;
|
||
for (const s of sentences(t).filter((x) => /commercialist/i.test(x))) {
|
||
check(
|
||
COMMERCIALISTA_OK.test(s),
|
||
where,
|
||
`«commercialista» usato fuori contesto in ${origin} (ammesso solo per la Dott.ssa Giulia Grasso, ODCEC, OCC): «${s}»`,
|
||
);
|
||
}
|
||
for (const bad of DICITURE_VIETATE) {
|
||
check(!t.toLowerCase().includes(bad), where, `dicitura vietata «${bad}» in ${origin}`);
|
||
}
|
||
}
|
||
|
||
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 === EXPECTED_HOURS,
|
||
where,
|
||
`JSON-LD: orari attesi ${EXPECTED_HOURS} (studio.orari.fasce), trovati ${hours}`,
|
||
);
|
||
for (const h of org.openingHoursSpecification ?? []) {
|
||
check(
|
||
JSON.stringify(h.dayOfWeek) === JSON.stringify(studio.orari.giorniSettimana),
|
||
where,
|
||
`JSON-LD: giorni di apertura ${JSON.stringify(h.dayOfWeek)} diversi da studio.orari.giorniSettimana`,
|
||
);
|
||
}
|
||
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}»`);
|
||
}
|
||
}
|
||
|
||
// CSS compatibile con i browser di vite.build.cssTarget (astro.config.mjs): media query con
|
||
// min-/max-width (la sintassi a intervallo non funziona su Safari/iOS < 16.4) e
|
||
// backdrop-filter anche senza prefisso (Chrome, Edge e Firefox ignorano -webkit-)
|
||
for (const issue of cssIssues(html)) fail(where, issue);
|
||
|
||
// nulla dopo </html> (es. uno <script> scritto fuori dal layout: errore di parsing HTML)
|
||
check(/<\/html>\s*$/i.test(html), where, 'contenuto dopo </html>: spostarlo dentro il layout');
|
||
|
||
// 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();
|
||
// almeno i 6 servizi del brief (§4.5): se ne possono aggiungere altri (docs/CONTENUTI.md)
|
||
check(
|
||
servizi.length >= 6,
|
||
'src/content/servizi',
|
||
`attesi almeno i 6 servizi del brief, trovati ${servizi.length}`,
|
||
);
|
||
// i sei servizi del brief (§4.5) con l'ancora del vecchio sito (§5.3): requisiti, non contenuti
|
||
const SERVIZI_BRIEF = [
|
||
['consulenza-fiscale-tributaria-e-societaria', 'consulenza-fiscale-tributaria-e-societaria-1'],
|
||
['contabilita-fiscale', 'contabilita-fiscale-2'],
|
||
['contenzioso-tributario', 'contenzioso-tributario-3'],
|
||
['centro-autorizzato-caf', 'centro-autorizzato-caf-4'],
|
||
['servizi-imprese-dipendenti-pensionati', 'servizi-alle-imprese-dipendenti-e-pensionati-5'],
|
||
['certificazione-atti-firma-digitale', 'certificazione-atti-mediante-firma-digitale-6'],
|
||
];
|
||
for (const [slug, anchor] of SERVIZI_BRIEF) {
|
||
check(
|
||
servizi.some((s) => s.slug === slug && s.anchor === anchor),
|
||
'src/content/servizi',
|
||
`manca il servizio del brief /servizi/${slug}/ con anchorLegacy «${anchor}» (link del vecchio sito)`,
|
||
);
|
||
}
|
||
for (const [key, label] of [
|
||
['slug', 'slug'],
|
||
['anchor', 'anchorLegacy'],
|
||
]) {
|
||
const values = servizi.map((s) => s[key]);
|
||
const repeated = [...new Set(values.filter((v, i) => values.indexOf(v) !== i))];
|
||
check(repeated.length === 0, 'src/content/servizi', `${label} ripetuti: ${repeated.join(', ')}`);
|
||
}
|
||
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',
|
||
);
|
||
for (const name of ['ts', 'ts_invio']) {
|
||
check(
|
||
all(contatti.doc, (n) => n.name === 'input' && attr(n, 'name') === name).length === 1,
|
||
contatti.file,
|
||
`campo ${name} 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');
|
||
}
|
||
}
|
||
|
||
// gestore PHP del modulo: nel sito solo con contactForm.mode = 'php' (docs/DEPLOY.md, sezione 6)
|
||
const phpHandler = existsSync(join(dist, 'contact.php'));
|
||
if (contactForm.mode === 'php') {
|
||
check(
|
||
phpHandler,
|
||
'dist/contact.php',
|
||
'contactForm.mode = "php" ma contact.php manca: copiare deploy/optional-php-form/contact.php in public/',
|
||
);
|
||
} else {
|
||
check(
|
||
!phpHandler,
|
||
'dist/contact.php',
|
||
`contact.php pubblicato con contactForm.mode = "${contactForm.mode}": toglierlo da public/ (la privacy policy non lo descrive)`,
|
||
);
|
||
}
|
||
|
||
/* ------------------------------------------------------------------ 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');
|
||
if (f.endsWith('.css')) for (const issue of cssIssues(src)) fail(`dist/_astro/${f}`, issue);
|
||
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')
|
||
: '';
|
||
// direttive cercate solo su righe attive (non commentate)
|
||
for (const [re, what] of [
|
||
[/^\s*ErrorDocument 404 \/404\.html\s*$/m, 'ErrorDocument 404 /404.html'],
|
||
[
|
||
/^\s*RedirectMatch 301 \^\/privacy\/\?\$ \/privacy-policy\/\s*$/m,
|
||
'redirect /privacy → /privacy-policy/',
|
||
],
|
||
[/^\s*Header always set X-Content-Type-Options "nosniff"\s*$/m, 'X-Content-Type-Options'],
|
||
[
|
||
/^\s*Header always set Referrer-Policy "strict-origin-when-cross-origin"\s*$/m,
|
||
'Referrer-Policy',
|
||
],
|
||
[/^\s*Header always set Permissions-Policy "[^"]+"\s*$/m, 'Permissions-Policy'],
|
||
[/^\s*Header always set X-Frame-Options "SAMEORIGIN"\s*$/m, 'X-Frame-Options'],
|
||
[/^\s*<FilesMatch "[^"]*\\\.map\$[^"]*">/m, 'blocco dei file .map'],
|
||
]) {
|
||
check(re.test(htaccess), 'dist/.htaccess', `manca: ${what}`);
|
||
}
|
||
|
||
// HSTS: commentato finché HTTPS non è verificato su tutto il dominio. Per attivarlo decommentare
|
||
// la riga in public/.htaccess E impostare qui HSTS_ATTIVO = true (docs/DEPLOY.md, sezione 2).
|
||
const HSTS_ATTIVO = false;
|
||
const hsts = /^\s*Header always set Strict-Transport-Security "max-age=(\d+)[^"]*"\s*$/m.exec(
|
||
htaccess,
|
||
);
|
||
if (HSTS_ATTIVO) {
|
||
check(
|
||
Boolean(hsts) && Number(hsts[1]) >= 31536000,
|
||
'dist/.htaccess',
|
||
'HSTS_ATTIVO = true ma Strict-Transport-Security non è attivo (max-age di almeno un anno)',
|
||
);
|
||
} else {
|
||
check(
|
||
/^\s*#\s*Header always set Strict-Transport-Security/m.test(htaccess),
|
||
'dist/.htaccess',
|
||
'manca la riga di HSTS (commentata)',
|
||
);
|
||
check(
|
||
!/^\s*Header always set Strict-Transport-Security/m.test(htaccess),
|
||
'dist/.htaccess',
|
||
'HSTS attivo: se HTTPS è verificato su tutto il dominio impostare HSTS_ATTIVO = true in scripts/check-compliance.mjs',
|
||
);
|
||
}
|
||
|
||
// 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.`);
|