Skip to content
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
Show all changes
20 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
155 changes: 144 additions & 11 deletions scripts/audit-reviewed-npm-graph.mts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
// SPDX-License-Identifier: Apache-2.0

import { spawnSync } from "node:child_process";
import { createHash } from "node:crypto";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
Expand All @@ -12,8 +13,10 @@ import {
packReviewedNpmArchive,
verifyInstalledNpmLock,
verifyReviewedNpmLock,
verifyReviewedNpmLockPackages,
} from "./lib/reviewed-npm-archive.mts";
import {
type AuditPolicyResult,
assertExceptionGraphs,
readAuditExceptionRegistry,
runReviewedNpmAudit,
Expand All @@ -39,13 +42,18 @@ type AuditConfig = Readonly<{
schemaVersion: 2;
severityThreshold: Severity;
}>;
type ReviewedAuditReport = Readonly<{ label: string; result: AuditPolicyResult }>;

const TRUSTED_REPO_ROOT = path.resolve(path.dirname(fileURLToPath(import.meta.url)), "..");
const TARGET_REPO_ROOT = fs.realpathSync(
path.resolve(process.env.NEMOCLAW_REVIEWED_NPM_AUDIT_TARGET_ROOT ?? TRUSTED_REPO_ROOT),
);
const CONFIG_PATH = resolveTrustedAuditConfigPath(TRUSTED_REPO_ROOT);
const SEVERITIES: readonly Severity[] = ["info", "low", "moderate", "high", "critical"];
const SOURCE_GRAPH = {
id: "nemoclaw-cli",
label: "NemoClaw CLI locked production graph",
} as const;
const OPENCLAW_DOMEXCEPTION_ALIAS = {
actualName: "@nolyfill/domexception",
aliasPackagePath: "node_modules/openclaw/node_modules/node-domexception",
Expand Down Expand Up @@ -230,6 +238,33 @@ function assertRegularFile(file: string, label: string): void {
}
}

export function materializeSourceGraph(
sourcePackage: string,
sourceLock: string,
destination: string,
registryOrigin: string,
installProductionDependencies: (directory: string) => void = (directory) =>
void run("npm", ["ci", "--ignore-scripts", "--omit=dev", "--no-audit", "--no-fund"], directory),
): string {
assertRegularFile(sourcePackage, "NemoClaw CLI package manifest");
assertRegularFile(sourceLock, "NemoClaw CLI lockfile");
verifyReviewedNpmLockPackages({ lockfilePath: sourceLock, omitDev: true, registryOrigin });
const lockSha256 = createHash("sha256").update(fs.readFileSync(sourceLock)).digest("hex");
fs.mkdirSync(destination);
fs.copyFileSync(sourcePackage, path.join(destination, "package.json"));
const installedLock = path.join(destination, "package-lock.json");
fs.copyFileSync(sourceLock, installedLock);
installProductionDependencies(destination);
verifyInstalledNpmLock({
expectedLockSha256: lockSha256,
installRoot: destination,
label: SOURCE_GRAPH.label,
lockfilePath: installedLock,
omitDev: true,
});
return destination;
}

export function normalizeOpenClawSignatureAlias(directory: string): void {
const {
actualName,
Expand Down Expand Up @@ -332,6 +367,94 @@ function auditLockedGraph(
return result;
}

function auditSourceGraph(
config: AuditConfig,
tempRoot: string,
exceptionFile: string,
artifactDirectory: string,
npmVersion: string,
) {
const sourcePackage = targetRepositoryPath("package.json", "NemoClaw CLI package manifest");
const sourceLock = targetRepositoryPath("package-lock.json", "NemoClaw CLI lockfile");
const sourceManifest = readJsonObject(sourcePackage, "NemoClaw CLI package manifest");
if (typeof sourceManifest.name !== "string" || typeof sourceManifest.version !== "string") {
throw new Error("NemoClaw CLI package manifest must declare its name and version");
}
const directory = materializeSourceGraph(
sourcePackage,
sourceLock,
path.join(tempRoot, "source-graph"),
config.registryOrigin,
);
return auditMaterializedSourceGraph({
directory,
exceptionFile,
artifactDirectory,
npmVersion,
packageSpec: `${sourceManifest.name}@${sourceManifest.version}`,
threshold: config.severityThreshold,
});
}

export function auditMaterializedSourceGraph(
options: Readonly<{
artifactDirectory: string;
directory: string;
exceptionFile: string;
npmVersion: string;
packageSpec: string;
threshold: Severity;
}>,
dependencies: Readonly<{
runAudit?: typeof runReviewedNpmAudit;
verifySignatures?: (directory: string) => void;
}> = {},
): AuditPolicyResult {
const result = (dependencies.runAudit ?? runReviewedNpmAudit)({
directory: options.directory,
exceptionFile: options.exceptionFile,
graph: SOURCE_GRAPH.id,
provenance: {
label: SOURCE_GRAPH.label,
nodeVersion: process.version,
npmVersion: options.npmVersion,
packageSpecs: [options.packageSpec],
},
reportFile: path.join(options.artifactDirectory, "source-graph.json"),
resultFile: path.join(options.artifactDirectory, "source-graph-policy.json"),
threshold: options.threshold,
throwOnBlock: false,
});
(
dependencies.verifySignatures ??
((directory) => run("npm", ["audit", "signatures", "--omit=dev"], directory))
)(options.directory);
return result;
}

export function assertReviewedAuditReportsPass(
reports: readonly ReviewedAuditReport[],
threshold: Severity,
): void {
const failures = reports
.filter(({ result }) => result.unacceptedBlockingAdvisories.length > 0)
.map(
({ label, result }) =>
`${label}: ${result.unacceptedBlockingAdvisories.length} unaccepted at or above ${threshold}`,
);
if (failures.length > 0)
throw new Error(`reviewed npm audit threshold failed\n${failures.join("\n")}`);
}

export function shouldAuditTargetSourceGraph(
trustedRepoRoot: string,
targetRepoRoot: string,
): boolean {
return (
fs.realpathSync(path.resolve(trustedRepoRoot)) !== fs.realpathSync(path.resolve(targetRepoRoot))
);
}

function main(): void {
const config = readConfig();
const expectedNode = `v${config.nodeVersion}`;
Expand All @@ -346,14 +469,33 @@ function main(): void {
const exceptionRegistry = readAuditExceptionRegistry(exceptionFile);
assertExceptionGraphs(
exceptionRegistry.policy,
new Set([config.archiveGraphId, ...config.lockedGraphs.map((graph) => graph.id)]),
new Set([
SOURCE_GRAPH.id,
config.archiveGraphId,
...config.lockedGraphs.map((graph) => graph.id),
]),
);
fs.rmSync(artifactDirectory, { recursive: true, force: true });
fs.mkdirSync(artifactDirectory, { recursive: true });
const npmVersion = run("npm", ["--version"], TRUSTED_REPO_ROOT).stdout.trim();
const tempRoot = fs.mkdtempSync(path.join(os.tmpdir(), "nemoclaw-reviewed-npm-audit-"));
try {
// Keep the same-tree exemption only until PR #8126 upgrades the root production lock.
const reports = [
...(shouldAuditTargetSourceGraph(TRUSTED_REPO_ROOT, TARGET_REPO_ROOT)
? [
{
label: SOURCE_GRAPH.label,
result: auditSourceGraph(
config,
tempRoot,
exceptionFile,
artifactDirectory,
npmVersion,
),
},
]
: []),
{
label: "reviewed archive graph",
result: runReviewedNpmAudit({
Expand Down Expand Up @@ -385,16 +527,7 @@ function main(): void {
),
})),
];
const failures: string[] = [];
for (const { label, result } of reports) {
if (result.unacceptedBlockingAdvisories.length > 0) {
failures.push(
`${label}: ${result.unacceptedBlockingAdvisories.length} unaccepted at or above ${config.severityThreshold}`,
);
}
}
if (failures.length > 0)
throw new Error(`reviewed npm audit threshold failed\n${failures.join("\n")}`);
assertReviewedAuditReportsPass(reports, config.severityThreshold);
} finally {
fs.rmSync(tempRoot, { recursive: true, force: true });
}
Expand Down
119 changes: 118 additions & 1 deletion scripts/lib/reviewed-npm-archive.mts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ export type ReviewedInstalledNpmLockRequest = Readonly<{
installRoot: string;
label: string;
lockfilePath: string;
omitDev?: boolean;
}>;

export type ReviewedNpmMetadata = Readonly<{
Expand Down Expand Up @@ -261,6 +262,92 @@ function packageNameFromLockLocation(location: string): string {
return packageName;
}

type LockDependency = Readonly<{ name: string; optional: boolean }>;

function lockDependencies(
record: Readonly<Record<string, unknown>>,
location: string,
): readonly LockDependency[] {
const dependencies = new Map<string, boolean>();
for (const [field, optional] of [
["dependencies", false],
["optionalDependencies", true],
] as const) {
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
const value = record[field];
if (value === undefined) continue;
if (typeof value !== "object" || value === null || Array.isArray(value)) {
throw new Error(
`reviewed npm lock has an invalid ${field} map: ${location || "root package"}`,
);
}
for (const name of Object.keys(value)) {
if (!EXACT_NPM_PACKAGE_SPEC.test(`${name}@0.0.0`)) {
throw new Error(
`reviewed npm lock has an invalid dependency name: ${location || "root package"}: ${name}`,
);
}
dependencies.set(name, optional);
}
}
return [...dependencies].map(([name, optional]) => ({ name, optional }));
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

function resolveLockDependencyLocation(
packages: Readonly<Record<string, Record<string, unknown>>>,
requesterLocation: string,
dependencyName: string,
): string | undefined {
let ancestorLocation = requesterLocation;
while (true) {
const candidate = ancestorLocation
? `${ancestorLocation}/node_modules/${dependencyName}`
: `node_modules/${dependencyName}`;
if (Object.prototype.hasOwnProperty.call(packages, candidate)) return candidate;
if (!ancestorLocation) return undefined;
const parentMarker = ancestorLocation.lastIndexOf("/node_modules/");
ancestorLocation = parentMarker >= 0 ? ancestorLocation.slice(0, parentMarker) : "";
}
}

function productionLockLocations(
packages: Readonly<Record<string, Record<string, unknown>>>,
): ReadonlySet<string> {
const root = packages[""];
if (!root || typeof root !== "object" || Array.isArray(root)) {
throw new Error("reviewed npm lock is missing its root package record");
}

const reachable = new Set<string>();
const pending: Array<Readonly<{ location: string; record: Record<string, unknown> }>> = [
{ location: "", record: root },
];
while (pending.length > 0) {
const current = pending.pop();
if (!current) break;
for (const dependency of lockDependencies(current.record, current.location)) {
const location = resolveLockDependencyLocation(
packages,
current.location,
dependency.name,
);
if (!location) {
if (dependency.optional) continue;
throw new Error(
`reviewed npm lock is missing a production dependency: ${current.location || "root package"}: ${dependency.name}`,
);
}
if (reachable.has(location)) continue;
const record = packages[location];
if (typeof record !== "object" || record === null || Array.isArray(record)) {
throw new Error(`reviewed npm lock has an invalid package record: ${location}`);
}
reachable.add(location);
pending.push({ location, record });
}
}
return reachable;
}

function verifyReviewedLockDigest(
lockfilePath: string,
expectedLockSha256: string,
Expand All @@ -281,15 +368,27 @@ function readReviewedLockPackages(
packages: Readonly<Record<string, Record<string, unknown>>>,
lockfilePath: string,
registryOrigin: string,
omitDev = false,
allowEmpty = false,
): readonly ReviewedNpmArchiveRequest[] {
const reviewed: ReviewedNpmArchiveRequest[] = [];
const identities = new Map<string, ReviewedNpmArchiveRequest>();
const productionLocations = omitDev ? productionLockLocations(packages) : undefined;
for (const [location, value] of Object.entries(packages)) {
if (location === "") continue;
if (typeof value !== "object" || value === null || Array.isArray(value)) {
throw new Error(`reviewed npm lock has an invalid package record: ${location}`);
}
const record = value as Record<string, unknown>;
if (productionLocations?.has(location) && record.dev === true) {
throw new Error(`reviewed npm lock marks a production dependency as dev: true: ${location}`);
}
if (omitDev && record.dev === true) continue;
if (Object.prototype.hasOwnProperty.call(record, "hasShrinkwrap")) {
throw new Error(
`reviewed npm lock package must not delegate to nested shrinkwrap: ${location}`,
);
}
const locationName = packageNameFromLockLocation(location);
const packageName = typeof record.name === "string" ? record.name : locationName;
const version = typeof record.version === "string" ? record.version : "";
Expand Down Expand Up @@ -331,12 +430,25 @@ function readReviewedLockPackages(
identities.set(packageSpec, request);
reviewed.push(request);
}
if (reviewed.length === 0) {
if (!allowEmpty && reviewed.length === 0) {
throw new Error(`reviewed npm lock contains no packages: ${lockfilePath}`);
}
return reviewed;
}

export function verifyReviewedNpmLockPackages(
request: Readonly<{ lockfilePath: string; omitDev?: boolean; registryOrigin: string }>,
): readonly string[] {
const registryOrigin = normalizeRegistryOrigin(request.registryOrigin);
return readReviewedLockPackages(
readReviewedLock(request.lockfilePath),
request.lockfilePath,
registryOrigin,
request.omitDev,
true,
).map(({ packageSpec }) => packageSpec);
}

export function verifyReviewedNpmLock(
request: ReviewedNpmLockRequest,
npmRunner: NpmRunner = runNpm,
Expand Down Expand Up @@ -401,9 +513,14 @@ export function verifyInstalledNpmLock(
const installRoot = resolve(request.installRoot);
const nodeModulesRoot = resolve(installRoot, "node_modules");
const verified: string[] = [];
const productionLocations = request.omitDev ? productionLockLocations(packages) : undefined;

for (const [location, record] of Object.entries(packages)) {
if (location === "") continue;
if (productionLocations?.has(location) && record.dev === true) {
throw new Error(`reviewed npm lock marks a production dependency as dev: true: ${location}`);
}
if (request.omitDev && record.dev === true) continue;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
const locationName = packageNameFromLockLocation(location);
const expectedName = typeof record.name === "string" ? record.name : locationName;
const expectedVersion = typeof record.version === "string" ? record.version : "";
Expand Down
Loading
Loading