@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
package/src/line-rules.ts CHANGED
@@ -4,11 +4,12 @@
4
4
  // detection and the block-rule parameter pass. Dead-code rules (unused imports, unreachable) are
5
5
  // invoked by the cli orchestrator before/after this module so the stable per-line emission order
6
6
  // stays a single contract.
7
- import { ruleSeverity } from "./config.ts";
7
+ import { ruleEnabled, ruleSeverity } from "./config.ts";
8
8
  import { type SourceFile } from "./discovery.ts";
9
9
  import { makeFinding } from "./findings.ts";
10
10
  import { escapeRegex, finding, isCommentedOutCode } from "./findings-helpers.ts";
11
11
  import { type NamingSurface, pushBooleanPrefixAt, pushIdentifierQualityAt, pushNegativeBooleanAt, pushShortVariableAt } from "./naming-pushers.ts";
12
+ import { processExecMetadata, type ProcessExecArgumentSource, type ProcessExecMetadata } from "./process-exec-metadata.ts";
12
13
  import { analyseReliabilityLine, analyseSwallowedCatches, analyseTypeSafetyLine, analyseUselessCatches } from "./safety-rules.ts";
13
14
  import { analyseSecurityFlowLine } from "./security-flow-rules.ts";
14
15
  import { codeLineForMatching } from "./source-text.ts";
@@ -44,12 +45,61 @@ interface LineRuleContext {
44
45
  codeChecks: LineRuleCheck[];
45
46
  literalChecks: LineRuleCheck[];
46
47
  variables: RegExp;
48
+ gates: LineRuleGates;
47
49
  }
48
50
 
49
51
  const CODE_LINE_CHECKS = codeLineChecks();
50
52
  const LITERAL_LINE_CHECKS = literalLineChecks();
51
53
  const VARIABLE_DECLARATIONS = /\b(?:const|let|for\s*\(\s*const|for\s*\(\s*let)\s+([A-Za-z_$][A-Za-z0-9_$]*)/g;
52
54
 
55
+ // Per-file rule-family switches. They avoid re-running helpers when every rule they emit is disabled.
56
+ interface LineRuleGates {
57
+ shouldRunTypeSafety: boolean;
58
+ shouldRunReliability: boolean;
59
+ shouldRunCommentedOutCode: boolean;
60
+ shouldRunBooleanNaming: boolean;
61
+ shouldRunHungarianNotation: boolean;
62
+ shouldRunOptionalChaining: boolean;
63
+ shouldRunNullishCoalescing: boolean;
64
+ shouldRunLooseEquality: boolean;
65
+ shouldRunStringTimer: boolean;
66
+ shouldRunSecurityFlow: boolean;
67
+ shouldRunVariableNaming: boolean;
68
+ shouldRunProcessExec: boolean;
69
+ shouldRunUselessCatch: boolean;
70
+ shouldRunSwallowedCatch: boolean;
71
+ }
72
+
73
+ const TYPE_SAFETY_RULE_IDS = [
74
+ "modernisation.double-cast",
75
+ "modernisation.non-null-assertion",
76
+ "modernisation.ts-comment-without-rationale",
77
+ "waste.exported-any",
78
+ ] as const;
79
+
80
+ const RELIABILITY_RULE_IDS = [
81
+ "security.async-foreach",
82
+ "security.floating-promise",
83
+ "security.throw-non-error",
84
+ ] as const;
85
+
86
+ const BOOLEAN_NAMING_RULE_IDS = [
87
+ "naming.boolean-prefix",
88
+ "naming.negative-boolean",
89
+ ] as const;
90
+
91
+ const SECURITY_FLOW_LINE_RULE_IDS = [
92
+ "security.dynamic-regexp",
93
+ "security.open-redirect-candidate",
94
+ "security.path-traversal-candidate",
95
+ "security.ssrf-candidate",
96
+ ] as const;
97
+
98
+ const VARIABLE_NAMING_RULE_IDS = [
99
+ "naming.identifier-quality",
100
+ "naming.short-variable",
101
+ ] as const;
102
+
53
103
  /*
54
104
  * Per-line rule pipeline plus the two multi-line catch detectors. Excludes analyseUnusedImports
55
105
  * and analyseUnreachable so the dead-code module can own them; the orchestrator in cli.ts wraps
@@ -58,6 +108,22 @@ const VARIABLE_DECLARATIONS = /\b(?:const|let|for\s*\(\s*const|for\s*\(\s*let)\s
58
108
  export function analyseLineRules(file: SourceFile, source: string, codeSource: string, config: Config, findings: Finding[]): void {
59
109
  const sourceLines = source.split(/\r?\n/);
60
110
  const codeLines = codeSource.split(/\r?\n/);
111
+ const gates: LineRuleGates = {
112
+ shouldRunTypeSafety: TYPE_SAFETY_RULE_IDS.some((ruleId) => ruleEnabled(config, ruleId)),
113
+ shouldRunReliability: RELIABILITY_RULE_IDS.some((ruleId) => ruleEnabled(config, ruleId)),
114
+ shouldRunCommentedOutCode: ruleEnabled(config, "waste.commented-out-code"),
115
+ shouldRunBooleanNaming: BOOLEAN_NAMING_RULE_IDS.some((ruleId) => ruleEnabled(config, ruleId)),
116
+ shouldRunHungarianNotation: ruleEnabled(config, "naming.hungarian-notation"),
117
+ shouldRunOptionalChaining: ruleEnabled(config, "modernisation.optional-chaining-candidate"),
118
+ shouldRunNullishCoalescing: ruleEnabled(config, "modernisation.nullish-coalescing-candidate"),
119
+ shouldRunLooseEquality: ruleEnabled(config, "modernisation.loose-equality"),
120
+ shouldRunStringTimer: ruleEnabled(config, "security.string-timer"),
121
+ shouldRunSecurityFlow: SECURITY_FLOW_LINE_RULE_IDS.some((ruleId) => ruleEnabled(config, ruleId)),
122
+ shouldRunVariableNaming: VARIABLE_NAMING_RULE_IDS.some((ruleId) => ruleEnabled(config, ruleId)),
123
+ shouldRunProcessExec: ruleEnabled(config, "security.process-exec"),
124
+ shouldRunUselessCatch: ruleEnabled(config, "waste.useless-catch"),
125
+ shouldRunSwallowedCatch: ruleEnabled(config, "waste.swallowed-catch"),
126
+ };
61
127
  const context: LineRuleContext = {
62
128
  file,
63
129
  line: "",
@@ -66,9 +132,10 @@ export function analyseLineRules(file: SourceFile, source: string, codeSource: s
66
132
  lineNumber: 0,
67
133
  config,
68
134
  findings,
69
- codeChecks: CODE_LINE_CHECKS,
70
- literalChecks: LITERAL_LINE_CHECKS,
135
+ codeChecks: CODE_LINE_CHECKS.filter((check) => ruleEnabled(config, check.ruleId)),
136
+ literalChecks: LITERAL_LINE_CHECKS.filter((check) => ruleEnabled(config, check.ruleId)),
71
137
  variables: VARIABLE_DECLARATIONS,
138
+ gates,
72
139
  };
73
140
  sourceLines.forEach((line, index) => {
74
141
  context.line = line;
@@ -78,26 +145,54 @@ export function analyseLineRules(file: SourceFile, source: string, codeSource: s
78
145
  analyseLineRuleContext(context);
79
146
  });
80
147
 
81
- analyseProcessExecCalls(file, source, codeSource, findings);
82
- analyseUselessCatches(file, codeSource, findings);
83
- analyseSwallowedCatches(file, source, codeSource, findings);
148
+ if (gates.shouldRunProcessExec) {
149
+ analyseProcessExecCalls(file, source, codeSource, findings);
150
+ }
151
+ if (gates.shouldRunUselessCatch) {
152
+ analyseUselessCatches(file, codeSource, findings);
153
+ }
154
+ if (gates.shouldRunSwallowedCatch) {
155
+ analyseSwallowedCatches(file, source, codeSource, findings);
156
+ }
84
157
  }
85
158
 
86
159
  // All per-line checks for a single line in their stable, deterministic emission order. Each helper
87
160
  // either no-ops (rule skipped or no match) or appends to `findings`.
88
161
  function analyseLineRuleContext(context: LineRuleContext): void {
89
- analyseTypeSafetyLine(context.file, context.line, context.codeLine, context.lineNumber, context.findings);
90
- analyseReliabilityLine(context.file, context.codeLine, context.lineNumber, context.findings);
91
- pushCommentedOutCodeFinding(context);
92
- pushBooleanPrefixFinding(context);
93
- pushHungarianNotationFindings(context);
94
- pushOptionalChainingFindings(context);
95
- pushNullishCoalescingFindings(context);
96
- pushLooseEqualityFinding(context);
97
- pushStringTimerFinding(context);
98
- analyseSecurityFlowLine(context.file, context.codeLine, context.lineNumber, context.findings);
162
+ if (context.gates.shouldRunTypeSafety) {
163
+ analyseTypeSafetyLine(context.file, context.line, context.codeLine, context.lineNumber, context.findings);
164
+ }
165
+ if (context.gates.shouldRunReliability) {
166
+ analyseReliabilityLine(context.file, context.codeLine, context.lineNumber, context.findings);
167
+ }
168
+ if (context.gates.shouldRunCommentedOutCode) {
169
+ pushCommentedOutCodeFinding(context);
170
+ }
171
+ if (context.gates.shouldRunBooleanNaming) {
172
+ pushBooleanPrefixFinding(context);
173
+ }
174
+ if (context.gates.shouldRunHungarianNotation) {
175
+ pushHungarianNotationFindings(context);
176
+ }
177
+ if (context.gates.shouldRunOptionalChaining) {
178
+ pushOptionalChainingFindings(context);
179
+ }
180
+ if (context.gates.shouldRunNullishCoalescing) {
181
+ pushNullishCoalescingFindings(context);
182
+ }
183
+ if (context.gates.shouldRunLooseEquality) {
184
+ pushLooseEqualityFinding(context);
185
+ }
186
+ if (context.gates.shouldRunStringTimer) {
187
+ pushStringTimerFinding(context);
188
+ }
189
+ if (context.gates.shouldRunSecurityFlow) {
190
+ analyseSecurityFlowLine(context.file, context.codeLine, context.lineNumber, context.findings);
191
+ }
99
192
  pushPatternCheckFindings(context);
100
- pushVariableNameFindings(context);
193
+ if (context.gates.shouldRunVariableNaming) {
194
+ pushVariableNameFindings(context);
195
+ }
101
196
  }
102
197
 
103
198
  // Code-shape rules: those that must match against the masked code (no comment or literal noise).
@@ -123,7 +218,7 @@ function literalLineChecks(): LineRuleCheck[] {
123
218
  { ruleId: "security.disabled-tls-verification", pattern: /\b(?:process\.env\.)?NODE_TLS_REJECT_UNAUTHORIZED\b\s*=\s*["']0["']|\brejectUnauthorized\s*:\s*false\b/i, message: "TLS certificate verification is disabled.", severity: "error", pillar: "security" },
124
219
  { ruleId: "security.javascript-url", pattern: /["'`]\s*javascript\s*:(?!\s+URL\b)/i, message: "javascript: URL literal can execute script.", severity: "error", pillar: "security" },
125
220
  { ruleId: "security.proto-access", pattern: /\[\s*["']__proto__["']\s*\]/, message: "Direct __proto__ access can enable prototype pollution.", severity: "warning", pillar: "security" },
126
- { ruleId: "security.sql-concatenation", pattern: /\b(?:query|execute|raw)\s*\(\s*(?:`[^`]*(?:SELECT|INSERT|UPDATE|DELETE)[^`]*\$\{|["'][^"']*(?:SELECT|INSERT|UPDATE|DELETE)[^"']*["']\s*\+)/i, message: "SQL text is composed with runtime string interpolation.", severity: "warning", pillar: "security" },
221
+ { ruleId: "security.sql-concatenation", pattern: /\b(?:query|execute|raw|prepare)\s*\(\s*(?:`[^`]*(?:SELECT|INSERT|UPDATE|DELETE)[^`]*\$\{|["'][^"']*(?:SELECT|INSERT|UPDATE|DELETE)[^"']*["']\s*\+)/i, message: "SQL text is composed with runtime string interpolation.", severity: "warning", pillar: "security" },
127
222
  { ruleId: "modernisation.date-now-candidate", pattern: /\bnew\s+Date\s*\(\s*\)\s*\.getTime\s*\(\s*\)|\bNumber\s*\(\s*new\s+Date\s*\(\s*\)\s*\)/, message: "Current-time expression can use Date.now().", severity: "advisory", pillar: "modernisation" },
128
223
  { ruleId: "modernisation.object-spread-candidate", pattern: /\bObject\.assign\s*\(\s*\{\s*\}\s*,/, message: "Object.assign clone can usually use object spread.", severity: "advisory", pillar: "modernisation" },
129
224
  { ruleId: "waste.console-log", pattern: /\bconsole\.(log|debug)\s*\(/, message: "console logging is committed in source.", severity: "advisory", pillar: "maintainability" },
@@ -476,8 +571,69 @@ function analyseProcessExecCalls(file: SourceFile, rawSource: string, codeSource
476
571
  if (isSafeProcessExecCall(file, callName, rawSource, start, rawSegment, codeSegment)) {
477
572
  continue;
478
573
  }
479
- findings.push(finding({ ruleId: "security.process-exec", message: "Child-process execution is used; validate arguments are not user-controlled.", file, line: byteLine(codeSource, start), severity: "warning", pillar: "security" }));
574
+ const metadata = processExecMetadata(callName, rawSource, start, rawSegment, codeSegment);
575
+ const grade = processExecGrade(metadata);
576
+ findings.push(
577
+ makeFinding({
578
+ ruleId: "security.process-exec",
579
+ message: grade.message,
580
+ filePath: file.displayPath,
581
+ line: byteLine(codeSource, start),
582
+ severity: grade.severity,
583
+ pillar: "security",
584
+ confidence: "high",
585
+ remediation: grade.remediation,
586
+ metadata: {
587
+ callName: metadata.callName,
588
+ argumentSource: metadata.argumentSource,
589
+ shellEnabled: metadata.isShellEnabled,
590
+ },
591
+ }),
592
+ );
593
+ }
594
+ }
595
+
596
+ // Every command-source shape has one compile-time class, so adding a metadata variant cannot fall
597
+ // through to a quieter grade until its security posture is chosen explicitly.
598
+ const PROCESS_EXEC_SOURCE_CLASSES = {
599
+ literal: "fixed",
600
+ "process-exec-path": "fixed",
601
+ "local-const": "fixed",
602
+ "local-builder": "dynamic",
603
+ parameter: "dynamic",
604
+ member: "dynamic",
605
+ template: "dynamic",
606
+ unknown: "dynamic",
607
+ } as const satisfies Record<ProcessExecArgumentSource, "dynamic" | "fixed">;
608
+
609
+ /*
610
+ * Severity follows the evidence the metadata already carries: only a shell-enabled call with a
611
+ * dynamic command keeps the warning. A fixed vector with the shell disabled becomes advisory and
612
+ * its message says what would make it dangerous instead of implying it already is; everything in
613
+ * between stays advisory with the review prompt, so the security pillar is not permanently
614
+ * occupied by calls the reviewer cannot change.
615
+ */
616
+ function processExecGrade(metadata: ProcessExecMetadata): { severity: Severity; message: string; remediation: string } {
617
+ const sourceClass = PROCESS_EXEC_SOURCE_CLASSES[metadata.argumentSource];
618
+ if (metadata.isShellEnabled && sourceClass === "dynamic") {
619
+ return {
620
+ severity: "warning",
621
+ message: "Child-process execution is used; validate arguments are not user-controlled.",
622
+ remediation: "Review the command source and shell mode; prefer fixed command vectors with shell disabled.",
623
+ };
480
624
  }
625
+ if (!metadata.isShellEnabled && sourceClass === "fixed") {
626
+ return {
627
+ severity: "advisory",
628
+ message: "Child-process execution uses a fixed command with shell disabled.",
629
+ remediation: "No action needed while the command stays fixed; revisit if the command or its arguments start deriving from user input or a shell gets enabled.",
630
+ };
631
+ }
632
+ return {
633
+ severity: "advisory",
634
+ message: "Child-process execution is used; validate arguments are not user-controlled.",
635
+ remediation: "Review the command source and shell mode; prefer fixed command vectors with shell disabled.",
636
+ };
481
637
  }
482
638
 
483
639
  // Excludes ordinary member calls such as `pattern.exec(...)`; module receivers like `cp.exec(...)`
@@ -12,6 +12,27 @@ import type { Config, Finding } from "./types.ts";
12
12
  */
13
13
  export type NamingSurface = "declaration" | "parameter" | "destructure" | "interface-field";
14
14
 
15
+ /**
16
+ * Selects the report guidance for a boolean's source surface. Contract fields point users to the
17
+ * complete replacement allowlist or a serialization map; local code receives a safe rename action.
18
+ * @param surface Naming origin shown in finding metadata; interface-field means a contract surface.
19
+ * @returns Remediation text and action metadata for the finding emitter.
20
+ */
21
+ export function booleanPrefixGuidance(surface: NamingSurface): { remediation: string; remediationAction: "APPLY" | "CONFIGURE"; configurationKey?: "allowlists.acceptedBooleanNames" } {
22
+ // Interface and named type-literal fields may be external keys that a rename would break.
23
+ if (surface === "interface-field") {
24
+ return {
25
+ remediation: "If this is an external contract key, include it in the complete replacement list at `allowlists.acceptedBooleanNames` or map it at the serialization boundary; otherwise rename the field with an intent-revealing prefix.",
26
+ remediationAction: "CONFIGURE",
27
+ configurationKey: "allowlists.acceptedBooleanNames",
28
+ };
29
+ }
30
+ return {
31
+ remediation: "Rename this boolean with an intent-revealing prefix such as is, has, can, should, or will.",
32
+ remediationAction: "APPLY",
33
+ };
34
+ }
35
+
15
36
  /*
16
37
  * Negative-framed booleans (disableX, noX, preventX, …) read as double negations at call sites.
17
38
  * `negativeBooleanAllowed` is the user-curated exemption list. Reports the stable
@@ -41,14 +62,14 @@ export function pushNegativeBooleanAt(file: SourceFile, line: number, name: stri
41
62
  }
42
63
 
43
64
  /*
44
- * Booleans should announce their boolean-ness with an `is`/`has`/`can`/… prefix. The accepted set
45
- * lives in `config.booleanPrefixes` so projects can tune it. Reports the stable
46
- * `naming.boolean-prefix` finding.
65
+ * Reports typed booleans without an accepted prefix or exact contract name. The finding keeps its
66
+ * stable identity while its surface selects safe local-rename or contract configuration guidance.
47
67
  */
48
68
  export function pushBooleanPrefixAt(file: SourceFile, line: number, name: string, config: Config, findings: Finding[], surface: NamingSurface): void {
49
69
  if (hasBooleanPrefix(name, config.booleanPrefixes) || isAcceptedBooleanStateName(name) || isAcceptedContractBooleanName(name, config, surface)) {
50
70
  return;
51
71
  }
72
+ const { remediation, ...remediationMetadata } = booleanPrefixGuidance(surface);
52
73
  findings.push(
53
74
  makeFinding({
54
75
  ruleId: "naming.boolean-prefix",
@@ -59,8 +80,8 @@ export function pushBooleanPrefixAt(file: SourceFile, line: number, name: string
59
80
  pillar: "naming",
60
81
  confidence: "medium",
61
82
  symbol: name,
62
- remediation: "Use a prefix such as is, has, can, should, or will.",
63
- metadata: { identifierName: name, surface },
83
+ remediation,
84
+ metadata: { identifierName: name, surface, ...remediationMetadata },
64
85
  }),
65
86
  );
66
87
  }