Skip to content

feat(probes): add initialize #362

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jun 29, 2025
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
5 changes: 5 additions & 0 deletions .changeset/four-bars-bet.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"@nodesecure/js-x-ray": minor
---

feat(probes): add initialize
2 changes: 1 addition & 1 deletion workspaces/js-x-ray/docs/AstAnalyser.md
Original file line number Diff line number Diff line change
Expand Up @@ -134,7 +134,7 @@ scanner.analyse("const foo = 'bar';", {

You can also create custom probes to detect specific pattern in the code you are analyzing.

A probe is a pair of two functions (`validateNode` and `main`) that will be called on each node of the AST. It will return a warning if the pattern is detected.
A probe is a pair of two required functions (`validateNode` and `main`) that will be called on each node of the AST and one optional function (`initialize`) that will be call before walking the AST.It will return a warning if the pattern is detected.

Below a basic probe that detect a string assignation to `danger`:

Expand Down
8 changes: 8 additions & 0 deletions workspaces/js-x-ray/src/ProbeRunner.js
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,7 @@ import isSyncIO from "./probes/isSyncIO.js";
* @property {(options: any) => void} teardown
* @property {boolean} [breakOnMatch=false]
* @property {string} [breakGroup]
* @property {(sourceFile: SourceFile) => void} [initialize]
*/

export const ProbeSignals = Object.freeze({
Expand Down Expand Up @@ -85,6 +86,13 @@ export class ProbeRunner {
typeof probe.main === "function",
`Invalid probe ${probe.name}: main must be a function`
);
assert(
typeof probe.initialize === "function" || probe.initialize === undefined,
`Invalid probe ${probe.name}: initialize must be a function or undefined`
);
if (probe.initialize) {
probe.initialize(sourceFile);
}
}

this.probes = probes;
Expand Down
35 changes: 0 additions & 35 deletions workspaces/js-x-ray/src/SourceFile.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,36 +11,6 @@ import * as trojan from "./obfuscators/trojan-source.js";

// CONSTANTS
const kMaximumEncodedLiterals = 10;
const kIdentifierOrMemberExps = [
"crypto.createHash",
"crypto.pbkdf2Sync",
"crypto.scryptSync",
"crypto.generateKeyPairSync",
"fs.readFileSync",
"fs.writeFileSync",
"fs.appendFileSync",
"fs.readSync",
"fs.writeSync",
"fs.readdirSync",
"fs.statSync",
"fs.mkdirSync",
"fs.renameSync",
"fs.unlinkSync",
"fs.symlinkSync",
"fs.openSync",
"fs.fstatSync",
"fs.linkSync",
"fs.realpathSync",
"child_process.execSync",
"child_process.spawnSync",
"child_process.execFileSync",
"zlib.deflateSync",
"zlib.inflateSync",
"zlib.gzipSync",
"zlib.gunzipSync",
"zlib.brotliCompressSync",
"zlib.brotliDecompressSync"
];

export class SourceFile {
inTryStatement = false;
Expand All @@ -56,11 +26,6 @@ export class SourceFile {
this.tracer = new VariableTracer()
.enableDefaultTracing();

kIdentifierOrMemberExps.forEach((identifierOrMemberExp) => this.tracer.trace(identifierOrMemberExp, {
followConsecutiveAssignment: true,
moduleName: identifierOrMemberExp.split(".")[0]
}));

let probes = ProbeRunner.Defaults;
if (Array.isArray(probesOptions.customProbes) && probesOptions.customProbes.length > 0) {
probes = probesOptions.skipDefaultProbes === true ? probesOptions.customProbes : [...probes, ...probesOptions.customProbes];
Expand Down
37 changes: 37 additions & 0 deletions workspaces/js-x-ray/src/probes/isSyncIO.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,35 @@ import { getCallExpressionIdentifier } from "@nodesecure/estree-ast-utils";

// Constants
const kTracedNodeCoreModules = ["fs", "crypto", "child_process", "zlib"];
const kSyncIOIdentifierOrMemberExps = [
"crypto.pbkdf2Sync",
"crypto.scryptSync",
"crypto.generateKeyPairSync",
"fs.readFileSync",
"fs.writeFileSync",
"fs.appendFileSync",
"fs.readSync",
"fs.writeSync",
"fs.readdirSync",
"fs.statSync",
"fs.mkdirSync",
"fs.renameSync",
"fs.unlinkSync",
"fs.symlinkSync",
"fs.openSync",
"fs.fstatSync",
"fs.linkSync",
"fs.realpathSync",
"child_process.execSync",
"child_process.spawnSync",
"child_process.execFileSync",
"zlib.deflateSync",
"zlib.inflateSync",
"zlib.gzipSync",
"zlib.gunzipSync",
"zlib.brotliCompressSync",
"zlib.brotliDecompressSync"
];

function validateNode(node, { tracer }) {
const id = getCallExpressionIdentifier(node, { tracer });
Expand All @@ -15,6 +44,13 @@ function validateNode(node, { tracer }) {
return [data !== null && data.identifierOrMemberExpr.endsWith("Sync")];
}

function initialize(sourceFile) {
kSyncIOIdentifierOrMemberExps.forEach((identifierOrMemberExp) => sourceFile.tracer.trace(identifierOrMemberExp, {
followConsecutiveAssignment: true,
moduleName: identifierOrMemberExp.split(".")[0]
}));
}

function main(node, { sourceFile }) {
sourceFile.addWarning("synchronous-io", node.callee.name, node.loc);
}
Expand All @@ -23,5 +59,6 @@ export default {
name: "isSyncIO",
validateNode,
main,
initialize,
breakOnMatch: false
};
8 changes: 8 additions & 0 deletions workspaces/js-x-ray/src/probes/isWeakCrypto.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,13 @@ function validateNode(node, { tracer }) {
return [data !== null && data.identifierOrMemberExpr === "crypto.createHash"];
}

function initialize(sourceFile) {
sourceFile.tracer.trace("crypto.createHash", {
followConsecutiveAssignment: true,
moduleName: "crypto"
});
}

function main(node, { sourceFile }) {
const arg = node.arguments.at(0);

Expand All @@ -33,5 +40,6 @@ export default {
name: "isWeakCrypto",
validateNode,
main,
initialize,
breakOnMatch: false
};
1 change: 1 addition & 0 deletions workspaces/js-x-ray/src/types/api.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,7 @@ interface AstAnalyserOptions {
interface Probe {
validateNode: Function | Function[];
main: Function;
initialize?: (sourceFile: SourceFile) => void;
}

interface Report {
Expand Down
28 changes: 20 additions & 8 deletions workspaces/js-x-ray/test/ProbeRunner.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,13 @@ import assert from "node:assert";

// Import Internal Dependencies
import { ProbeRunner, ProbeSignals } from "../src/ProbeRunner.js";
import { SourceFile } from "../src/SourceFile.js";

describe("ProbeRunner", () => {
describe("constructor", () => {
it("should instanciate class with Defaults probes when none are provide", () => {
const pr = new ProbeRunner(null);
const pr = new ProbeRunner(new SourceFile(""));

assert.strictEqual(pr.sourceFile, null);
assert.strictEqual(pr.probes, ProbeRunner.Defaults);
});

Expand All @@ -23,8 +23,7 @@ describe("ProbeRunner", () => {
}
];

const pr = new ProbeRunner(null, fakeProbe);
assert.strictEqual(pr.sourceFile, null);
const pr = new ProbeRunner(new SourceFile(""), fakeProbe);
assert.strictEqual(pr.probes, fakeProbe);
});

Expand All @@ -36,8 +35,7 @@ describe("ProbeRunner", () => {
teardown: mock.fn()
}];

const pr = new ProbeRunner(null, fakeProbe);
assert.strictEqual(pr.sourceFile, null);
const pr = new ProbeRunner(new SourceFile(""), fakeProbe);
assert.strictEqual(pr.probes, fakeProbe);
});

Expand All @@ -48,7 +46,7 @@ describe("ProbeRunner", () => {
};

function instantiateProbeRunner() {
return new ProbeRunner(null, [fakeProbe]);
return new ProbeRunner(new SourceFile(""), [fakeProbe]);
}

assert.throws(instantiateProbeRunner, Error, "Invalid probe");
Expand All @@ -61,7 +59,21 @@ describe("ProbeRunner", () => {
};

function instantiateProbeRunner() {
return new ProbeRunner(null, [fakeProbe]);
return new ProbeRunner(new SourceFile(""), [fakeProbe]);
}

assert.throws(instantiateProbeRunner, Error, "Invalid probe");
});

it("should fail if initialize is present and not a function", () => {
const fakeProbe = {
validateNode: mock.fn(),
main: mock.fn(),
initialize: null
};

function instantiateProbeRunner() {
return new ProbeRunner(new SourceFile(""), [fakeProbe]);
}

assert.throws(instantiateProbeRunner, Error, "Invalid probe");
Expand Down