Swadhin Biswas Feature/ai code reviewer (#73) · 8/2/2026
105a287
168 lines · 5.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
#!/usr/bin/env node
/**
 * Dependency vulnerability audit.
 *
 * - Regenerates a `package-lock.json` (sibling to `bun.lock`) so that
 *   `npm audit` can use it. The file is git-ignored; CI regenerates it.
 * - Runs `npm audit --audit-level=high` and surfaces a non-zero exit
 *   code if any unallowed high/critical advisories remain.
 * - Supports a `KNOWN_ACCEPTED` allowlist for vulnerabilities that
 *   require breaking version migrations and are tracked in
 *   `docs/administration/security.md` with documented mitigations.
 *
 * Exit codes:
 *   0 — pass (no disallowed high/critical; moderate/known-accepted tolerated)
 *   1 — fail (disallowed high/critical vulnerability present)
 *   2 — script error
 */
import { existsSync, readFileSync, statSync, copyFileSync, mkdtempSync, rmSync } from "node:fs";
import { resolve, join } from "node:path";
import { tmpdir } from "node:os";
import { spawnSync } from "node:child_process";

const ROOT = resolve(process.cwd());
const LOCKFILE = resolve(ROOT, "package-lock.json");
const ALLOWLIST = resolve(ROOT, "docs/administration/known-accepted-vulns.json");
const AUDIT_REGISTRY = "https://registry.npmjs.org";
const LOCKFILE_MAX_AGE_HOURS = 24;

const log = (level, msg) => console.log(`[${new Date().toISOString()}] [${level}] ${msg}`);

function regenerateLockfile() {
  log("info", "Regenerating package-lock.json from package.json (--package-lock-only)…");
  const root = ROOT;
  const attempts = [
    {
      label: "clean temp directory (isolated package.json)",
      run: () => {
        const tmp = mkdtempSync(join(tmpdir(), "och-audit-"));
        copyFileSync(join(root, "package.json"), join(tmp, "package.json"));
        try {
          return spawnSync("npm", ["install", "--package-lock-only", "--no-audit", "--no-fund", "--ignore-scripts", "--legacy-peer-deps", `--registry=${AUDIT_REGISTRY}`], { cwd: tmp, stdio: "inherit" });
        } finally {
          try {
            const generated = join(tmp, "package-lock.json");
            if (existsSync(generated)) copyFileSync(generated, LOCKFILE);
          } catch { /* best-effort */ }
          rmSync(tmp, { recursive: true, force: true });
        }
      },
    },
    {
      label: "root (--ignore-scripts --legacy-peer-deps)",
      run: () => spawnSync("npm", ["install", "--package-lock-only", "--no-audit", "--no-fund", "--ignore-scripts", "--legacy-peer-deps", `--registry=${AUDIT_REGISTRY}`], { cwd: root, stdio: "inherit" }),
    },
    {
      label: "root (default)",
      run: () => spawnSync("npm", ["install", "--package-lock-only", "--no-audit", "--no-fund", `--registry=${AUDIT_REGISTRY}`], { cwd: root, stdio: "inherit" }),
    },
  ];
  for (let i = 0; i < attempts.length; i++) {
    const a = attempts[i];
    log("info", `Lockfile regen attempt ${i + 1}: ${a.label}`);
    const r = a.run();
    if (r.status === 0) {
      return;
    }
    log("warn", `Lockfile regen attempt ${i + 1} failed (exit ${r.status})`);
  }
  if (existsSync(LOCKFILE)) {
    log("warn", "Falling back to existing package-lock.json (may be stale)");
    return;
  }
  log("error", "Failed to regenerate package-lock.json and no fallback exists");
  process.exit(2);
}

function lockfileIsFresh() {
  if (!existsSync(LOCKFILE)) return false;
  const ageHours = (Date.now() - statSync(LOCKFILE).mtimeMs) / 3_600_000;
  return ageHours < LOCKFILE_MAX_AGE_HOURS;
}

function loadAllowlist() {
  if (!existsSync(ALLOWLIST)) return new Set();
  try {
    const data = JSON.parse(readFileSync(ALLOWLIST, "utf8"));
    return new Set(data.accepted ?? []);
  } catch (e) {
    log("error", `Could not parse ${ALLOWLIST}: ${e.message}`);
    return new Set();
  }
}

function runAudit() {
  log("info", `Running npm audit (registry=${AUDIT_REGISTRY})…`);
  if (!existsSync(LOCKFILE)) {
    log("error", "No package-lock.json to audit against");
    process.exit(2);
  }
  const r = spawnSync(
    "npm",
    ["audit", `--registry=${AUDIT_REGISTRY}`, "--json"],
    { encoding: "utf8" }
  );

  let report = {};
  try {
    report = JSON.parse(r.stdout || "{}");
  } catch (e) {
    log("error", `Could not parse npm audit output: ${e.message}`);
    if (r.stderr) console.error(r.stderr);
    process.exit(2);
  }
  const meta = report.metadata?.vulnerabilities ?? {};
  const summary = {
    critical: meta.critical ?? 0,
    high: meta.high ?? 0,
    moderate: meta.moderate ?? 0,
    low: meta.low ?? 0,
    info: meta.info ?? 0,
  };
  log(
    "info",
    `Vulnerabilities: critical=${summary.critical} high=${summary.high} moderate=${summary.moderate} low=${summary.low} info=${summary.info}`,
  );

  const allow = loadAllowlist();
  const blockers = [];
  const accepted = [];
  for (const [name, info] of Object.entries(report.vulnerabilities ?? {})) {
    if (info.severity !== "high" && info.severity !== "critical") continue;
    if (allow.has(name)) {
      accepted.push(name);
      continue;
    }
    const fix = info.fixAvailable;
    const fixStr = fix
      ? typeof fix === "object"
        ? `${fix.name}@${fix.version} (breaking=${fix.isSemVerMajor})`
        : "non-breaking patch available"
      : "NO FIX AVAILABLE";
    blockers.push(`  - ${name} (${info.severity}) :: fix: ${fixStr}`);
  }

  if (accepted.length) {
    log(
      "info",
      `Known-accepted (tracked in ${ALLOWLIST}): ${accepted.join(", ")}`,
    );
  }

  if (blockers.length) {
    log("error", `Audit FAILED — ${blockers.length} disallowed high/critical:`);
    for (const line of blockers) console.error(line);
    process.exit(1);
  }

  log("info", "Audit PASSED — no disallowed high/critical vulnerabilities");
}

function main() {
  if (!lockfileIsFresh()) regenerateLockfile();
  else log("info", "Reusing existing package-lock.json (fresh)");
  runAudit();
}

main();