Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
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
121 changes: 109 additions & 12 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -551,21 +551,19 @@ function readDirectDependencyNames(projectPath: string, prodOnly: boolean): Set<
}

try {
const raw = JSON.parse(fs.readFileSync(packageJsonPath, "utf8"));
const directNames = new Set<string>();
const sections: Array<Record<string, unknown> | undefined> = [
raw?.dependencies,
raw?.optionalDependencies,
];
if (!prodOnly) {
sections.push(raw?.devDependencies);
const rootManifest = readPackageJsonObject(packageJsonPath);
if (!rootManifest) {
return null;
}

for (const section of sections) {
if (!section || typeof section !== "object") continue;
for (const name of Object.keys(section)) {
directNames.add(name);
}
addDependencyNamesFromManifest(directNames, rootManifest, prodOnly);

const workspacePatterns = readWorkspacePatterns(rootManifest);
for (const workspacePackageJsonPath of resolveWorkspacePackageJsonPaths(projectPath, workspacePatterns)) {
const workspaceManifest = readPackageJsonObject(workspacePackageJsonPath);
if (!workspaceManifest) continue;
addDependencyNamesFromManifest(directNames, workspaceManifest, prodOnly);
}

return directNames;
Expand All @@ -574,6 +572,105 @@ function readDirectDependencyNames(projectPath: string, prodOnly: boolean): Set<
}
}

function readPackageJsonObject(filePath: string): Record<string, unknown> | null {
try {
const raw = JSON.parse(fs.readFileSync(filePath, "utf8"));
return raw && typeof raw === "object" ? raw as Record<string, unknown> : null;
} catch {
return null;
}
}

function addDependencyNamesFromManifest(
target: Set<string>,
manifest: Record<string, unknown>,
prodOnly: boolean,
) {
const sections: Array<Record<string, unknown> | undefined> = [
isRecord(manifest.dependencies) ? manifest.dependencies : undefined,
isRecord(manifest.optionalDependencies) ? manifest.optionalDependencies : undefined,
];
if (!prodOnly) {
sections.push(isRecord(manifest.devDependencies) ? manifest.devDependencies : undefined);
}

for (const section of sections) {
if (!section) continue;
for (const name of Object.keys(section)) {
target.add(name);
}
}
}

function readWorkspacePatterns(manifest: Record<string, unknown>): string[] {
const workspaces = manifest.workspaces;
if (Array.isArray(workspaces)) {
return workspaces.filter((value): value is string => typeof value === "string");
}

if (isRecord(workspaces) && Array.isArray(workspaces.packages)) {
return workspaces.packages.filter((value): value is string => typeof value === "string");
}

return [];
}

function resolveWorkspacePackageJsonPaths(projectPath: string, patterns: string[]): string[] {
const matches = new Set<string>();

for (const pattern of patterns) {
const normalized = pattern.replace(/\\/g, "/").replace(/\/+$/, "");
if (!normalized) continue;

for (const relativeDir of expandWorkspacePattern(projectPath, normalized.split("/").filter(Boolean), "")) {
const packageJsonPath = path.join(projectPath, relativeDir, "package.json");
if (fs.existsSync(packageJsonPath)) {
matches.add(packageJsonPath);
}
}
}

return [...matches];
}

function expandWorkspacePattern(projectPath: string, segments: string[], currentRelativePath: string): string[] {
if (segments.length === 0) {
return currentRelativePath ? [currentRelativePath] : [];
}

const [segment, ...rest] = segments;
if (segment === "*") {
const baseDir = currentRelativePath ? path.join(projectPath, currentRelativePath) : projectPath;
let entries: fs.Dirent[] = [];
try {
entries = fs.readdirSync(baseDir, { withFileTypes: true });
} catch {
return [];
}

return entries
.filter(entry => entry.isDirectory())
.flatMap(entry => {
const nextRelativePath = currentRelativePath
? path.join(currentRelativePath, entry.name)
: entry.name;
return expandWorkspacePattern(projectPath, rest, nextRelativePath);
});
}

const nextRelativePath = currentRelativePath ? path.join(currentRelativePath, segment) : segment;
const nextAbsolutePath = path.join(projectPath, nextRelativePath);
if (!fs.existsSync(nextAbsolutePath) || !fs.statSync(nextAbsolutePath).isDirectory()) {
return [];
}

return expandWorkspacePattern(projectPath, rest, nextRelativePath);
}

function isRecord(value: unknown): value is Record<string, unknown> {
return !!value && typeof value === "object" && !Array.isArray(value);
}

function formatAdvisoryDbFreshness(lastSyncAt: string | null): string {
if (!lastSyncAt) {
return chalk.yellow("unknown");
Expand Down
73 changes: 73 additions & 0 deletions tests/cli-integration.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
import { jest } from "@jest/globals";
import { EventEmitter } from "node:events";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { PassThrough } from "node:stream";
import type { Finding, PackageRef, ScanInput } from "../src/types.js";
import { stripAnsi } from "../src/utils/chalk.js";
Expand Down Expand Up @@ -243,6 +246,76 @@ describe("CLI integration", () => {
});
});

it("includes child workspace dependency names in direct classification context", async () => {
const projectDir = fs.mkdtempSync(path.join(os.tmpdir(), "cve-lite-workspace-context-"));
const clientDir = path.join(projectDir, "packages", "client");
const experienceDir = path.join(projectDir, "packages", "experience");

fs.mkdirSync(clientDir, { recursive: true });
fs.mkdirSync(experienceDir, { recursive: true });
fs.writeFileSync(
path.join(projectDir, "package.json"),
JSON.stringify({
name: "fixture",
private: true,
workspaces: ["packages/*"],
dependencies: {
husky: "^9.1.7",
},
}),
"utf8",
);
fs.writeFileSync(
path.join(clientDir, "package.json"),
JSON.stringify({
name: "client",
private: true,
dependencies: {
"@eslint/eslintrc": "3.2.0",
},
}),
"utf8",
);

parseArgsMock.mockReturnValue({
command: "scan",
options: {
failOn: "critical",
batchSize: "100",
searchDepth: "4",
minSeverity: "medium",
},
projectArg: projectDir,
});
loadPackagesMock.mockReturnValue(
createScanInput({
mode: "resolved-lockfile",
source: "package-lock",
filePath: path.join(projectDir, "package-lock.json"),
packages: [
{
name: "@eslint/eslintrc",
version: "3.2.0",
ecosystem: "npm",
paths: [["project", "@eslint/eslintrc"]],
},
],
}),
);

try {
const result = await runIndexModule();

expect(result.exitCode).toBe(0);
expect(scanPackagesMock).toHaveBeenCalled();
const context = scanPackagesMock.mock.calls[0]?.[3] as { directDependencyNames?: Set<string> } | undefined;
expect(context?.directDependencyNames?.has("husky")).toBe(true);
expect(context?.directDependencyNames?.has("@eslint/eslintrc")).toBe(true);
} finally {
fs.rmSync(projectDir, { recursive: true, force: true });
}
});

it("prints the versioned banner and exits when --version is requested", async () => {
parseArgsMock.mockReturnValue({
command: "scan",
Expand Down
Loading