@holmdigital/engine 3.3.13 → 4.0.1

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/dist/cli/index.js CHANGED
@@ -1012,11 +1012,14 @@ function klarsprakLegalLine(dosLagenReference, opts) {
1012
1012
  }
1013
1013
  if (isNotYetLaw) {
1014
1014
  const phrase2 = criterionPhrase(level, opts?.wcagCriteria ?? "", title);
1015
- return `\xC4nnu inte lagkrav, varken DOS-lagen eller lagen om vissa produkters och tj\xE4nsters tillg\xE4nglighet. ${phrase2} tillkom i WCAG 2.2 och blir bindande i b\xE5da lagarna n\xE4r EN 301 549 V4.x refereras i EU:s officiella tidning, v\xE4ntat 30 november 2026.`;
1015
+ if (opts?.sector === "private") {
1016
+ return `\xC4nnu inte lagkrav enligt lagen (2023:254) om vissa produkters och tj\xE4nsters tillg\xE4nglighet. ${phrase2} tillkom i WCAG 2.2. Det ger presumtion enligt 9 \xA7 n\xE4r en harmoniserad standard som omfattar kriteriet har offentliggjorts i Europeiska unionens officiella tidning under direktiv (EU) 2019/882.`;
1017
+ }
1018
+ return `\xC4nnu inte lagkrav enligt DOS-lagen (2018:1937). ${phrase2} tillkom i WCAG 2.2. Det blir bindande n\xE4r MDFFS 2019:2 5 \xA7 \xE4ndras till en version av EN 301 549 som omfattar kriteriet.`;
1016
1019
  }
1017
1020
  const phrase = criterionPhrase(level, opts?.wcagCriteria ?? "", title);
1018
1021
  if (opts?.sector === "private") {
1019
- return `Lagkrav: lagen om vissa produkters och tj\xE4nsters tillg\xE4nglighet (2023:254), 6 och 9 \xA7\xA7. ${phrase}. EN 301 549-version f\xF6r denna lag \xE4r inte verifierad.`;
1022
+ return `Lagkrav om tj\xE4nsten omfattas av lagen (2023:254) 4 \xA7 och inte tillhandah\xE5lls av ett mikrof\xF6retag (10 \xA7): webbplatser och appar ska vara uppfattningsbara, hanterbara, begripliga och robusta (6 \xA7 och f\xF6rordningen (2023:676) bilaga 2 punkt 3). Lagen n\xE4mner inte WCAG. ${phrase} \xE4r ett vedertaget s\xE4tt att visa detta, men ger presumtion enligt 9 \xA7 f\xF6rst n\xE4r en harmoniserad standard som omfattar kriteriet har offentliggjorts i Europeiska unionens officiella tidning.`;
1020
1023
  }
1021
1024
  const en = opts?.en301549Criteria && opts.en301549Criteria !== "N/A" && opts.en301549Criteria !== "Unknown" ? `, EN 301 549 ${opts.en301549Criteria}` : "";
1022
1025
  return `Lagkrav: DOS-lagen (2018:1937), 10 \xA7. ${phrase}${en}.`;
@@ -1538,6 +1541,7 @@ function evaluateNoScriptCoverage(textLengthWithoutJs, textLengthWithJs, hasNoSc
1538
1541
  async function probeWithoutJavaScript(browser, options) {
1539
1542
  const page = await browser.newPage();
1540
1543
  try {
1544
+ if (options.preparePage) await options.preparePage(page);
1541
1545
  if (options.userAgent) await page.setUserAgent(options.userAgent);
1542
1546
  if (options.viewport) await page.setViewport(options.viewport);
1543
1547
  await page.setJavaScriptEnabled(false);
@@ -1561,6 +1565,146 @@ async function probeWithoutJavaScript(browser, options) {
1561
1565
  }
1562
1566
  }
1563
1567
 
1568
+ // src/core/network-guard.ts
1569
+ init_cjs_shims();
1570
+ var import_promises = require("dns/promises");
1571
+ var import_node_net = require("net");
1572
+ var PrivateHostError = class extends Error {
1573
+ host;
1574
+ reason;
1575
+ constructor(url, host, reason) {
1576
+ super(
1577
+ `Refusing to scan '${url}': ${host} resolves to ${reason}. Private and internal addresses are blocked by default, so the engine cannot be used to reach internal services. To scan your own local development server, pass --allow-private-hosts (library: allowPrivateHosts: true).`
1578
+ );
1579
+ this.name = "PrivateHostError";
1580
+ this.host = host;
1581
+ this.reason = reason;
1582
+ }
1583
+ };
1584
+ function blockedIPv4(ip) {
1585
+ const p = ip.split(".").map(Number);
1586
+ if (p.length !== 4 || p.some((n) => !Number.isInteger(n) || n < 0 || n > 255)) return "a malformed IPv4 address";
1587
+ const [a, b] = p;
1588
+ if (a === 0) return "this-network 0.0.0.0/8";
1589
+ if (a === 10) return "private 10.0.0.0/8";
1590
+ if (a === 127) return "loopback 127.0.0.0/8";
1591
+ if (a === 169 && b === 254) {
1592
+ return ip === "169.254.169.254" ? "the cloud metadata service 169.254.169.254" : "link-local 169.254.0.0/16";
1593
+ }
1594
+ if (a === 172 && b >= 16 && b <= 31) return "private 172.16.0.0/12";
1595
+ if (a === 192 && b === 168) return "private 192.168.0.0/16";
1596
+ if (a === 100 && b >= 64 && b <= 127) return "carrier-grade NAT 100.64.0.0/10";
1597
+ if (a === 192 && b === 0) return "IETF protocol assignments 192.0.0.0/24";
1598
+ if (a >= 224) return "multicast or reserved 224.0.0.0/4";
1599
+ return null;
1600
+ }
1601
+ function blockedIPv6(ip) {
1602
+ const lower = ip.toLowerCase();
1603
+ const mapped = lower.match(/^::ffff:(\d+\.\d+\.\d+\.\d+)$/);
1604
+ if (mapped) return blockedIPv4(mapped[1]);
1605
+ if (lower === "::1") return "loopback ::1";
1606
+ if (lower === "::") return "unspecified ::";
1607
+ if (/^f[cd]/.test(lower)) return "unique local fc00::/7";
1608
+ if (/^fe[89ab]/.test(lower)) return "link-local fe80::/10";
1609
+ if (/^ff/.test(lower)) return "multicast ff00::/8";
1610
+ return null;
1611
+ }
1612
+ var systemResolver = (hostname) => (0, import_promises.lookup)(hostname, { all: true });
1613
+ async function blockedHostReason(hostname, resolve = systemResolver) {
1614
+ const host = hostname.replace(/^\[|\]$/g, "");
1615
+ const literal = (0, import_node_net.isIP)(host);
1616
+ if (literal === 4) return blockedIPv4(host);
1617
+ if (literal === 6) return blockedIPv6(host);
1618
+ let addresses;
1619
+ try {
1620
+ addresses = await resolve(host);
1621
+ } catch {
1622
+ return "an address that could not be resolved (blocked: the guard fails closed)";
1623
+ }
1624
+ if (addresses.length === 0) return "no address (blocked: the guard fails closed)";
1625
+ for (const { address, family } of addresses) {
1626
+ const reason = family === 6 ? blockedIPv6(address) : blockedIPv4(address);
1627
+ if (reason) return reason;
1628
+ }
1629
+ return null;
1630
+ }
1631
+ async function assertPublicHost(url, resolve = systemResolver) {
1632
+ const { hostname } = new URL(url);
1633
+ const reason = await blockedHostReason(hostname, resolve);
1634
+ if (reason) throw new PrivateHostError(url, hostname, reason);
1635
+ }
1636
+ var LOCAL_SCHEMES = /* @__PURE__ */ new Set(["data:", "blob:", "about:"]);
1637
+ async function guardPage(page, resolve = systemResolver) {
1638
+ const verdicts = /* @__PURE__ */ new Map();
1639
+ const blocked = [];
1640
+ const verdictFor = (hostname) => {
1641
+ let verdict = verdicts.get(hostname);
1642
+ if (!verdict) {
1643
+ verdict = blockedHostReason(hostname, resolve);
1644
+ verdicts.set(hostname, verdict);
1645
+ }
1646
+ return verdict;
1647
+ };
1648
+ await page.setRequestInterception(true);
1649
+ page.on("request", (request) => {
1650
+ void (async () => {
1651
+ let reason;
1652
+ let host = "";
1653
+ try {
1654
+ const target = new URL(request.url());
1655
+ host = target.hostname;
1656
+ if (LOCAL_SCHEMES.has(target.protocol)) {
1657
+ reason = null;
1658
+ } else if (target.protocol === "http:" || target.protocol === "https:") {
1659
+ reason = await verdictFor(target.hostname);
1660
+ } else {
1661
+ reason = `the unsupported scheme ${target.protocol}`;
1662
+ }
1663
+ } catch {
1664
+ reason = "an address the guard could not check";
1665
+ }
1666
+ try {
1667
+ if (reason) {
1668
+ blocked.push({ url: request.url(), host, reason });
1669
+ await request.abort("blockedbyclient");
1670
+ } else {
1671
+ await request.continue();
1672
+ }
1673
+ } catch {
1674
+ }
1675
+ })();
1676
+ });
1677
+ return () => [...blocked];
1678
+ }
1679
+
1680
+ // src/core/browser-launch.ts
1681
+ init_cjs_shims();
1682
+ function puppeteerArgsFromEnv(env = process.env) {
1683
+ return (env.PUPPETEER_ARGS ?? "").split(/\s+/).filter(Boolean);
1684
+ }
1685
+ function sandboxRequested(policy, env = process.env) {
1686
+ return policy.sandbox !== false && !puppeteerArgsFromEnv(env).includes("--no-sandbox");
1687
+ }
1688
+ function chromeLaunchArgs(policy, env = process.env) {
1689
+ return [
1690
+ ...policy.sandbox === false ? ["--no-sandbox", "--disable-setuid-sandbox"] : [],
1691
+ ...policy.invalidHttpsCert ? ["--ignore-certificate-errors", "--allow-insecure-localhost"] : [],
1692
+ ...policy.extraArgs ?? [],
1693
+ ...puppeteerArgsFromEnv(env)
1694
+ ];
1695
+ }
1696
+ function explainLaunchFailure(error, policy, env = process.env) {
1697
+ const original = error instanceof Error ? error : new Error(String(error));
1698
+ if (!sandboxRequested(policy, env) || !/sandbox|user namespace|setuid|crbug\.com\/638180/i.test(original.message)) {
1699
+ return original;
1700
+ }
1701
+ const chromeSaid = original.message.split("\n").find((line) => /sandbox|namespace|setuid/i.test(line))?.trim() ?? original.message.split("\n")[0];
1702
+ return new Error(
1703
+ `Chrome could not start its sandbox. The sandbox is on by default because the engine renders third-party pages. Chrome cannot use it when running as root (for example in a container without a USER) or where unprivileged user namespaces are restricted (for example on Ubuntu 24.04 CI runners). Either run as a regular user in an environment that allows the sandbox, or disable it explicitly with --no-sandbox (library: sandbox: false, or PUPPETEER_ARGS="--no-sandbox"). Only disable it for pages you trust.
1704
+ Chrome said: ${chromeSaid}`
1705
+ );
1706
+ }
1707
+
1564
1708
  // src/core/regulatory-scanner.ts
1565
1709
  var import_node_fs = require("fs");
1566
1710
  function wcagTagToCriterion(tag) {
@@ -1620,7 +1764,7 @@ function isInterstitialPage(pageTitle, hasMetaRefresh, bodyTextLength) {
1620
1764
  return false;
1621
1765
  }
1622
1766
  function getEngineVersion() {
1623
- return "3.3.13";
1767
+ return "4.0.1";
1624
1768
  }
1625
1769
  function getStandardsVersion() {
1626
1770
  try {
@@ -1634,6 +1778,7 @@ function getStandardsVersion() {
1634
1778
  var SCAN_USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36";
1635
1779
  var RegulatoryScanner = class {
1636
1780
  browser = null;
1781
+ blockedRequests = () => [];
1637
1782
  options;
1638
1783
  htmlValidator;
1639
1784
  constructor(options) {
@@ -1670,6 +1815,9 @@ var RegulatoryScanner = class {
1670
1815
  let interstitialSuspected;
1671
1816
  let passedCount = 0;
1672
1817
  try {
1818
+ if (!this.options.allowPrivateHosts) {
1819
+ await assertPublicHost(this.options.url);
1820
+ }
1673
1821
  await this.initBrowser();
1674
1822
  const page = await this.getPage();
1675
1823
  if (this.options.viewport) {
@@ -1684,6 +1832,10 @@ var RegulatoryScanner = class {
1684
1832
  });
1685
1833
  break;
1686
1834
  } catch (e) {
1835
+ const stopped = this.blockedRequests()[0];
1836
+ if (stopped && e instanceof Error && e.message.includes("ERR_BLOCKED_BY_CLIENT")) {
1837
+ throw new PrivateHostError(this.options.url, stopped.host, `${stopped.reason}, reached during navigation (for example through a redirect)`);
1838
+ }
1687
1839
  retries--;
1688
1840
  if (retries === 0) throw e;
1689
1841
  this.log(`Navigation failed, retrying... (${retries} attempts left)`);
@@ -1763,6 +1915,11 @@ var RegulatoryScanner = class {
1763
1915
  }
1764
1916
  const scanDuration = Date.now() - startTime;
1765
1917
  const result = this.generateResultPackage(allReports, passedCount, scanDuration, pageTitle, pageLanguage, interstitialSuspected);
1918
+ const blockedCount = this.blockedRequests().length;
1919
+ if (blockedCount > 0) {
1920
+ result.metadata.blockedPrivateRequests = blockedCount;
1921
+ this.log(`Sp\xE4rrade ${blockedCount} f\xF6rfr\xE5gningar till privata eller interna adresser (Intern #53).`);
1922
+ }
1766
1923
  if (result.complianceStatus !== "INCONCLUSIVE") {
1767
1924
  if (htmlValidation) {
1768
1925
  result.htmlValidation = htmlValidation;
@@ -1777,20 +1934,27 @@ var RegulatoryScanner = class {
1777
1934
  }
1778
1935
  }
1779
1936
  async initBrowser() {
1780
- this.browser = await import_puppeteer.default.launch({
1781
- headless: this.options.headless,
1782
- args: [
1783
- "--no-sandbox",
1784
- "--disable-setuid-sandbox",
1785
- "--disable-blink-features=AutomationControlled",
1786
- // Gömmer att det är en robot
1787
- ...this.options.invalidHttpsCert ? ["--ignore-certificate-errors", "--allow-insecure-localhost"] : []
1788
- ]
1789
- });
1937
+ const policy = {
1938
+ sandbox: this.options.sandbox,
1939
+ invalidHttpsCert: this.options.invalidHttpsCert,
1940
+ extraArgs: ["--disable-blink-features=AutomationControlled"]
1941
+ // Gömmer att det är en robot
1942
+ };
1943
+ try {
1944
+ this.browser = await import_puppeteer.default.launch({
1945
+ headless: this.options.headless,
1946
+ args: chromeLaunchArgs(policy)
1947
+ });
1948
+ } catch (e) {
1949
+ throw explainLaunchFailure(e, policy);
1950
+ }
1790
1951
  }
1791
1952
  async getPage() {
1792
1953
  if (!this.browser) throw new Error("Browser not initialized");
1793
1954
  const page = await this.browser.newPage();
1955
+ if (!this.options.allowPrivateHosts) {
1956
+ this.blockedRequests = await guardPage(page);
1957
+ }
1794
1958
  await page.setUserAgent(SCAN_USER_AGENT);
1795
1959
  return page;
1796
1960
  }
@@ -1817,7 +1981,11 @@ var RegulatoryScanner = class {
1817
1981
  // vi skulle mäta två olika sidor, inte JS-effekten.
1818
1982
  url: this.options.url,
1819
1983
  userAgent: SCAN_USER_AGENT,
1820
- viewport: this.options.viewport
1984
+ viewport: this.options.viewport,
1985
+ // Sondens sida får samma spärr som huvudsidan.
1986
+ preparePage: this.options.allowPrivateHosts ? void 0 : async (probePage) => {
1987
+ await guardPage(probePage);
1988
+ }
1821
1989
  });
1822
1990
  return evaluateNoScriptCoverage(
1823
1991
  measurement.textLength,
@@ -3092,11 +3260,16 @@ ${renderNoScriptSection(result)}
3092
3260
  // src/reporting/pdf-generator.ts
3093
3261
  init_cjs_shims();
3094
3262
  var import_puppeteer2 = __toESM(require("puppeteer"));
3095
- async function generatePDF(htmlContent, outputPath) {
3096
- const browser = await import_puppeteer2.default.launch({
3097
- headless: true,
3098
- args: ["--no-sandbox", "--disable-setuid-sandbox"]
3099
- });
3263
+ async function generatePDF(htmlContent, outputPath, policy = {}) {
3264
+ let browser;
3265
+ try {
3266
+ browser = await import_puppeteer2.default.launch({
3267
+ headless: true,
3268
+ args: chromeLaunchArgs(policy)
3269
+ });
3270
+ } catch (e) {
3271
+ throw explainLaunchFailure(e, policy);
3272
+ }
3100
3273
  try {
3101
3274
  const page = await browser.newPage();
3102
3275
  await page.setContent(htmlContent, {
@@ -3125,7 +3298,7 @@ var import_react = __toESM(require("react"));
3125
3298
  var import_server = require("react-dom/server");
3126
3299
  var import_components = require("@holmdigital/components");
3127
3300
  var import_standards3 = require("@holmdigital/standards");
3128
- var import_promises = __toESM(require("fs/promises"));
3301
+ var import_promises2 = __toESM(require("fs/promises"));
3129
3302
  var import_path = __toESM(require("path"));
3130
3303
  init_needs_review();
3131
3304
  var EVALUATION_METHOD = {
@@ -3185,65 +3358,46 @@ var RESPONSE_TIME_DEFAULT = {
3185
3358
  "en-ca": "2 days",
3186
3359
  "en-au": "2 days"
3187
3360
  };
3188
- var NATIONAL_LAW_FALLBACK = {
3189
- en: "applicable accessibility requirements",
3190
- sv: "g\xE4llande tillg\xE4nglighetskrav",
3191
- no: "gjeldende tilgjengelighetskrav",
3192
- da: "g\xE6ldende tilg\xE6ngelighedskrav",
3193
- fi: "sovellettavat saavutettavuusvaatimukset",
3194
- de: "die geltenden Barrierefreiheitsanforderungen",
3195
- nl: "de geldende toegankelijkheidseisen",
3196
- fr: "la r\xE9glementation d'accessibilit\xE9 applicable",
3197
- es: "los requisitos de accesibilidad aplicables",
3198
- it: "i requisiti di accessibilit\xE0 applicabili",
3199
- pt: "os requisitos de acessibilidade aplic\xE1veis",
3200
- pl: "obowi\u0105zuj\u0105ce wymagania dost\u0119pno\u015Bci"
3201
- };
3202
- function resolveNationalLawReference(country, sector, lang = "en") {
3203
- const inForce = (law2) => !!law2 && law2.inForce !== false;
3204
- if (country === "AU") {
3205
- const ddaLaw = (0, import_standards3.getNationalLaws)("AU").find((l) => l.euFramework === "DDA" && inForce(l));
3206
- return ddaLaw ? `${ddaLaw.fullName}` : "Disability Discrimination Act 1992 (Cth)";
3207
- }
3208
- if (country === "US") {
3209
- const usLaws = (0, import_standards3.getNationalLaws)("US").filter(inForce);
3210
- const adaLaw = usLaws.find((l) => l.euFramework === "ADA" && l.scope === sector);
3211
- if (adaLaw) {
3212
- if (sector === "public") {
3213
- const s508 = usLaws.find((l) => l.id === "us-508");
3214
- return s508 ? `${adaLaw.fullName} (${adaLaw.law}) & ${s508.fullName} (${s508.law})` : `${adaLaw.fullName} (${adaLaw.law})`;
3215
- }
3216
- const hhs504 = usLaws.find((l) => l.euFramework === "REHAB" && l.scope === "private");
3217
- return hhs504 ? `${adaLaw.fullName} (${adaLaw.law}) & ${hhs504.fullName} (${hhs504.law})` : `${adaLaw.fullName} (${adaLaw.law})`;
3218
- }
3219
- }
3220
- const law = (0, import_standards3.getNationalLawForSector)(country, sector);
3221
- if (law) {
3222
- const shortName = law.law.trim();
3223
- const longName = law.fullName.trim();
3224
- const redundant = longName === shortName || longName.startsWith(shortName);
3225
- return redundant ? longName : `${longName} (${shortName})`;
3226
- }
3227
- const langKey = lang.split("-")[0];
3228
- return NATIONAL_LAW_FALLBACK[langKey] ?? NATIONAL_LAW_FALLBACK.en;
3361
+ var REVIEWER_PLACEHOLDERS = [
3362
+ "{<extern akt\xF6r>}",
3363
+ "{<ekstern akt\xF8r>}",
3364
+ "{<ekstern aktor>}",
3365
+ "{<ulkoinen taho>}",
3366
+ "{<externe partij>}",
3367
+ "{<externer Dritter>}",
3368
+ "{<tiers externe>}",
3369
+ "{<tercero externo>}",
3370
+ "{<terza parte>}",
3371
+ "{<terceiro externo>}",
3372
+ "{<podmiot zewn\u0119trzny>}",
3373
+ "{<third party>}"
3374
+ ];
3375
+ function resolveSwedishEnforcementContent(enforcementBody, nationalLaw) {
3376
+ return `${enforcementBody} har ansvaret f\xF6r tillsyn \xF6ver ${nationalLaw}. Du kan anm\xE4la till ${enforcementBody} om du tycker att v\xE5r digitala service har brister i tillg\xE4nglighet.
3377
+
3378
+ Du kan ocks\xE5 anm\xE4la till ${enforcementBody} om du tycker att v\xE5r bed\xF6mning av vad som \xE4r osk\xE4ligt betungande ska granskas, om du tycker att v\xE5r tillg\xE4nglighetsredog\xF6relse har brister eller om du tycker att vi inte har hanterat din beg\xE4ran om tillg\xE4ngligg\xF6rande korrekt.
3379
+
3380
+ Du kan anm\xE4la direkt till Digg via tj\xE4nsten f\xF6r anm\xE4lan om bristande tillg\xE4nglighet: https://www.digg.se/tdosanmalan`;
3229
3381
  }
3230
3382
  async function generateStatementContent(result, lang = "en", format = "html", metadata) {
3383
+ const reviewMethod = metadata?.reviewMethod;
3384
+ const reviewerName = typeof metadata?.reviewer?.name === "string" ? metadata.reviewer.name.trim() : "";
3385
+ if (reviewMethod === "external-review" && reviewerName === "") {
3386
+ throw new Error(
3387
+ "reviewMethod 'external-review' requires metadata.reviewer with a non-empty name: the organisation that performed the review, e.g. { reviewMethod: 'external-review', reviewer: { name: 'Example Audit AB' } }. The statement names it as the reviewer. Use 'self-assessment' (the default) if the statement is based on your own testing, such as this scan."
3388
+ );
3389
+ }
3231
3390
  const templatePath = import_path.default.join(__dirname, "templates", `${lang}.json`);
3232
3391
  let template;
3233
3392
  try {
3234
- const data = await import_promises.default.readFile(templatePath, "utf-8");
3393
+ const data = await import_promises2.default.readFile(templatePath, "utf-8");
3235
3394
  template = JSON.parse(data);
3236
3395
  } catch {
3237
3396
  throw new Error(
3238
3397
  `Accessibility statement template not found for locale "${lang}". Expected file at: ${templatePath}`
3239
3398
  );
3240
3399
  }
3241
- let complianceLevel = "full";
3242
- if (result.stats.critical > 0 || result.legalSummary && result.legalSummary.eaaDeadlineViolations > 0) {
3243
- complianceLevel = "non-compliant";
3244
- } else if (result.score < 100) {
3245
- complianceLevel = "partial";
3246
- }
3400
+ const complianceLevel = "partial";
3247
3401
  const issuesMap = /* @__PURE__ */ new Map();
3248
3402
  violationsOf(result.reports).forEach((report) => {
3249
3403
  if (!issuesMap.has(report.ruleId)) {
@@ -3292,7 +3446,7 @@ async function generateStatementContent(result, lang = "en", format = "html", me
3292
3446
  ];
3293
3447
  for (const p of possiblePaths) {
3294
3448
  try {
3295
- const logoBuffer = await import_promises.default.readFile(p);
3449
+ const logoBuffer = await import_promises2.default.readFile(p);
3296
3450
  logoUrl = `data:image/jpeg;base64,${logoBuffer.toString("base64")}`;
3297
3451
  break;
3298
3452
  } catch {
@@ -3314,6 +3468,10 @@ async function generateStatementContent(result, lang = "en", format = "html", me
3314
3468
  name: "HolmDigital Regulatory Engine",
3315
3469
  url: "https://holmdigital.se"
3316
3470
  },
3471
+ // Intern #95: HTML-utlåtandet renderas av komponenten, så metodvalet och
3472
+ // granskaren måste följa med dit. Annars gäller valet bara Markdown.
3473
+ reviewMethod,
3474
+ reviewer: metadata?.reviewer,
3317
3475
  logoUrl,
3318
3476
  // Placeholders make it obvious the consumer must supply real contact info.
3319
3477
  // Previous fallback leaked HolmDigital's own contact details into customer statements.
@@ -3406,15 +3564,10 @@ async function generateStatementContent(result, lang = "en", format = "html", me
3406
3564
  "{<m\xE9thode>}": props.evaluationMethod || "Automated Scan",
3407
3565
  "{<m\xE9todo>}": props.evaluationMethod || "Automated Scan",
3408
3566
  "{<method>}": props.evaluationMethod || "Automated Scan",
3409
- "{<extern akt\xF6r>}": props.generatorTool?.name || "HolmDigital Engine",
3410
- "{<ekstern akt\xF8r>}": props.generatorTool?.name || "HolmDigital Engine",
3411
- "{<ekstern aktor>}": props.generatorTool?.name || "HolmDigital Engine",
3412
- "{<ulkoinen taho>}": props.generatorTool?.name || "HolmDigital Engine",
3413
- "{<externe partij>}": props.generatorTool?.name || "HolmDigital Engine",
3414
- "{<externer Dritter>}": props.generatorTool?.name || "HolmDigital Engine",
3415
- "{<tiers externe>}": props.generatorTool?.name || "HolmDigital Engine",
3416
- "{<tercero externo>}": props.generatorTool?.name || "HolmDigital Engine",
3417
- "{<third party>}": props.generatorTool?.name || "HolmDigital Engine",
3567
+ // Intern #95: granskarens plats fylls bara ur reviewer, aldrig ur
3568
+ // generatorTool. Den renderas bara när metodvalet är en uttalad
3569
+ // extern granskning, och då är namnet kontrollerat ovan.
3570
+ ...Object.fromEntries(REVIEWER_PLACEHOLDERS.map((p) => [p, reviewerName])),
3418
3571
  "{<enforcement_body>}": (() => {
3419
3572
  if (country === "US") {
3420
3573
  const adaLaw = (0, import_standards3.getNationalLaws)("US").find((l) => l.euFramework === "ADA" && l.scope === sector && l.inForce !== false);
@@ -3422,7 +3575,7 @@ async function generateStatementContent(result, lang = "en", format = "html", me
3422
3575
  }
3423
3576
  return (0, import_standards3.getEnforcementBody)(country, sector);
3424
3577
  })(),
3425
- "{<national_law>}": resolveNationalLawReference(country, sector, lang),
3578
+ "{<national_law>}": (0, import_standards3.resolveNationalLawReference)(country, sector, lang),
3426
3579
  "{<ahrc_url>}": "https://www.humanrights.gov.au/complaints",
3427
3580
  "{<brister>}": nonComplianceItems.length > 0 ? nonComplianceItems.map((item) => `* ${item}`).join("\n") : lang === "sv" ? "Inga k\xE4nda brister." : "No known issues.",
3428
3581
  "{<puutteet>}": nonComplianceItems.length > 0 ? nonComplianceItems.map((item) => `* ${item}`).join("\n") : lang === "fi" ? "Ei tiedossa olevia puutteita." : "No known issues.",
@@ -3436,7 +3589,17 @@ async function generateStatementContent(result, lang = "en", format = "html", me
3436
3589
  "{<braki>}": nonComplianceItems.length > 0 ? nonComplianceItems.map((item) => `* ${item}`).join("\n") : "Brak znanych problem\xF3w.",
3437
3590
  "{<issues>}": nonComplianceItems.length > 0 ? nonComplianceItems.map((item) => `* ${item}`).join("\n") : "No known issues."
3438
3591
  };
3439
- const processText = (text) => {
3592
+ const choiceIndex = (kind, parts) => {
3593
+ if (kind === "method") {
3594
+ if (reviewMethod === "external-review") return 1;
3595
+ if (reviewMethod === "no-review") return parts > 2 ? 2 : 1;
3596
+ return 0;
3597
+ }
3598
+ if (complianceLevel === "partial") return 1;
3599
+ if (complianceLevel === "non-compliant") return parts > 2 ? 2 : 1;
3600
+ return 0;
3601
+ };
3602
+ const processText = (text, kind = "compliance") => {
3440
3603
  let processed = text;
3441
3604
  processed = processed.replace(/\[([\s\S]*?)\]/g, (_match, content2) => {
3442
3605
  if (content2.includes("{<svarstid>}") || content2.includes("{<svartid>}") || content2.includes("{<response time>}")) {
@@ -3450,27 +3613,28 @@ async function generateStatementContent(result, lang = "en", format = "html", me
3450
3613
  }
3451
3614
  return content2;
3452
3615
  });
3616
+ const values = [];
3453
3617
  processed = processed.replace(/\{<[^>]+>\}/g, (match) => {
3454
- return substitutions[match] !== void 0 ? substitutions[match] : match;
3618
+ values.push(substitutions[match] !== void 0 ? substitutions[match] : match);
3619
+ return `\uE000${values.length - 1}\uE000`;
3455
3620
  });
3456
3621
  processed = processed.replace(/\{([^{}]*?)\}/g, (_match, content2) => {
3457
3622
  const parts = content2.split("/");
3458
3623
  if (parts.length >= 2) {
3459
- let idx = 0;
3460
- if (complianceLevel === "partial") idx = 1;
3461
- if (complianceLevel === "non-compliant") idx = parts.length > 2 ? 2 : 1;
3462
- return parts[idx].trim();
3624
+ return parts[choiceIndex(kind, parts.length)].trim();
3463
3625
  }
3464
3626
  return _match;
3465
3627
  });
3466
- return processed;
3628
+ return processed.replace(/\uE000(\d+)\uE000/g, (_m, i) => values[Number(i)]);
3467
3629
  };
3468
3630
  const title = processText(template.title);
3469
3631
  const intro = processText(template.intro);
3470
3632
  const enforcementBody = String(substitutions["{<enforcement_body>}"] ?? "").trim();
3471
3633
  const sections = template.sections.map((s) => {
3472
3634
  if (s.id === "enforcement" && enforcementBody === "") return null;
3473
- const body = processText(s.content).trim();
3635
+ if (s.sectors && !s.sectors.includes(sector)) return null;
3636
+ const delad = s.id === "enforcement" ? (0, import_standards3.getEnforcementStatementText)(country, sector, lang) : null;
3637
+ const body = (delad ?? (s.id === "enforcement" && country === "SE" && lang === "sv" && sector === "public" ? resolveSwedishEnforcementContent(enforcementBody, substitutions["{<national_law>}"] ?? "") : processText(s.content, s.id === "testing" ? "method" : "compliance"))).trim();
3474
3638
  if (body === "") return null;
3475
3639
  return s.title ? `## ${s.title}
3476
3640
 
@@ -3490,8 +3654,8 @@ Generated using [${props.generatorTool?.name || "HolmDigital Engine"}](${props.g
3490
3654
  async function generateStatement(result, outputPath, lang = "en", format = "html", metadata) {
3491
3655
  const content = await generateStatementContent(result, lang, format, metadata);
3492
3656
  const dir = import_path.default.dirname(outputPath);
3493
- await import_promises.default.mkdir(dir, { recursive: true });
3494
- await import_promises.default.writeFile(outputPath, content, "utf-8");
3657
+ await import_promises2.default.mkdir(dir, { recursive: true });
3658
+ await import_promises2.default.writeFile(outputPath, content, "utf-8");
3495
3659
  }
3496
3660
 
3497
3661
  // src/cli/parse-options.ts
@@ -3514,6 +3678,25 @@ function parseHydrationWait(raw) {
3514
3678
  }
3515
3679
  return ms;
3516
3680
  }
3681
+ var REVIEW_METHODS = ["self-assessment", "external-review", "no-review"];
3682
+ var isReviewMethod = (value) => REVIEW_METHODS.includes(value);
3683
+ function parseReviewOptions(rawMethod, rawReviewer) {
3684
+ if (rawMethod === void 0 || rawMethod === null) return {};
3685
+ const method = String(rawMethod).trim();
3686
+ if (!isReviewMethod(method)) {
3687
+ throw new InvalidOptionError(
3688
+ `Invalid --review-method value '${String(rawMethod)}'. Expected one of: ${REVIEW_METHODS.join(", ")}.`
3689
+ );
3690
+ }
3691
+ if (method !== "external-review") return { reviewMethod: method };
3692
+ const name = typeof rawReviewer === "string" ? rawReviewer.trim() : "";
3693
+ if (name === "") {
3694
+ throw new InvalidOptionError(
3695
+ `--review-method external-review requires --reviewer <name> (or "reviewer" in the config file): the organisation that performed the review, e.g. --reviewer "Example Audit AB". Use self-assessment (the default) if the statement is based on your own testing, such as this scan.`
3696
+ );
3697
+ }
3698
+ return { reviewMethod: method, reviewer: { name } };
3699
+ }
3517
3700
 
3518
3701
  // src/cli/url-guard.ts
3519
3702
  init_cjs_shims();
@@ -3662,13 +3845,18 @@ function renderNoScriptAdvisory(noScript) {
3662
3845
  }
3663
3846
  var program = new import_commander.Command();
3664
3847
  program.name("hd-a11y-scan").description("HolmDigital Regulatory Scanner").version(getEngineVersion());
3665
- program.argument("<url>", "URL to scan").option("--lang <code>", "Language code (en, sv)").option("--ci", "Run in CI/CD mode (exit code 1 on critical failures)").option("--generate-tests", "Generate Pseudo-Automation tests").option("--json", "Output as JSON").option("--junit <path>", "Generate JUnit XML report").option("--pdf <path>", "Generate PDF report to path").option("--statement <path>", "Generate accessibility statement HTML to path").option("--format <type>", "Output format for statement (html, md)", "html").option("--viewport <size>", 'Set viewport (e.g. "mobile", "desktop", "1024x768")').option("--threshold <level>", "Severity threshold (critical, high, medium, low)").option("--api-key <key>", "API key for HolmDigital Cloud").option("--cloud-url <url>", "Cloud API URL").option("--invalid-https-cert", "Allow scanning on pages with invalid https certificate").option("--email <email>", "Contact email for accessibility statement").option("--phone <number>", "Contact phone number for accessibility statement").option("--org <name>", "Organization name for accessibility statement").option("--response-time <time>", "Expected response time for accessibility statement").option("--country <code>", "Country code for accessibility statement enforcement body").option("--sector <type>", "Sector type: public (WAD) or private (EAA)", "public").option("--publish-date <date>", "Publish date for the website (YYYY-MM-DD)").option("--light", "Light scan: fast score-only mode (skips HTML validation and detailed legal mapping)").option("--audience <mode>", "Output audience: developer (default) or plain", "developer").option("--plain", "Alias for --audience plain (klarspr\xE5ksl\xE4ge for non-technical recipients)").option("--noscript-check", "Robustness probe: measure how much content is available without JavaScript. Advisory only, never affects the compliance score.").option("--wait-for-hydration <ms>", `Milliseconds to wait after network idle so client-rendered SPAs finish hydrating before axe runs (default 2500, 0 disables, max ${MAX_HYDRATION_WAIT_MS})`).action(async (url, cliOptions) => {
3848
+ program.argument("<url>", "URL to scan").option("--lang <code>", "Language code (en, sv)").option("--ci", "Run in CI/CD mode (exit code 1 on critical failures)").option("--generate-tests", "Generate Pseudo-Automation tests").option("--json", "Output as JSON").option("--junit <path>", "Generate JUnit XML report").option("--pdf <path>", "Generate PDF report to path").option("--statement <path>", "Generate accessibility statement HTML to path").option("--format <type>", "Output format for statement (html, md)", "html").option("--viewport <size>", 'Set viewport (e.g. "mobile", "desktop", "1024x768")').option("--threshold <level>", "Severity threshold (critical, high, medium, low)").option("--api-key <key>", "API key for HolmDigital Cloud").option("--cloud-url <url>", "Cloud API URL").option("--invalid-https-cert", "Allow scanning on pages with invalid https certificate").option("--allow-private-hosts", "Allow private and internal addresses such as localhost, 10.x and 192.168.x (blocked by default, for the page and every request it makes)").option("--no-sandbox", "Disable the Chrome sandbox. Only for pages you trust; needed when running as root or where user namespaces are restricted").option("--email <email>", "Contact email for accessibility statement").option("--phone <number>", "Contact phone number for accessibility statement").option("--org <name>", "Organization name for accessibility statement").option("--response-time <time>", "Expected response time for accessibility statement").option("--country <code>", "Country code for accessibility statement enforcement body").option("--sector <type>", "Sector type: public (WAD) or private (EAA)", "public").option("--publish-date <date>", "Publish date for the website (YYYY-MM-DD)").option("--review-method <method>", "How the statement assessment was made: self-assessment (default), external-review (requires --reviewer) or no-review").option("--reviewer <name>", "Organisation that performed the external review, named in the statement (used with --review-method external-review)").option("--light", "Light scan: fast score-only mode (skips HTML validation and detailed legal mapping)").option("--audience <mode>", "Output audience: developer (default) or plain", "developer").option("--plain", "Alias for --audience plain (klarspr\xE5ksl\xE4ge for non-technical recipients)").option("--noscript-check", "Robustness probe: measure how much content is available without JavaScript. Advisory only, never affects the compliance score.").option("--wait-for-hydration <ms>", `Milliseconds to wait after network idle so client-rendered SPAs finish hydrating before axe runs (default 2500, 0 disables, max ${MAX_HYDRATION_WAIT_MS})`).action(async (url, cliOptions) => {
3666
3849
  const explorer = (0, import_cosmiconfig.cosmiconfig)("a11y");
3667
3850
  const configResult = await explorer.search();
3668
3851
  const fileConfig = configResult ? configResult.config : {};
3669
3852
  let waitForHydrationMs;
3853
+ let review = {};
3670
3854
  try {
3671
3855
  waitForHydrationMs = cliOptions.waitForHydration !== void 0 ? parseHydrationWait(cliOptions.waitForHydration) : fileConfig.waitForHydrationMs !== void 0 ? parseHydrationWait(String(fileConfig.waitForHydrationMs)) : void 0;
3856
+ review = parseReviewOptions(
3857
+ cliOptions.reviewMethod || fileConfig.reviewMethod,
3858
+ cliOptions.reviewer || fileConfig.reviewer
3859
+ );
3672
3860
  } catch (e) {
3673
3861
  if (e instanceof InvalidOptionError) {
3674
3862
  console.error(import_chalk2.default.red(e.message));
@@ -3691,6 +3879,11 @@ program.argument("<url>", "URL to scan").option("--lang <code>", "Language code
3691
3879
  apiKey: cliOptions.apiKey || fileConfig.apiKey,
3692
3880
  cloudUrl: cliOptions.cloudUrl || fileConfig.cloudUrl || "https://cloud.holmdigital.se",
3693
3881
  invalidHttpsCert: cliOptions.invalidHttpsCert ?? fileConfig.invalidHttpsCert ?? false,
3882
+ // Intern #53 steg 2: spärren och sandboxen är på som standard.
3883
+ allowPrivateHosts: cliOptions.allowPrivateHosts ?? fileConfig.allowPrivateHosts ?? false,
3884
+ // Commander sätter sandbox: true som standard för en --no-sandbox-flagga,
3885
+ // så CLI-värdet kan bara säga nej. Config-filen får också säga nej.
3886
+ sandbox: cliOptions.sandbox === false ? false : fileConfig.sandbox !== false,
3694
3887
  // Metadata for accessibility statement
3695
3888
  email: cliOptions.email || fileConfig.email,
3696
3889
  phone: cliOptions.phone || fileConfig.phone,
@@ -3699,6 +3892,8 @@ program.argument("<url>", "URL to scan").option("--lang <code>", "Language code
3699
3892
  country: cliOptions.country || fileConfig.country,
3700
3893
  sector: cliOptions.sector || fileConfig.sector || "public",
3701
3894
  publishDate: cliOptions.publishDate || fileConfig.publishDate,
3895
+ reviewMethod: review.reviewMethod,
3896
+ reviewer: review.reviewer,
3702
3897
  light: cliOptions.light ?? fileConfig.light ?? false,
3703
3898
  plain: cliOptions.plain ?? fileConfig.plain ?? false,
3704
3899
  // Commander camelCase:ar --noscript-check till noscriptCheck.
@@ -3748,6 +3943,8 @@ program.argument("<url>", "URL to scan").option("--lang <code>", "Language code
3748
3943
  silent: options.json || options.light,
3749
3944
  severityThreshold: options.threshold,
3750
3945
  invalidHttpsCert: options.invalidHttpsCert,
3946
+ allowPrivateHosts: options.allowPrivateHosts,
3947
+ sandbox: options.sandbox,
3751
3948
  light: options.light,
3752
3949
  noScriptCheck: options.noScriptCheck,
3753
3950
  waitForHydrationMs: options.waitForHydrationMs
@@ -3758,7 +3955,7 @@ program.argument("<url>", "URL to scan").option("--lang <code>", "Language code
3758
3955
  if (options.pdf) {
3759
3956
  if (spinner) spinner.start(t("cli.generating_pdf"));
3760
3957
  const html = options.audience === "plain" ? generateReportHTML(result, options.sector, "plain", plainFallbackFrom) : generateReportHTML(result, options.sector);
3761
- await generatePDF(html, options.pdf);
3958
+ await generatePDF(html, options.pdf, { sandbox: options.sandbox });
3762
3959
  if (spinner) spinner.succeed(t("cli.pdf_saved", { path: options.pdf }));
3763
3960
  }
3764
3961
  if (options.statement && result.complianceStatus === "INCONCLUSIVE") {
@@ -3773,7 +3970,9 @@ program.argument("<url>", "URL to scan").option("--lang <code>", "Language code
3773
3970
  responseTime: options.responseTime,
3774
3971
  country: options.country,
3775
3972
  sector: options.sector,
3776
- publishDate: options.publishDate
3973
+ publishDate: options.publishDate,
3974
+ reviewMethod: options.reviewMethod,
3975
+ reviewer: options.reviewer
3777
3976
  };
3778
3977
  if (options.statement.toLowerCase().endsWith(".pdf")) {
3779
3978
  const htmlContent = await generateStatementContent(result, options.lang, "html", metadata);