@blundergoat/gruff-ts 0.2.0 → 0.3.1

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 (48) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/README.md +81 -13
  3. package/docs/README.md +2 -0
  4. package/docs/agent-hook.md +80 -0
  5. package/docs/ci-integration.md +16 -0
  6. package/docs/configuration.md +21 -5
  7. package/docs/output-formats.md +10 -0
  8. package/docs/philosophy.md +21 -0
  9. package/docs/releasing.md +5 -5
  10. package/docs/rules.md +26 -18
  11. package/package.json +5 -5
  12. package/scripts/bump-version.sh +1 -1
  13. package/src/analyser.ts +48 -37
  14. package/src/blocks.ts +23 -70
  15. package/src/changed-regions.ts +390 -0
  16. package/src/check-ignore.ts +49 -0
  17. package/src/class-rules.ts +80 -33
  18. package/src/cli-program.ts +106 -12
  19. package/src/comment-rules.ts +5 -1
  20. package/src/config-parse.ts +458 -0
  21. package/src/config-preservation.ts +1 -1
  22. package/src/config.ts +215 -460
  23. package/src/constants.ts +1 -1
  24. package/src/context-doc-rules.ts +2 -4
  25. package/src/dashboard.ts +7 -4
  26. package/src/discovery.ts +88 -32
  27. package/src/findings-helpers.ts +41 -5
  28. package/src/findings.ts +10 -0
  29. package/src/fixture-purpose-rules.ts +7 -9
  30. package/src/fixtures/rule-catalogue-security-doctrine.ts +28 -0
  31. package/src/init-config.ts +3 -0
  32. package/src/line-rules.ts +7 -5
  33. package/src/naming-pushers.ts +35 -6
  34. package/src/profiles.ts +231 -0
  35. package/src/project-config-rules.ts +5 -5
  36. package/src/project-rules.ts +6 -117
  37. package/src/report-html.ts +1 -1
  38. package/src/report-renderers.ts +98 -7
  39. package/src/rule-list.ts +23 -2
  40. package/src/rules.ts +11 -12
  41. package/src/safety-rules.ts +16 -6
  42. package/src/scoring.ts +43 -5
  43. package/src/security-flow-rules.ts +533 -0
  44. package/src/sensitive-data-rules.ts +138 -2
  45. package/src/static-analysis-redundant-rules.ts +411 -0
  46. package/src/test-block-rules.ts +115 -53
  47. package/src/test-fixtures.ts +50 -9
  48. package/src/types.ts +79 -2
@@ -3,6 +3,52 @@
3
3
  import type { SourceFile } from "./discovery.ts";
4
4
  import { makeFinding } from "./findings.ts";
5
5
  import type { Finding } from "./types.ts";
6
+ import { createRequire } from "node:module";
7
+
8
+ // Syntax-only TypeScript/JavaScript parser (ADR-012): ts.createSourceFile only -
9
+ // no type checker, program, language service, or emit. Loaded via createRequire
10
+ // because typescript ships as CommonJS; usage stays bounded to syntax walking.
11
+ const require = createRequire(import.meta.url);
12
+ const typescriptSyntax = require("typescript") as typeof import("typescript");
13
+
14
+ type TsSourceFile = import("typescript").SourceFile;
15
+ type TsNode = import("typescript").Node;
16
+ type TsCallLikeExpression = import("typescript").CallExpression | import("typescript").NewExpression;
17
+
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.
20
+ function getSourceFile(file: SourceFile, source: string): TsSourceFile | null {
21
+ try {
22
+ return typescriptSyntax.createSourceFile(file.displayPath, source, typescriptSyntax.ScriptTarget.Latest, true, scriptKindFor(file.displayPath));
23
+ } catch {
24
+ return null;
25
+ }
26
+ }
27
+
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.
39
+ function walk(node: TsNode, visit: (node: TsNode) => boolean | void): void {
40
+ if (visit(node) === false) {
41
+ return;
42
+ }
43
+ typescriptSyntax.forEachChild(node, (child) => {
44
+ walk(child, visit);
45
+ });
46
+ }
47
+
48
+ // Zero-based start line of a node, for aligning with 1-based finding lines.
49
+ function lineIndexOf(parsedSource: TsSourceFile, node: TsNode): number {
50
+ return parsedSource.getLineAndCharacterOfPosition(node.getStart(parsedSource)).line;
51
+ }
6
52
 
7
53
  // External input token that can be visibly matched on one source line.
8
54
  interface SourceToken {
@@ -110,3 +156,490 @@ function securityFlowFinding(file: SourceFile, line: number, rule: SecurityFlowR
110
156
  metadata: { sourceKind, sinkKind: rule.sinkKind },
111
157
  });
112
158
  }
159
+
160
+ // --- 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.
166
+
167
+ // One tainted local: the 0-based line of the originating external source, the
168
+ // source kind for metadata, and how many alias hops removed it is (cap below).
169
+ interface TaintRecord {
170
+ line: number;
171
+ kind: string;
172
+ depth: number;
173
+ }
174
+
175
+ // Bundles the syntax context each sink matcher needs so all text extraction remains anchored
176
+ // to the parsed source file instead of raw substrings.
177
+ interface AstSinkInput {
178
+ callee: string;
179
+ call: TsCallLikeExpression;
180
+ sourceFile: TsSourceFile;
181
+ unsafeXmlParsers: ReadonlySet<string>;
182
+ }
183
+
184
+ // Describes one AST sink candidate. Some AST-only rules report same-line direct-source
185
+ // evidence because no legacy line scanner owns those rule ids.
186
+ interface AstFlowSink {
187
+ ruleId: string;
188
+ sinkKind: string;
189
+ shouldReportSameLine?: boolean;
190
+ isSink: (input: AstSinkInput) => boolean;
191
+ }
192
+
193
+ // AST sink matchers for the flow-upgraded rules. `callee` is the source text of
194
+ // the call/new expression's callee (e.g. "fs.readFile", "RegExp",
195
+ // "axios.get"); the patterns mirror the same-line callPattern sinks above.
196
+ const AST_FLOW_SINKS: readonly AstFlowSink[] = [
197
+ {
198
+ ruleId: "security.path-traversal-candidate",
199
+ sinkKind: "filesystem-path",
200
+ isSink: ({ callee }) =>
201
+ /(?:^|\.)(?:readFile|readFileSync|writeFile|writeFileSync|appendFile|appendFileSync|createReadStream|createWriteStream|stat|statSync|readdir|readdirSync|unlink|unlinkSync|rm|rmSync|mkdir|mkdirSync)$/.test(
202
+ callee,
203
+ ),
204
+ },
205
+ {
206
+ ruleId: "security.ssrf-candidate",
207
+ sinkKind: "network-request",
208
+ isSink: ({ callee }) =>
209
+ /(?:^|\.)fetch$/.test(callee) ||
210
+ /^axios\.(?:get|post|put|patch|delete|request)$/.test(callee) ||
211
+ /^https?\.(?:request|get)$/.test(callee),
212
+ },
213
+ {
214
+ ruleId: "security.open-redirect-candidate",
215
+ sinkKind: "redirect",
216
+ isSink: ({ callee }) =>
217
+ /^(?:res|reply|response)\.redirect$/.test(callee) ||
218
+ /^redirect$/.test(callee) ||
219
+ /^(?:location|window\.location)\.(?:assign|replace)$/.test(callee),
220
+ },
221
+ {
222
+ ruleId: "security.dynamic-regexp",
223
+ sinkKind: "regular-expression",
224
+ isSink: ({ callee }) => /^RegExp$/.test(callee),
225
+ },
226
+ {
227
+ ruleId: "security.unsafe-deserialization",
228
+ sinkKind: "deserialization",
229
+ shouldReportSameLine: true,
230
+ isSink: ({ callee, call, sourceFile }) => isUnsafeDeserializationSink(callee, call, sourceFile),
231
+ },
232
+ {
233
+ ruleId: "security.xxe-candidate",
234
+ sinkKind: "xml-entity-expansion",
235
+ shouldReportSameLine: true,
236
+ isSink: ({ callee, call, unsafeXmlParsers }) => isXxeSink(callee, call, unsafeXmlParsers),
237
+ },
238
+ ];
239
+
240
+ const MAX_ALIAS_DEPTH = 2;
241
+ const MAX_SCOPE_NODES = 4000;
242
+
243
+ /**
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.
247
+ * Invariant: this pass never uses TypeScript type-checking, emit, or schema changes.
248
+ *
249
+ * @param file - discovered script file whose display path anchors emitted fingerprints
250
+ * @param source - full source text to parse with syntax-only TypeScript APIs
251
+ * @param findings - accumulator that receives additional AST flow findings
252
+ */
253
+ export function analyseSecurityFlow(file: SourceFile, source: string, findings: Finding[]): void {
254
+ const parsedSource = getSourceFile(file, source);
255
+ if (!parsedSource) {
256
+ return;
257
+ }
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.
261
+ const flowFindings: Finding[] = [];
262
+ try {
263
+ const scopes: TsNode[] = [parsedSource];
264
+ walk(parsedSource, (node) => {
265
+ if (isFunctionLike(node)) {
266
+ scopes.push(node);
267
+ }
268
+ });
269
+ for (const scope of scopes) {
270
+ analyseFlowScope(parsedSource, scope, file, flowFindings);
271
+ }
272
+ } catch {
273
+ return;
274
+ }
275
+ for (const flow of flowFindings) {
276
+ findings.push(flow);
277
+ }
278
+ }
279
+
280
+ /**
281
+ * 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.
283
+ *
284
+ * @param parsedSource - syntax tree that owns positions and text extraction
285
+ * @param scopeOwner - top-level source file or function-like node to scan
286
+ * @param file - discovered file used for stable finding locations
287
+ * @param findings - accumulator that receives sink findings for this scope
288
+ */
289
+ function analyseFlowScope(parsedSource: TsSourceFile, scopeOwner: TsNode, file: SourceFile, findings: Finding[]): void {
290
+ const tainted = new Map<string, TaintRecord>();
291
+ const unsafeXmlParsers = new Set<string>();
292
+ let budget = MAX_SCOPE_NODES;
293
+ walk(scopeOwner, (node) => {
294
+ if (budget <= 0) {
295
+ return false;
296
+ }
297
+ budget -= 1;
298
+ if (isFunctionLike(node) && node !== scopeOwner) {
299
+ return false;
300
+ }
301
+ recordUnsafeXmlParser(parsedSource, node, unsafeXmlParsers);
302
+ recordTaint(parsedSource, node, tainted);
303
+ reportSink(parsedSource, node, tainted, unsafeXmlParsers, file, findings);
304
+ return;
305
+ });
306
+ }
307
+
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 {
313
+ if (typescriptSyntax.isVariableDeclaration(node)) {
314
+ recordVariableTaint(parsedSource, node, tainted);
315
+ return;
316
+ }
317
+ if (typescriptSyntax.isBinaryExpression(node) && node.operatorToken.kind === typescriptSyntax.SyntaxKind.EqualsToken && typescriptSyntax.isIdentifier(node.left)) {
318
+ const nextRecord = taintRecordFromExpression(parsedSource, node.right, tainted);
319
+ if (nextRecord) {
320
+ tainted.set(node.left.text, nextRecord);
321
+ } else {
322
+ tainted.delete(node.left.text);
323
+ }
324
+ }
325
+ }
326
+
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 {
330
+ if (!node.initializer) {
331
+ return;
332
+ }
333
+ const record = taintRecordFromExpression(parsedSource, node.initializer, tainted);
334
+ if (!record) {
335
+ return;
336
+ }
337
+ if (typescriptSyntax.isIdentifier(node.name)) {
338
+ tainted.set(node.name.text, record);
339
+ return;
340
+ }
341
+ taintBindingNames(node.name, record, tainted);
342
+ }
343
+
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 {
346
+ if (isFunctionLike(expression)) {
347
+ return undefined;
348
+ }
349
+ const kind = sourceKindOf(parsedSource, expression);
350
+ if (kind !== undefined) {
351
+ return { line: lineIndexOf(parsedSource, expression), kind, depth: 1 };
352
+ }
353
+ if (!typescriptSyntax.isIdentifier(expression)) {
354
+ return undefined;
355
+ }
356
+ const upstream = tainted.get(expression.text);
357
+ if (upstream?.depth !== undefined && upstream.depth < MAX_ALIAS_DEPTH) {
358
+ return { line: upstream.line, kind: upstream.kind, depth: upstream.depth + 1 };
359
+ }
360
+ return undefined;
361
+ }
362
+
363
+ // Applies one proven source record to each simple identifier in a destructuring pattern.
364
+ function taintBindingNames(name: import("typescript").BindingName, record: TaintRecord, tainted: Map<string, TaintRecord>): void {
365
+ if (typescriptSyntax.isIdentifier(name)) {
366
+ tainted.set(name.text, record);
367
+ return;
368
+ }
369
+ for (const element of name.elements) {
370
+ if (typescriptSyntax.isOmittedExpression(element)) {
371
+ continue;
372
+ }
373
+ taintBindingNames(element.name, record, tainted);
374
+ }
375
+ }
376
+
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.
379
+ function recordUnsafeXmlParser(parsedSource: TsSourceFile, node: TsNode, unsafeXmlParsers: Set<string>): void {
380
+ if (!typescriptSyntax.isVariableDeclaration(node) || !typescriptSyntax.isIdentifier(node.name) || !node.initializer) {
381
+ return;
382
+ }
383
+ if (isUnsafeXmlParserConstruction(parsedSource, node.initializer)) {
384
+ unsafeXmlParsers.add(node.name.text);
385
+ }
386
+ }
387
+
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.
390
+ function reportSink(
391
+ parsedSource: TsSourceFile,
392
+ node: TsNode,
393
+ tainted: Map<string, TaintRecord>,
394
+ unsafeXmlParsers: ReadonlySet<string>,
395
+ file: SourceFile,
396
+ findings: Finding[],
397
+ ): void {
398
+ reportRedirectAssignmentSink(parsedSource, node, tainted, file, findings);
399
+ const call = callLikeExpression(node);
400
+ if (!call) {
401
+ return;
402
+ }
403
+ const callee = call.expression.getText(parsedSource);
404
+ const sink = AST_FLOW_SINKS.find((candidate) => candidate.isSink({ callee, call, sourceFile: parsedSource, unsafeXmlParsers }));
405
+ if (!sink) {
406
+ return;
407
+ }
408
+ const hit = taintedInput(call, parsedSource, tainted);
409
+ if (!hit) {
410
+ return;
411
+ }
412
+ const sinkLine = lineIndexOf(parsedSource, call);
413
+ if (sinkLine === hit.line && sink.shouldReportSameLine !== true) {
414
+ return;
415
+ }
416
+ findings.push(flowFinding(file, sinkLine, sink.ruleId, sink.sinkKind, hit.kind, hit.depth));
417
+ }
418
+
419
+ // Reports redirect assignment flows; invariant: same-line cases stay with the legacy scanner.
420
+ function reportRedirectAssignmentSink(parsedSource: TsSourceFile, node: TsNode, tainted: Map<string, TaintRecord>, file: SourceFile, findings: Finding[]): void {
421
+ if (!typescriptSyntax.isBinaryExpression(node) || node.operatorToken.kind !== typescriptSyntax.SyntaxKind.EqualsToken) {
422
+ return;
423
+ }
424
+ const left = node.left.getText(parsedSource);
425
+ if (!/^(?:location|window\.location)\.href$/.test(left)) {
426
+ return;
427
+ }
428
+ const hit = taintedExpression(node.right, parsedSource, tainted);
429
+ if (!hit) {
430
+ return;
431
+ }
432
+ const sinkLine = lineIndexOf(parsedSource, node);
433
+ if (sinkLine === hit.line) {
434
+ return;
435
+ }
436
+ findings.push(flowFinding(file, sinkLine, "security.open-redirect-candidate", "redirect", hit.kind, hit.depth));
437
+ }
438
+
439
+ // Normalises calls and constructors because `RegExp(value)` and `new RegExp(value)`
440
+ // are equivalent dynamic-regexp sinks for this syntax-only pass.
441
+ function callLikeExpression(node: TsNode): TsCallLikeExpression | undefined {
442
+ return typescriptSyntax.isCallExpression(node) || typescriptSyntax.isNewExpression(node) ? node : undefined;
443
+ }
444
+
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 {
448
+ for (const argument of call.arguments ?? []) {
449
+ const found = taintedExpression(argument, parsedSource, tainted);
450
+ if (found) {
451
+ return found;
452
+ }
453
+ }
454
+ return undefined;
455
+ }
456
+
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 {
459
+ let found: TaintRecord | undefined;
460
+ if (isFunctionLike(expression)) {
461
+ return undefined;
462
+ }
463
+ walk(expression, (node) => {
464
+ if (found) {
465
+ return false;
466
+ }
467
+ if (node !== expression && isFunctionLike(node)) {
468
+ return false;
469
+ }
470
+ if (isSafeWrapperExpression(parsedSource, node)) {
471
+ return false;
472
+ }
473
+ if (typescriptSyntax.isIdentifier(node)) {
474
+ const record = tainted.get(node.text);
475
+ if (record) {
476
+ found = record;
477
+ return false;
478
+ }
479
+ }
480
+ const kind = sourceKindOf(parsedSource, node);
481
+ if (kind !== undefined) {
482
+ found = { line: lineIndexOf(parsedSource, node), kind, depth: 0 };
483
+ return false;
484
+ }
485
+ return;
486
+ });
487
+ return found;
488
+ }
489
+
490
+ // Unsafe-deserialization sinks execute or inflate attacker-controlled serialized/code content.
491
+ function isUnsafeDeserializationSink(callee: string, call: TsCallLikeExpression, parsedSource: TsSourceFile): boolean {
492
+ return (
493
+ /^eval$/.test(callee) ||
494
+ /^Function$/.test(callee) ||
495
+ /(?:^|\.)unserialize$/.test(callee) ||
496
+ isUnsafeYamlLoad(callee, call, parsedSource) ||
497
+ /^vm\.(?:runInNewContext|runInThisContext|runInContext)$/.test(callee) ||
498
+ /^(?:vm\.)?Script$/.test(callee)
499
+ );
500
+ }
501
+
502
+ // js-yaml load is treated as unsafe unless the caller pins a safe schema in the options object.
503
+ function isUnsafeYamlLoad(callee: string, call: TsCallLikeExpression, parsedSource: TsSourceFile): boolean {
504
+ if (!/^(?:yaml|YAML|jsYaml|jsyaml)\.load$/.test(callee)) {
505
+ return false;
506
+ }
507
+ return !hasSafeYamlSchema(call, parsedSource);
508
+ }
509
+
510
+ // Safe YAML schema evidence must be local to the load options so the finding is deterministic.
511
+ function hasSafeYamlSchema(call: TsCallLikeExpression, parsedSource: TsSourceFile): boolean {
512
+ const options = call.arguments?.[1];
513
+ 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
+ }
515
+
516
+ // XXE sinks are XML parser calls whose local syntax explicitly enables entity expansion.
517
+ function isXxeSink(callee: string, call: TsCallLikeExpression, unsafeXmlParsers: ReadonlySet<string>): boolean {
518
+ const parserMethod = callee.match(/^([A-Za-z_$][A-Za-z0-9_$]*)\.(?:parse|parseFromString)$/);
519
+ return (
520
+ (isLibxmlEntityExpandingCall(callee) && hasUnsafeXmlParserOption(call)) ||
521
+ (parserMethod !== null && unsafeXmlParsers.has(parserMethod[1] ?? "")) ||
522
+ isInlineUnsafeXmlParserCall(callee)
523
+ );
524
+ }
525
+
526
+ // libxmljs-style APIs expose entity expansion through call options such as `noent: true`.
527
+ function isLibxmlEntityExpandingCall(callee: string): boolean {
528
+ return /^(?:libxmljs\.)?(?:parseXml|parseXmlString)$/.test(callee);
529
+ }
530
+
531
+ // Looks for parser options that opt into entity expansion or external DTD loading.
532
+ function hasUnsafeXmlParserOption(call: TsCallLikeExpression): boolean {
533
+ return (call.arguments ?? []).some((argument) => /\b(?:noent|dtdload|processEntities)\s*:\s*true\b|\bresolveEntity\s*:/.test(argument.getText()));
534
+ }
535
+
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.
538
+ function isInlineUnsafeXmlParserCall(callee: string): boolean {
539
+ return (
540
+ /\bnew\s+XMLParser\s*\([^)]*\bprocessEntities\s*:\s*true[^)]*\)\.parse$/.test(callee) ||
541
+ /\bnew\s+DOMParser\s*\([^)]*\bresolveEntity\s*:[^)]*\)\.parseFromString$/.test(callee)
542
+ );
543
+ }
544
+
545
+ // Parser constructors are considered unsafe only when entity expansion is visibly enabled nearby.
546
+ function isUnsafeXmlParserConstruction(parsedSource: TsSourceFile, expr: TsNode): boolean {
547
+ if (!typescriptSyntax.isNewExpression(expr)) {
548
+ return false;
549
+ }
550
+ const callee = expr.expression.getText(parsedSource);
551
+ const text = expr.getText(parsedSource);
552
+ return (
553
+ (/^(?:XMLParser|fastXmlParser\.XMLParser)$/.test(callee) && /\bprocessEntities\s*:\s*true\b/.test(text)) ||
554
+ (/^(?:DOMParser|xmldom\.DOMParser)$/.test(callee) && /\bresolveEntity\s*:/.test(text))
555
+ );
556
+ }
557
+
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 {
561
+ if (isSafeWrapperExpression(parsedSource, expr)) {
562
+ return undefined;
563
+ }
564
+ if (isSourceTextLiteral(expr)) {
565
+ return undefined;
566
+ }
567
+ const text = expr.getText(parsedSource);
568
+ for (const token of SOURCE_TOKENS) {
569
+ if (token.pattern.test(text)) {
570
+ return token.kind;
571
+ }
572
+ }
573
+ return undefined;
574
+ }
575
+
576
+ // Literal text can mention `req.query.path` in docs or fixtures without being external input.
577
+ function isSourceTextLiteral(expr: TsNode): boolean {
578
+ return typescriptSyntax.isStringLiteral(expr) || typescriptSyntax.isNoSubstitutionTemplateLiteral(expr);
579
+ }
580
+
581
+ // Regex escaping helpers are sanitizer evidence for dynamic-regexp flow; walking their arguments
582
+ // would otherwise re-taint an already-escaped pattern value.
583
+ function isSafeWrapperExpression(parsedSource: TsSourceFile, expr: TsNode): boolean {
584
+ if (!typescriptSyntax.isCallExpression(expr)) {
585
+ return false;
586
+ }
587
+ const callee = expr.expression.getText(parsedSource);
588
+ return /^(?:escapeRegExp|escapeStringRegexp|regexpEscape|RegExp\.escape)$/.test(callee);
589
+ }
590
+
591
+ // Identifies scope boundaries that must not inherit taint from enclosing functions.
592
+ function isFunctionLike(node: TsNode): boolean {
593
+ return (
594
+ typescriptSyntax.isFunctionDeclaration(node) ||
595
+ typescriptSyntax.isFunctionExpression(node) ||
596
+ typescriptSyntax.isArrowFunction(node) ||
597
+ typescriptSyntax.isMethodDeclaration(node) ||
598
+ typescriptSyntax.isConstructorDeclaration(node) ||
599
+ typescriptSyntax.isGetAccessorDeclaration(node) ||
600
+ typescriptSyntax.isSetAccessorDeclaration(node)
601
+ );
602
+ }
603
+
604
+ /**
605
+ * Build an AST-flow finding with the same stable location and metadata contract as line rules.
606
+ * Invariant: fingerprints continue to derive only from rule id, file path, line, and symbol.
607
+ *
608
+ * @param file - discovered file that owns the finding path
609
+ * @param lineIndex - zero-based sink line from the parsed source file
610
+ * @param ruleId - security rule id to emit
611
+ * @param sinkKind - sink category for machine-readable metadata
612
+ * @param sourceKind - external input category for machine-readable metadata
613
+ * @param flowDepth - bounded alias distance between source and sink
614
+ */
615
+ function flowFinding(file: SourceFile, lineIndex: number, ruleId: string, sinkKind: string, sourceKind: string, flowDepth: number): Finding {
616
+ const base = securityRuleDetails(ruleId);
617
+ return makeFinding({
618
+ ruleId,
619
+ message: base ? base.message : "External input reaches a risky sink across lines.",
620
+ filePath: file.displayPath,
621
+ line: lineIndex + 1,
622
+ severity: "warning",
623
+ pillar: "security",
624
+ confidence: "medium",
625
+ remediation: base ? base.remediation : "Validate external input before it reaches the sink.",
626
+ metadata: { sourceKind, sinkKind, flowDepth },
627
+ });
628
+ }
629
+
630
+ // Supplies messages/remediation for both same-line rule ids and AST-only security candidates.
631
+ function securityRuleDetails(ruleId: string): Pick<SecurityFlowRule, "message" | "remediation"> | undefined {
632
+ return (
633
+ SECURITY_FLOW_RULES.find((rule) => rule.ruleId === ruleId) ??
634
+ ({
635
+ "security.unsafe-deserialization": {
636
+ message: "External input reaches an unsafe deserialization or dynamic code-loading sink.",
637
+ remediation: "Use a schema-bound parser or validate and decode data without executing code.",
638
+ },
639
+ "security.xxe-candidate": {
640
+ message: "External XML input reaches an XML parser configured to expand entities.",
641
+ remediation: "Disable external entity expansion and use hardened XML parser options.",
642
+ },
643
+ } as const)[ruleId]
644
+ );
645
+ }