From cd4c5715831fbc16bd5b0cad897cc3bf2342ca64 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E2=80=9Ccaneryy=E2=80=9D?= Date: Tue, 24 Nov 2026 18:03:15 +0300 Subject: [PATCH] feat(ci): audit production JavaScript dependencies Add a production-only pnpm audit gate with a high severity threshold, time-boxed exceptions, and coverage workflow enforcement. --- .github/workflows/coverage.yml | 6 + audit-exceptions.json | 180 ++++++++++++++++ docs/CI.md | 21 ++ package.json | 4 +- scripts/audit-prod-deps.mjs | 340 +++++++++++++++++++++++++++++++ scripts/audit-prod-deps.test.mjs | 171 ++++++++++++++++ 6 files changed, 721 insertions(+), 1 deletion(-) create mode 100644 audit-exceptions.json create mode 100644 scripts/audit-prod-deps.mjs create mode 100644 scripts/audit-prod-deps.test.mjs diff --git a/.github/workflows/coverage.yml b/.github/workflows/coverage.yml index 0ecfc2c..8b2cc2c 100644 --- a/.github/workflows/coverage.yml +++ b/.github/workflows/coverage.yml @@ -55,6 +55,12 @@ jobs: - name: Validate pinned Rust toolchain alignment run: pnpm ci:rust-toolchain:test && pnpm ci:rust-toolchain:check + - name: Test production dependency audit gate + run: pnpm audit:prod:test + + - name: Audit production JavaScript dependencies + run: pnpm audit:prod + - name: Mainnet readiness matches the committed manifest (recorded fixture, no RPC, no secrets) run: | pnpm --filter @sub-rosa/sdk exec tsx scripts/mainnet-ready.ts --strict --fixture diff --git a/audit-exceptions.json b/audit-exceptions.json new file mode 100644 index 0000000..f0811a5 --- /dev/null +++ b/audit-exceptions.json @@ -0,0 +1,180 @@ +{ + "$schema_comment": "Time-boxed exceptions for production pnpm audit (Issue #529). Each entry needs id, package, reason, expiresOn (YYYY-MM-DD), and trackingIssue.", + "exceptions": [ + { + "id": "GHSA-pmwg-cvhr-8vh7", + "package": "axios", + "reason": "Baseline production advisory recorded when enabling the CI gate; upgrade or replace axios before expiry", + "expiresOn": "2027-02-24", + "trackingIssue": "#529" + }, + { + "id": "GHSA-pf86-5x62-jrwf", + "package": "axios", + "reason": "Baseline production advisory recorded when enabling the CI gate; upgrade or replace axios before expiry", + "expiresOn": "2027-02-24", + "trackingIssue": "#529" + }, + { + "id": "GHSA-6chq-wfr3-2hj9", + "package": "axios", + "reason": "Baseline production advisory recorded when enabling the CI gate; upgrade or replace axios before expiry", + "expiresOn": "2027-02-24", + "trackingIssue": "#529" + }, + { + "id": "GHSA-q8qp-cvcw-x6jj", + "package": "axios", + "reason": "Baseline production advisory recorded when enabling the CI gate; upgrade or replace axios before expiry", + "expiresOn": "2027-02-24", + "trackingIssue": "#529" + }, + { + "id": "GHSA-hfxv-24rg-xrqf", + "package": "axios", + "reason": "Baseline production advisory recorded when enabling the CI gate; upgrade or replace axios before expiry", + "expiresOn": "2027-02-24", + "trackingIssue": "#529" + }, + { + "id": "GHSA-777c-7fjr-54vf", + "package": "axios", + "reason": "Baseline production advisory recorded when enabling the CI gate; upgrade or replace axios before expiry", + "expiresOn": "2027-02-24", + "trackingIssue": "#529" + }, + { + "id": "GHSA-p92q-9vqr-4j8v", + "package": "axios", + "reason": "Baseline production advisory recorded when enabling the CI gate; upgrade or replace axios before expiry", + "expiresOn": "2027-02-24", + "trackingIssue": "#529" + }, + { + "id": "GHSA-j5f8-grm9-p9fc", + "package": "axios", + "reason": "Baseline production advisory recorded when enabling the CI gate; upgrade or replace axios before expiry", + "expiresOn": "2027-02-24", + "trackingIssue": "#529" + }, + { + "id": "GHSA-3g43-6gmg-66jw", + "package": "axios", + "reason": "Baseline production advisory recorded when enabling the CI gate; upgrade or replace axios before expiry", + "expiresOn": "2027-02-24", + "trackingIssue": "#529" + }, + { + "id": "GHSA-35jp-ww65-95wh", + "package": "axios", + "reason": "Baseline production advisory recorded when enabling the CI gate; upgrade or replace axios before expiry", + "expiresOn": "2027-02-24", + "trackingIssue": "#529" + }, + { + "id": "GHSA-hmw2-7cc7-3qxx", + "package": "form-data", + "reason": "Baseline production advisory recorded when enabling the CI gate; upgrade or replace form-data before expiry", + "expiresOn": "2027-02-24", + "trackingIssue": "#529" + }, + { + "id": "GHSA-pjwm-pj3p-43mv", + "package": "axios", + "reason": "Baseline production advisory recorded when enabling the CI gate; upgrade or replace axios before expiry", + "expiresOn": "2027-02-24", + "trackingIssue": "#529" + }, + { + "id": "GHSA-82x6-q7mm-w9cf", + "package": "toml", + "reason": "Baseline production advisory recorded when enabling the CI gate; upgrade or replace toml before expiry", + "expiresOn": "2027-02-24", + "trackingIssue": "#529" + }, + { + "id": "GHSA-v5mp-jgw5-2x6j", + "package": "toml", + "reason": "Baseline production advisory recorded when enabling the CI gate; upgrade or replace toml before expiry", + "expiresOn": "2027-02-24", + "trackingIssue": "#529" + }, + { + "id": "GHSA-mghh-pgcx-3jjj", + "package": "axios", + "reason": "Baseline production advisory recorded when enabling the CI gate; upgrade or replace axios before expiry", + "expiresOn": "2027-02-24", + "trackingIssue": "#529" + }, + { + "id": "GHSA-3pq3-5fj3-cg6v", + "package": "axios", + "reason": "Baseline production advisory recorded when enabling the CI gate; upgrade or replace axios before expiry", + "expiresOn": "2027-02-24", + "trackingIssue": "#529" + }, + { + "id": "GHSA-542g-h47m-68v8", + "package": "axios", + "reason": "Baseline production advisory recorded when enabling the CI gate; upgrade or replace axios before expiry", + "expiresOn": "2027-02-24", + "trackingIssue": "#529" + }, + { + "id": "GHSA-q3jh-wrc6-jgq8", + "package": "follow-redirects", + "reason": "Baseline production advisory recorded when enabling the CI gate; upgrade or replace follow-redirects before expiry", + "expiresOn": "2027-02-24", + "trackingIssue": "#529" + }, + { + "id": "GHSA-8r9p-f939-6h3c", + "package": "follow-redirects", + "reason": "Baseline production advisory recorded when enabling the CI gate; upgrade or replace follow-redirects before expiry", + "expiresOn": "2027-02-24", + "trackingIssue": "#529" + }, + { + "id": "GHSA-4qx8-w7c3-pj3p", + "package": "toml", + "reason": "Baseline production advisory recorded when enabling the CI gate; upgrade or replace toml before expiry", + "expiresOn": "2027-02-24", + "trackingIssue": "#529" + }, + { + "id": "GHSA-9j65-hcg3-gc64", + "package": "toml", + "reason": "Baseline production advisory recorded when enabling the CI gate; upgrade or replace toml before expiry", + "expiresOn": "2027-02-24", + "trackingIssue": "#529" + }, + { + "id": "GHSA-9qmh-m7c6-f92p", + "package": "toml", + "reason": "Baseline production advisory recorded when enabling the CI gate; upgrade or replace toml before expiry", + "expiresOn": "2027-02-24", + "trackingIssue": "#529" + }, + { + "id": "GHSA-mrhx-c7xc-m3w5", + "package": "zod", + "reason": "Baseline production advisory recorded when enabling the CI gate; upgrade or replace zod before expiry", + "expiresOn": "2027-02-24", + "trackingIssue": "#529" + }, + { + "id": "GHSA-mrwp-f3q8-3g9p", + "package": "follow-redirects", + "reason": "Baseline production advisory recorded when enabling the CI gate; upgrade or replace follow-redirects before expiry", + "expiresOn": "2027-02-24", + "trackingIssue": "#529" + }, + { + "id": "GHSA-h895-cgqg-jf52", + "package": "toml", + "reason": "Baseline production advisory recorded when enabling the CI gate; upgrade or replace toml before expiry", + "expiresOn": "2027-02-24", + "trackingIssue": "#529" + } + ] +} diff --git a/docs/CI.md b/docs/CI.md index bd5cf0b..f709b58 100644 --- a/docs/CI.md +++ b/docs/CI.md @@ -75,6 +75,27 @@ The `TypeScript coverage` workflow runs `pnpm time:guard:test` followed by first-party code calls the clock or timer globals outside `@sub-rosa/time`. Both commands are blocking CI steps and can be run locally from the root. +## Production dependency audit + +Production JavaScript dependencies are audited in the TypeScript coverage +workflow (`.github/workflows/coverage.yml`) via `scripts/audit-prod-deps.mjs` +(`pnpm audit --prod --audit-level=high --json`): + +- **Severity threshold:** `high` and `critical` advisories in production + dependencies block by default (override with `--audit-level ` or + `PNPM_AUDIT_LEVEL`). +- **Exception process:** Temporary exceptions for unpatched transitive + advisories must be recorded in `audit-exceptions.json` with `id`, `package`, + `reason`, `expiresOn` (`YYYY-MM-DD`), and `trackingIssue`. Expired or + incomplete exceptions fail the check automatically. + +Run locally with: + +```bash +pnpm audit:prod:test +pnpm audit:prod +``` + ## Test coverage gate The repository enforces a minimum **aggregate line coverage** threshold for diff --git a/package.json b/package.json index 4b43c77..760e970 100644 --- a/package.json +++ b/package.json @@ -105,6 +105,8 @@ "line-lengths:check": "node scripts/check-line-lengths.mjs", "line-lengths:test": "node --test scripts/check-line-lengths.test.mjs", "wf-creds:check": "node scripts/check-workflow-credentials.mjs", - "wf-creds:test": "node --test scripts/check-workflow-credentials.test.mjs" + "wf-creds:test": "node --test scripts/check-workflow-credentials.test.mjs", + "audit:prod": "node scripts/audit-prod-deps.mjs", + "audit:prod:test": "node --test scripts/audit-prod-deps.test.mjs" } } diff --git a/scripts/audit-prod-deps.mjs b/scripts/audit-prod-deps.mjs new file mode 100644 index 0000000..363a719 --- /dev/null +++ b/scripts/audit-prod-deps.mjs @@ -0,0 +1,340 @@ +#!/usr/bin/env node +// Copyright (c) 2026 Sub Rosa contributors +import { execFileSync } from "node:child_process"; +import { existsSync, readFileSync } from "node:fs"; +import { dirname, resolve } from "node:path"; +import { fileURLToPath, pathToFileURL } from "node:url"; +import { createLogger } from "../packages/logging/src/index.cjs"; + +const diagnostics = createLogger("scripts.audit-prod-deps"); + +const __dirname = dirname(fileURLToPath(import.meta.url)); +const DEFAULT_ROOT = resolve(__dirname, ".."); + +export const DEFAULT_AUDIT_LEVEL = "high"; +export const AUDIT_COMMAND = "pnpm audit --prod --audit-level=high --json"; +export const SEVERITY_RANK = { + info: 0, + low: 1, + moderate: 2, + high: 3, + critical: 4, +}; + +/** + * Build the exact pnpm CLI arguments for a production-only audit. + * @param {string} [auditLevel] + */ +export function buildPnpmAuditArgs(auditLevel = DEFAULT_AUDIT_LEVEL) { + if (!(auditLevel in SEVERITY_RANK)) { + throw new Error(`Unsupported audit severity level: ${auditLevel}`); + } + return ["audit", "--prod", `--audit-level=${auditLevel}`, "--json"]; +} + +/** + * Validate a single time-boxed audit exception entry. + * Every exception must include `id`, `package`, `reason`, `expiresOn` (ISO YYYY-MM-DD), + * and `trackingIssue`. + * @param {unknown} entry + * @param {number} [nowMs] + */ +export function validateAuditException(entry, nowMs = Date.now()) { + if (!entry || typeof entry !== "object") { + return { valid: false, reason: "Exception entry must be an object" }; + } + const required = ["id", "package", "reason", "expiresOn", "trackingIssue"]; + for (const field of required) { + if (typeof entry[field] !== "string" || !entry[field].trim()) { + return { + valid: false, + reason: `Exception is missing required string field "${field}"`, + }; + } + } + if (!/^\d{4}-\d{2}-\d{2}$/.test(entry.expiresOn)) { + return { + valid: false, + reason: `Exception ${entry.id} has invalid expiresOn date "${entry.expiresOn}" (expected YYYY-MM-DD)`, + }; + } + const expiryMs = Date.parse(`${entry.expiresOn}T23:59:59.999Z`); + if (!Number.isFinite(expiryMs) || expiryMs < nowMs) { + return { + valid: false, + reason: `Exception ${entry.id} for ${entry.package} expired on ${entry.expiresOn}`, + }; + } + return { valid: true }; +} + +/** + * Normalize advisories from either classic `advisories` maps or npm/pnpm + * `vulnerabilities` objects into a common list. + * @param {object} report + */ +export function collectAdvisories(report) { + /** @type {{ id: string, package: string, severity: string, title: string }[]} */ + const list = []; + const advisoriesObj = report?.advisories ?? {}; + + for (const [key, adv] of Object.entries(advisoriesObj)) { + if (!adv || typeof adv !== "object") continue; + list.push({ + id: String(adv.github_advisory_id ?? adv.id ?? key), + package: String(adv.module_name ?? adv.name ?? "unknown"), + severity: String(adv.severity ?? "info").toLowerCase(), + title: String(adv.title ?? "Production dependency vulnerability"), + }); + } + + const vulns = report?.vulnerabilities; + if (vulns && typeof vulns === "object" && !Array.isArray(vulns)) { + for (const [pkgName, entry] of Object.entries(vulns)) { + if (!entry || typeof entry !== "object") continue; + const via = Array.isArray(entry.via) ? entry.via : []; + const advisoryVia = via.filter((v) => v && typeof v === "object"); + if (advisoryVia.length === 0) { + list.push({ + id: String(entry.name ?? pkgName), + package: String(pkgName), + severity: String(entry.severity ?? "info").toLowerCase(), + title: String(entry.title ?? entry.name ?? "Production dependency vulnerability"), + }); + continue; + } + for (const item of advisoryVia) { + list.push({ + id: String(item.url?.match(/GHSA-[a-z0-9-]+/i)?.[0] ?? item.source ?? item.id ?? pkgName), + package: String(item.name ?? pkgName), + severity: String(item.severity ?? entry.severity ?? "info").toLowerCase(), + title: String(item.title ?? "Production dependency vulnerability"), + }); + } + } + } + + return list; +} + +/** + * Evaluate parsed `pnpm audit --prod --json` output against the configured + * severity threshold and validated exception list. + * @param {object} report + * @param {{ auditLevel?: string, exceptions?: object[], nowMs?: number }} [options] + */ +export function evaluateAuditReport( + report, + { + auditLevel = DEFAULT_AUDIT_LEVEL, + exceptions = [], + nowMs = Date.now(), + } = {}, +) { + if (!(auditLevel in SEVERITY_RANK)) { + throw new Error(`Unsupported audit severity level: ${auditLevel}`); + } + const thresholdRank = SEVERITY_RANK[auditLevel]; + const invalidExceptions = []; + const activeExceptionMap = new Map(); + + for (const ex of exceptions) { + const check = validateAuditException(ex, nowMs); + if (!check.valid) { + invalidExceptions.push(check.reason); + } else { + activeExceptionMap.set(`${ex.id}:${ex.package}`, ex); + } + } + + const blockingAdvisories = []; + const ignoredAdvisories = []; + + for (const adv of collectAdvisories(report)) { + const rank = SEVERITY_RANK[adv.severity] ?? 0; + if (rank < thresholdRank) continue; + + if (activeExceptionMap.has(`${adv.id}:${adv.package}`)) { + ignoredAdvisories.push({ id: adv.id, package: adv.package, severity: adv.severity }); + } else { + blockingAdvisories.push(adv); + } + } + + return { + ok: invalidExceptions.length === 0 && blockingAdvisories.length === 0, + auditLevel, + blockingAdvisories, + ignoredAdvisories, + invalidExceptions, + }; +} + +/** + * Load and return exception entries from audit-exceptions.json. + * @param {string} exceptionsPath + */ +export function loadExceptionsFile(exceptionsPath) { + if (!exceptionsPath || !existsSync(exceptionsPath)) return []; + const parsed = JSON.parse(readFileSync(exceptionsPath, "utf8")); + return Array.isArray(parsed.exceptions) ? parsed.exceptions : []; +} + +/** + * Validate that contributor-facing scripts, docs, exceptions file, and CI wiring exist. + * @param {string} [rootDir] + */ +export function validateAuditProdSetup(rootDir = DEFAULT_ROOT) { + const errors = []; + const exceptionsPath = resolve(rootDir, "audit-exceptions.json"); + const pkgJsonPath = resolve(rootDir, "package.json"); + const ciDocsPath = resolve(rootDir, "docs/CI.md"); + const workflowPath = resolve(rootDir, ".github/workflows/coverage.yml"); + + if (!existsSync(exceptionsPath)) { + errors.push("Missing audit-exceptions.json at repository root"); + } else { + try { + const parsed = JSON.parse(readFileSync(exceptionsPath, "utf8")); + if (!Array.isArray(parsed.exceptions)) { + errors.push('audit-exceptions.json must define an "exceptions" array'); + } + } catch (err) { + errors.push(`audit-exceptions.json is not valid JSON: ${err.message}`); + } + } + + if (existsSync(pkgJsonPath)) { + const pkg = JSON.parse(readFileSync(pkgJsonPath, "utf8")); + const scripts = pkg.scripts ?? {}; + if (!scripts["audit:prod"]) { + errors.push("package.json must define the audit:prod script"); + } + if (!scripts["audit:prod:test"]) { + errors.push("package.json must define the audit:prod:test script"); + } + } else { + errors.push("Missing package.json at repository root"); + } + + if (existsSync(ciDocsPath)) { + const docs = readFileSync(ciDocsPath, "utf8"); + if (!docs.includes("Production dependency audit")) { + errors.push('docs/CI.md must document the "Production dependency audit" section'); + } + if (!docs.includes("--prod") || !docs.includes("audit-level")) { + errors.push("docs/CI.md must document production-only pnpm audit with a severity threshold"); + } + if (!docs.includes("audit-exceptions.json")) { + errors.push("docs/CI.md must document the audit-exceptions.json exception process"); + } + } else { + errors.push("Missing docs/CI.md"); + } + + if (existsSync(workflowPath)) { + const workflow = readFileSync(workflowPath, "utf8"); + if (!workflow.includes("pnpm audit:prod:test") || !workflow.includes("pnpm audit:prod")) { + errors.push( + ".github/workflows/coverage.yml must run pnpm audit:prod:test and pnpm audit:prod", + ); + } + } else { + errors.push("Missing .github/workflows/coverage.yml"); + } + + return { ok: errors.length === 0, errors }; +} + +function main() { + const args = process.argv.slice(2); + let auditLevel = process.env.PNPM_AUDIT_LEVEL ?? DEFAULT_AUDIT_LEVEL; + let fixturePath = null; + let exceptionsPath = resolve(DEFAULT_ROOT, "audit-exceptions.json"); + let setupOnly = false; + + for (let i = 0; i < args.length; i++) { + if (args[i] === "--audit-level" && i + 1 < args.length) { + auditLevel = args[++i]; + } else if (args[i] === "--fixture" && i + 1 < args.length) { + fixturePath = resolve(args[++i]); + } else if (args[i] === "--exceptions" && i + 1 < args.length) { + exceptionsPath = resolve(args[++i]); + } else if (args[i] === "--setup-only") { + setupOnly = true; + } + } + + const setup = validateAuditProdSetup(DEFAULT_ROOT); + if (!setup.ok) { + for (const err of setup.errors) { + diagnostics.error("audit-prod-setup-failed", `FAIL: ${err}`); + } + process.exit(1); + } + + if (setupOnly) { + diagnostics.info( + "audit-prod-setup-passed", + `PASS: Production pnpm audit policy (threshold=${DEFAULT_AUDIT_LEVEL}) is configured.`, + ); + return; + } + + const pnpmArgs = buildPnpmAuditArgs(auditLevel); + let rawJson; + + if (fixturePath) { + rawJson = readFileSync(fixturePath, "utf8"); + } else { + try { + rawJson = execFileSync("pnpm", pnpmArgs, { + cwd: DEFAULT_ROOT, + encoding: "utf8", + stdio: ["ignore", "pipe", "pipe"], + }); + } catch (err) { + rawJson = err.stdout ? String(err.stdout) : ""; + if (!rawJson.trim()) { + diagnostics.error( + "audit-prod-exec-failed", + `Failed to execute pnpm ${pnpmArgs.join(" ")}: ${err.message}`, + ); + process.exit(1); + } + } + } + + let report; + try { + report = JSON.parse(rawJson); + } catch (err) { + diagnostics.error("audit-prod-json-failed", `pnpm audit JSON parse failed: ${err.message}`); + process.exit(1); + } + + const exceptions = loadExceptionsFile(exceptionsPath); + const evaluation = evaluateAuditReport(report, { auditLevel, exceptions }); + + if (!evaluation.ok) { + for (const reason of evaluation.invalidExceptions) { + diagnostics.error("audit-prod-invalid-exception", `Invalid audit exception: ${reason}`); + } + for (const adv of evaluation.blockingAdvisories) { + diagnostics.error( + "audit-prod-blocking-advisory", + `[${adv.severity.toUpperCase()}] ${adv.id} in ${adv.package}: ${adv.title}`, + ); + } + process.exit(1); + } + + diagnostics.info( + "audit-prod-passed", + `Production dependency audit passed (threshold=${auditLevel}, exceptions=${evaluation.ignoredAdvisories.length}).`, + ); +} + +if (import.meta.url === pathToFileURL(process.argv[1] ?? "").href) { + main(); +} diff --git a/scripts/audit-prod-deps.test.mjs b/scripts/audit-prod-deps.test.mjs new file mode 100644 index 0000000..78ecf28 --- /dev/null +++ b/scripts/audit-prod-deps.test.mjs @@ -0,0 +1,171 @@ +// Copyright (c) 2026 Sub Rosa contributors +import assert from "node:assert/strict"; +import { describe, it } from "node:test"; +import { readFileSync } from "node:fs"; +import { fileURLToPath } from "node:url"; + +import { + AUDIT_COMMAND, + DEFAULT_AUDIT_LEVEL, + buildPnpmAuditArgs, + collectAdvisories, + evaluateAuditReport, + validateAuditException, + validateAuditProdSetup, +} from "./audit-prod-deps.mjs"; + +const REPO_ROOT = fileURLToPath(new URL("..", import.meta.url)); +const FIXED_NOW = Date.parse("2026-06-01T00:00:00.000Z"); + +describe("audit-prod-deps", () => { + it("builds production-only pnpm audit arguments with default high threshold", () => { + assert.equal(DEFAULT_AUDIT_LEVEL, "high"); + assert.equal(AUDIT_COMMAND, "pnpm audit --prod --audit-level=high --json"); + assert.deepEqual(buildPnpmAuditArgs(), [ + "audit", + "--prod", + "--audit-level=high", + "--json", + ]); + }); + + it("passes on the repository root configuration", () => { + const res = validateAuditProdSetup(REPO_ROOT); + assert.equal(res.ok, true, `Expected pass, got errors: ${res.errors.join("; ")}`); + }); + + it("passes when no advisories meet or exceed the high threshold", () => { + const report = { + advisories: { + 1: { + github_advisory_id: "GHSA-low-1111", + module_name: "some-pkg", + severity: "moderate", + title: "Moderate issue", + }, + }, + }; + const res = evaluateAuditReport(report, { nowMs: FIXED_NOW }); + assert.equal(res.ok, true); + assert.equal(res.blockingAdvisories.length, 0); + }); + + it("fails when a high or critical production advisory has no exception", () => { + const report = { + advisories: { + 100: { + github_advisory_id: "GHSA-crit-9999", + module_name: "ws", + severity: "critical", + title: "DoS in ws", + }, + }, + }; + const res = evaluateAuditReport(report, { nowMs: FIXED_NOW }); + assert.equal(res.ok, false); + assert.equal(res.blockingAdvisories.length, 1); + assert.equal(res.blockingAdvisories[0].id, "GHSA-crit-9999"); + assert.equal(res.blockingAdvisories[0].package, "ws"); + }); + + it("allows a high advisory only when covered by an unexpired, complete exception", () => { + const report = { + advisories: { + 100: { + github_advisory_id: "GHSA-high-1234", + module_name: "elliptic", + severity: "high", + title: "Curve twist issue", + }, + }, + }; + const validException = { + id: "GHSA-high-1234", + package: "elliptic", + reason: "Transitive dependency not invoked on untrusted curve inputs", + expiresOn: "2026-07-01", + trackingIssue: "#529", + }; + + const res = evaluateAuditReport(report, { + exceptions: [validException], + nowMs: FIXED_NOW, + }); + assert.equal(res.ok, true); + assert.equal(res.ignoredAdvisories.length, 1); + }); + + it("rejects expired or incomplete audit exceptions", () => { + const expired = validateAuditException( + { + id: "GHSA-high-1234", + package: "elliptic", + reason: "Waiting on upstream release", + expiresOn: "2026-05-01", + trackingIssue: "#529", + }, + FIXED_NOW, + ); + assert.equal(expired.valid, false); + assert.match(expired.reason, /expired/); + + const missingField = validateAuditException( + { + id: "GHSA-high-1234", + package: "elliptic", + reason: "", + expiresOn: "2026-07-01", + trackingIssue: "#529", + }, + FIXED_NOW, + ); + assert.equal(missingField.valid, false); + assert.match(missingField.reason, /reason/); + }); + + it("collects advisories from npm-style vulnerabilities maps", () => { + const report = { + vulnerabilities: { + lodash: { + name: "lodash", + severity: "high", + via: [ + { + source: 123, + name: "lodash", + severity: "high", + title: "Prototype pollution", + url: "https://github.com/advisories/GHSA-lodash-high", + }, + ], + }, + }, + }; + const list = collectAdvisories(report); + assert.equal(list.length, 1); + assert.equal(list[0].id, "GHSA-lodash-high"); + assert.equal(list[0].package, "lodash"); + assert.equal(list[0].severity, "high"); + }); + + it("runs audit:prod test and check as blocking CI steps in coverage.yml", () => { + const workflow = readFileSync( + new URL("../.github/workflows/coverage.yml", import.meta.url), + "utf8", + ); + const scripts = JSON.parse( + readFileSync(new URL("../package.json", import.meta.url), "utf8"), + ).scripts; + assert.equal(scripts["audit:prod"], "node scripts/audit-prod-deps.mjs"); + assert.equal(scripts["audit:prod:test"], "node --test scripts/audit-prod-deps.test.mjs"); + const job = workflow.match(/^ coverage:\n([\s\S]*)$/m)?.[1]; + assert.ok(job, "coverage job must exist"); + assert.doesNotMatch(job, /\bcontinue-on-error\s*:/); + const testStep = job.indexOf(" run: pnpm audit:prod:test\n"); + const auditStep = job.indexOf(" run: pnpm audit:prod\n"); + assert.ok( + testStep >= 0 && auditStep > testStep, + "audit:prod must follow audit:prod:test in the coverage job", + ); + }); +});