@blundergoat/gruff-ts 0.3.2 → 0.5.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 (52) hide show
  1. package/CHANGELOG.md +54 -1
  2. package/README.md +16 -6
  3. package/SECURITY.md +2 -1
  4. package/docs/README.md +1 -4
  5. package/docs/agent-hook.md +15 -3
  6. package/docs/configuration.md +47 -1
  7. package/docs/dashboard.md +3 -3
  8. package/docs/reports-and-ci.md +36 -0
  9. package/docs/rules.md +52 -37
  10. package/package.json +1 -1
  11. package/src/analyser.ts +540 -154
  12. package/src/baseline-options.ts +90 -0
  13. package/src/baseline.ts +39 -3
  14. package/src/blocks.ts +116 -77
  15. package/src/changed-regions.ts +80 -11
  16. package/src/class-rules.ts +226 -76
  17. package/src/cli-program.ts +65 -15
  18. package/src/cli.ts +4 -2
  19. package/src/comment-rules.ts +58 -13
  20. package/src/comment-scanner.ts +27 -0
  21. package/src/complexity-metrics.ts +244 -0
  22. package/src/config.ts +56 -16
  23. package/src/constants.ts +1 -1
  24. package/src/context-doc-rules.ts +9 -10
  25. package/src/dead-code-rules.ts +10 -3
  26. package/src/discovery.ts +66 -22
  27. package/src/doc-rules.ts +22 -53
  28. package/src/findings-helpers.ts +127 -1
  29. package/src/findings.ts +4 -0
  30. package/src/fixture-purpose-rules.ts +39 -5
  31. package/src/github-actions-rules.ts +24 -1
  32. package/src/hook-contract.ts +120 -27
  33. package/src/init-config.ts +15 -5
  34. package/src/line-rules.ts +175 -19
  35. package/src/naming-pushers.ts +26 -5
  36. package/src/parsed-script.ts +652 -0
  37. package/src/process-exec-metadata.ts +163 -0
  38. package/src/profiles.ts +14 -0
  39. package/src/project-config-rules.ts +36 -18
  40. package/src/project-rules.ts +159 -42
  41. package/src/public-exports.ts +220 -0
  42. package/src/report-renderers.ts +58 -4
  43. package/src/rules.ts +15 -15
  44. package/src/scoring.ts +13 -4
  45. package/src/security-flow-rules.ts +169 -24
  46. package/src/sensitive-data-rules.ts +256 -80
  47. package/src/source-text.ts +9 -26
  48. package/src/static-analysis-redundant-rules.ts +46 -2
  49. package/src/test-block-rules.ts +118 -14
  50. package/src/test-fixtures.ts +4 -1
  51. package/src/text-scans.ts +8 -1
  52. package/src/types.ts +17 -0
@@ -2,6 +2,7 @@
2
2
  // report only when an external-input token is visibly inside a known risky sink expression.
3
3
  import type { SourceFile } from "./discovery.ts";
4
4
  import { makeFinding } from "./findings.ts";
5
+ import { parseScript } from "./parsed-script.ts";
5
6
  import type { Finding } from "./types.ts";
6
7
  import { createRequire } from "node:module";
7
8
 
@@ -14,27 +15,21 @@ const typescriptSyntax = require("typescript") as typeof import("typescript");
14
15
  type TsSourceFile = import("typescript").SourceFile;
15
16
  type TsNode = import("typescript").Node;
16
17
  type TsCallLikeExpression = import("typescript").CallExpression | import("typescript").NewExpression;
18
+ type TsNamedImportBindings = import("typescript").NamedImportBindings;
17
19
 
18
20
  // Parse a discovered script to a syntax-only AST; null on non-parseable input so
19
21
  // callers use the same-line scan. Parser exceptions recover to null as fallback.
22
+ // Routed through the shared parse boundary rather than calling `createSourceFile` here, so this
23
+ // fallback is counted: an analysis-path caller that stopped threading the run's parse would double
24
+ // the measured parse count instead of re-parsing every script undetected.
20
25
  function getSourceFile(file: SourceFile, source: string): TsSourceFile | null {
21
26
  try {
22
- return typescriptSyntax.createSourceFile(file.displayPath, source, typescriptSyntax.ScriptTarget.Latest, true, scriptKindFor(file.displayPath));
27
+ return parseScript(file, source)?.sourceFile ?? null;
23
28
  } catch {
24
29
  return null;
25
30
  }
26
31
  }
27
32
 
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
33
  // Depth-first walk; return false from visit to skip a node's children.
39
34
  function walk(node: TsNode, visit: (node: TsNode) => boolean | void): void {
40
35
  if (visit(node) === false) {
@@ -92,7 +87,7 @@ const SECURITY_FLOW_RULES: readonly SecurityFlowRule[] = [
92
87
  message: "External input reaches a redirect or browser navigation sink.",
93
88
  sinkKind: "redirect",
94
89
  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,
90
+ callPattern: /\b(?:(?:res|reply|response)\.redirect|(?:location|window\.location)\.(?:assign|replace))\s*\(|\b(?:location|window\.location)\.href\s*=/g,
96
91
  },
97
92
  {
98
93
  ruleId: "security.dynamic-regexp",
@@ -179,6 +174,7 @@ interface AstSinkInput {
179
174
  call: TsCallLikeExpression;
180
175
  sourceFile: TsSourceFile;
181
176
  unsafeXmlParsers: ReadonlySet<string>;
177
+ isFrameworkRedirectCallee: boolean;
182
178
  }
183
179
 
184
180
  // Describes one AST sink candidate. Some AST-only rules report same-line direct-source
@@ -213,10 +209,10 @@ const AST_FLOW_SINKS: readonly AstFlowSink[] = [
213
209
  {
214
210
  ruleId: "security.open-redirect-candidate",
215
211
  sinkKind: "redirect",
216
- isSink: ({ callee }) =>
212
+ isSink: ({ callee, isFrameworkRedirectCallee }) =>
217
213
  /^(?:res|reply|response)\.redirect$/.test(callee) ||
218
- /^redirect$/.test(callee) ||
219
- /^(?:location|window\.location)\.(?:assign|replace)$/.test(callee),
214
+ /^(?:location|window\.location)\.(?:assign|replace)$/.test(callee) ||
215
+ isFrameworkRedirectCallee,
220
216
  },
221
217
  {
222
218
  ruleId: "security.dynamic-regexp",
@@ -240,6 +236,50 @@ const AST_FLOW_SINKS: readonly AstFlowSink[] = [
240
236
  const MAX_ALIAS_DEPTH = 2;
241
237
  const MAX_SCOPE_NODES = 4000;
242
238
 
239
+ // Framework redirects are plain imported functions, so their local alias is the syntax-only
240
+ // evidence that distinguishes them from unrelated helpers named `redirect`.
241
+ function importedFrameworkRedirectCallees(parsedSource: TsSourceFile): ReadonlySet<string> {
242
+ const callees = new Set<string>();
243
+ for (const statement of parsedSource.statements) {
244
+ if (!typescriptSyntax.isImportDeclaration(statement) || !typescriptSyntax.isStringLiteral(statement.moduleSpecifier)) {
245
+ continue;
246
+ }
247
+ if (!isFrameworkRedirectModule(statement.moduleSpecifier.text)) {
248
+ continue;
249
+ }
250
+ const importClause = statement.importClause;
251
+ if (!importClause || importClause.isTypeOnly || !importClause.namedBindings) {
252
+ continue;
253
+ }
254
+ collectRedirectAliases(importClause.namedBindings, callees);
255
+ }
256
+ return callees;
257
+ }
258
+
259
+ // Only these framework modules export a throw-to-navigate redirect; matching the module first
260
+ // avoids treating every imported `redirect` helper as a navigation sink. React Router ships the
261
+ // same data-router `redirect` from both its core and DOM packages.
262
+ function isFrameworkRedirectModule(moduleName: string): boolean {
263
+ return moduleName === "next/navigation" ||
264
+ /^react-router(?:-dom)?$/.test(moduleName) ||
265
+ /^@remix-run\/(?:node|cloudflare|deno|server-runtime)$/.test(moduleName);
266
+ }
267
+
268
+ // Records the local alias each binding style gives the framework `redirect` export: the member
269
+ // path for a namespace import, the (possibly renamed) local name for named imports.
270
+ function collectRedirectAliases(namedBindings: TsNamedImportBindings, callees: Set<string>): void {
271
+ if (typescriptSyntax.isNamespaceImport(namedBindings)) {
272
+ callees.add(`${namedBindings.name.text}.redirect`);
273
+ return;
274
+ }
275
+ for (const element of namedBindings.elements) {
276
+ const importedName = element.propertyName?.text ?? element.name.text;
277
+ if (!element.isTypeOnly && importedName === "redirect") {
278
+ callees.add(element.name.text);
279
+ }
280
+ }
281
+ }
282
+
243
283
  /**
244
284
  * Per-file AST pass. Parses the file once (syntax-only) and reports cross-line
245
285
  * source-to-sink flows for the existing security-flow rule ids. Does nothing
@@ -249,9 +289,12 @@ const MAX_SCOPE_NODES = 4000;
249
289
  * @param file - discovered script file whose display path anchors emitted fingerprints
250
290
  * @param source - full source text to parse with syntax-only TypeScript APIs
251
291
  * @param findings - accumulator that receives additional AST flow findings
292
+ * @param sharedSourceFile - the run's shared parse result; null/undefined falls back to a local parse
252
293
  */
253
- export function analyseSecurityFlow(file: SourceFile, source: string, findings: Finding[]): void {
254
- const parsedSource = getSourceFile(file, source);
294
+ export function analyseSecurityFlow(file: SourceFile, source: string, findings: Finding[], sharedSourceFile?: TsSourceFile | null): void {
295
+ // Prefer the shared per-run parse (one parse per script); the local parse remains only as the
296
+ // fallback for direct callers that have no boundary result, such as focused unit tests.
297
+ const parsedSource = sharedSourceFile ?? getSourceFile(file, source);
255
298
  if (!parsedSource) {
256
299
  return;
257
300
  }
@@ -260,6 +303,7 @@ export function analyseSecurityFlow(file: SourceFile, source: string, findings:
260
303
  // partial result. The same-line scan remains the fallback for such files.
261
304
  const flowFindings: Finding[] = [];
262
305
  try {
306
+ const frameworkRedirectCallees = importedFrameworkRedirectCallees(parsedSource);
263
307
  const scopes: TsNode[] = [parsedSource];
264
308
  walk(parsedSource, (node) => {
265
309
  if (isFunctionLike(node)) {
@@ -267,7 +311,7 @@ export function analyseSecurityFlow(file: SourceFile, source: string, findings:
267
311
  }
268
312
  });
269
313
  for (const scope of scopes) {
270
- analyseFlowScope(parsedSource, scope, file, flowFindings);
314
+ analyseFlowScope(parsedSource, scope, frameworkRedirectCallees, file, flowFindings);
271
315
  }
272
316
  } catch {
273
317
  return;
@@ -286,7 +330,13 @@ export function analyseSecurityFlow(file: SourceFile, source: string, findings:
286
330
  * @param file - discovered file used for stable finding locations
287
331
  * @param findings - accumulator that receives sink findings for this scope
288
332
  */
289
- function analyseFlowScope(parsedSource: TsSourceFile, scopeOwner: TsNode, file: SourceFile, findings: Finding[]): void {
333
+ function analyseFlowScope(
334
+ parsedSource: TsSourceFile,
335
+ scopeOwner: TsNode,
336
+ frameworkRedirectCallees: ReadonlySet<string>,
337
+ file: SourceFile,
338
+ findings: Finding[],
339
+ ): void {
290
340
  const tainted = new Map<string, TaintRecord>();
291
341
  const unsafeXmlParsers = new Set<string>();
292
342
  let budget = MAX_SCOPE_NODES;
@@ -300,7 +350,7 @@ function analyseFlowScope(parsedSource: TsSourceFile, scopeOwner: TsNode, file:
300
350
  }
301
351
  recordUnsafeXmlParser(parsedSource, node, unsafeXmlParsers);
302
352
  recordTaint(parsedSource, node, tainted);
303
- reportSink(parsedSource, node, tainted, unsafeXmlParsers, file, findings);
353
+ reportSink(parsedSource, node, tainted, unsafeXmlParsers, frameworkRedirectCallees, file, findings);
304
354
  return;
305
355
  });
306
356
  }
@@ -385,13 +435,14 @@ function recordUnsafeXmlParser(parsedSource: TsSourceFile, node: TsNode, unsafeX
385
435
  }
386
436
  }
387
437
 
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.
438
+ // Reports a finding when a sink call consumes a tainted local. Invariant: legacy scanners retain
439
+ // same-line ownership except for imported framework redirects, which have no safe line-regex equivalent.
390
440
  function reportSink(
391
441
  parsedSource: TsSourceFile,
392
442
  node: TsNode,
393
443
  tainted: Map<string, TaintRecord>,
394
444
  unsafeXmlParsers: ReadonlySet<string>,
445
+ frameworkRedirectCallees: ReadonlySet<string>,
395
446
  file: SourceFile,
396
447
  findings: Finding[],
397
448
  ): void {
@@ -401,7 +452,8 @@ function reportSink(
401
452
  return;
402
453
  }
403
454
  const callee = call.expression.getText(parsedSource);
404
- const sink = AST_FLOW_SINKS.find((candidate) => candidate.isSink({ callee, call, sourceFile: parsedSource, unsafeXmlParsers }));
455
+ const isFrameworkRedirectCallee = frameworkRedirectCallees.has(callee) && !isFrameworkRedirectShadowed(call, callee);
456
+ const sink = AST_FLOW_SINKS.find((candidate) => candidate.isSink({ callee, call, sourceFile: parsedSource, unsafeXmlParsers, isFrameworkRedirectCallee }));
405
457
  if (!sink) {
406
458
  return;
407
459
  }
@@ -410,12 +462,105 @@ function reportSink(
410
462
  return;
411
463
  }
412
464
  const sinkLine = lineIndexOf(parsedSource, call);
413
- if (sinkLine === hit.line && sink.shouldReportSameLine !== true) {
465
+ const reportsSameLine = sink.shouldReportSameLine === true || isFrameworkRedirectCallee;
466
+ if (sinkLine === hit.line && !reportsSameLine) {
414
467
  return;
415
468
  }
416
469
  findings.push(flowFinding(file, sinkLine, sink.ruleId, sink.sinkKind, hit.kind, hit.depth));
417
470
  }
418
471
 
472
+ // Imported redirect aliases stop being sink evidence inside a lexical scope that declares the
473
+ // alias again. Syntax-only binding checks cover parameters and local value declarations.
474
+ function isFrameworkRedirectShadowed(call: TsCallLikeExpression, callee: string): boolean {
475
+ const rootName = callee.split(".", 1)[0];
476
+ if (!rootName) {
477
+ return false;
478
+ }
479
+ for (let ancestor = call.parent; ancestor && !typescriptSyntax.isSourceFile(ancestor); ancestor = ancestor.parent) {
480
+ if (functionLikeBindsName(ancestor, rootName) || lexicalStatementsBindName(ancestor, rootName) || loopOrCatchBindsName(ancestor, rootName)) {
481
+ return true;
482
+ }
483
+ }
484
+ return false;
485
+ }
486
+
487
+ // Function parameters bind identifiers throughout their body. Only a declaration or a named
488
+ // function expression also binds its own name there - a method or accessor name is a property key
489
+ // reached through the object, so a method called `redirect` still sees the imported `redirect`.
490
+ function functionLikeBindsName(node: TsNode, name: string): boolean {
491
+ if (!isFunctionLike(node)) {
492
+ return false;
493
+ }
494
+ const functionNode = node as TsNode & {
495
+ name?: import("typescript").PropertyName;
496
+ parameters: readonly import("typescript").ParameterDeclaration[];
497
+ };
498
+ const bindsOwnName = typescriptSyntax.isFunctionDeclaration(node) || typescriptSyntax.isFunctionExpression(node);
499
+ if (bindsOwnName && functionNode.name && typescriptSyntax.isIdentifier(functionNode.name) && functionNode.name.text === name) {
500
+ return true;
501
+ }
502
+ return functionNode.parameters.some((parameter) => bindingNameContains(parameter.name, name));
503
+ }
504
+
505
+ // Block-level value declarations shadow an import across the whole lexical block, including its
506
+ // temporal-dead-zone prefix. Case clauses carry their own direct statement list.
507
+ function lexicalStatementsBindName(node: TsNode, name: string): boolean {
508
+ if (typescriptSyntax.isBlock(node) || typescriptSyntax.isModuleBlock(node) || typescriptSyntax.isCaseClause(node) || typescriptSyntax.isDefaultClause(node)) {
509
+ return node.statements.some((statement) => statementBindsName(statement, name));
510
+ }
511
+ return false;
512
+ }
513
+
514
+ // Loops and catch clauses introduce bindings outside a nested statement list.
515
+ function loopOrCatchBindsName(node: TsNode, name: string): boolean {
516
+ if (typescriptSyntax.isCatchClause(node)) {
517
+ return node.variableDeclaration ? bindingNameContains(node.variableDeclaration.name, name) : false;
518
+ }
519
+ if (typescriptSyntax.isForStatement(node)) {
520
+ return node.initializer && typescriptSyntax.isVariableDeclarationList(node.initializer)
521
+ ? variableDeclarationListBindsName(node.initializer, name)
522
+ : false;
523
+ }
524
+ if (typescriptSyntax.isForInStatement(node) || typescriptSyntax.isForOfStatement(node)) {
525
+ return typescriptSyntax.isVariableDeclarationList(node.initializer)
526
+ ? variableDeclarationListBindsName(node.initializer, name)
527
+ : false;
528
+ }
529
+ return false;
530
+ }
531
+
532
+ // Only runtime declarations count: type-only declarations do not shadow an imported value.
533
+ function statementBindsName(statement: import("typescript").Statement, name: string): boolean {
534
+ if (typescriptSyntax.isVariableStatement(statement)) {
535
+ return variableDeclarationListBindsName(statement.declarationList, name);
536
+ }
537
+ if (typescriptSyntax.isFunctionDeclaration(statement) || typescriptSyntax.isClassDeclaration(statement) || typescriptSyntax.isEnumDeclaration(statement)) {
538
+ return statement.name?.text === name;
539
+ }
540
+ if (typescriptSyntax.isImportEqualsDeclaration(statement)) {
541
+ return statement.name.text === name;
542
+ }
543
+ if (typescriptSyntax.isModuleDeclaration(statement) && typescriptSyntax.isIdentifier(statement.name)) {
544
+ return statement.name.text === name;
545
+ }
546
+ return false;
547
+ }
548
+
549
+ // Variable declaration lists may contain identifier or destructuring bindings.
550
+ function variableDeclarationListBindsName(list: import("typescript").VariableDeclarationList, name: string): boolean {
551
+ return list.declarations.some((declaration) => bindingNameContains(declaration.name, name));
552
+ }
553
+
554
+ // Recurses through object and array binding patterns without inspecting property names.
555
+ function bindingNameContains(bindingName: import("typescript").BindingName, name: string): boolean {
556
+ if (typescriptSyntax.isIdentifier(bindingName)) {
557
+ return bindingName.text === name;
558
+ }
559
+ return bindingName.elements.some((element) =>
560
+ !typescriptSyntax.isOmittedExpression(element) && bindingNameContains(element.name, name),
561
+ );
562
+ }
563
+
419
564
  // Reports redirect assignment flows; invariant: same-line cases stay with the legacy scanner.
420
565
  function reportRedirectAssignmentSink(parsedSource: TsSourceFile, node: TsNode, tainted: Map<string, TaintRecord>, file: SourceFile, findings: Finding[]): void {
421
566
  if (!typescriptSyntax.isBinaryExpression(node) || node.operatorToken.kind !== typescriptSyntax.SyntaxKind.EqualsToken) {