All files collect-input-sources.ts

89.23% Statements 58/65
68.57% Branches 24/35
100% Functions 0/0
91.07% Lines 51/56

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165              4x 4x 4x     13x   13x 3x   3x     4x                                               4x 4x     90x       1136x 1136x     71x 71x 71x   53x 53x     58x 58x     13x           13x 13x 13x 13x     99x     9x     4x 4x       1x     8x     8x 8x 8x             2x 2x                 3x 3x   3x                 1x 1x     99x   13x     13x   1x       13x 13x 13x                       13x   90x   90x      
import * as ts from 'typescript';
 
import { getFunctionName, isFunctionLike } from './ast-helpers.js';
import { getLineAndCharacter } from './utils.js';
 
import type { FileEntry, InputSourceInfo } from './types.js';
 
const HIGH_CONFIDENCE_PARAM = /^(req|request|body|rawBody|formData|payload|query|headers|params)$/i;
const MEDIUM_CONFIDENCE_PARAM = /^(input|event|message)$/i;
const SOURCE_PARAM_PATTERNS = /^(req|request|body|input|payload|data|params|query|headers|event|message|ctx|context|args|rawBody|formData)/i;
 
function getParamConfidence(params: string[]): 'high' | 'medium' | 'low' {
  let hasMedium = false;
  for (const p of params) {
    if (HIGH_CONFIDENCE_PARAM.test(p)) return 'high';
    Eif (MEDIUM_CONFIDENCE_PARAM.test(p)) hasMedium = true;
  }
  return hasMedium ? 'medium' : 'low';
}
 
const SINK_CALL_PATTERNS: Array<{ pattern: RegExp; kind: string }> = [
  { pattern: /^eval$/, kind: 'eval' },
  { pattern: /^Function$/, kind: 'eval' },
  { pattern: /\.exec(Sync)?$/, kind: 'exec' },
  { pattern: /^child_process\.(exec|spawn|fork)/, kind: 'exec' },
  { pattern: /^execSync$|^spawnSync$/, kind: 'exec' },
  { pattern: /^cp\.exec$|^cp\.spawn$/, kind: 'exec' },
  { pattern: /\.innerHTML$|\.outerHTML$/, kind: 'innerHTML' },
  { pattern: /dangerouslySetInnerHTML/, kind: 'innerHTML' },
  { pattern: /\.query$|\.execute$/, kind: 'sql' },
  { pattern: /\.redirect$/, kind: 'redirect' },
  { pattern: /\.send$|\.json$|\.write$/, kind: 'response' },
  { pattern: /fs\.(writeFile|appendFile)/, kind: 'fs-write' },
  { pattern: /writeFileSync|appendFileSync/, kind: 'fs-write' },
  // Path traversal sinks
  { pattern: /fs\.(readFile|readFileSync|createReadStream)/, kind: 'fs-read' },
  { pattern: /readFileSync|readFile/, kind: 'fs-read' },
  { pattern: /path\.(resolve|join)/, kind: 'path-resolve' },
  // SSRF sinks
  { pattern: /^fetch$/, kind: 'ssrf' },
  { pattern: /^(http|https)\.(request|get)/, kind: 'ssrf' },
  { pattern: /axios\.(get|post|put|delete|request)/, kind: 'ssrf' },
];
 
const SCHEMA_VALIDATOR_PATTERNS = /\.(validate|parse|safeParse|parseAsync|check|verify)\s*\(/;
const VALIDATOR_LIB_PATTERNS = /^(z|zod|Joi|yup|ajv|validator|superstruct|io-ts)\./;
 
export function collectInputSourceProfile(sourceFile: ts.SourceFile, _fileRelative: string, fileEntry: FileEntry): void {
  const inputSources: InputSourceInfo[] = [];
 
  const visitFn = (node: ts.Node): void => {
    if (!isFunctionLike(node)) {
      ts.forEachChild(node, visitFn);
      return;
    }
 
    const fnNode = node as ts.FunctionLikeDeclaration;
    const params = fnNode.parameters;
    const sourceParams: string[] = [];
    for (const p of params) {
      const name = p.name.getText(sourceFile);
      if (SOURCE_PARAM_PATTERNS.test(name)) sourceParams.push(name);
    }
    if (sourceParams.length === 0) {
      ts.forEachChild(node, visitFn);
      return;
    }
 
    const body = fnNode.body;
    if (!body) {
      ts.forEachChild(node, visitFn);
      return;
    }
 
    const sinkKinds = new Set<string>();
    let hasValidation = false;
    const callsWithInputArgs: Array<{ callee: string; lineStart: number }> = [];
    const sourceParamSet = new Set(sourceParams);
 
    const walkBody = (child: ts.Node): void => {
      Iif (isFunctionLike(child) && child !== node) return;
 
      if (ts.isCallExpression(child)) {
        const callText = child.expression.getText(sourceFile);
        for (const sink of SINK_CALL_PATTERNS) {
          if (sink.pattern.test(callText)) {
            sinkKinds.add(sink.kind);
            break;
          }
        }
        if (SCHEMA_VALIDATOR_PATTERNS.test(callText) || VALIDATOR_LIB_PATTERNS.test(callText)) {
          hasValidation = true;
        }
        for (const arg of child.arguments) {
          const argText = arg.getText(sourceFile);
          for (const sp of sourceParamSet) {
            if (argText === sp || argText.startsWith(sp + '.') || argText.startsWith(sp + '[')) {
              const loc = getLineAndCharacter(sourceFile, child);
              callsWithInputArgs.push({ callee: callText, lineStart: loc.lineStart });
              break;
            }
          }
        }
      }
 
      if (ts.isTypeOfExpression(child)) {
        const operand = child.expression.getText(sourceFile);
        Eif (sourceParamSet.has(operand)) hasValidation = true;
      }
 
      if (ts.isPrefixUnaryExpression(child) && child.operator === ts.SyntaxKind.ExclamationToken) {
        const operand = child.operand.getText(sourceFile);
        if (sourceParamSet.has(operand)) hasValidation = true;
      }
 
      if (ts.isIfStatement(child) || ts.isConditionalExpression(child)) {
        const cond = ts.isIfStatement(child) ? child.expression : child.condition;
        const condText = cond.getText(sourceFile);
        for (const sp of sourceParamSet) {
          if (condText.includes(sp)) { hasValidation = true; break; }
        }
      }
 
      if (ts.isCallExpression(child) && child.expression.getText(sourceFile).endsWith('instanceof')) {
        hasValidation = true;
      }
 
      if (ts.isBinaryExpression(child) && child.operatorToken.kind === ts.SyntaxKind.InstanceOfKeyword) {
        const leftText = child.left.getText(sourceFile);
        Eif (sourceParamSet.has(leftText)) hasValidation = true;
      }
 
      ts.forEachChild(child, walkBody);
    };
    ts.forEachChild(body, walkBody);
 
    if (ts.isTemplateExpression(body) || ts.isBlock(body)) {
      const bodyText = body.getText(sourceFile);
      for (const sp of sourceParamSet) {
        if (bodyText.includes(sp + '?.')) { hasValidation = true; break; }
      }
    }
 
    const fnLoc = getLineAndCharacter(sourceFile, node);
    const fnName = getFunctionName(node, sourceFile);
    inputSources.push({
      functionName: fnName,
      lineStart: fnLoc.lineStart,
      lineEnd: fnLoc.lineEnd,
      sourceParams,
      hasSinkInBody: sinkKinds.size > 0,
      sinkKinds: [...sinkKinds],
      hasValidation,
      callsWithInputArgs,
      paramConfidence: getParamConfidence(sourceParams),
    });
 
    ts.forEachChild(node, visitFn);
  };
  ts.forEachChild(sourceFile, visitFn);
 
  fileEntry.inputSources = inputSources;
}