@blundergoat/gruff-ts 0.4.0 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/CHANGELOG.md +123 -1
  2. package/CONTRIBUTING.md +32 -25
  3. package/README.md +55 -46
  4. package/SECURITY.md +18 -30
  5. package/UPGRADING.md +101 -0
  6. package/bin/gruff-ts +3 -0
  7. package/docs/README.md +11 -13
  8. package/docs/agent-hook.md +33 -24
  9. package/docs/ci-integration.md +38 -24
  10. package/docs/configuration.md +173 -71
  11. package/docs/dashboard.md +12 -13
  12. package/docs/output-formats.md +100 -25
  13. package/docs/philosophy.md +2 -2
  14. package/docs/reports-and-ci.md +14 -157
  15. package/docs/rules.md +140 -106
  16. package/package.json +10 -8
  17. package/src/analyser.ts +886 -282
  18. package/src/baseline-file.ts +867 -0
  19. package/src/baseline-identity.ts +463 -0
  20. package/src/baseline-options.ts +139 -34
  21. package/src/baseline.ts +85 -55
  22. package/src/blocks.ts +579 -364
  23. package/src/changed-regions.ts +414 -65
  24. package/src/check-ignore.ts +28 -13
  25. package/src/class-rules.ts +461 -302
  26. package/src/cli-program.ts +956 -166
  27. package/src/cli.ts +9 -2
  28. package/src/comment-rules.ts +277 -414
  29. package/src/comment-scanner.ts +363 -44
  30. package/src/complexity-metrics.ts +320 -0
  31. package/src/config-load-error.ts +17 -8
  32. package/src/config-parse.ts +291 -98
  33. package/src/config-preservation.ts +81 -26
  34. package/src/config.ts +778 -210
  35. package/src/constants.ts +7 -6
  36. package/src/context-doc-rules.ts +188 -61
  37. package/src/dashboard.ts +88 -23
  38. package/src/dead-code-rules.ts +153 -74
  39. package/src/discovery.ts +521 -148
  40. package/src/doc-rules.ts +592 -147
  41. package/src/duplicate-test-group-rules.ts +359 -0
  42. package/src/findings-helpers.ts +240 -89
  43. package/src/findings.ts +48 -24
  44. package/src/fixture-purpose-rules.ts +226 -48
  45. package/src/github-actions-event-guards.ts +331 -0
  46. package/src/github-actions-rules.ts +336 -106
  47. package/src/hook-contract.ts +708 -211
  48. package/src/init-config.ts +169 -114
  49. package/src/inline-suppressions.ts +340 -0
  50. package/src/limit-band.ts +56 -0
  51. package/src/line-rules.ts +331 -419
  52. package/src/migrate-config.ts +670 -0
  53. package/src/naming-pushers.ts +33 -107
  54. package/src/parsed-script.ts +1206 -0
  55. package/src/pillar-summary.ts +56 -40
  56. package/src/profiles.ts +97 -71
  57. package/src/project-config-rules.ts +335 -146
  58. package/src/project-rules.ts +237 -115
  59. package/src/public-exports.ts +284 -0
  60. package/src/report-html.ts +217 -85
  61. package/src/report-renderers.ts +864 -195
  62. package/src/rule-list.ts +166 -46
  63. package/src/rules.ts +100 -104
  64. package/src/safety-rules.ts +191 -132
  65. package/src/scoring.ts +255 -52
  66. package/src/security-flow-rules.ts +930 -109
  67. package/src/selectors.ts +169 -0
  68. package/src/sensitive-data-rules.ts +502 -375
  69. package/src/sensitive-exclusions.ts +435 -0
  70. package/src/source-text.ts +380 -148
  71. package/src/static-analysis-redundant-rules.ts +298 -41
  72. package/src/test-block-rules.ts +422 -228
  73. package/src/text-scans.ts +67 -9
  74. package/src/types.ts +222 -71
  75. package/tsconfig.json +2 -1
  76. package/src/process-exec-metadata.ts +0 -153
  77. package/src/test-fixtures.ts +0 -668
@@ -1,7 +1,10 @@
1
- // Conservative source-to-sink security candidates. These are deliberately same-line checks: they
2
- // report only when an external-input token is visibly inside a known risky sink expression.
1
+ // Finds candidate security issues in TypeScript and JavaScript during analysis.
2
+ //
3
+ // Uses written source and local assignments to connect inputs with calls worth reviewing.
4
+ // A finding points the developer to the code to inspect, with no need to run the scanned project.
3
5
  import type { SourceFile } from "./discovery.ts";
4
6
  import { makeFinding } from "./findings.ts";
7
+ import { parseScript } from "./parsed-script.ts";
5
8
  import type { Finding } from "./types.ts";
6
9
  import { createRequire } from "node:module";
7
10
 
@@ -14,28 +17,31 @@ const typescriptSyntax = require("typescript") as typeof import("typescript");
14
17
  type TsSourceFile = import("typescript").SourceFile;
15
18
  type TsNode = import("typescript").Node;
16
19
  type TsCallLikeExpression = import("typescript").CallExpression | import("typescript").NewExpression;
20
+ type TsNamedImportBindings = import("typescript").NamedImportBindings;
17
21
 
18
- // Parse a discovered script to a syntax-only AST; null on non-parseable input so
19
- // callers use the same-line scan. Parser exceptions recover to null as fallback.
22
+ /**
23
+ * Parse source text for a discovered file through the shared syntax-only parser; script parsing increments the shared parse count.
24
+ * Parser exceptions stay silent because full scans retain their separate same-line pass.
25
+ *
26
+ * @param file - discovered file passed to the shared script parser
27
+ * @param source - source text to parse into a syntax tree
28
+ * @returns An AST even with syntax diagnostics, or null to skip AST flow for non-script input or parser exceptions.
29
+ */
20
30
  function getSourceFile(file: SourceFile, source: string): TsSourceFile | null {
21
31
  try {
22
- return typescriptSyntax.createSourceFile(file.displayPath, source, typescriptSyntax.ScriptTarget.Latest, true, scriptKindFor(file.displayPath));
32
+ return parseScript(file, source)?.sourceFile ?? null;
23
33
  } catch {
24
34
  return null;
25
35
  }
26
36
  }
27
37
 
28
- // Maps file extensions to TypeScript parser script kind so JSX files parse with JSX grammar.
29
- function scriptKindFor(path: string) {
30
- if (path.endsWith(".tsx")) return typescriptSyntax.ScriptKind.TSX;
31
- if (path.endsWith(".jsx")) return typescriptSyntax.ScriptKind.JSX;
32
- if (path.endsWith(".js") || path.endsWith(".mjs") || path.endsWith(".cjs")) {
33
- return typescriptSyntax.ScriptKind.JS;
34
- }
35
- return typescriptSyntax.ScriptKind.TS;
36
- }
37
-
38
- // Depth-first walk; return false from visit to skip a node's children.
38
+ /**
39
+ * Walk the subtree rooted at a node depth-first, calling the visitor before its children.
40
+ *
41
+ * @param node - root AST node of the subtree to traverse
42
+ * @param visit - callback invoked for each visited node; returning false skips that node's children
43
+ * @returns Nothing. The visitor performs the work at each visited node.
44
+ */
39
45
  function walk(node: TsNode, visit: (node: TsNode) => boolean | void): void {
40
46
  if (visit(node) === false) {
41
47
  return;
@@ -45,7 +51,13 @@ function walk(node: TsNode, visit: (node: TsNode) => boolean | void): void {
45
51
  });
46
52
  }
47
53
 
48
- // Zero-based start line of a node, for aligning with 1-based finding lines.
54
+ /**
55
+ * Compute a node's zero-based start line so callers can convert it to a one-based finding line.
56
+ *
57
+ * @param parsedSource - parsed syntax tree that owns the node's character offsets
58
+ * @param node - AST node whose start position is mapped to a line index
59
+ * @returns Zero-based start line of node within parsedSource.
60
+ */
49
61
  function lineIndexOf(parsedSource: TsSourceFile, node: TsNode): number {
50
62
  return parsedSource.getLineAndCharacterOfPosition(node.getStart(parsedSource)).line;
51
63
  }
@@ -56,6 +68,9 @@ interface SourceToken {
56
68
  pattern: RegExp;
57
69
  }
58
70
 
71
+ // Each imported reader records function scopes whose hoisted locals hide its import.
72
+ type FileReadBindings = ReadonlyMap<string, ReadonlySet<TsNode>>;
73
+
59
74
  // One source-to-sink heuristic: a risky call pattern plus the remediation attached to its finding.
60
75
  interface SecurityFlowRule {
61
76
  ruleId: string;
@@ -72,6 +87,10 @@ const SOURCE_TOKENS: readonly SourceToken[] = [
72
87
  { kind: "browser-location", pattern: /\blocation\.search\b|\bURLSearchParams\s*\(\s*location\.search\b/ },
73
88
  ];
74
89
 
90
+ // The receivers the request source token reads. A nested function declaring one as its own parameter is a handler
91
+ // whose request is its own argument, so `textOutsideRequestHandlers` blanks its reads of that name.
92
+ const REQUEST_RECEIVER_NAMES: ReadonlySet<string> = new Set(["req", "request", "ctx"]);
93
+
75
94
  const SECURITY_FLOW_RULES: readonly SecurityFlowRule[] = [
76
95
  {
77
96
  ruleId: "security.path-traversal-candidate",
@@ -92,7 +111,7 @@ const SECURITY_FLOW_RULES: readonly SecurityFlowRule[] = [
92
111
  message: "External input reaches a redirect or browser navigation sink.",
93
112
  sinkKind: "redirect",
94
113
  remediation: "Redirect only to relative paths or destinations from an allowlist.",
95
- callPattern: /\b(?:(?:res|reply|response)\.redirect|redirect|(?:location|window\.location)\.(?:assign|replace))\s*\(|\b(?:location|window\.location)\.href\s*=/g,
114
+ callPattern: /\b(?:(?:res|reply|response)\.redirect|(?:location|window\.location)\.(?:assign|replace))\s*\(|\b(?:location|window\.location)\.href\s*=/g,
96
115
  },
97
116
  {
98
117
  ruleId: "security.dynamic-regexp",
@@ -103,7 +122,18 @@ const SECURITY_FLOW_RULES: readonly SecurityFlowRule[] = [
103
122
  },
104
123
  ];
105
124
 
106
- // Same-line matching is intentional: reports stable candidate findings without implying full taint analysis.
125
+ /**
126
+ * Scan one source line for same-line external-input-to-sink matches.
127
+ *
128
+ * Same-line matching is intentional: reports stable candidate findings without implying full taint analysis.
129
+ * Shared sink matchers reset only when a recognized source token is found.
130
+ *
131
+ * @param file - discovered file whose display path anchors emitted findings
132
+ * @param codeLine - single source line checked for the first catalogue source pattern and matching sink calls
133
+ * @param lineNumber - one-based line number assigned to appended findings
134
+ * @param findings - accumulator that receives matching candidate findings
135
+ * @returns Nothing. Appends to findings at lineNumber in file for matching sinks, leaving matchers and findings untouched if no source matches.
136
+ */
107
137
  export function analyseSecurityFlowLine(file: SourceFile, codeLine: string, lineNumber: number, findings: Finding[]): void {
108
138
  const source = sourceToken(codeLine);
109
139
  if (!source) {
@@ -116,12 +146,25 @@ export function analyseSecurityFlowLine(file: SourceFile, codeLine: string, line
116
146
  }
117
147
  }
118
148
 
119
- // Returns the first visible external-input token so emitted metadata stays deterministic.
149
+ /**
150
+ * Match a source line against SOURCE_TOKENS in catalogue order for deterministic metadata.
151
+ *
152
+ * @param codeLine - single source line checked for recognized external-input tokens
153
+ * @returns The first matching SOURCE_TOKENS entry, or undefined when the line contains no recognized external-input token.
154
+ */
120
155
  function sourceToken(codeLine: string): SourceToken | undefined {
121
156
  return SOURCE_TOKENS.find((source) => source.pattern.test(codeLine));
122
157
  }
123
158
 
124
- // Confirms the external-input token appears inside the same bounded sink call segment.
159
+ /**
160
+ * Check whether a bounded sink call segment contains external-input evidence.
161
+ * Resets callPattern.lastIndex to zero; testing a global or sticky sourcePattern can also advance or reset its lastIndex.
162
+ *
163
+ * @param codeLine - single source line searched for sink calls
164
+ * @param sourcePattern - external-input pattern tested against each bounded call segment
165
+ * @param callPattern - sink matcher that must have the global flag to enumerate call sites
166
+ * @returns True if sourcePattern matches a bounded call segment selected by callPattern, or false when no segment contains source evidence.
167
+ */
125
168
  function sourceAppearsInSink(codeLine: string, sourcePattern: RegExp, callPattern: RegExp): boolean {
126
169
  callPattern.lastIndex = 0;
127
170
  for (const call of codeLine.matchAll(callPattern)) {
@@ -133,16 +176,31 @@ function sourceAppearsInSink(codeLine: string, sourcePattern: RegExp, callPatter
133
176
  return false;
134
177
  }
135
178
 
136
- // Keeps matching on one visible call because multiline dataflow is deliberately out of scope.
179
+ /**
180
+ * Extract a bounded source slice from a sink call start for same-line sink matching.
181
+ * Stops at the first closing parenthesis or 240 characters.
182
+ *
183
+ * @param codeLine - single source line containing the candidate sink call
184
+ * @param callStart - zero-based start offset of the call match within codeLine
185
+ * @returns Bounded slice from callStart up to the first closing parenthesis, or up to 240 characters if none occurs.
186
+ */
137
187
  function singleLineCallSegment(codeLine: string, callStart: number): string {
138
- // maxSegmentLength limit: 240 chars covers normal calls while avoiding later same-line matches.
188
+ // Cap the text inspected per candidate call; this is a bounded heuristic, not balanced-parenthesis parsing.
139
189
  const maxSegmentLength = 240;
140
190
  const segment = codeLine.slice(callStart, callStart + maxSegmentLength);
141
191
  const close = segment.indexOf(")");
142
192
  return close === -1 ? segment : segment.slice(0, close + 1);
143
193
  }
144
194
 
145
- // Stable finding contract for source-to-sink rules: medium confidence plus source/sink metadata only.
195
+ /**
196
+ * Build a warning finding with a stable finding contract: medium confidence and metadata containing sourceKind and the rule's sink kind.
197
+ *
198
+ * @param file - discovered file whose display path locates the finding
199
+ * @param line - one-based line number of the candidate sink
200
+ * @param rule - rule definition supplying the finding's id, message, remediation, and sink kind
201
+ * @param sourceKind - external-input category recorded in finding metadata
202
+ * @returns A medium-confidence security warning at the supplied file and line.
203
+ */
146
204
  function securityFlowFinding(file: SourceFile, line: number, rule: SecurityFlowRule, sourceKind: string): Finding {
147
205
  return makeFinding({
148
206
  ruleId: rule.ruleId,
@@ -158,11 +216,9 @@ function securityFlowFinding(file: SourceFile, line: number, rule: SecurityFlowR
158
216
  }
159
217
 
160
218
  // --- Bounded intra-function AST flow (ADR-012) -------------------------
161
- // Augments the same-line checks above: detects an external-input value assigned
162
- // to a local variable and later passed (across lines, within one function) to a
163
- // known sink. The same-line pass above is untouched, so its findings and
164
- // fingerprints are unchanged; this pass only adds genuinely cross-line cases and
165
- // skips any flow whose source and sink share a line.
219
+ //
220
+ // Augments the same-line checks above by tracking local variables assigned from external input to sinks across lines within one function.
221
+ // Same-line flows remain owned by the line pass so existing fingerprints never move; this pass adds cross-line flows and AST-only sinks.
166
222
 
167
223
  // One tainted local: the 0-based line of the originating external source, the
168
224
  // source kind for metadata, and how many alias hops removed it is (cap below).
@@ -172,6 +228,13 @@ interface TaintRecord {
172
228
  depth: number;
173
229
  }
174
230
 
231
+ // Deserialization needs content provenance while the other sinks still inspect path influence.
232
+ interface FlowInputs {
233
+ tainted: Map<string, TaintRecord>;
234
+ contentTainted: Map<string, TaintRecord>;
235
+ fileReadCallees: FileReadBindings;
236
+ }
237
+
175
238
  // Bundles the syntax context each sink matcher needs so all text extraction remains anchored
176
239
  // to the parsed source file instead of raw substrings.
177
240
  interface AstSinkInput {
@@ -179,6 +242,7 @@ interface AstSinkInput {
179
242
  call: TsCallLikeExpression;
180
243
  sourceFile: TsSourceFile;
181
244
  unsafeXmlParsers: ReadonlySet<string>;
245
+ isFrameworkRedirectCallee: boolean;
182
246
  }
183
247
 
184
248
  // Describes one AST sink candidate. Some AST-only rules report same-line direct-source
@@ -213,10 +277,10 @@ const AST_FLOW_SINKS: readonly AstFlowSink[] = [
213
277
  {
214
278
  ruleId: "security.open-redirect-candidate",
215
279
  sinkKind: "redirect",
216
- isSink: ({ callee }) =>
280
+ isSink: ({ callee, isFrameworkRedirectCallee }) =>
217
281
  /^(?:res|reply|response)\.redirect$/.test(callee) ||
218
- /^redirect$/.test(callee) ||
219
- /^(?:location|window\.location)\.(?:assign|replace)$/.test(callee),
282
+ /^(?:location|window\.location)\.(?:assign|replace)$/.test(callee) ||
283
+ isFrameworkRedirectCallee,
220
284
  },
221
285
  {
222
286
  ruleId: "security.dynamic-regexp",
@@ -241,33 +305,333 @@ const MAX_ALIAS_DEPTH = 2;
241
305
  const MAX_SCOPE_NODES = 4000;
242
306
 
243
307
  /**
244
- * Per-file AST pass. Parses the file once (syntax-only) and reports cross-line
245
- * source-to-sink flows for the existing security-flow rule ids. Does nothing
246
- * when the file cannot be parsed, so the same-line scan remains the fallback.
308
+ * Collect runtime filesystem-reader names imported from fs, node:fs, and their promises modules (promises support readFile only).
309
+ * Only these imports establish the filename/content boundary; unrelated helpers retain ordinary taint.
310
+ *
311
+ * @param parsedSource - parsed syntax tree whose top-level imports are inspected
312
+ * @returns Set of imported reader callees including default/namespace member paths and named local aliases, or an empty set if none qualify.
313
+ */
314
+ function importedFileReadCallees(parsedSource: TsSourceFile): ReadonlySet<string> {
315
+ const callees = new Set<string>();
316
+ for (const statement of parsedSource.statements) {
317
+ if (!typescriptSyntax.isImportDeclaration(statement) || !typescriptSyntax.isStringLiteral(statement.moduleSpecifier)) continue;
318
+ const moduleName = statement.moduleSpecifier.text;
319
+ if (!/^(?:node:)?fs(?:\/promises)?$/.test(moduleName)) continue;
320
+ const clause = statement.importClause;
321
+ if (!clause || clause.isTypeOnly) continue;
322
+ const methods = moduleName.endsWith("/promises") ? ["readFile"] : ["readFile", "readFileSync"];
323
+ for (const name of fileReadBindingNames(clause, methods)) callees.add(name);
324
+ }
325
+ return callees;
326
+ }
327
+
328
+ /**
329
+ * Extract callable reader names exposed by a non-type-only import clause for the requested methods.
330
+ * Skips named type-only imports; the caller must exclude whole type-only import clauses.
331
+ *
332
+ * @param clause - import clause whose default, namespace, and named bindings are inspected
333
+ * @param methods - filesystem reader method names allowed for the imported module
334
+ * @returns Default/namespace member paths and matching named local aliases, or an empty array if none match.
335
+ */
336
+ function fileReadBindingNames(clause: import("typescript").ImportClause, methods: readonly string[]): string[] {
337
+ const names: string[] = [];
338
+ if (clause.name) for (const method of methods) names.push(`${clause.name.text}.${method}`);
339
+ const bindings = clause.namedBindings;
340
+ if (!bindings) return names;
341
+ if (typescriptSyntax.isNamespaceImport(bindings)) {
342
+ for (const method of methods) names.push(`${bindings.name.text}.${method}`);
343
+ } else {
344
+ for (const binding of bindings.elements) {
345
+ if (!binding.isTypeOnly && methods.includes(binding.propertyName?.text ?? binding.name.text)) names.push(binding.name.text);
346
+ }
347
+ }
348
+ return names;
349
+ }
350
+
351
+ /**
352
+ * Normalizes a simple identifier or dotted property chain (such as `fs . readFileSync`) into compact `a.b` text without whitespace or comments.
353
+ *
354
+ * @param expr - AST expression inspected as an identifier or chain of property accesses
355
+ * @returns Compact dotted name when `expr` is an identifier or property-access chain, or undefined for other expression shapes.
356
+ */
357
+ function dottedIdentifierPath(expr: TsNode): string | undefined {
358
+ if (typescriptSyntax.isParenthesizedExpression(expr)) {
359
+ return dottedIdentifierPath(expr.expression);
360
+ }
361
+ if (typescriptSyntax.isIdentifier(expr)) {
362
+ return expr.text;
363
+ }
364
+ if (typescriptSyntax.isPropertyAccessExpression(expr)) {
365
+ const receiver = dottedIdentifierPath(expr.expression);
366
+ return receiver === undefined ? undefined : `${receiver}.${expr.name.text}`;
367
+ }
368
+ return undefined;
369
+ }
370
+
371
+ /**
372
+ * Check whether an AST node is an unshadowed call to an imported filesystem reader.
373
+ * Returning false leaves the expression eligible for content taint.
374
+ *
375
+ * @param node - AST node tested as a call expression
376
+ * @param parsedSource - parsed syntax tree used to extract the callee text
377
+ * @param bindings - imported-reader names and their hoisted shadowing scopes
378
+ * @returns True if node is a call whose normalized callee belongs to bindings with no visible reader shadowing; otherwise false.
379
+ */
380
+ function isImportedFileRead(node: TsNode, parsedSource: TsSourceFile, bindings: FileReadBindings): boolean {
381
+ if (!typescriptSyntax.isCallExpression(node)) return false;
382
+ const callee = dottedIdentifierPath(node.expression) ?? node.expression.getText(parsedSource);
383
+ return bindings.has(callee) && !isFileReadBindingShadowed(node, callee, bindings);
384
+ }
385
+
386
+ /**
387
+ * Build reader exemptions from imports in parsedSource and drop exemptions for unshadowed assignments to tracked reader members
388
+ * so that replacement methods remain eligible for content taint.
389
+ *
390
+ * A module too large to walk drops every exemption, so file reads stay reported.
391
+ * A function or static block too large to walk loses the exemptions inside it; a reader assigned there loses its exemption everywhere.
392
+ *
393
+ * @param parsedSource - parsed syntax tree providing imports and assignment target text
394
+ * @param scopes - function, module, and static-block scope roots scanned for hoisted shadowing and member writes
395
+ * @returns Map of reader names to shadowing scopes, or an empty map when no readers exist or the module root exceeds the node budget.
396
+ */
397
+ function fileReadBindingsForScopes(parsedSource: TsSourceFile, scopes: readonly TsNode[]): FileReadBindings {
398
+ const bindings = new Map([...importedFileReadCallees(parsedSource)].map((callee) => [callee, new Set<TsNode>()]));
399
+ if (bindings.size === 0) return bindings;
400
+ const writes: TsNode[] = [];
401
+ const exhaustedScopes: TsNode[] = [];
402
+ for (const scope of scopes) {
403
+ // A scope too large to walk fully cannot prove that a file reader was left untouched.
404
+ if (!indexFileReadScope(scope, bindings, writes)) {
405
+ // Module-level exhaustion can hide top-level hoisting or reassignment that affects every scope, so fail closed globally.
406
+ if (scope === parsedSource) {
407
+ return new Map();
408
+ }
409
+ exhaustedScopes.push(scope);
410
+ }
411
+ }
412
+ for (const write of writes) {
413
+ const callee = writtenFileReadCallee(write, parsedSource);
414
+ if (callee && bindings.has(callee) && !isFileReadBindingShadowed(write, callee, bindings)) bindings.delete(callee);
415
+ }
416
+ // Scope-local exhaustion fails closed for that scope and drops any member reader whose text matches an assignment in the exhausted body.
417
+ for (const exhaustedScope of exhaustedScopes) {
418
+ dropExhaustedScopeWrittenCallees(exhaustedScope.getText(parsedSource), bindings);
419
+ // Treat the oversized scope as shadowing every reader, so reads inside it lose the exemption and can still be reported.
420
+ for (const shadowedScopes of bindings.values()) {
421
+ shadowedScopes.add(exhaustedScope);
422
+ }
423
+ }
424
+ return bindings;
425
+ }
426
+
427
+ /**
428
+ * Drops tracked member-reader bindings globally when an exhausted scope's source text appears to assign to that member.
429
+ * Mutates `bindings` in place so an unwalked tail beyond `MAX_SCOPE_NODES` cannot monkey-patch a reader while leaving sibling exemptions active.
430
+ *
431
+ * @param scopeText - source text of a function or static-block scope that exceeded `MAX_SCOPE_NODES`
432
+ * @param bindings - mutable reader-binding map whose member entries are removed on assignment matches
433
+ * @returns Nothing. Deletes matching member callees from `bindings` in place.
434
+ */
435
+ function dropExhaustedScopeWrittenCallees(scopeText: string, bindings: Map<string, Set<TsNode>>): void {
436
+ // Check each tracked reader, such as `fs.readFileSync`, for an assignment in the oversized scope.
437
+ for (const callee of [...bindings.keys()]) {
438
+ const dotIndex = callee.indexOf(".");
439
+ // A bare imported name cannot be replaced through a member write, so only `module.method` readers are checked.
440
+ if (dotIndex === -1) {
441
+ continue;
442
+ }
443
+ const rootPattern = escapeRegExpLiteral(callee.slice(0, dotIndex));
444
+ const methodPattern = escapeRegExpLiteral(callee.slice(dotIndex + 1));
445
+ const memberWritePattern = new RegExp(
446
+ `(?<![\\w$])${rootPattern}\\s*(?:\\.\\s*${methodPattern}(?![\\w$])|\\[\\s*["']${methodPattern}["']\\s*\\])\\s*(?:\\?\\?|&&|\\|\\||\\*\\*|<<|>>>?|[+\\-*/%&|^])?=(?!=)`,
447
+ );
448
+ // Text such as `fs.readFileSync = fake` in the unwalked scope may replace the reader, so its exemption is dropped everywhere.
449
+ if (memberWritePattern.test(scopeText)) {
450
+ bindings.delete(callee);
451
+ }
452
+ }
453
+ }
454
+
455
+ /**
456
+ * Escapes regular-expression metacharacters in an identifier segment before interpolating it into a pattern.
457
+ * Identifiers may start with `$`, so callers bound matches with `(?<![\w$])` rather than `\b`.
458
+ *
459
+ * @param literalText - raw identifier text such as `fs` or `$fs`
460
+ * @returns Escaped string safe for literal matching inside `RegExp`.
461
+ */
462
+ function escapeRegExpLiteral(literalText: string): string {
463
+ return literalText.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
464
+ }
465
+
466
+ /**
467
+ * Scan a scope for hoisted reader shadowing and assignment targets while skipping nested functions and static blocks.
468
+ * Mutates both bindings and writes in place.
469
+ *
470
+ * @param scope - root AST node of the scope to scan up to MAX_SCOPE_NODES
471
+ * @param bindings - mutable map from reader names to shadowing scopes updated with hoisted var declarations
472
+ * @param writes - mutable list receiving assignment left-hand targets for replacement checks
473
+ * @returns True when the scan completes within the node budget, or false on exhaustion leaving partial records to discard.
474
+ */
475
+ function indexFileReadScope(scope: TsNode, bindings: Map<string, Set<TsNode>>, writes: TsNode[]): boolean {
476
+ let budget = MAX_SCOPE_NODES;
477
+ walk(scope, (node) => {
478
+ if (budget-- <= 0) return false;
479
+ if ((isFunctionLike(node) || typescriptSyntax.isClassStaticBlockDeclaration(node)) && node !== scope) return false;
480
+ recordHoistedFileReadBindings(node, scope, bindings);
481
+ if (typescriptSyntax.isBinaryExpression(node) && node.operatorToken.kind >= typescriptSyntax.SyntaxKind.FirstAssignment && node.operatorToken.kind <= typescriptSyntax.SyntaxKind.LastAssignment) {
482
+ writes.push(node.left);
483
+ }
484
+ return;
485
+ });
486
+ return budget >= 0;
487
+ }
488
+
489
+ /**
490
+ * Record hoisted var declarations that shadow an imported reader root name in the enclosing scope.
491
+ * Block-scoped let/const declarations and non-declaration nodes leave bindings unchanged.
492
+ *
493
+ * @param node - AST node inspected as a non-block-scoped variable declaration list
494
+ * @param scope - enclosing scope boundary recorded when a reader root name matches
495
+ * @param bindings - mutable reader-to-scope sets updated in place for matching reader root names
496
+ * @returns Nothing. Adds scope to matching entries in bindings when a var declaration binds a reader root name.
497
+ */
498
+ function recordHoistedFileReadBindings(node: TsNode, scope: TsNode, bindings: Map<string, Set<TsNode>>): void {
499
+ if (!typescriptSyntax.isVariableDeclarationList(node) || (node.flags & typescriptSyntax.NodeFlags.BlockScoped)) return;
500
+ for (const [callee, shadowedScopes] of bindings) {
501
+ if (variableDeclarationListBindsName(node, callee.split(".", 1)[0] ?? "")) shadowedScopes.add(scope);
502
+ }
503
+ }
504
+
505
+ /**
506
+ * Normalize an assignment target to a reader call spelling, unwrapping parentheses and string-literal element access.
507
+ *
508
+ * @param node - assignment left-hand AST node to normalize
509
+ * @param parsedSource - parsed syntax tree used to read expression text
510
+ * @returns Dotted property text for property or string-literal element access, or undefined for other target shapes.
511
+ */
512
+ function writtenFileReadCallee(node: TsNode, parsedSource: TsSourceFile): string | undefined {
513
+ if (typescriptSyntax.isParenthesizedExpression(node)) return writtenFileReadCallee(node.expression, parsedSource);
514
+ // Normalize property access so `fs . readFileSync = ...` invalidates the `fs.readFileSync` reader binding reliably.
515
+ if (typescriptSyntax.isPropertyAccessExpression(node)) return dottedIdentifierPath(node) ?? node.getText(parsedSource);
516
+ if (typescriptSyntax.isElementAccessExpression(node) && typescriptSyntax.isStringLiteral(node.argumentExpression)) {
517
+ const receiver = dottedIdentifierPath(node.expression) ?? node.expression.getText(parsedSource);
518
+ return `${receiver}.${node.argumentExpression.text}`;
519
+ }
520
+ return undefined;
521
+ }
522
+
523
+ /**
524
+ * Check whether an imported reader call is hidden by a lexical binding, a hoisted shadowing scope, or a named class expression.
525
+ * These extra guards apply only to reader exemptions; redirect matching uses the common lexical checks.
526
+ *
527
+ * @param node - AST call or write site where the imported reader appears
528
+ * @param callee - imported reader call spelling whose root identifier is checked
529
+ * @param bindings - hoisted shadowing scopes per reader name; a missing entry adds no hoisted evidence
530
+ * @returns True if callee is shadowed at node by lexical bindings, recorded scopes, or a named class expression; otherwise false.
531
+ */
532
+ function isFileReadBindingShadowed(node: TsNode, callee: string, bindings: FileReadBindings): boolean {
533
+ if (isImportedCalleeShadowed(node, callee)) return true;
534
+ const shadowedScopes = bindings.get(callee);
535
+ const rootName = callee.split(".", 1)[0];
536
+ for (let ancestor = node.parent; ancestor; ancestor = ancestor.parent) {
537
+ if (shadowedScopes?.has(ancestor)) return true;
538
+ if (typescriptSyntax.isClassExpression(ancestor) && ancestor.name?.text === rootName) return true;
539
+ }
540
+ return false;
541
+ }
542
+
543
+ /**
544
+ * Collect local redirect call names imported from supported framework packages, ignoring unrelated and type-only bindings.
545
+ *
546
+ * @param parsedSource - parsed syntax tree whose top-level imports are inspected
547
+ * @returns Set of local redirect aliases from named imports and member paths from namespace imports, or an empty set if none match.
548
+ */
549
+ function importedFrameworkRedirectCallees(parsedSource: TsSourceFile): ReadonlySet<string> {
550
+ const callees = new Set<string>();
551
+ for (const statement of parsedSource.statements) {
552
+ if (!typescriptSyntax.isImportDeclaration(statement) || !typescriptSyntax.isStringLiteral(statement.moduleSpecifier)) {
553
+ continue;
554
+ }
555
+ if (!isFrameworkRedirectModule(statement.moduleSpecifier.text)) {
556
+ continue;
557
+ }
558
+ const importClause = statement.importClause;
559
+ if (!importClause || importClause.isTypeOnly || !importClause.namedBindings) {
560
+ continue;
561
+ }
562
+ collectRedirectAliases(importClause.namedBindings, callees);
563
+ }
564
+ return callees;
565
+ }
566
+
567
+ /**
568
+ * Check whether a module specifier belongs to the supported framework redirect allowlist to exclude unrelated redirect helpers.
569
+ * Recognizes next/navigation, React Router's core and DOM packages, and supported Remix runtime packages.
570
+ *
571
+ * @param moduleName - import-source module specifier text
572
+ * @returns True if moduleName matches the framework redirect allowlist; otherwise false.
573
+ */
574
+ function isFrameworkRedirectModule(moduleName: string): boolean {
575
+ return moduleName === "next/navigation" ||
576
+ /^react-router(?:-dom)?$/.test(moduleName) ||
577
+ /^@remix-run\/(?:node|cloudflare|deno|server-runtime)$/.test(moduleName);
578
+ }
579
+
580
+ /**
581
+ * Record the local alias each binding style gives the framework redirect export, skipping named specifiers marked type-only.
582
+ *
583
+ * @param namedBindings - namespace or named import bindings from a framework redirect import
584
+ * @param callees - mutable set receiving the namespace member path or renamed local redirect names
585
+ * @returns Nothing. Adds redirect aliases from namedBindings to callees in place.
586
+ */
587
+ function collectRedirectAliases(namedBindings: TsNamedImportBindings, callees: Set<string>): void {
588
+ if (typescriptSyntax.isNamespaceImport(namedBindings)) {
589
+ callees.add(`${namedBindings.name.text}.redirect`);
590
+ return;
591
+ }
592
+ for (const element of namedBindings.elements) {
593
+ const importedName = element.propertyName?.text ?? element.name.text;
594
+ if (!element.isTypeOnly && importedName === "redirect") {
595
+ callees.add(element.name.text);
596
+ }
597
+ }
598
+ }
599
+
600
+ /**
601
+ * Collect syntax-only source-to-sink findings. A local script parse increments the shared parse count.
602
+ * An unavailable parse or failed traversal leaves findings unchanged; full scans retain the separate same-line pass.
247
603
  * Invariant: this pass never uses TypeScript type-checking, emit, or schema changes.
248
604
  *
249
605
  * @param file - discovered script file whose display path anchors emitted fingerprints
250
606
  * @param source - full source text to parse with syntax-only TypeScript APIs
251
607
  * @param findings - accumulator that receives additional AST flow findings
608
+ * @param sharedSourceFile - the run's shared parse result. Null or undefined triggers a local parse.
609
+ * @returns Nothing. Appends AST flow findings after a successful traversal.
252
610
  */
253
- export function analyseSecurityFlow(file: SourceFile, source: string, findings: Finding[]): void {
254
- const parsedSource = getSourceFile(file, source);
611
+ export function analyseSecurityFlow(file: SourceFile, source: string, findings: Finding[], sharedSourceFile?: TsSourceFile | null): void {
612
+ // Reuse the run's AST when available to avoid parsing and counting the script twice.
613
+ const parsedSource = sharedSourceFile ?? getSourceFile(file, source);
255
614
  if (!parsedSource) {
256
615
  return;
257
616
  }
258
- // Collect into a local buffer so an error-recovery tree (where node.getText or
259
- // node.getStart can throw) degrades to "no AST findings" without leaking a
260
- // partial result. The same-line scan remains the fallback for such files.
617
+ // Recovery-tree text or position access can throw, so publish the local buffer only after traversal succeeds.
618
+ // This optional pass reports security evidence; recovery failures add no reliable evidence, so they stay silent.
619
+ // Discarding the buffer avoids partial results, while full scans retain separate same-line candidates.
261
620
  const flowFindings: Finding[] = [];
262
621
  try {
622
+ const frameworkRedirectCallees = importedFrameworkRedirectCallees(parsedSource);
263
623
  const scopes: TsNode[] = [parsedSource];
624
+ const staticBlocks: TsNode[] = [];
264
625
  walk(parsedSource, (node) => {
265
626
  if (isFunctionLike(node)) {
266
627
  scopes.push(node);
628
+ } else if (typescriptSyntax.isClassStaticBlockDeclaration(node)) {
629
+ staticBlocks.push(node);
267
630
  }
268
631
  });
632
+ const fileReadCallees = fileReadBindingsForScopes(parsedSource, [...scopes, ...staticBlocks]);
269
633
  for (const scope of scopes) {
270
- analyseFlowScope(parsedSource, scope, file, flowFindings);
634
+ analyseFlowScope(parsedSource, scope, frameworkRedirectCallees, fileReadCallees, file, flowFindings);
271
635
  }
272
636
  } catch {
273
637
  return;
@@ -279,15 +643,28 @@ export function analyseSecurityFlow(file: SourceFile, source: string, findings:
279
643
 
280
644
  /**
281
645
  * Walk one function or the module top level and record bounded local taint evidence.
282
- * Invariant: nested functions are pruned so captured variables never imply inter-procedural flow.
646
+ * Invariant: each scope starts with fresh taint maps and its walk skips nested functions, so nested-function sinks never see outer tainted locals.
647
+ * When the node budget runs out, the rest of the scope contributes no findings.
283
648
  *
284
649
  * @param parsedSource - syntax tree that owns positions and text extraction
285
650
  * @param scopeOwner - top-level source file or function-like node to scan
651
+ * @param frameworkRedirectCallees - local names of framework redirect functions this file imports; an unshadowed call to one is a redirect sink
652
+ * @param fileReadCallees - imported file readers and the scopes shadowing each; an unshadowed read keeps a tainted filename out of content taint
286
653
  * @param file - discovered file used for stable finding locations
287
654
  * @param findings - accumulator that receives sink findings for this scope
655
+ * @returns - Nothing. Appends the scope's sink findings to the supplied accumulator.
288
656
  */
289
- function analyseFlowScope(parsedSource: TsSourceFile, scopeOwner: TsNode, file: SourceFile, findings: Finding[]): void {
657
+ function analyseFlowScope(
658
+ parsedSource: TsSourceFile,
659
+ scopeOwner: TsNode,
660
+ frameworkRedirectCallees: ReadonlySet<string>,
661
+ fileReadCallees: FileReadBindings,
662
+ file: SourceFile,
663
+ findings: Finding[],
664
+ ): void {
290
665
  const tainted = new Map<string, TaintRecord>();
666
+ const contentTainted = new Map<string, TaintRecord>();
667
+ const inputs = { tainted, contentTainted, fileReadCallees };
291
668
  const unsafeXmlParsers = new Set<string>();
292
669
  let budget = MAX_SCOPE_NODES;
293
670
  walk(scopeOwner, (node) => {
@@ -300,22 +677,29 @@ function analyseFlowScope(parsedSource: TsSourceFile, scopeOwner: TsNode, file:
300
677
  }
301
678
  recordUnsafeXmlParser(parsedSource, node, unsafeXmlParsers);
302
679
  recordTaint(parsedSource, node, tainted);
303
- reportSink(parsedSource, node, tainted, unsafeXmlParsers, file, findings);
680
+ recordTaint(parsedSource, node, contentTainted, fileReadCallees);
681
+ reportSink(parsedSource, node, inputs, unsafeXmlParsers, frameworkRedirectCallees, file, findings);
304
682
  return;
305
683
  });
306
684
  }
307
685
 
308
- // Marks a local tainted when it is initialised directly from an external source,
309
- // or one hop from another tainted local (`const alias = tainted`), bounded by
310
- // MAX_ALIAS_DEPTH. Function-valued initialisers are skipped so a source token
311
- // inside a callback body never taints the function variable itself.
312
- function recordTaint(parsedSource: TsSourceFile, node: TsNode, tainted: Map<string, TaintRecord>): void {
686
+ /**
687
+ * Update local provenance for variable declarations or identifier assignments, clearing an assignment's entry when its new value has no source.
688
+ * Function initializers add no record; without fileReads, alias lookup uses bare identifiers instead of compound expressions.
689
+ *
690
+ * @param parsedSource - parsed syntax tree used for expression text and line positions
691
+ * @param node - AST node inspected as a variable declaration or simple identifier assignment
692
+ * @param tainted - mutable map of local variable names to source provenance records
693
+ * @param fileReads - optional reader bindings that mask proven reader calls and enable depth-bounded compound alias lookup
694
+ * @returns Nothing. Updates tainted in place for declarations and identifier assignments.
695
+ */
696
+ function recordTaint(parsedSource: TsSourceFile, node: TsNode, tainted: Map<string, TaintRecord>, fileReads?: FileReadBindings): void {
313
697
  if (typescriptSyntax.isVariableDeclaration(node)) {
314
- recordVariableTaint(parsedSource, node, tainted);
698
+ recordVariableTaint(parsedSource, node, tainted, fileReads);
315
699
  return;
316
700
  }
317
701
  if (typescriptSyntax.isBinaryExpression(node) && node.operatorToken.kind === typescriptSyntax.SyntaxKind.EqualsToken && typescriptSyntax.isIdentifier(node.left)) {
318
- const nextRecord = taintRecordFromExpression(parsedSource, node.right, tainted);
702
+ const nextRecord = taintRecordFromExpression(parsedSource, node.right, tainted, fileReads);
319
703
  if (nextRecord) {
320
704
  tainted.set(node.left.text, nextRecord);
321
705
  } else {
@@ -324,13 +708,21 @@ function recordTaint(parsedSource: TsSourceFile, node: TsNode, tainted: Map<stri
324
708
  }
325
709
  }
326
710
 
327
- // Records taint introduced by declarations, including simple object/array destructuring from
328
- // external-input expressions. Non-identifier binding details are intentionally skipped.
329
- function recordVariableTaint(parsedSource: TsSourceFile, node: import("typescript").VariableDeclaration, tainted: Map<string, TaintRecord>): void {
711
+ /**
712
+ * Record source provenance from a variable declaration's initializer for each bound identifier, including nested destructuring.
713
+ * Missing initializers or untainted values leave existing entries unchanged; destructured names share one record regardless of keys or defaults.
714
+ *
715
+ * @param parsedSource - parsed syntax tree used to inspect the initializer and compute source lines
716
+ * @param node - variable declaration whose initializer and binding pattern are analysed
717
+ * @param tainted - mutable map of local provenance updated in place
718
+ * @param fileReads - optional reader bindings that mask proven reader calls and enable compound alias lookup
719
+ * @returns Nothing. Writes provenance entries into tainted for each identifier bound by node.
720
+ */
721
+ function recordVariableTaint(parsedSource: TsSourceFile, node: import("typescript").VariableDeclaration, tainted: Map<string, TaintRecord>, fileReads?: FileReadBindings): void {
330
722
  if (!node.initializer) {
331
723
  return;
332
724
  }
333
- const record = taintRecordFromExpression(parsedSource, node.initializer, tainted);
725
+ const record = taintRecordFromExpression(parsedSource, node.initializer, tainted, fileReads);
334
726
  if (!record) {
335
727
  return;
336
728
  }
@@ -341,26 +733,41 @@ function recordVariableTaint(parsedSource: TsSourceFile, node: import("typescrip
341
733
  taintBindingNames(node.name, record, tainted);
342
734
  }
343
735
 
344
- // Derives the bounded taint record for one expression and keeps alias depth deterministic.
345
- function taintRecordFromExpression(parsedSource: TsSourceFile, expression: TsNode, tainted: Map<string, TaintRecord>): TaintRecord | undefined {
736
+ /**
737
+ * Derive provenance for an expression from direct sources or bounded aliases, incrementing depth on successful alias propagation.
738
+ *
739
+ * @param parsedSource - parsed syntax tree used to classify direct sources and extract text
740
+ * @param expression - initializer or right-hand expression evaluated for provenance
741
+ * @param tainted - existing local provenance records consulted for identifier or compound aliases
742
+ * @param fileReads - optional reader bindings that mask reader calls and enable compound-value alias searches
743
+ * @returns Direct record at depth 1, incremented alias record below MAX_ALIAS_DEPTH, or undefined when ineligible including function values.
744
+ */
745
+ function taintRecordFromExpression(parsedSource: TsSourceFile, expression: TsNode, tainted: Map<string, TaintRecord>, fileReads?: FileReadBindings): TaintRecord | undefined {
346
746
  if (isFunctionLike(expression)) {
347
747
  return undefined;
348
748
  }
349
- const kind = sourceKindOf(parsedSource, expression);
749
+ const kind = sourceKindOf(parsedSource, expression, fileReads);
350
750
  if (kind !== undefined) {
351
751
  return { line: lineIndexOf(parsedSource, expression), kind, depth: 1 };
352
752
  }
353
- if (!typescriptSyntax.isIdentifier(expression)) {
354
- return undefined;
355
- }
356
- const upstream = tainted.get(expression.text);
753
+ const upstream = typescriptSyntax.isIdentifier(expression)
754
+ ? tainted.get(expression.text)
755
+ : fileReads ? taintedExpression(expression, parsedSource, tainted, fileReads, MAX_ALIAS_DEPTH - 1) : undefined;
357
756
  if (upstream?.depth !== undefined && upstream.depth < MAX_ALIAS_DEPTH) {
358
757
  return { line: upstream.line, kind: upstream.kind, depth: upstream.depth + 1 };
359
758
  }
360
759
  return undefined;
361
760
  }
362
761
 
363
- // Applies one proven source record to each simple identifier in a destructuring pattern.
762
+ /**
763
+ * Propagate shared source provenance across every identifier in a binding pattern, including nested object and array destructuring.
764
+ * Array holes are ignored and tainted is mutated in place.
765
+ *
766
+ * @param name - identifier or destructuring binding pattern receiving provenance
767
+ * @param record - shared source provenance record assigned to each bound identifier
768
+ * @param tainted - mutable local provenance map updated in place
769
+ * @returns Nothing. Writes record into tainted for every identifier bound by name.
770
+ */
364
771
  function taintBindingNames(name: import("typescript").BindingName, record: TaintRecord, tainted: Map<string, TaintRecord>): void {
365
772
  if (typescriptSyntax.isIdentifier(name)) {
366
773
  tainted.set(name.text, record);
@@ -374,8 +781,14 @@ function taintBindingNames(name: import("typescript").BindingName, record: Taint
374
781
  }
375
782
  }
376
783
 
377
- // Records locals that hold an XML parser configured to expand entities. Later `parser.parse(xml)`
378
- // calls are XXE sinks only for these explicitly unsafe parser instances.
784
+ /**
785
+ * Record local variables initialized with XMLParser (processEntities: true) or DOMParser (resolveEntity) constructor options.
786
+ *
787
+ * @param parsedSource - parsed syntax tree used to inspect constructor text
788
+ * @param node - AST node tested as an identifier-bound variable declaration
789
+ * @param unsafeXmlParsers - mutable set receiving flagged local parser variable names for later XXE sink checks
790
+ * @returns Nothing. Adds matching local parser names to unsafeXmlParsers in place.
791
+ */
379
792
  function recordUnsafeXmlParser(parsedSource: TsSourceFile, node: TsNode, unsafeXmlParsers: Set<string>): void {
380
793
  if (!typescriptSyntax.isVariableDeclaration(node) || !typescriptSyntax.isIdentifier(node.name) || !node.initializer) {
381
794
  return;
@@ -385,38 +798,223 @@ function recordUnsafeXmlParser(parsedSource: TsSourceFile, node: TsNode, unsafeX
385
798
  }
386
799
  }
387
800
 
388
- // Emits a finding when a sink call consumes a tainted local. Because legacy same-line
389
- // scanners own existing rule ids, same-line AST reports are limited to AST-only rules.
801
+ /**
802
+ * Check redirect assignments and sink calls for request-derived input.
803
+ * Same-line invariant: legacy scanners own these cases except for opted-in sink rules and unshadowed imported framework redirects.
804
+ *
805
+ * @param parsedSource - parsed file used to read expressions and locate them in source
806
+ * @param node - source node checked for an assignment or call
807
+ * @param inputs - tracked request flows and file readers used to distinguish path influence from content influence
808
+ * @param unsafeXmlParsers - parser names that qualify for the XML sink rule
809
+ * @param frameworkRedirectCallees - imported redirect names to recognize where their bindings are visible
810
+ * @param file - source file used to locate the emitted findings
811
+ * @param findings - caller's accumulator for qualifying findings
812
+ * @returns Nothing. Appends any matching findings to the accumulator.
813
+ */
390
814
  function reportSink(
391
815
  parsedSource: TsSourceFile,
392
816
  node: TsNode,
393
- tainted: Map<string, TaintRecord>,
817
+ inputs: FlowInputs,
394
818
  unsafeXmlParsers: ReadonlySet<string>,
819
+ frameworkRedirectCallees: ReadonlySet<string>,
395
820
  file: SourceFile,
396
821
  findings: Finding[],
397
822
  ): void {
398
- reportRedirectAssignmentSink(parsedSource, node, tainted, file, findings);
823
+ reportRedirectAssignmentSink(parsedSource, node, inputs.tainted, file, findings);
399
824
  const call = callLikeExpression(node);
400
825
  if (!call) {
401
826
  return;
402
827
  }
403
828
  const callee = call.expression.getText(parsedSource);
404
- const sink = AST_FLOW_SINKS.find((candidate) => candidate.isSink({ callee, call, sourceFile: parsedSource, unsafeXmlParsers }));
829
+ const isFrameworkRedirectCallee = frameworkRedirectCallees.has(callee) && !isImportedCalleeShadowed(call, callee);
830
+ const sink = AST_FLOW_SINKS.find((candidate) => candidate.isSink({ callee, call, sourceFile: parsedSource, unsafeXmlParsers, isFrameworkRedirectCallee }));
405
831
  if (!sink) {
406
832
  return;
407
833
  }
408
- const hit = taintedInput(call, parsedSource, tainted);
834
+ // A request-controlled filename proves path influence, not control of the bytes read.
835
+ const contentOnly = sink.ruleId === "security.unsafe-deserialization";
836
+ const hit = taintedInput(call, parsedSource, contentOnly ? inputs.contentTainted : inputs.tainted, contentOnly ? inputs.fileReadCallees : undefined);
409
837
  if (!hit) {
410
838
  return;
411
839
  }
412
840
  const sinkLine = lineIndexOf(parsedSource, call);
413
- if (sinkLine === hit.line && sink.shouldReportSameLine !== true) {
841
+ const reportsSameLine = sink.shouldReportSameLine === true || isFrameworkRedirectCallee;
842
+ if (sinkLine === hit.line && !reportsSameLine) {
414
843
  return;
415
844
  }
416
- findings.push(flowFinding(file, sinkLine, sink.ruleId, sink.sinkKind, hit.kind, hit.depth));
845
+ const sinkForm = sink.ruleId === "security.unsafe-deserialization" ? unsafeDeserializationSinkForm(callee) : undefined;
846
+ findings.push(flowFinding(file, sinkLine, sink.ruleId, sink.sinkKind, hit.kind, hit.depth, sinkForm));
847
+ }
848
+
849
+ type DeserializationSinkForm = "eval" | "function-constructor" | "unserialize" | "yaml-load" | "vm";
850
+
851
+ /**
852
+ * Classifies an unsafe-deserialization callee into a closed token so duplicate-eval merging never suppresses a co-located `vm` or `yaml` sink.
853
+ *
854
+ * @param callee - normalized sink callee text matched by `isUnsafeDeserializationSink`
855
+ * @returns Closed sink mechanism token (`"eval"`, `"function-constructor"`, `"unserialize"`, `"yaml-load"`, or `"vm"`).
856
+ */
857
+ function unsafeDeserializationSinkForm(callee: string): DeserializationSinkForm {
858
+ if (/^eval$/.test(callee)) {
859
+ return "eval";
860
+ }
861
+ if (/^Function$/.test(callee)) {
862
+ return "function-constructor";
863
+ }
864
+ if (/(?:^|\.)unserialize$/.test(callee)) {
865
+ return "unserialize";
866
+ }
867
+ if (/^(?:yaml|YAML|jsYaml|jsyaml)\.load$/.test(callee)) {
868
+ return "yaml-load";
869
+ }
870
+ return "vm";
871
+ }
872
+
873
+ /**
874
+ * Check whether an imported callee's root name is rebound around a call by a parameter, local declaration, loop binding, or catch binding.
875
+ * Scans ancestors below the source file.
876
+ *
877
+ * @param call - AST call use site from which enclosing scopes are walked upward
878
+ * @param callee - source spelling of the callee whose root identifier is checked
879
+ * @returns True if callee's root name is shadowed by an enclosing binding, or false if unshadowed or root is empty.
880
+ */
881
+ function isImportedCalleeShadowed(call: TsNode, callee: string): boolean {
882
+ const rootName = callee.split(".", 1)[0];
883
+ if (!rootName) {
884
+ return false;
885
+ }
886
+ for (let ancestor = call.parent; ancestor && !typescriptSyntax.isSourceFile(ancestor); ancestor = ancestor.parent) {
887
+ if (functionLikeBindsName(ancestor, rootName) || lexicalStatementsBindName(ancestor, rootName) || loopOrCatchBindsName(ancestor, rootName)) {
888
+ return true;
889
+ }
890
+ }
891
+ return false;
892
+ }
893
+
894
+ /**
895
+ * Check whether a function-like node binds an identifier through a parameter or its own declaration/expression name.
896
+ * Methods and accessors contribute only parameter bindings because their property names do not hide imported functions.
897
+ *
898
+ * @param node - AST node inspected as a function-like scope boundary
899
+ * @param name - identifier name checked for local binding
900
+ * @returns True if node binds name via parameter or function declaration/expression name; false for non-function nodes or no match.
901
+ */
902
+ function functionLikeBindsName(node: TsNode, name: string): boolean {
903
+ if (!isFunctionLike(node)) {
904
+ return false;
905
+ }
906
+ const functionNode = node as TsNode & {
907
+ name?: import("typescript").PropertyName;
908
+ parameters: readonly import("typescript").ParameterDeclaration[];
909
+ };
910
+ const bindsOwnName = typescriptSyntax.isFunctionDeclaration(node) || typescriptSyntax.isFunctionExpression(node);
911
+ if (bindsOwnName && functionNode.name && typescriptSyntax.isIdentifier(functionNode.name) && functionNode.name.text === name) {
912
+ return true;
913
+ }
914
+ return functionNode.parameters.some((parameter) => bindingNameContains(parameter.name, name));
915
+ }
916
+
917
+ /**
918
+ * Check whether a lexical block or switch clause binds a name via direct runtime statements, including its temporal-dead-zone prefix.
919
+ *
920
+ * @param node - AST block, module block, case clause, or default clause to inspect
921
+ * @param name - identifier name checked against direct value declarations
922
+ * @returns True if node is a block or switch clause whose direct statements bind name; otherwise false.
923
+ */
924
+ function lexicalStatementsBindName(node: TsNode, name: string): boolean {
925
+ if (typescriptSyntax.isBlock(node) || typescriptSyntax.isModuleBlock(node) || typescriptSyntax.isCaseClause(node) || typescriptSyntax.isDefaultClause(node)) {
926
+ return node.statements.some((statement) => statementBindsName(statement, name));
927
+ }
928
+ return false;
929
+ }
930
+
931
+ /**
932
+ * Check whether a loop or catch clause binds an identifier in its catch variable or variable-declaration initializer.
933
+ *
934
+ * @param node - AST node inspected as a catch clause or for/for-in/for-of loop
935
+ * @param name - identifier name checked against the clause's local bindings
936
+ * @returns True if node binds name; missing catch variables, non-declaration loop initializers, and other node kinds return false.
937
+ */
938
+ function loopOrCatchBindsName(node: TsNode, name: string): boolean {
939
+ if (typescriptSyntax.isCatchClause(node)) {
940
+ return node.variableDeclaration ? bindingNameContains(node.variableDeclaration.name, name) : false;
941
+ }
942
+ if (typescriptSyntax.isForStatement(node)) {
943
+ return node.initializer && typescriptSyntax.isVariableDeclarationList(node.initializer)
944
+ ? variableDeclarationListBindsName(node.initializer, name)
945
+ : false;
946
+ }
947
+ if (typescriptSyntax.isForInStatement(node) || typescriptSyntax.isForOfStatement(node)) {
948
+ return typescriptSyntax.isVariableDeclarationList(node.initializer)
949
+ ? variableDeclarationListBindsName(node.initializer, name)
950
+ : false;
951
+ }
952
+ return false;
953
+ }
954
+
955
+ /**
956
+ * Check whether a statement introduces a runtime value binding for name; only runtime declarations count
957
+ * because type-only declarations do not shadow an imported value.
958
+ *
959
+ * @param statement - AST statement checked for variable, function, class, enum, import-equals, or identifier namespace declarations
960
+ * @param name - identifier name tested against the statement's runtime bindings
961
+ * @returns True if statement declares a runtime binding matching name; otherwise false.
962
+ */
963
+ function statementBindsName(statement: import("typescript").Statement, name: string): boolean {
964
+ if (typescriptSyntax.isVariableStatement(statement)) {
965
+ return variableDeclarationListBindsName(statement.declarationList, name);
966
+ }
967
+ if (typescriptSyntax.isFunctionDeclaration(statement) || typescriptSyntax.isClassDeclaration(statement) || typescriptSyntax.isEnumDeclaration(statement)) {
968
+ return statement.name?.text === name;
969
+ }
970
+ if (typescriptSyntax.isImportEqualsDeclaration(statement)) {
971
+ return statement.name.text === name;
972
+ }
973
+ if (typescriptSyntax.isModuleDeclaration(statement) && typescriptSyntax.isIdentifier(statement.name)) {
974
+ return statement.name.text === name;
975
+ }
976
+ return false;
977
+ }
978
+
979
+ /**
980
+ * Check whether any declaration in a variable declaration list binds an identifier, including nested destructuring, for import-shadow checks.
981
+ *
982
+ * @param list - variable declaration list whose declarators are inspected
983
+ * @param name - identifier name checked across all declarator binding patterns
984
+ * @returns True if any declaration in list binds name; otherwise false.
985
+ */
986
+ function variableDeclarationListBindsName(list: import("typescript").VariableDeclarationList, name: string): boolean {
987
+ return list.declarations.some((declaration) => bindingNameContains(declaration.name, name));
417
988
  }
418
989
 
419
- // Reports redirect assignment flows; invariant: same-line cases stay with the legacy scanner.
990
+ /**
991
+ * Check whether a binding pattern declares a local identifier, including nested object and array destructuring.
992
+ * Property keys and omitted array elements are ignored.
993
+ *
994
+ * @param bindingName - identifier or destructuring pattern inspected recursively
995
+ * @param name - target identifier name to match against bound locals
996
+ * @returns True if bindingName declares name; an empty binding pattern or non-matching pattern returns false.
997
+ */
998
+ function bindingNameContains(bindingName: import("typescript").BindingName, name: string): boolean {
999
+ if (typescriptSyntax.isIdentifier(bindingName)) {
1000
+ return bindingName.text === name;
1001
+ }
1002
+ return bindingName.elements.some((element) =>
1003
+ !typescriptSyntax.isOmittedExpression(element) && bindingNameContains(element.name, name),
1004
+ );
1005
+ }
1006
+
1007
+ /**
1008
+ * Check for a location.href or window.location.href assignment receiving a direct source or tracked tainted value.
1009
+ * Same-line invariant: skips same-line hits because the legacy scanner looks for direct source tokens in the sink segment.
1010
+ *
1011
+ * @param parsedSource - parsed syntax tree used to inspect assignment text and sink line
1012
+ * @param node - AST node tested as an equals assignment to location.href or window.location.href
1013
+ * @param tainted - local provenance map consulted for right-hand side taint
1014
+ * @param file - discovered file whose display path locates emitted findings
1015
+ * @param findings - accumulator receiving cross-line open-redirect candidate findings
1016
+ * @returns Nothing. Appends a finding to findings when a cross-line assignment match qualifies.
1017
+ */
420
1018
  function reportRedirectAssignmentSink(parsedSource: TsSourceFile, node: TsNode, tainted: Map<string, TaintRecord>, file: SourceFile, findings: Finding[]): void {
421
1019
  if (!typescriptSyntax.isBinaryExpression(node) || node.operatorToken.kind !== typescriptSyntax.SyntaxKind.EqualsToken) {
422
1020
  return;
@@ -436,17 +1034,29 @@ function reportRedirectAssignmentSink(parsedSource: TsSourceFile, node: TsNode,
436
1034
  findings.push(flowFinding(file, sinkLine, "security.open-redirect-candidate", "redirect", hit.kind, hit.depth));
437
1035
  }
438
1036
 
439
- // Normalises calls and constructors because `RegExp(value)` and `new RegExp(value)`
440
- // are equivalent dynamic-regexp sinks for this syntax-only pass.
1037
+ /**
1038
+ * Narrow an AST node to a call or constructor expression because both forms can be dynamic-regexp sinks handled through one interface.
1039
+ *
1040
+ * @param node - AST node checked for CallExpression or NewExpression syntax
1041
+ * @returns node unchanged when it is a call or constructor expression, or undefined when it is neither.
1042
+ */
441
1043
  function callLikeExpression(node: TsNode): TsCallLikeExpression | undefined {
442
1044
  return typescriptSyntax.isCallExpression(node) || typescriptSyntax.isNewExpression(node) ? node : undefined;
443
1045
  }
444
1046
 
445
- // Finds the first tainted identifier or direct external-input expression in sink arguments.
446
- // Because sanitizer wrappers deliberately consume user input, their subtrees are pruned.
447
- function taintedInput(call: TsCallLikeExpression, parsedSource: TsSourceFile, tainted: Map<string, TaintRecord>): TaintRecord | undefined {
1047
+ /**
1048
+ * Search call arguments in order for the first tainted expression record; prunes functions and sanitizer calls, though direct-source checks
1049
+ * can still see pruned function or sanitizer text in an ancestor.
1050
+ *
1051
+ * @param call - call or constructor expression whose arguments are searched in order
1052
+ * @param parsedSource - parsed syntax tree used for source-text extraction and line mapping
1053
+ * @param tainted - local provenance map consulted for tainted identifier references
1054
+ * @param fileReads - optional reader bindings that mask proven reader calls and exclude property-key aliases
1055
+ * @returns First source record found across arguments, or undefined for absent arguments or no match.
1056
+ */
1057
+ function taintedInput(call: TsCallLikeExpression, parsedSource: TsSourceFile, tainted: Map<string, TaintRecord>, fileReads?: FileReadBindings): TaintRecord | undefined {
448
1058
  for (const argument of call.arguments ?? []) {
449
- const found = taintedExpression(argument, parsedSource, tainted);
1059
+ const found = taintedExpression(argument, parsedSource, tainted, fileReads);
450
1060
  if (found) {
451
1061
  return found;
452
1062
  }
@@ -454,8 +1064,18 @@ function taintedInput(call: TsCallLikeExpression, parsedSource: TsSourceFile, ta
454
1064
  return undefined;
455
1065
  }
456
1066
 
457
- // Finds taint inside one sink-relevant expression while pruning callbacks passed as ancillary args.
458
- function taintedExpression(expression: TsNode, parsedSource: TsSourceFile, tainted: Map<string, TaintRecord>): TaintRecord | undefined {
1067
+ /**
1068
+ * Search an expression for direct sources or tainted aliases while pruning functions and sanitizer calls (direct-source checks can still see
1069
+ * their text because they scan ancestor text). With fileReads, skips proven reader calls and excludes property-key aliases.
1070
+ *
1071
+ * @param expression - root expression node walked for taint evidence
1072
+ * @param parsedSource - parsed syntax tree used for text extraction and line lookup
1073
+ * @param tainted - local provenance map consulted for tracked identifiers
1074
+ * @param fileReads - optional reader bindings enabling content-only filtering of proven reads and property keys
1075
+ * @param maxAliasDepth - depth limit applied to alias records only (defaults to MAX_ALIAS_DEPTH)
1076
+ * @returns First eligible taint record found, or undefined if none qualifies.
1077
+ */
1078
+ function taintedExpression(expression: TsNode, parsedSource: TsSourceFile, tainted: Map<string, TaintRecord>, fileReads?: FileReadBindings, maxAliasDepth = MAX_ALIAS_DEPTH): TaintRecord | undefined {
459
1079
  let found: TaintRecord | undefined;
460
1080
  if (isFunctionLike(expression)) {
461
1081
  return undefined;
@@ -467,17 +1087,16 @@ function taintedExpression(expression: TsNode, parsedSource: TsSourceFile, taint
467
1087
  if (node !== expression && isFunctionLike(node)) {
468
1088
  return false;
469
1089
  }
1090
+ if (fileReads && isImportedFileRead(node, parsedSource, fileReads)) return false;
470
1091
  if (isSafeWrapperExpression(parsedSource, node)) {
471
1092
  return false;
472
1093
  }
473
- if (typescriptSyntax.isIdentifier(node)) {
474
- const record = tainted.get(node.text);
475
- if (record) {
476
- found = record;
477
- return false;
478
- }
1094
+ const record = taintedIdentifierRecord(node, tainted, maxAliasDepth, fileReads !== undefined);
1095
+ if (record) {
1096
+ found = record;
1097
+ return false;
479
1098
  }
480
- const kind = sourceKindOf(parsedSource, node);
1099
+ const kind = sourceKindOf(parsedSource, node, fileReads);
481
1100
  if (kind !== undefined) {
482
1101
  found = { line: lineIndexOf(parsedSource, node), kind, depth: 0 };
483
1102
  return false;
@@ -487,7 +1106,31 @@ function taintedExpression(expression: TsNode, parsedSource: TsSourceFile, taint
487
1106
  return found;
488
1107
  }
489
1108
 
490
- // Unsafe-deserialization sinks execute or inflate attacker-controlled serialized/code content.
1109
+ /**
1110
+ * Look up an identifier in tainted only when its alias depth does not exceed maxAliasDepth.
1111
+ *
1112
+ * @param node - AST node tested as a local identifier reference
1113
+ * @param tainted - local provenance map indexed by identifier name
1114
+ * @param maxAliasDepth - maximum alias depth permitted for returned records
1115
+ * @param contentOnly - when true, excludes property-access names and property-assignment keys so key spelling cannot stand in for a local value
1116
+ * @returns Matching source record within the depth limit, or undefined for non-identifiers, excluded keys, unknown locals, or deeper records.
1117
+ */
1118
+ function taintedIdentifierRecord(node: TsNode, tainted: Map<string, TaintRecord>, maxAliasDepth: number, contentOnly: boolean): TaintRecord | undefined {
1119
+ if (!typescriptSyntax.isIdentifier(node)) return undefined;
1120
+ const propertyKey = isPropertyAccessName(node) || (typescriptSyntax.isPropertyAssignment(node.parent) && node.parent.name === node);
1121
+ if (contentOnly && propertyKey) return undefined;
1122
+ const record = tainted.get(node.text);
1123
+ return record && record.depth <= maxAliasDepth ? record : undefined;
1124
+ }
1125
+
1126
+ /**
1127
+ * Check whether a call's spelling identifies a supported deserialization or dynamic-code sink.
1128
+ *
1129
+ * @param callee - source text of the call or constructor callee
1130
+ * @param call - call expression supplying arguments for YAML schema checks
1131
+ * @param parsedSource - parsed syntax tree used to read argument text
1132
+ * @returns True for supported deserialization or dynamic-code sinks; safe-schema YAML loads and other names return false.
1133
+ */
491
1134
  function isUnsafeDeserializationSink(callee: string, call: TsCallLikeExpression, parsedSource: TsSourceFile): boolean {
492
1135
  return (
493
1136
  /^eval$/.test(callee) ||
@@ -499,7 +1142,14 @@ function isUnsafeDeserializationSink(callee: string, call: TsCallLikeExpression,
499
1142
  );
500
1143
  }
501
1144
 
502
- // js-yaml load is treated as unsafe unless the caller pins a safe schema in the options object.
1145
+ /**
1146
+ * Check whether a call is a recognized YAML load lacking safe-schema option text; missing options make a recognized load unsafe.
1147
+ *
1148
+ * @param callee - source text of the call target matched against recognized YAML loaders
1149
+ * @param call - call expression whose second argument is checked for safe-schema options
1150
+ * @param parsedSource - parsed syntax tree used to inspect option text
1151
+ * @returns True if callee is a recognized YAML load without safe-schema options; other callees return false.
1152
+ */
503
1153
  function isUnsafeYamlLoad(callee: string, call: TsCallLikeExpression, parsedSource: TsSourceFile): boolean {
504
1154
  if (!/^(?:yaml|YAML|jsYaml|jsyaml)\.load$/.test(callee)) {
505
1155
  return false;
@@ -507,13 +1157,27 @@ function isUnsafeYamlLoad(callee: string, call: TsCallLikeExpression, parsedSour
507
1157
  return !hasSafeYamlSchema(call, parsedSource);
508
1158
  }
509
1159
 
510
- // Safe YAML schema evidence must be local to the load options so the finding is deterministic.
1160
+ /**
1161
+ * Check whether a YAML load's second argument text contains schema: followed by FAILSAFE_SCHEMA, JSON_SCHEMA, or CORE_SCHEMA.
1162
+ * Accepts an optional qualifier and can also match nested, quoted, or commented text.
1163
+ *
1164
+ * @param call - call expression whose second argument supplies YAML options
1165
+ * @param parsedSource - parsed syntax tree used to read the options argument text
1166
+ * @returns True when safe-schema text is found; missing options return false so the YAML load receives no safe-schema exemption.
1167
+ */
511
1168
  function hasSafeYamlSchema(call: TsCallLikeExpression, parsedSource: TsSourceFile): boolean {
512
1169
  const options = call.arguments?.[1];
513
1170
  return options !== undefined && /\bschema\s*:\s*(?:[A-Za-z_$][A-Za-z0-9_$]*\.)?(?:FAILSAFE_SCHEMA|JSON_SCHEMA|CORE_SCHEMA)\b/.test(options.getText(parsedSource));
514
1171
  }
515
1172
 
516
- // XXE sinks are XML parser calls whose local syntax explicitly enables entity expansion.
1173
+ /**
1174
+ * Check callee text and call options for XXE sink syntax, including locals initialized by flagged parser constructions.
1175
+ *
1176
+ * @param callee - source text of the call target checked for parser methods or inline construction
1177
+ * @param call - call expression whose arguments are checked for unsafe libxml options
1178
+ * @param unsafeXmlParsers - local parser variable names recorded as constructed with entity expansion enabled
1179
+ * @returns True for flagged libxml options, recorded parser methods, or inline unsafe parser constructions; otherwise false.
1180
+ */
517
1181
  function isXxeSink(callee: string, call: TsCallLikeExpression, unsafeXmlParsers: ReadonlySet<string>): boolean {
518
1182
  const parserMethod = callee.match(/^([A-Za-z_$][A-Za-z0-9_$]*)\.(?:parse|parseFromString)$/);
519
1183
  return (
@@ -523,18 +1187,33 @@ function isXxeSink(callee: string, call: TsCallLikeExpression, unsafeXmlParsers:
523
1187
  );
524
1188
  }
525
1189
 
526
- // libxmljs-style APIs expose entity expansion through call options such as `noent: true`.
1190
+ /**
1191
+ * Check whether a callee names parseXml or parseXmlString, optionally qualified by libxmljs, for subsequent unsafe-option checks.
1192
+ * A name match alone does not establish entity expansion because the caller checks the call's options.
1193
+ *
1194
+ * @param callee - source text of the call expression target
1195
+ * @returns True if callee matches parseXml or parseXmlString (optionally prefixed with libxmljs); otherwise false.
1196
+ */
527
1197
  function isLibxmlEntityExpandingCall(callee: string): boolean {
528
1198
  return /^(?:libxmljs\.)?(?:parseXml|parseXmlString)$/.test(callee);
529
1199
  }
530
1200
 
531
- // Looks for parser options that opt into entity expansion or external DTD loading.
1201
+ /**
1202
+ * Perform textual option checks on call arguments for unsafe XML entity-expansion flags.
1203
+ *
1204
+ * @param call - call expression whose arguments are inspected as source text
1205
+ * @returns True if any argument contains noent, dtdload, or processEntities set to true, or a resolveEntity property; missing arguments return false.
1206
+ */
532
1207
  function hasUnsafeXmlParserOption(call: TsCallLikeExpression): boolean {
533
1208
  return (call.arguments ?? []).some((argument) => /\b(?:noent|dtdload|processEntities)\s*:\s*true\b|\bresolveEntity\s*:/.test(argument.getText()));
534
1209
  }
535
1210
 
536
- // Inline `new XMLParser(...).parse(...)` and `new DOMParser(...).parseFromString(...)` keep options
537
- // in the callee expression, so the callee text carries the entity-expansion evidence.
1211
+ /**
1212
+ * Check whether callee text matches an inline XMLParser or DOMParser call with entity-expansion option syntax.
1213
+ *
1214
+ * @param callee - source text of the call target
1215
+ * @returns True for inline new XMLParser(...).parse with processEntities: true or new DOMParser(...).parseFromString with resolveEntity; else false.
1216
+ */
538
1217
  function isInlineUnsafeXmlParserCall(callee: string): boolean {
539
1218
  return (
540
1219
  /\bnew\s+XMLParser\s*\([^)]*\bprocessEntities\s*:\s*true[^)]*\)\.parse$/.test(callee) ||
@@ -542,7 +1221,13 @@ function isInlineUnsafeXmlParserCall(callee: string): boolean {
542
1221
  );
543
1222
  }
544
1223
 
545
- // Parser constructors are considered unsafe only when entity expansion is visibly enabled nearby.
1224
+ /**
1225
+ * Check whether an expression constructs XMLParser (with processEntities: true) or DOMParser (with resolveEntity).
1226
+ *
1227
+ * @param parsedSource - parsed syntax tree used to inspect constructor callee and argument text
1228
+ * @param expr - AST expression tested as a NewExpression parser construction
1229
+ * @returns True for recognized XMLParser or DOMParser constructions containing unsafe-option syntax; other expressions return false.
1230
+ */
546
1231
  function isUnsafeXmlParserConstruction(parsedSource: TsSourceFile, expr: TsNode): boolean {
547
1232
  if (!typescriptSyntax.isNewExpression(expr)) {
548
1233
  return false;
@@ -555,17 +1240,39 @@ function isUnsafeXmlParserConstruction(parsedSource: TsSourceFile, expr: TsNode)
555
1240
  );
556
1241
  }
557
1242
 
558
- // Classifies an initialiser expression as an external-input source. Mirrors the
559
- // same-line SOURCE_TOKENS patterns, applied to the expression's source text.
560
- function sourceKindOf(parsedSource: TsSourceFile, expr: TsNode): string | undefined {
1243
+ /**
1244
+ * Identify the first recognized external-input source in an expression so a flow finding can report where an unchecked value came from.
1245
+ *
1246
+ * @param parsedSource - parsed syntax tree used to inspect wrapper calls and blank nested handler parameters
1247
+ * @param expr - AST expression evaluated for external-input tokens
1248
+ * @param fileReads - optional reader bindings whose calls are masked so file contents remain distinct from file paths
1249
+ * @returns First matching source kind string, or undefined for no input evidence such as plain text or a recognized escaping call.
1250
+ */
1251
+ function sourceKindOf(parsedSource: TsSourceFile, expr: TsNode, fileReads?: FileReadBindings): string | undefined {
1252
+ // A recognized escaping helper is evidence that the developer prepared the value for this check.
561
1253
  if (isSafeWrapperExpression(parsedSource, expr)) {
562
1254
  return undefined;
563
1255
  }
1256
+ // A literal in code or a template with no substitutions supplies text rather than a request value.
564
1257
  if (isSourceTextLiteral(expr)) {
565
1258
  return undefined;
566
1259
  }
567
- const text = expr.getText(parsedSource);
1260
+ let text = textOutsideRequestHandlers(parsedSource, expr);
1261
+ // Without recognized file reads, there are no read paths to mask from input classification.
1262
+ if (fileReads?.size) {
1263
+ const start = expr.getStart(parsedSource);
1264
+ walk(expr, (node) => {
1265
+ // Keep other calls visible. A file read's path is separate from the file contents the developer uses.
1266
+ if (!isImportedFileRead(node, parsedSource, fileReads)) return;
1267
+ const from = node.getStart(parsedSource) - start;
1268
+ const endOffset = node.getEnd() - start;
1269
+ text = text.slice(0, from) + " ".repeat(endOffset - from) + text.slice(endOffset);
1270
+ return false;
1271
+ });
1272
+ }
1273
+ // Use the first recognized input kind to describe the starting point in the finding.
568
1274
  for (const token of SOURCE_TOKENS) {
1275
+ // When the remaining source matches this check, show its input kind in the report.
569
1276
  if (token.pattern.test(text)) {
570
1277
  return token.kind;
571
1278
  }
@@ -573,13 +1280,107 @@ function sourceKindOf(parsedSource: TsSourceFile, expr: TsNode): string | undefi
573
1280
  return undefined;
574
1281
  }
575
1282
 
576
- // Literal text can mention `req.query.path` in docs or fixtures without being external input.
1283
+ /**
1284
+ * Blank local request parameters inside nested non-contributing handlers while retaining source offsets and evidence from value-producing callbacks.
1285
+ *
1286
+ * @param parsedSource - parsed syntax tree used to locate expression and parameter offsets
1287
+ * @param expr - AST expression whose text is filtered for nested handler request bindings
1288
+ * @returns Expression text with non-contributing nested handler request parameters replaced by spaces.
1289
+ */
1290
+ function textOutsideRequestHandlers(parsedSource: TsSourceFile, expr: TsNode): string {
1291
+ const expressionStart = expr.getStart(parsedSource);
1292
+ let text = expr.getText(parsedSource);
1293
+ walk(expr, (node) => {
1294
+ // Keep expressions and value-producing callbacks in view when they can supply input to the current finding.
1295
+ if (node === expr || !isFunctionLike(node) || contributesCallbackValue(node)) {
1296
+ return;
1297
+ }
1298
+ const declaredNames = declaredRequestParameterNames(node);
1299
+ // A nested handler with no recognized request parameter has no local request names to hide.
1300
+ if (declaredNames.size === 0) {
1301
+ return;
1302
+ }
1303
+ walk(node, (inner) => {
1304
+ // Mask the handler's parameter references. A property named req, such as this.req, is a different binding.
1305
+ if (typescriptSyntax.isIdentifier(inner) && declaredNames.has(inner.text) && !isPropertyAccessName(inner)) {
1306
+ const blankStart = inner.getStart(parsedSource) - expressionStart;
1307
+ const blankEnd = inner.getEnd() - expressionStart;
1308
+ text = text.slice(0, blankStart) + " ".repeat(blankEnd - blankStart) + text.slice(blankEnd);
1309
+ }
1310
+ });
1311
+ return;
1312
+ });
1313
+ return text;
1314
+ }
1315
+
1316
+ /**
1317
+ * Collect direct identifier parameter names matching req, request, or ctx for the scanner's name-based filter.
1318
+ *
1319
+ * @param node - function-like AST node whose direct parameter list is inspected
1320
+ * @returns Set of matching parameter names; an empty set means the scanner skips blanking for this function.
1321
+ */
1322
+ function declaredRequestParameterNames(node: TsNode): Set<string> {
1323
+ const { parameters } = node as import("typescript").SignatureDeclaration;
1324
+ return new Set(parameters.flatMap((parameter) => (typescriptSyntax.isIdentifier(parameter.name) && REQUEST_RECEIVER_NAMES.has(parameter.name.text) ? [parameter.name.text] : [])));
1325
+ }
1326
+
1327
+ /**
1328
+ * Check whether a function-like node is immediately invoked or passed to a known value-producing collection/promise method.
1329
+ *
1330
+ * @param node - function-like AST node whose parent call context is inspected
1331
+ * @returns True when the callback can contribute its return value to the enclosing expression; otherwise false.
1332
+ */
1333
+ function contributesCallbackValue(node: TsNode): boolean {
1334
+ // Extra parentheses around a function do not change whether its value is used.
1335
+ while (typescriptSyntax.isParenthesizedExpression(node.parent)) {
1336
+ node = node.parent;
1337
+ }
1338
+ const parent = node.parent;
1339
+ // Developers can invoke a function through call or apply. Reading one of those properties alone supplies no result.
1340
+ if (typescriptSyntax.isPropertyAccessExpression(parent) && parent.expression === node) {
1341
+ return (parent.name.text === "call" || parent.name.text === "apply")
1342
+ && typescriptSyntax.isCallExpression(parent.parent) && parent.parent.expression === parent;
1343
+ }
1344
+ // A function merely stored as a value does not contribute its body to the current finding.
1345
+ if (!typescriptSyntax.isCallExpression(parent)) {
1346
+ return false;
1347
+ }
1348
+ // An immediately invoked function can pass its return value into the expression being checked.
1349
+ if (parent.expression === node) {
1350
+ return true;
1351
+ }
1352
+ // Known collection and promise methods use a callback result, such as a value returned from then.
1353
+ return parent.arguments[0] === node && typescriptSyntax.isPropertyAccessExpression(parent.expression)
1354
+ && /^(?:map|flatMap|reduce|reduceRight|then|catch)$/u.test(parent.expression.name.text);
1355
+ }
1356
+
1357
+ /**
1358
+ * Check whether a node is the property name of a dotted property access (such as this.req), where it reads no local binding.
1359
+ *
1360
+ * @param identifier - AST node compared against its parent PropertyAccessExpression name
1361
+ * @returns True when identifier names the property in a dotted access; otherwise false.
1362
+ */
1363
+ function isPropertyAccessName(identifier: TsNode): boolean {
1364
+ return typescriptSyntax.isPropertyAccessExpression(identifier.parent) && identifier.parent.name === identifier;
1365
+ }
1366
+
1367
+ /**
1368
+ * Check whether an expression is plain literal text rather than an interpolated template or dynamic expression.
1369
+ *
1370
+ * @param expr - AST expression tested as a string literal or substitution-free template literal
1371
+ * @returns True for string literals and substitution-free template literals; other expressions including interpolating templates return false.
1372
+ */
577
1373
  function isSourceTextLiteral(expr: TsNode): boolean {
578
1374
  return typescriptSyntax.isStringLiteral(expr) || typescriptSyntax.isNoSubstitutionTemplateLiteral(expr);
579
1375
  }
580
1376
 
581
- // Regex escaping helpers are sanitizer evidence for dynamic-regexp flow; walking their arguments
582
- // would otherwise re-taint an already-escaped pattern value.
1377
+ /**
1378
+ * Check whether an expression calls a recognized regexp-escaping helper so callers can treat it as sanitizer evidence and skip its argument subtree.
1379
+ *
1380
+ * @param parsedSource - parsed syntax tree used to extract the call target text
1381
+ * @param expr - AST node tested as a CallExpression
1382
+ * @returns True when expr calls a recognized regexp-escaping helper; non-calls and other names return false.
1383
+ */
583
1384
  function isSafeWrapperExpression(parsedSource: TsSourceFile, expr: TsNode): boolean {
584
1385
  if (!typescriptSyntax.isCallExpression(expr)) {
585
1386
  return false;
@@ -588,7 +1389,12 @@ function isSafeWrapperExpression(parsedSource: TsSourceFile, expr: TsNode): bool
588
1389
  return /^(?:escapeRegExp|escapeStringRegexp|regexpEscape|RegExp\.escape)$/.test(callee);
589
1390
  }
590
1391
 
591
- // Identifies scope boundaries that must not inherit taint from enclosing functions.
1392
+ /**
1393
+ * Check whether an AST node is a function-like boundary that receives separate taint analysis.
1394
+ *
1395
+ * @param node - AST node tested against function, arrow, method, constructor, and accessor kinds
1396
+ * @returns True for functions, arrows, methods, constructors, and accessors; other nodes return false.
1397
+ */
592
1398
  function isFunctionLike(node: TsNode): boolean {
593
1399
  return (
594
1400
  typescriptSyntax.isFunctionDeclaration(node) ||
@@ -611,8 +1417,18 @@ function isFunctionLike(node: TsNode): boolean {
611
1417
  * @param sinkKind - sink category for machine-readable metadata
612
1418
  * @param sourceKind - external input category for machine-readable metadata
613
1419
  * @param flowDepth - bounded alias distance between source and sink
1420
+ * @param sinkForm - closed sink mechanism token attached for `security.unsafe-deserialization`; omit for other rules
1421
+ * @returns A medium-confidence security warning on the one-based sink line, with the rule's own message and remediation or generic cross-line text.
614
1422
  */
615
- function flowFinding(file: SourceFile, lineIndex: number, ruleId: string, sinkKind: string, sourceKind: string, flowDepth: number): Finding {
1423
+ function flowFinding(
1424
+ file: SourceFile,
1425
+ lineIndex: number,
1426
+ ruleId: string,
1427
+ sinkKind: string,
1428
+ sourceKind: string,
1429
+ flowDepth: number,
1430
+ sinkForm?: DeserializationSinkForm,
1431
+ ): Finding {
616
1432
  const base = securityRuleDetails(ruleId);
617
1433
  return makeFinding({
618
1434
  ruleId,
@@ -623,11 +1439,16 @@ function flowFinding(file: SourceFile, lineIndex: number, ruleId: string, sinkKi
623
1439
  pillar: "security",
624
1440
  confidence: "medium",
625
1441
  remediation: base ? base.remediation : "Validate external input before it reaches the sink.",
626
- metadata: { sourceKind, sinkKind, flowDepth },
1442
+ metadata: { sourceKind, sinkKind, flowDepth, ...(sinkForm === undefined ? {} : { sinkForm }) },
627
1443
  });
628
1444
  }
629
1445
 
630
- // Supplies messages/remediation for both same-line rule ids and AST-only security candidates.
1446
+ /**
1447
+ * Look up message and remediation text for both same-line rule ids and AST-only security candidates.
1448
+ *
1449
+ * @param ruleId - security rule identifier emitted by a same-line or AST flow sink
1450
+ * @returns Message and remediation pair for known rules, or undefined if ruleId is unrecognized.
1451
+ */
631
1452
  function securityRuleDetails(ruleId: string): Pick<SecurityFlowRule, "message" | "remediation"> | undefined {
632
1453
  return (
633
1454
  SECURITY_FLOW_RULES.find((rule) => rule.ruleId === ruleId) ??