@rgaa-audit/cli 0.0.0-stage → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/audit.js ADDED
@@ -0,0 +1,836 @@
1
+ /**
2
+ * src/audit.js — Orchestrateur principal
3
+ * Coordonne : browser → simulator → rules → reporter
4
+ */
5
+
6
+ 'use strict';
7
+
8
+ const fs = require('node:fs');
9
+ const path = require('node:path');
10
+
11
+ const { createBrowser, closeBrowser } = require('./browser');
12
+ const { simulateHumanActions } = require('./simulator');
13
+ const { runDomRules, runDarkSchemeContrast, runAlternateThemeContrast, computeScore } = require('./rules');
14
+ const { createPagePreparer, applyAlternateTheme } = require('./page-prep');
15
+ const { validatePageHtml } = require('./html-validation');
16
+ const { findTemplateIssues, compareWithBaseline } = require('./aggregate');
17
+ const { captureFindings, attachCaptureData } = require('./captures');
18
+
19
+ const MAX_CAPTURES = 40;
20
+ const { requireShared } = require('./shared');
21
+
22
+ const { ENGINE_VERSION } = requireShared('rgaa-rules.js');
23
+ const { generateReport } = require('./reporters');
24
+ const { fillRgaaGridFromReports } = require('./reporters/ods-grid');
25
+ const { log, success, warn } = require('./logger');
26
+
27
+ const ALLOWED_PROTOCOLS = new Set(['http:', 'https:']);
28
+ const EXPLICITLY_BLOCKED_PROTOCOLS = new Set(['file:', 'data:', 'javascript:']);
29
+ const TRACKING_PARAM_PREFIXES = ['utm_'];
30
+ const TRACKING_PARAMS = new Set(['gclid', 'fbclid', 'mc_cid', 'mc_eid', '_hsenc', '_hsmi', 'pk_campaign', 'pk_kwd']);
31
+ const PARASITIC_PATH_PATTERNS = [/(?:^|\/)cdn-cgi\//i, /(?:^|\/)track(?:ing)?(?:\/|$)/i, /(?:^|\/)analytics(?:\/|$)/i];
32
+
33
+ const DEFAULT_MAX_PAGES = 100;
34
+ const SAFE_CRAWL_MAX_PAGES = 20;
35
+ const MAX_LINK_CANDIDATES = 2500;
36
+ const MAX_SITEMAP_BYTES = 2 * 1024 * 1024;
37
+
38
+ async function runAudit(url, opts = {}) {
39
+ const {
40
+ output = 'json',
41
+ save = '',
42
+ vulgarizedSave = '',
43
+ odsTemplate = '',
44
+ odsSave = '',
45
+ odsReplicateAllSheets = false,
46
+ simulate = true,
47
+ depth = 1,
48
+ headless = true,
49
+ outputDir = '',
50
+ debug = false,
51
+ verbose = false,
52
+ safeCrawl = false,
53
+ strictSecurity = false,
54
+ colorScheme = 'auto',
55
+ dismiss = 'auto',
56
+ themeClick = '',
57
+ themeScript = '',
58
+ validateHtml = false,
59
+ baseline = '',
60
+ captures = true,
61
+ } = opts;
62
+
63
+ const debugEnabled = Boolean(debug || verbose);
64
+ const safeCrawlEnabled = Boolean(safeCrawl || strictSecurity);
65
+ const debugLog = createDebugLogger(debugEnabled);
66
+
67
+ const auditedUrl = validateAuditUrl(url, {
68
+ safeCrawl: safeCrawlEnabled,
69
+ allowFileProtocol: !safeCrawlEnabled,
70
+ });
71
+ const resolvedSave = resolveOutputPath(save, { outputDir });
72
+ const resolvedVulgarizedSave = resolveOutputPath(vulgarizedSave, { outputDir });
73
+ const resolvedOdsTemplate = odsTemplate ? path.resolve(odsTemplate) : '';
74
+ const baselineReport = baseline ? loadBaseline(baseline) : null;
75
+ const resolvedOdsSave = resolveOutputPath(odsSave, { outputDir });
76
+
77
+ log(`\n♿ RGAA Audit CLI — ${auditedUrl}\n`);
78
+
79
+ const startTime = Date.now();
80
+ let browser;
81
+ let page;
82
+ const navigationProfile = {
83
+ preferDomContentLoadedOrigins: new Set(),
84
+ warnedOrigins: new Set(),
85
+ };
86
+ const browserDebugEvents = [];
87
+
88
+ try {
89
+ // ── 1. NAVIGATEUR ────────────────────────
90
+ log('🌐 Lancement du navigateur…');
91
+ ({ browser, page } = await createBrowser({
92
+ headless,
93
+ debug: debugEnabled,
94
+ onDebugEvent: (event) => {
95
+ if (browserDebugEvents.length >= 200) return;
96
+ browserDebugEvents.push(event);
97
+ },
98
+ }));
99
+
100
+ const preparePage = createPagePreparer(page, { dismiss });
101
+ // Toute navigation (page suivante, rechargement de la simulation…) repasse par ici.
102
+ const open = async (url) => {
103
+ await navigateWithFallback(page, url, navigationProfile, debugLog);
104
+ await preparePage();
105
+ };
106
+
107
+ log(`📄 Chargement de ${auditedUrl}…`);
108
+ await navigateWithFallback(page, auditedUrl, navigationProfile, debugLog);
109
+ await page.waitForTimeout(1000);
110
+ await preparePage();
111
+
112
+ const rootTitle = await page.title();
113
+ success(` Titre : "${rootTitle}"`);
114
+
115
+ // ── 2. SÉLECTION DES PAGES À AUDITER ─────
116
+ const targetPlan = await buildAuditTargets(page, auditedUrl, {
117
+ depth,
118
+ safeCrawl: safeCrawlEnabled,
119
+ debugLog,
120
+ });
121
+
122
+ if (targetPlan.requestedDepth > targetPlan.maxPages) {
123
+ debugLog(`Profondeur demandée (${targetPlan.requestedDepth}) limitée à ${targetPlan.maxPages}`);
124
+ }
125
+
126
+ const targets = targetPlan.targets;
127
+ if (targets.length > 1) {
128
+ success(` Pages retenues pour audit : ${targets.length}`);
129
+ }
130
+
131
+ // ── 3. AUDIT DES PAGES ────────────────────
132
+ const allResults = [];
133
+ let darkScheme = colorScheme === 'light' ? 'off' : (colorScheme === 'both' ? 'on' : 'auto');
134
+ const screenshotsDir = path.join(outputDir || '.', 'audit-screenshots');
135
+ let capturesTaken = 0;
136
+ const pages = [];
137
+ const pagesSkipped = [];
138
+ let simulationResults = null;
139
+
140
+ for (let i = 0; i < targets.length; i++) {
141
+ const targetUrl = targets[i];
142
+ const label = targets.length > 1 ? ` (${i + 1}/${targets.length})` : '';
143
+ log(`\n🔍 Audit DOM (règles RGAA 4.1.2)${label} — ${targetUrl}`);
144
+
145
+ try {
146
+ if (i > 0) {
147
+ await open(targetUrl);
148
+ await page.waitForTimeout(500);
149
+ }
150
+ } catch (e) {
151
+ const reason = normalizeSkipReason(e);
152
+ warn(` Page ignorée (${reason}) : ${targetUrl}`);
153
+ pagesSkipped.push({ url: targetUrl, reason });
154
+ continue;
155
+ }
156
+
157
+ let pageTitle = targetUrl;
158
+ let domResults = [];
159
+ try {
160
+ pageTitle = await safePageTitle(page, targetUrl);
161
+ domResults = (await runDomRules(page)).map((r) => ({
162
+ ...r,
163
+ pageUrl: targetUrl,
164
+ pageTitle,
165
+ }));
166
+ } catch (e) {
167
+ const reason = normalizeSkipReason(e);
168
+ warn(` Audit DOM impossible (${reason}) : ${targetUrl}`);
169
+ pagesSkipped.push({ url: targetUrl, reason });
170
+ continue;
171
+ }
172
+
173
+ if (captures && capturesTaken < MAX_CAPTURES) {
174
+ capturesTaken += await captureFindings(page, domResults, {
175
+ dir: path.join(screenshotsDir, 'non-conformites'),
176
+ prefix: `p${String(i + 1).padStart(2, '0')}`,
177
+ max: Math.min(6, MAX_CAPTURES - capturesTaken),
178
+ }).catch(() => 0);
179
+ }
180
+
181
+ let pageSimulation = null;
182
+ if (simulate && i === 0) {
183
+ log('\n⌨️ Simulation d\'actions humaines (page principale)…');
184
+ pageSimulation = await simulateHumanActions(page, {
185
+ reload: () => open(targetUrl),
186
+ screenshotsDir,
187
+ });
188
+ simulationResults = pageSimulation;
189
+ }
190
+
191
+ if (darkScheme !== 'off') {
192
+ try {
193
+ const darkResults = await runDarkSchemeContrast(page, { reload: () => open(targetUrl) });
194
+ if (darkResults) {
195
+ darkScheme = 'on';
196
+ domResults.push(...darkResults.map((r) => ({ ...r, pageUrl: targetUrl, pageTitle })));
197
+ } else if (darkScheme === 'auto') {
198
+ darkScheme = 'off';
199
+ debugLog('Aucun thème sombre (prefers-color-scheme) détecté : passe sombre désactivée');
200
+ }
201
+ } catch (e) {
202
+ warn(` Passe thème sombre impossible (${normalizeSkipReason(e)}) : ${targetUrl}`);
203
+ }
204
+ }
205
+
206
+ if (validateHtml) {
207
+ try {
208
+ const htmlFindings = await validatePageHtml(page);
209
+ domResults.push(...htmlFindings.map((r) => ({ ...r, pageUrl: targetUrl, pageTitle })));
210
+ const errors = htmlFindings.filter((f) => f.status === 'NC').reduce((n, f) => n + f.count, 0);
211
+ log(` Validation HTML : ${errors ? `${errors} erreur(s)` : 'aucune erreur'}`);
212
+ } catch (e) {
213
+ warn(` Validation HTML impossible : ${String(e?.message || e).split('\n')[0]}`);
214
+ }
215
+ }
216
+
217
+ if (themeClick || themeScript) {
218
+ try {
219
+ const altResults = await runAlternateThemeContrast(page, {
220
+ apply: () => applyAlternateTheme(page, { click: themeClick, script: themeScript }),
221
+ revert: themeClick ? () => applyAlternateTheme(page, { click: themeClick }) : null,
222
+ reload: () => open(targetUrl),
223
+ });
224
+ if (altResults) domResults.push(...altResults.map((r) => ({ ...r, pageUrl: targetUrl, pageTitle })));
225
+ } catch (e) {
226
+ warn(` Passe thème alternatif impossible (${String(e?.message || e).split('\n')[0]}) : ${targetUrl}`);
227
+ }
228
+ }
229
+
230
+ const pageResults = mergeResults(domResults, pageSimulation, targetUrl, pageTitle);
231
+ const pageScore = computeScore(pageResults);
232
+
233
+ allResults.push(...pageResults);
234
+ pages.push({
235
+ url: targetUrl,
236
+ title: pageTitle,
237
+ score: pageScore,
238
+ nonConformes: pageScore.nonConformes,
239
+ conformes: pageScore.conformes,
240
+ aVerifier: pageScore.aVerifier,
241
+ });
242
+ }
243
+
244
+ // ── 4. SCORE GLOBAL ───────────────────────
245
+ const score = computeScore(allResults);
246
+ const transparency = summarizeResultQualification(allResults);
247
+ printSummary(score, rootTitle, auditedUrl, pages.length, transparency);
248
+
249
+ // ── 5. RAPPORT ────────────────────────────
250
+ const report = {
251
+ engineVersion: ENGINE_VERSION,
252
+ url: auditedUrl,
253
+ title: rootTitle,
254
+ timestamp: new Date().toISOString(),
255
+ duration: Math.round((Date.now() - startTime) / 1000),
256
+ requestedDepth: Math.max(1, Number(depth) || 1),
257
+ pagesAudited: pages.length,
258
+ pages,
259
+ pagesSkipped,
260
+ score,
261
+ transparency,
262
+ results: allResults,
263
+ simulation: simulationResults?.summary || null,
264
+ };
265
+
266
+ if (pages.length > 1) {
267
+ report.templateIssues = findTemplateIssues(allResults);
268
+ printTemplateIssues(report.templateIssues, pages.length);
269
+ }
270
+ if (baselineReport) {
271
+ report.baseline = { file: path.resolve(baseline), ...compareWithBaseline(report, baselineReport) };
272
+ printBaselineSummary(report.baseline);
273
+ }
274
+
275
+ if (debugEnabled) {
276
+ report.debug = {
277
+ browserEvents: browserDebugEvents,
278
+ crawlIgnored: targetPlan.ignored,
279
+ safeCrawl: safeCrawlEnabled,
280
+ };
281
+ }
282
+
283
+ if (resolvedOdsTemplate && resolvedOdsSave) {
284
+ const perPageReports = buildPerPageReports(report);
285
+ const odsResult = fillRgaaGridFromReports({
286
+ reports: perPageReports,
287
+ templatePath: resolvedOdsTemplate,
288
+ outputPath: resolvedOdsSave,
289
+ replicateToAllSheets: !!odsReplicateAllSheets,
290
+ });
291
+ const resolvedOdsPath = path.resolve(odsResult.outputPath);
292
+ report.ods = {
293
+ outputPath: resolvedOdsPath,
294
+ filledSheets: odsResult.filledSheets,
295
+ filledCriteria: odsResult.filledCriteria,
296
+ };
297
+ success(`📊 Grille ODS sauvegardée : ${resolvedOdsPath}`);
298
+ } else if (resolvedOdsTemplate || resolvedOdsSave) {
299
+ warn(' Export ODS ignoré: fournir --ods-template et --ods-save ensemble.');
300
+ }
301
+
302
+ const outputStr = await generateReport(['html', 'vulgarized'].includes(output) ? attachCaptureData(report) : report, output);
303
+
304
+ if (resolvedSave) {
305
+ safeWriteReport(resolvedSave, outputStr);
306
+ success(`\n📁 Rapport sauvegardé : ${resolvedSave}`);
307
+ } else {
308
+ console.log('\n' + outputStr);
309
+ }
310
+
311
+ if (resolvedVulgarizedSave) {
312
+ const reportForVulgarized = attachCaptureData(attachOdsDownloadPayload(report));
313
+ const vulgarized = await generateReport(reportForVulgarized, 'vulgarized');
314
+ safeWriteReport(resolvedVulgarizedSave, vulgarized);
315
+ success(`📄 Rapport vulgarisé sauvegardé : ${resolvedVulgarizedSave}`);
316
+ }
317
+
318
+ return report;
319
+ } finally {
320
+ if (browser) await closeBrowser(browser);
321
+ }
322
+ }
323
+
324
+ function loadBaseline(file) {
325
+ let parsed;
326
+ try {
327
+ parsed = JSON.parse(fs.readFileSync(path.resolve(file), 'utf8'));
328
+ } catch (err) {
329
+ throw new Error(`Rapport de référence illisible (${file}) : ${err.message}`);
330
+ }
331
+ if (!parsed || !Array.isArray(parsed.results)) {
332
+ throw new Error(`Rapport de référence invalide (${file}) : tableau « results » absent.`);
333
+ }
334
+ return parsed;
335
+ }
336
+
337
+ function printTemplateIssues(issues, pageCount) {
338
+ if (!issues.length) return;
339
+ log(`\n Défauts de gabarit (même non-conformité sur plusieurs pages) :`);
340
+ for (const issue of issues.slice(0, 8)) {
341
+ console.log(` ${issue.id.padEnd(5)} ${issue.pageCount}/${pageCount} pages — ${issue.message.slice(0, 110)}`);
342
+ }
343
+ if (issues.length > 8) log(` … et ${issues.length - 8} autre(s), voir templateIssues dans le rapport JSON.`);
344
+ }
345
+
346
+ function printBaselineSummary(diff) {
347
+ log(`\n Comparaison avec la référence${diff.baselineTimestamp ? ` du ${diff.baselineTimestamp.slice(0, 10)}` : ''} :`);
348
+ if (diff.engineChanged) {
349
+ warn(` Moteur différent (${diff.baselineEngineVersion || 'inconnu'} → ${ENGINE_VERSION}) : des écarts peuvent venir de l’outil, pas du site.`);
350
+ }
351
+ const line = ` ${diff.newCount} nouvelle(s) non-conformité(s), ${diff.resolvedCount} résolue(s)`;
352
+ if (diff.newCount) warn(line);
353
+ else success(line);
354
+ for (const item of diff.added.slice(0, 10)) {
355
+ console.log(` + ${item.id.padEnd(5)} ${item.page} — ${item.message.slice(0, 100)}`);
356
+ }
357
+ }
358
+
359
+ function mergeResults(domResults, simResults, pageUrl, pageTitle) {
360
+ const all = [...domResults];
361
+ if (simResults?.findings) {
362
+ all.push(
363
+ ...simResults.findings.map((finding) => ({
364
+ ...finding,
365
+ pageUrl: finding.pageUrl || pageUrl,
366
+ pageTitle: finding.pageTitle || pageTitle,
367
+ })),
368
+ );
369
+ }
370
+ return all;
371
+ }
372
+
373
+ function buildPerPageReports(report) {
374
+ const pages = Array.isArray(report.pages) ? report.pages : [];
375
+ const byPage = new Map();
376
+ for (const result of report.results || []) {
377
+ const pageUrl = result?.pageUrl || report.url || '';
378
+ if (!byPage.has(pageUrl)) byPage.set(pageUrl, []);
379
+ byPage.get(pageUrl).push(result);
380
+ }
381
+
382
+ return pages
383
+ .map((p) => ({
384
+ title: p.title || p.url || 'Page',
385
+ url: p.url || '',
386
+ results: byPage.get(p.url || '') || [],
387
+ }))
388
+ .filter((p) => p.results.length > 0);
389
+ }
390
+
391
+ function attachOdsDownloadPayload(report) {
392
+ if (!report?.ods?.outputPath) return report;
393
+ try {
394
+ const bytes = fs.readFileSync(report.ods.outputPath);
395
+ return {
396
+ ...report,
397
+ odsDownload: {
398
+ fileName: path.basename(report.ods.outputPath) || 'rgaa-grille.ods',
399
+ mimeType: 'application/vnd.oasis.opendocument.spreadsheet',
400
+ base64: bytes.toString('base64'),
401
+ },
402
+ };
403
+ } catch (err) {
404
+ warn(` Impossible d’intégrer le téléchargement ODS dans le rapport vulgarisé: ${err.message}`);
405
+ return report;
406
+ }
407
+ }
408
+
409
+
410
+ function summarizeResultQualification(results = []) {
411
+ const output = {
412
+ method: {
413
+ automaticChecks: 'Contrôles techniques automatiques sur le DOM et quelques interactions.',
414
+ heuristicChecks: 'Signaux probables mais contextuels. Ils peuvent contenir des faux positifs.',
415
+ manualChecks: 'Points nécessitant une vérification humaine (contexte, pertinence, parcours réels).',
416
+ },
417
+ disclaimers: [
418
+ 'Ce rapport est un pré-audit automatique basé sur le RGAA 4.1.2.',
419
+ 'Le score ne compte que les critères tranchés automatiquement (C et NC) : ce n’est pas un taux de conformité RGAA.',
420
+ 'Les constats « à vérifier » (NT) n’entrent pas dans le score et demandent un contrôle humain.',
421
+ ],
422
+ statusCounts: {},
423
+ resultTypeCounts: {},
424
+ confidenceCounts: {},
425
+ severityCounts: {},
426
+ manualReviewRecommendedCount: 0,
427
+ totalFindings: 0,
428
+ };
429
+
430
+ for (const result of results) {
431
+ output.totalFindings++;
432
+ const resultType = String(result?.resultType || 'unknown');
433
+ const confidence = String(result?.confidence || 'unknown');
434
+ const severity = String(result?.severity || 'unknown');
435
+ const status = String(result?.status || 'unknown');
436
+ output.statusCounts[status] = (output.statusCounts[status] || 0) + 1;
437
+
438
+ output.resultTypeCounts[resultType] = (output.resultTypeCounts[resultType] || 0) + 1;
439
+ output.confidenceCounts[confidence] = (output.confidenceCounts[confidence] || 0) + 1;
440
+ output.severityCounts[severity] = (output.severityCounts[severity] || 0) + 1;
441
+ if (result?.manualReviewRecommended) output.manualReviewRecommendedCount++;
442
+ }
443
+
444
+ return output;
445
+ }
446
+
447
+ function printSummary(score, title, url, pagesAudited = 1, transparency = null) {
448
+ const bar = '█'.repeat(Math.round(score.taux / 5)) + '░'.repeat(20 - Math.round(score.taux / 5));
449
+ const color = score.taux >= 75 ? '\x1b[32m' : score.taux >= 50 ? '\x1b[33m' : '\x1b[31m';
450
+ const reset = '\x1b[0m';
451
+ const stripAnsi = (value) => String(value).replace(/\x1B\[[0-9;]*m/g, '');
452
+
453
+ const lines = [
454
+ ` Score technique détectable : ${String(score.taux + '%').padEnd(5)} ${bar}`,
455
+ ` Conformes : ${String(score.conformes).padEnd(4)} critères`,
456
+ ` Non conformes: ${String(score.nonConformes).padEnd(4)} critères`,
457
+ ` À vérifier : ${String(score.aVerifier || 0).padEnd(4)} critères`,
458
+ ` N/A : ${String(score.na).padEnd(4)} critères`,
459
+ ` Pages auditées: ${String(pagesAudited).padEnd(4)}`,
460
+ ];
461
+ const innerWidth = Math.max(...lines.map((line) => stripAnsi(line).length));
462
+ const framed = [`┌${'─'.repeat(innerWidth)}┐`, ...lines.map((line) => `│${line.padEnd(innerWidth)}│`), `└${'─'.repeat(innerWidth)}┘`].join('\n');
463
+
464
+ console.log(`
465
+ ${color}${framed}${reset}
466
+ Score = critères C / (C + NC). Les critères « à vérifier » n’y entrent pas.
467
+ Indicateur technique automatique (non équivalent à une conformité RGAA).
468
+ `);
469
+
470
+ if (!transparency) return;
471
+
472
+ const typeCounts = transparency.resultTypeCounts || {};
473
+ const confidenceCounts = transparency.confidenceCounts || {};
474
+ const severityCounts = transparency.severityCounts || {};
475
+
476
+ const formatCounts = (counts) => Object.entries(counts)
477
+ .sort((a, b) => b[1] - a[1])
478
+ .map(([key, value]) => `${key}:${value}`)
479
+ .join(' · ') || 'aucun';
480
+
481
+ console.log(` Types de résultats : ${formatCounts(typeCounts)}`);
482
+ console.log(` Niveaux confiance : ${formatCounts(confidenceCounts)}`);
483
+ console.log(` Gravité : ${formatCounts(severityCounts)}`);
484
+ console.log(` Vérif. manuelle recommandée: ${transparency.manualReviewRecommendedCount}/${transparency.totalFindings}`);
485
+ }
486
+
487
+
488
+ function createDebugLogger(enabled, sink = log) {
489
+ return (message) => {
490
+ if (!enabled) return;
491
+ sink(` [debug] ${message}`);
492
+ };
493
+ }
494
+
495
+ function isAllowedProtocol(protocol) {
496
+ return ALLOWED_PROTOCOLS.has(String(protocol || '').toLowerCase());
497
+ }
498
+
499
+ function validateAuditUrl(input, { safeCrawl = false, allowFileProtocol = false } = {}) {
500
+ let parsed;
501
+ try {
502
+ parsed = new URL(String(input || '').trim());
503
+ } catch {
504
+ throw new Error('URL invalide: fournir une URL absolue (http:// ou https://).');
505
+ }
506
+
507
+ const protocol = parsed.protocol.toLowerCase();
508
+ if (EXPLICITLY_BLOCKED_PROTOCOLS.has(protocol)) {
509
+ if (protocol === 'file:' && allowFileProtocol) {
510
+ if (safeCrawl) {
511
+ throw new Error('Mode safe-crawl: schéma file: interdit.');
512
+ }
513
+ parsed.hash = '';
514
+ return parsed.href;
515
+ }
516
+ throw new Error(`Schéma interdit pour des raisons de sécurité: ${protocol}`);
517
+ }
518
+ if (!isAllowedProtocol(protocol)) {
519
+ throw new Error(`Schéma non supporté: ${protocol}. Seuls http: et https: sont autorisés.`);
520
+ }
521
+
522
+ if (!parsed.hostname) {
523
+ throw new Error('URL invalide: hôte manquant.');
524
+ }
525
+ if (parsed.username || parsed.password) {
526
+ throw new Error('URL invalide: identifiants dans l’URL non autorisés.');
527
+ }
528
+
529
+ if (safeCrawl && parsed.search) {
530
+ throw new Error('Mode safe-crawl: URL de départ avec paramètres de requête non autorisée.');
531
+ }
532
+
533
+ parsed.hash = '';
534
+ return parsed.href;
535
+ }
536
+
537
+ function resolveDepthLimit(depth, { safeCrawl = false } = {}) {
538
+ const requested = Math.max(1, Number(depth) || 1);
539
+ const hardLimit = safeCrawl ? SAFE_CRAWL_MAX_PAGES : DEFAULT_MAX_PAGES;
540
+ return Math.min(requested, hardLimit);
541
+ }
542
+
543
+ function resolveOutputPath(targetPath, { outputDir = '' } = {}) {
544
+ if (!targetPath) return '';
545
+
546
+ const candidate = String(targetPath);
547
+ if (candidate.includes('\0')) {
548
+ throw new Error('Chemin de sortie invalide.');
549
+ }
550
+
551
+ const baseDir = outputDir ? path.resolve(String(outputDir)) : process.cwd();
552
+ return path.isAbsolute(candidate) ? path.resolve(candidate) : path.resolve(baseDir, candidate);
553
+ }
554
+
555
+ function safeWriteReport(filePath, content) {
556
+ const dirPath = path.dirname(filePath);
557
+
558
+ // Crée l’arborescence de sortie pour éviter les erreurs d’écriture implicites.
559
+ fs.mkdirSync(dirPath, { recursive: true, mode: 0o750 });
560
+ fs.writeFileSync(filePath, content, {
561
+ encoding: 'utf8',
562
+ mode: 0o600,
563
+ });
564
+ }
565
+
566
+ async function buildAuditTargets(page, startUrl, options = {}) {
567
+ const { depth = 1, safeCrawl = false, debugLog = () => {} } = options;
568
+
569
+ const requestedDepth = Math.max(1, Number(depth) || 1);
570
+ const maxPages = resolveDepthLimit(requestedDepth, { safeCrawl });
571
+ if (maxPages === 1) {
572
+ return {
573
+ targets: [startUrl],
574
+ ignored: [],
575
+ requestedDepth,
576
+ maxPages,
577
+ };
578
+ }
579
+
580
+ const base = new URL(startUrl);
581
+ const sectionPrefix = detectSectionPrefix(base.pathname);
582
+ const unique = new Set([startUrl]);
583
+ const ignored = [];
584
+
585
+ const noteIgnored = (source, raw, reason) => {
586
+ if (ignored.length >= 500) return;
587
+ const entry = {
588
+ source,
589
+ reason,
590
+ url: typeof raw === 'string' ? raw : String(raw || ''),
591
+ };
592
+ ignored.push(entry);
593
+ debugLog(`URL ignorée [${source}] (${reason}) : ${entry.url}`);
594
+ };
595
+
596
+ const addMany = (urls = [], source = 'unknown') => {
597
+ for (const raw of urls) {
598
+ if (unique.size >= maxPages) break;
599
+ const normalized = normalizeAuditTargetUrl(raw, {
600
+ base,
601
+ sectionPrefix,
602
+ safeCrawl,
603
+ });
604
+
605
+ if (!normalized.ok) {
606
+ noteIgnored(source, raw, normalized.reason);
607
+ continue;
608
+ }
609
+
610
+ if (unique.has(normalized.value)) {
611
+ continue;
612
+ }
613
+ unique.add(normalized.value);
614
+ }
615
+ };
616
+
617
+ addMany(await fetchSitemapUrls(base, { safeCrawl, debugLog }), 'sitemap');
618
+ if (unique.size < maxPages) addMany(await collectInternalLinks(page), 'dom-links');
619
+
620
+ return {
621
+ targets: Array.from(unique).slice(0, maxPages),
622
+ ignored,
623
+ requestedDepth,
624
+ maxPages,
625
+ };
626
+ }
627
+
628
+ function normalizeAuditTargetUrl(rawUrl, { base, sectionPrefix = '', safeCrawl = false } = {}) {
629
+ const raw = typeof rawUrl === 'string' ? rawUrl.trim() : '';
630
+ if (!raw) return { ok: false, reason: 'url vide' };
631
+
632
+ let parsed;
633
+ try {
634
+ parsed = new URL(raw, base.href);
635
+ } catch {
636
+ return { ok: false, reason: 'url invalide' };
637
+ }
638
+
639
+ const protocol = parsed.protocol.toLowerCase();
640
+ if (!isAllowedProtocol(protocol)) {
641
+ return { ok: false, reason: `schéma non autorisé (${protocol})` };
642
+ }
643
+
644
+ if (parsed.origin !== base.origin) {
645
+ return { ok: false, reason: 'origine externe' };
646
+ }
647
+
648
+ const pathname = parsed.pathname || '/';
649
+ if (sectionPrefix && pathname !== sectionPrefix && !pathname.startsWith(`${sectionPrefix}/`)) {
650
+ return { ok: false, reason: 'hors section cible' };
651
+ }
652
+
653
+ if (parsed.username || parsed.password) {
654
+ return { ok: false, reason: 'identifiants dans url' };
655
+ }
656
+
657
+ if (isPageAsset(pathname)) {
658
+ return { ok: false, reason: 'ressource non auditée' };
659
+ }
660
+
661
+ if (PARASITIC_PATH_PATTERNS.some((pattern) => pattern.test(pathname))) {
662
+ return { ok: false, reason: 'chemin parasite/tracking' };
663
+ }
664
+
665
+ parsed.hash = '';
666
+ stripTrackingParams(parsed.searchParams);
667
+
668
+ if (safeCrawl && parsed.search) {
669
+ return { ok: false, reason: 'query refusée en safe-crawl' };
670
+ }
671
+
672
+ if (parsed.pathname.endsWith('/')) {
673
+ parsed.pathname = parsed.pathname.slice(0, -1) || '/';
674
+ }
675
+
676
+ const normalized = parsed.href;
677
+ if (normalized.length > 2048) {
678
+ return { ok: false, reason: 'url trop longue' };
679
+ }
680
+
681
+ return { ok: true, value: normalized };
682
+ }
683
+
684
+ function stripTrackingParams(searchParams) {
685
+ for (const key of Array.from(searchParams.keys())) {
686
+ const lower = key.toLowerCase();
687
+ const isTrackingPrefix = TRACKING_PARAM_PREFIXES.some((prefix) => lower.startsWith(prefix));
688
+ if (isTrackingPrefix || TRACKING_PARAMS.has(lower)) {
689
+ searchParams.delete(key);
690
+ }
691
+ }
692
+ }
693
+
694
+ function isPageAsset(urlPath) {
695
+ return /\.(?:pdf|jpg|jpeg|png|gif|svg|webp|mp4|mp3|zip|xml|webm|ico|woff2?|ttf|eot|css|js)(?:$|\?)/i.test(urlPath);
696
+ }
697
+
698
+ function detectSectionPrefix(pathname) {
699
+ const urlPath = String(pathname || '/');
700
+ const segments = urlPath.split('/').filter(Boolean);
701
+ if (!segments.length) return '';
702
+ return `/${segments[0]}`;
703
+ }
704
+
705
+ async function fetchSitemapUrls(baseUrl, { safeCrawl = false, debugLog = () => {} } = {}) {
706
+ const sitemapUrl = `${baseUrl.origin}/sitemap.xml`;
707
+ const timeoutMs = safeCrawl ? 3000 : 6000;
708
+ const controller = new AbortController();
709
+ const timeout = setTimeout(() => controller.abort(), timeoutMs);
710
+
711
+ try {
712
+ const res = await fetch(sitemapUrl, {
713
+ method: 'GET',
714
+ signal: controller.signal,
715
+ headers: {
716
+ Accept: 'application/xml,text/xml;q=0.9,*/*;q=0.1',
717
+ },
718
+ });
719
+
720
+ if (!res.ok) {
721
+ debugLog(`Sitemap ignoré (${res.status}) : ${sitemapUrl}`);
722
+ return [];
723
+ }
724
+
725
+ const xml = await res.text();
726
+ if (xml.length > MAX_SITEMAP_BYTES) {
727
+ debugLog(`Sitemap trop volumineux (${xml.length} octets) : ${sitemapUrl}`);
728
+ return [];
729
+ }
730
+
731
+ const urls = [];
732
+ const re = /<loc>(.*?)<\/loc>/gims;
733
+ const maxEntries = safeCrawl ? 300 : 1200;
734
+ let match;
735
+ while ((match = re.exec(xml)) !== null && urls.length < maxEntries) {
736
+ urls.push((match[1] || '').trim());
737
+ }
738
+
739
+ return urls;
740
+ } catch (err) {
741
+ debugLog(`Sitemap inaccessible : ${sitemapUrl} (${String(err?.message || err)})`);
742
+ return [];
743
+ } finally {
744
+ clearTimeout(timeout);
745
+ }
746
+ }
747
+
748
+ async function collectInternalLinks(page) {
749
+ try {
750
+ return await page.evaluate((maxCandidates) =>
751
+ Array.from(document.querySelectorAll('a[href]'))
752
+ .map((a) => a.getAttribute('href') || '')
753
+ .filter(Boolean)
754
+ .slice(0, maxCandidates)
755
+ .map((href) => {
756
+ try {
757
+ return new URL(href, location.href).href;
758
+ } catch {
759
+ return '';
760
+ }
761
+ })
762
+ .filter(Boolean),
763
+ MAX_LINK_CANDIDATES);
764
+ } catch {
765
+ return [];
766
+ }
767
+ }
768
+
769
+ async function safePageTitle(page, fallback) {
770
+ try {
771
+ return await page.title();
772
+ } catch {
773
+ return fallback;
774
+ }
775
+ }
776
+
777
+ function normalizeSkipReason(err) {
778
+ const msg = String(err?.message || err || '')
779
+ .replace(/\s+/g, ' ')
780
+ .trim();
781
+ if (/Timeout/i.test(msg)) return 'timeout';
782
+ if (/ERR_|net::|Navigation/i.test(msg)) return 'navigation error';
783
+ return 'unexpected error';
784
+ }
785
+
786
+ async function navigateWithFallback(page, url, profile = {}, debugLog = () => {}) {
787
+ const origin = safeOrigin(url);
788
+ const preferDomContentLoadedOrigins = profile.preferDomContentLoadedOrigins || new Set();
789
+ const warnedOrigins = profile.warnedOrigins || new Set();
790
+
791
+ if (origin && preferDomContentLoadedOrigins.has(origin)) {
792
+ await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 45000 });
793
+ return;
794
+ }
795
+
796
+ try {
797
+ await page.goto(url, { waitUntil: 'networkidle', timeout: 8000 });
798
+ return;
799
+ } catch (err) {
800
+ const isTimeout = /Timeout/i.test(String(err?.message || err || ''));
801
+ if (!isTimeout) throw err;
802
+
803
+ if (origin) preferDomContentLoadedOrigins.add(origin);
804
+ if (origin && !warnedOrigins.has(origin)) {
805
+ warn(' networkidle instable sur ce domaine, navigation basculée en domcontentloaded');
806
+ warnedOrigins.add(origin);
807
+ }
808
+ debugLog(`Fallback navigation domcontentloaded activée pour ${url}`);
809
+ await page.goto(url, { waitUntil: 'domcontentloaded', timeout: 45000 });
810
+ }
811
+ }
812
+
813
+ function safeOrigin(url) {
814
+ try {
815
+ return new URL(url).origin;
816
+ } catch {
817
+ return '';
818
+ }
819
+ }
820
+
821
+ module.exports = {
822
+ runAudit,
823
+ loadBaseline,
824
+ computeScore,
825
+ _internals: {
826
+ createDebugLogger,
827
+ isAllowedProtocol,
828
+ validateAuditUrl,
829
+ resolveDepthLimit,
830
+ resolveOutputPath,
831
+ safeWriteReport,
832
+ normalizeAuditTargetUrl,
833
+ stripTrackingParams,
834
+ isPageAsset,
835
+ },
836
+ };