NodeSecure / js-x-ray

JavaScript & Node.js open-source SAST scanner. A static analyser for detecting most common malicious patterns 🔬.
MIT License
229 stars 26 forks source link

Refactor runASTAnalysis functions to use class AstAnalyser #216

Closed jean-michelet closed 9 months ago

jean-michelet commented 9 months ago

The aim of this PR is to make the project more flexible and allow users to add new behaviors more easily.

I've created an AstAnalyser class that implements the logic originally contained in runASTAnalysis and runASTAnalysisOnFile. The class can be extended and has a dependency on any EStree-compatible parser that respects the following abstraction:

interface SourceParser {
  parse(source: string, options: unknown): ESTree.Program;
}

interface AstAnalyser {
  constructor(parser: SourceParser): void;
  analyse: (str: string, options?: Omit<RuntimeOptions, "customParser">) => Report;
  analyzeFile(pathToFile: string, options?: Omit<RuntimeFileOptions, "customParser">): Promise<ReportOnFile>;
}

Example:

const jsAnalyser = new AstAnalyser(new JsSourceParser());
const tsAnalyser = new AstAnalyser(new TsSourceParser());

I removed the class SourceParser to favor composition over inheritance. Responsibility for preparing source code (deleting html comments etc.) for analysis can be assigned to the new class AstAnalyser. It removes the need for this class from the workspaces, wich could be problematic to create the TsSourceParser (214).

I kept the functions runASTAnalysis and runASTAnalysisOnFile so my additions extend the possibilities without breaking the existing. Users can pass a custom parser to these functions without having to completely modify their code:

function runASTAnalysis(
  str,
  options = Object.create(null)
) {
  const {
    customParser = new JsSourceParser(),
    ...opts
  } = options;

  const analyser = new AstAnalyser(customParser);

  return analyser.analyse(str, opts);
}

I've moved the tests for these functions to the new AstAnalyser class and replaced them with integration tests verifying that the functions call the AstAnalyser methods with the right arguments.

fraxken commented 9 months ago

@allcontributors please add @jean-michelet for code, test, doc

allcontributors[bot] commented 9 months ago

@fraxken

I've put up a pull request to add @jean-michelet! :tada: