Skip to content
Closed
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
104 changes: 104 additions & 0 deletions packages/scanner/tests/scan.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,104 @@
import { describe, expect, it, mock, beforeEach } from "bun:test";
import { existsSync, readFileSync } from "node:fs";

const mockExistsSync = mock();
const mockReadFileSync = mock();

mock.module("node:fs", () => ({
existsSync: mockExistsSync,
readFileSync: mockReadFileSync,
}));

import { scan } from "../src/scan";

describe("scan - detectInjection", () => {
beforeEach(() => {
mockExistsSync.mockReset();
mockReadFileSync.mockReset();
});

it("should return empty findings if package.json is missing or unreadable", async () => {
mockExistsSync.mockImplementation((path: string) => {
if (path.endsWith("package-lock.json")) return true;
if (path.endsWith("package.json")) return false;
return false;
});

mockReadFileSync.mockImplementation((path: string) => {
if (path.endsWith("package-lock.json")) {
return JSON.stringify({
lockfileVersion: 2,
packages: {
"node_modules/pkg-a": { version: "1.0.0" }
}
});
}
if (path.endsWith("package.json")) {
throw new Error("File not found");
}
return "";
});

const result = await scan("/test-dir");
expect(result.findings).toEqual([]);
});

it("should return empty findings if package.json is invalid JSON", async () => {
mockExistsSync.mockImplementation((path: string) => {
if (path.endsWith("package-lock.json")) return true;
return true;
});

mockReadFileSync.mockImplementation((path: string) => {
if (path.endsWith("package-lock.json")) {
return JSON.stringify({
lockfileVersion: 2,
packages: {
"node_modules/pkg-a": { version: "1.0.0" }
}
});
}
if (path.endsWith("package.json")) {
return "invalid { json";
}
return "";
});

const result = await scan("/test-dir");
expect(result.findings).toEqual([]);
});

it("should detect injection when package is in lockfile but not in package.json", async () => {
mockExistsSync.mockImplementation((path: string) => {
if (path.endsWith("package-lock.json")) return true;
if (path.endsWith("package.json")) return true;
return false;
});

mockReadFileSync.mockImplementation((path: string) => {
if (path.endsWith("package-lock.json")) {
return JSON.stringify({
lockfileVersion: 3,
packages: {
"": { version: "1.0.0" },
"node_modules/pkg-a": { version: "1.0.0" },
"node_modules/pkg-b": { version: "2.0.0" }
}
});
}
if (path.endsWith("package.json")) {
return JSON.stringify({
dependencies: {
"pkg-a": "1.0.0"
}
});
}
return "";
});

const result = await scan("/test-dir");
const injections = result.findings.filter(f => f.type === 'injection');
expect(injections).toHaveLength(1);
expect(injections[0].package).toBe("pkg-b");
});
});
Loading