import { homedir, userInfo } from "node:os"; import { readFileSync, accessSync, constants as fsConstants, statSync } from "node:fs"; import { dirname } from "node:path"; import { shellQuote } from "./util/io.mjs"; import * as npm from "./tools/npm.mjs"; import * as pnpm from "./tools/pnpm.mjs"; import * as yarn from "./tools/yarn.mjs"; import * as bun from "./tools/bun.mjs"; import * as cargo from "./tools/cargo.mjs"; import * as mise from "./tools/mise.mjs"; import * as uv from "./tools/uv.mjs"; import * as bundler from "./tools/bundler.mjs"; import * as aube from "./tools/aube.mjs"; import * as composer from "./tools/composer.mjs"; import { scanProject } from "./project.mjs"; const TOOLS = [npm, pnpm, yarn, bun, cargo, mise, uv, bundler, aube, composer]; // Default cooldown for the hardening bundle. Override per-invocation with // `--days N`; the default tracks the safest value we'd recommend. const BUNDLE_DAYS = 1; export const VERSION = JSON.parse( readFileSync(new URL("../package.json", import.meta.url), "utf8") ).version; const USAGE = `pmsec [options] Zero-config install-time supply-chain hardening across npm, pnpm, yarn, bun, cargo, mise, uv, bundler, aube, composer. Default action enables every safe-by-default key each tool exposes (cooldown, audit-level, trust-policy, hardened mode, attestation re-verification, ...). No knobs. Options: --check Verify the bundle is in place (exit 1 if anything missing) --project [DIR] With --check: scan DIR (default cwd) project configs for keys weakening the baseline --disable Remove the hardening bundle from selected tools --doctor Diagnose effective paths/owner/uid (read-only; for unattended-deployment debugging) --tool TOOL[,TOOL] Restrict to specific tools (npm,pnpm,yarn,bun,cargo,mise,uv,bundler,aube,composer) --days N Override cooldown days (default 1) --force Overwrite stricter existing cooldowns and hardening values (otherwise enable is monotonic) --json Emit JSON output -V, --version Show version -h, --help Show this help Examples: npx pmsec npx pmsec --days 7 npx pmsec --days 1 --force npx pmsec --check npx pmsec --check --project npx pmsec --disable --tool npm `; function parseDays(raw) { const n = Number(raw); if (!Number.isInteger(n) || n < 1) throw new Error(`--days must be a positive integer (got "${raw}")`); return n; } function parse(argv) { const opts = { mode: "enable", json: false, only: null, days: BUNDLE_DAYS, force: false, help: false, version: false, project: null }; let modeSet = false; const setMode = (m) => { if (modeSet && opts.mode !== m) throw new Error(`--check, --disable, and --doctor are mutually exclusive`); opts.mode = m; modeSet = true; }; const positional = []; for (let i = 0; i < argv.length; i++) { const a = argv[i]; if (a === "-h" || a === "--help") opts.help = true; else if (a === "-V" || a === "--version") opts.version = true; else if (a === "--json") opts.json = true; else if (a === "--force") opts.force = true; else if (a === "--check") setMode("check"); else if (a === "--disable") setMode("disable"); else if (a === "--doctor") setMode("doctor"); else if (a === "--project") opts.project = argv[i + 1] && !argv[i + 1].startsWith("-") ? argv[++i] : "."; else if (a.startsWith("--project=")) opts.project = a.slice(10); else if (a === "--tool") opts.only = argv[++i].split(","); else if (a.startsWith("--tool=")) opts.only = a.slice(7).split(","); else if (a === "--days") opts.days = parseDays(argv[++i]); else if (a.startsWith("--days=")) opts.days = parseDays(a.slice(7)); else if (a.startsWith("-")) throw new Error(`unknown flag: ${a}`); else positional.push(a); } if (positional.length) throw new Error(`unexpected argument: ${positional[0]}`); if (opts.project !== null && opts.mode !== "check") throw new Error(`--project requires --check`); return opts; } function selectTools(only) { if (!only) return TOOLS; const found = TOOLS.filter(t => only.includes(t.name)); const missing = only.filter(n => !TOOLS.some(t => t.name === n)); if (missing.length) throw new Error(`unknown tool(s): ${missing.join(",")}`); return found; } function preflightWarn(t, ctx) { if (typeof t.preflight !== "function") return null; const pf = t.preflight(ctx); return pf?.message ?? null; } async function gatherStatus(targets, ctx) { return Promise.all(targets.map(async t => { const r = await t.read(ctx); const row = { tool: t.name, key: r.key ?? t.key, path: r.path, configured: r.configured, days: r.days, extras: r.extras ?? [], warn: r.migrateWarn ?? preflightWarn(t, ctx) }; if (r.selector) row.selector = r.selector; // Not serialized: an unwired selector or unmigrated legacy layer fails check. Object.defineProperty(row, "layerFail", { value: Boolean(r.migrateWarn) || r.selector?.wired === false }); return row; })); } function renderHuman(rows, min) { const lines = []; for (const r of rows) { const status = r.days === null ? "MISSING" : r.days < min ? "STALE " : "OK "; const value = r.configured ?? "(unset)"; const tail = r.warn ? `\n ⚠ ${r.warn}` : ""; lines.push(`${status} ${r.tool.padEnd(4)} ${r.key} = ${value} [${r.path}]${tail}`); for (const e of r.extras) { const exStatus = e.ok ? "OK " : e.configured === null ? "MISSING" : "STALE "; const exValue = e.defaultEnforced ? `(default — runtime enforces ${e.expected})` : (e.configured ?? "(unset)"); lines.push(`${exStatus} ${r.tool.padEnd(4)} ${e.key} = ${exValue} [${r.path}]`); } if (r.selector) { const selStatus = r.selector.wired ? "OK " : "MISSING"; lines.push(`${selStatus} ${r.tool.padEnd(4)} env includes "pmsec" = ${r.selector.wired} [${r.selector.path}]`); } } return lines.join("\n") + "\n"; } async function runCheck(targets, { json, days }, ctx, out, err) { const rows = await gatherStatus(targets, ctx); const failingPrimary = rows.filter(r => r.days === null || r.days < days); const failingExtras = rows.flatMap(r => r.extras.filter(e => !e.ok)); const failingLayers = rows.filter(r => r.layerFail); const ok = failingPrimary.length === 0 && failingExtras.length === 0 && failingLayers.length === 0; if (json) out.write(JSON.stringify({ bundleDays: days, rows, ok }, null, 2) + "\n"); else out.write(renderHuman(rows, days)); if (failingPrimary.length) err.write(`pmsec: ${failingPrimary.length} tool(s) below ${days} days — run \`pmsec\`\n`); if (failingExtras.length) err.write(`pmsec: ${failingExtras.length} hardening setting(s) not at safe value — run \`pmsec\`\n`); if (failingLayers.length) err.write(`pmsec: ${failingLayers.length} tool(s) with config layers not wired — run \`pmsec\`\n`); return ok ? 0 : 1; } function runProjectCheck({ json, days, project, only }, out, err) { const rows = scanProject(project, only); const ok = rows.length === 0; if (json) out.write(JSON.stringify({ scope: "project", bundleDays: days, rows, ok }, null, 2) + "\n"); else if (ok) out.write(`OK project: no weakening keys [${project}]\n`); else for (const r of rows) out.write(`WEAK ${r.tool.padEnd(4)} ${r.key} = ${r.configured} (${r.reason}) [${r.path}]\n`); if (!ok) err.write(`pmsec: ${rows.length} project setting(s) weaken the baseline\n`); return ok ? 0 : 1; } // `pmsec doctor` runs read-only and reports the same path resolution that // enable/check/disable would do, plus identity (uid/euid) and parent-dir // writability — the smallest set of facts an operator needs to diagnose // "pmsec ran but wrote to nowhere" (root's $HOME) or "wrote a file no one // can read" (chown failed under SIP/SELinux). Never mutates the filesystem. function probePath(p, uid) { const parent = dirname(p); let exists = false, writable = false, parentExists = false, owner = null; try { accessSync(p, fsConstants.F_OK); exists = true; } catch {} if (exists) { try { accessSync(p, fsConstants.W_OK); writable = true; } catch {} try { const st = statSync(p); // Only POSIX uids are meaningful; on win32 st.uid is 0 and ignored downstream. owner = uid === null ? null : st.uid; } catch {} } try { accessSync(parent, fsConstants.F_OK); parentExists = true; } catch {} // Walk up to the deepest existing ancestor — pmsec runs mkdir -p, so what // matters is whether that ancestor is writable, not the literal parent. let probe = parent, ancestor = null; while (probe && probe !== dirname(probe)) { try { accessSync(probe, fsConstants.F_OK); ancestor = probe; break; } catch {} probe = dirname(probe); } let parentWritable = false; if (ancestor) { try { accessSync(ancestor, fsConstants.W_OK); parentWritable = true; } catch {} } return { path: p, parent, exists, writable, parentExists, parentWritable, owner }; } function runDoctor(targets, json, ctx, out) { const isPosix = ctx.platform !== "win32" && typeof process.getuid === "function"; const uid = isPosix ? process.getuid() : null; const euid = isPosix && typeof process.geteuid === "function" ? process.geteuid() : uid; let username = null; try { username = userInfo().username; } catch {} const tools = targets.map(t => { const p = t.path(ctx); const probe = probePath(p, uid); return { tool: t.name, key: t.key, ...probe }; }); // doctor.ok is intentionally narrow: the parent directory must be writable // by the running uid. Everything else is informational. const okFlag = tools.every(t => t.parentWritable); const report = { doctor: true, version: VERSION, platform: ctx.platform, uid, euid, username, home: ctx.home, pmsecHome: ctx.pmsecHome ?? null, pmsecHomeSource: ctx.pmsecHome ? "PMSEC_HOME" : "HOME", tools, ok: okFlag, }; if (json) { out.write(JSON.stringify(report, null, 2) + "\n"); return okFlag ? 0 : 1; } out.write(`pmsec ${VERSION} doctor\n`); out.write(` platform : ${ctx.platform}\n`); if (isPosix) out.write(` uid/euid : ${uid}/${euid}${username ? ` (${username})` : ""}\n`); out.write(` HOME : ${ctx.home}\n`); out.write(` PMSEC_HOME : ${ctx.pmsecHome ?? "(unset — using HOME)"}\n\n`); for (const t of tools) { const flag = t.parentWritable ? "ok " : "BLOCK "; const ownerSuffix = t.exists && t.owner !== null ? ` (uid=${t.owner})` : ""; out.write(`${flag} ${t.tool.padEnd(4)} ${t.path}${ownerSuffix}\n`); if (!t.parentWritable) { // Only surface noise when there's a real problem. "parent missing but // mkdir -p can fix it" is the common case and isn't worth a line. out.write(` no writable ancestor for ${t.parent}\n`); } } if (!okFlag) out.write(`\npmsec doctor: at least one parent directory is not writable as uid ${uid ?? "(non-POSIX)"}.\n`); return okFlag ? 0 : 1; } function explainFsError(e, tool) { if (e?.code === "EACCES" || e?.code === "EPERM") { const p = e.path ?? ""; const q = p ? shellQuote(p) : ""; return `${tool}: cannot write ${p} (${e.code}). Check file ownership: \`ls -la ${q}\` — if owned by root, run \`sudo chown -h $(id -u):$(id -g) ${q}\`.`; } if (e?.code === "EROFS") return `${tool}: ${e.path ?? ""} is on a read-only filesystem (EROFS).`; return `${tool}: ${e?.message ?? e}`; } async function runEnable(targets, json, days, force, ctx, out, err) { // Each tool writes a different config file; safe to run in parallel. // Promise.all preserves input order in the results array. const results = await Promise.all(targets.map(async t => { const warn = preflightWarn(t, ctx); try { let effective = days; let kept = false; if (!force) { const current = await t.read(ctx); const currentDays = current.days ?? 0; effective = Math.max(currentDays, days); kept = currentDays >= days && currentDays > 0; } const r = await t.write(effective, { ...ctx, force }); return { tool: t.name, path: r.path, days: effective, requested: days, kept, forced: force, ok: true, warn }; } catch (e) { return { tool: t.name, path: e?.path ?? null, days, requested: days, kept: false, forced: force, ok: false, error: explainFsError(e, t.name), warn }; } })); const failures = results.filter(r => !r.ok).map(r => ({ tool: r.tool, error: r.error })); const warnings = results.filter(r => r.warn).map(r => ({ tool: r.tool, warn: r.warn })); if (json) out.write(JSON.stringify({ enabled: true, bundleDays: days, results, warnings, ok: failures.length === 0 }, null, 2) + "\n"); else for (const r of results) { if (r.ok) { const action = r.kept ? "keep " : "enable "; const note = r.kept ? ` (kept existing ${r.days}d ≥ ${r.requested}d)` : ""; const tail = r.warn ? `\n ⚠ ${r.warn}` : ""; out.write(`${action} ${r.tool.padEnd(4)} [${r.path}]${note}${tail}\n`); } else { out.write(`FAIL ${r.tool.padEnd(4)} ${r.error}\n`); } } for (const f of failures) err.write(`pmsec: ${f.error}\n`); if (warnings.length) err.write(`pmsec: ${warnings.length} tool(s) configured but runtime may silently ignore the cooldown — see ⚠ above\n`); return failures.length ? 1 : 0; } async function runDisable(targets, json, ctx, out, err) { const results = await Promise.all(targets.map(async t => { try { const r = await t.unset(ctx); return { tool: t.name, path: r.path, removed: r.removed, ok: true }; } catch (e) { return { tool: t.name, path: e?.path ?? null, removed: false, ok: false, error: explainFsError(e, t.name) }; } })); const failures = results.filter(r => !r.ok).map(r => ({ tool: r.tool, error: r.error })); if (json) out.write(JSON.stringify({ results, ok: failures.length === 0 }, null, 2) + "\n"); else for (const r of results) { if (!r.ok) out.write(`FAIL ${r.tool.padEnd(4)} ${r.error}\n`); else out.write(`${r.removed ? "disable " : "skip "} ${r.tool.padEnd(4)} [${r.path}]\n`); } for (const f of failures) err.write(`pmsec: ${f.error}\n`); return failures.length ? 1 : 0; } export async function run(argv, { env = process.env, home = homedir(), platform = process.platform, out = process.stdout, err = process.stderr, } = {}) { let opts; try { opts = parse(argv); } catch (e) { err.write(`pmsec: ${e.message}\n`); return 2; } if (opts.version) { out.write(`pmsec ${VERSION}\n`); return 0; } if (opts.help) { out.write(USAGE); return 0; } let targets; try { targets = selectTools(opts.only); } catch (e) { err.write(`pmsec: ${e.message}\n`); return 2; } // PMSEC_HOME redirects every path (e.g. `sudo PMSEC_HOME=/home/u pmsec`); // writeAtomic then guards and hands files back to that home's owner. const pmsecHome = env.PMSEC_HOME || null; const ctx = { env, home: pmsecHome ?? home, platform, pmsecHome }; try { if (opts.project !== null) return runProjectCheck(opts, out, err); if (opts.mode === "check") return await runCheck(targets, opts, ctx, out, err); if (opts.mode === "disable") return await runDisable(targets, opts.json, ctx, out, err); if (opts.mode === "doctor") return runDoctor(targets, opts.json, ctx, out); return await runEnable(targets, opts.json, opts.days, opts.force, ctx, out, err); } catch (e) { err.write(`pmsec: ${e.message}\n`); return 1; } }