@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
package/src/line-rules.ts CHANGED
@@ -1,21 +1,27 @@
1
- // Per-line and per-source line rules: security/modernisation regex passes, type-safety
2
- // (ts-comment, non-null, double-cast, exported-any), reliability (async-forEach, floating-promise,
3
- // non-Error throw, useless/swallowed catches), and the naming-pusher fanout used by both line
4
- // detection and the block-rule parameter pass. Dead-code rules (unused imports, unreachable) are
5
- // invoked by the cli orchestrator before/after this module so the stable per-line emission order
6
- // stays a single contract.
1
+ // Runs per-line and multi-line catch checks over each TypeScript or JavaScript source file during analysis.
2
+ //
3
+ // Evaluates enabled line-level rule families in a fixed order so finding lists stay deterministic across runs:
4
+ // - security and modernisation regex passes, type-safety checks, reliability checks, and variable naming;
5
+ // - dead-code passes (`analyseUnusedImports`, `analyseUnreachable`) are scheduled separately by `analyser.ts`.
6
+ import { createRequire } from "node:module";
7
7
  import { ruleEnabled, ruleSeverity } from "./config.ts";
8
8
  import { type SourceFile } from "./discovery.ts";
9
- import { makeFinding } from "./findings.ts";
10
- import { escapeRegex, finding, isCommentedOutCode } from "./findings-helpers.ts";
11
- import { type NamingSurface, pushBooleanPrefixAt, pushIdentifierQualityAt, pushNegativeBooleanAt, pushShortVariableAt } from "./naming-pushers.ts";
12
- import { processExecMetadata } from "./process-exec-metadata.ts";
9
+ import { finding } from "./findings-helpers.ts";
10
+ import { pushIdentifierQualityAt, pushShortVariableAt } from "./naming-pushers.ts";
11
+ import { codeLineFlags, type ParsedScript } from "./parsed-script.ts";
12
+ import { ruleDescriptors } from "./rules.ts";
13
13
  import { analyseReliabilityLine, analyseSwallowedCatches, analyseTypeSafetyLine, analyseUselessCatches } from "./safety-rules.ts";
14
14
  import { analyseSecurityFlowLine } from "./security-flow-rules.ts";
15
15
  import { codeLineForMatching } from "./source-text.ts";
16
- import { byteLine } from "./text-scans.ts";
17
16
  import type { Config, Finding, Pillar, Severity } from "./types.ts";
18
17
 
18
+ // TypeScript is CommonJS at runtime; literal guards only walk the shared parse (ADR-012).
19
+ const require = createRequire(import.meta.url);
20
+ const typescriptSyntax = require("typescript") as typeof import("typescript");
21
+
22
+ type TsSourceFile = import("typescript").SourceFile;
23
+ type TsNode = import("typescript").Node;
24
+
19
25
  // Descriptor for one regex-backed line rule. `pattern` is the cheap test and `globalPattern`
20
26
  // (optional) is used when the rule needs all matches for emission, not just the first hit.
21
27
  interface LineRuleCheck {
@@ -39,9 +45,17 @@ interface LineRuleContext {
39
45
  // forward look-ahead (for-of body brace-balancing in `pushVariableNameFindings`) can scan beyond
40
46
  // the current line without re-splitting the source.
41
47
  codeLines: readonly string[];
48
+ // The raw source lines, so a directive's rationale can be read from the comment lines above it.
49
+ sourceLines: readonly string[];
50
+ // One flag per line, true where it carries code; the for-of body span counts only these lines.
51
+ isCodeLine: readonly boolean[];
42
52
  lineNumber: number;
43
53
  config: Config;
44
54
  findings: Finding[];
55
+ // 1-based lines whose only `.innerHTML =` assignments take a plain string or a template without substitutions.
56
+ fixedInnerHtmlLines: ReadonlySet<number>;
57
+ // 1-based lines whose eval calls all take one fixed string or substitution-free template.
58
+ fixedEvalLines: ReadonlySet<number>;
45
59
  codeChecks: LineRuleCheck[];
46
60
  literalChecks: LineRuleCheck[];
47
61
  variables: RegExp;
@@ -56,16 +70,9 @@ const VARIABLE_DECLARATIONS = /\b(?:const|let|for\s*\(\s*const|for\s*\(\s*let)\s
56
70
  interface LineRuleGates {
57
71
  shouldRunTypeSafety: boolean;
58
72
  shouldRunReliability: boolean;
59
- shouldRunCommentedOutCode: boolean;
60
- shouldRunBooleanNaming: boolean;
61
- shouldRunHungarianNotation: boolean;
62
- shouldRunOptionalChaining: boolean;
63
- shouldRunNullishCoalescing: boolean;
64
- shouldRunLooseEquality: boolean;
65
73
  shouldRunStringTimer: boolean;
66
74
  shouldRunSecurityFlow: boolean;
67
75
  shouldRunVariableNaming: boolean;
68
- shouldRunProcessExec: boolean;
69
76
  shouldRunUselessCatch: boolean;
70
77
  shouldRunSwallowedCatch: boolean;
71
78
  }
@@ -79,15 +86,9 @@ const TYPE_SAFETY_RULE_IDS = [
79
86
 
80
87
  const RELIABILITY_RULE_IDS = [
81
88
  "security.async-foreach",
82
- "security.floating-promise",
83
89
  "security.throw-non-error",
84
90
  ] as const;
85
91
 
86
- const BOOLEAN_NAMING_RULE_IDS = [
87
- "naming.boolean-prefix",
88
- "naming.negative-boolean",
89
- ] as const;
90
-
91
92
  const SECURITY_FLOW_LINE_RULE_IDS = [
92
93
  "security.dynamic-regexp",
93
94
  "security.open-redirect-candidate",
@@ -100,27 +101,28 @@ const VARIABLE_NAMING_RULE_IDS = [
100
101
  "naming.short-variable",
101
102
  ] as const;
102
103
 
103
- /*
104
- * Per-line rule pipeline plus the two multi-line catch detectors. Excludes analyseUnusedImports
105
- * and analyseUnreachable so the dead-code module can own them; the orchestrator in cli.ts wraps
106
- * this call with those rules to preserve the stable, deterministic emission order.
104
+ /**
105
+ * Run per-line checks and multi-line catch detectors when their rules are enabled.
106
+ * The analyser schedules analyseUnusedImports and analyseUnreachable separately to preserve stable finding order.
107
+ *
108
+ * @param file - Source file used to attribute findings.
109
+ * @param source - Original source text used by literal and catch checks.
110
+ * @param codeSource - Masked source text used for code matching.
111
+ * @param config - Rule switches and tracking tokens for the enabled checks.
112
+ * @param findings - Collector for line and catch findings.
113
+ * @param parsed - Optional syntax tree. Literal guards use text behavior when the parse is absent or has diagnostics.
114
+ * @returns Nothing. Appends findings and resets the shared variable matcher before checking each line.
107
115
  */
108
- export function analyseLineRules(file: SourceFile, source: string, codeSource: string, config: Config, findings: Finding[]): void {
116
+ export function analyseLineRules(file: SourceFile, source: string, codeSource: string, config: Config, findings: Finding[], parsed?: ParsedScript): void {
117
+ const syntax = parsed?.diagnostics.length === 0 ? parsed.sourceFile : undefined;
109
118
  const sourceLines = source.split(/\r?\n/);
110
119
  const codeLines = codeSource.split(/\r?\n/);
111
120
  const gates: LineRuleGates = {
112
121
  shouldRunTypeSafety: TYPE_SAFETY_RULE_IDS.some((ruleId) => ruleEnabled(config, ruleId)),
113
122
  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
123
  shouldRunStringTimer: ruleEnabled(config, "security.string-timer"),
121
124
  shouldRunSecurityFlow: SECURITY_FLOW_LINE_RULE_IDS.some((ruleId) => ruleEnabled(config, ruleId)),
122
125
  shouldRunVariableNaming: VARIABLE_NAMING_RULE_IDS.some((ruleId) => ruleEnabled(config, ruleId)),
123
- shouldRunProcessExec: ruleEnabled(config, "security.process-exec"),
124
126
  shouldRunUselessCatch: ruleEnabled(config, "waste.useless-catch"),
125
127
  shouldRunSwallowedCatch: ruleEnabled(config, "waste.swallowed-catch"),
126
128
  };
@@ -129,9 +131,13 @@ export function analyseLineRules(file: SourceFile, source: string, codeSource: s
129
131
  line: "",
130
132
  codeLine: "",
131
133
  codeLines,
134
+ sourceLines,
135
+ isCodeLine: gates.shouldRunVariableNaming ? codeLineFlags(source, parsed) : [],
132
136
  lineNumber: 0,
133
137
  config,
134
138
  findings,
139
+ fixedInnerHtmlLines: ruleEnabled(config, "security.inner-html") ? fixedInnerHtmlAssignmentLines(sourceLines, syntax) : new Set(),
140
+ fixedEvalLines: ruleEnabled(config, "security.eval-call") ? fixedEvalCallLines(syntax) : new Set(),
135
141
  codeChecks: CODE_LINE_CHECKS.filter((check) => ruleEnabled(config, check.ruleId)),
136
142
  literalChecks: LITERAL_LINE_CHECKS.filter((check) => ruleEnabled(config, check.ruleId)),
137
143
  variables: VARIABLE_DECLARATIONS,
@@ -145,44 +151,27 @@ export function analyseLineRules(file: SourceFile, source: string, codeSource: s
145
151
  analyseLineRuleContext(context);
146
152
  });
147
153
 
148
- if (gates.shouldRunProcessExec) {
149
- analyseProcessExecCalls(file, source, codeSource, findings);
150
- }
151
154
  if (gates.shouldRunUselessCatch) {
152
155
  analyseUselessCatches(file, codeSource, findings);
153
156
  }
154
157
  if (gates.shouldRunSwallowedCatch) {
155
- analyseSwallowedCatches(file, source, codeSource, findings);
158
+ analyseSwallowedCatches(file, source, codeSource, findings, config.trackingTokens);
156
159
  }
157
160
  }
158
161
 
159
- // All per-line checks for a single line in their stable, deterministic emission order. Each helper
160
- // either no-ops (rule skipped or no match) or appends to `findings`.
162
+ /**
163
+ * Runs per-line checks using the current line and rule gates in the supplied context.
164
+ *
165
+ * @param context - Per-line scratch state holding the current line, rule gates, and findings array.
166
+ * @returns Nothing. Appends matches to the context's findings in stable order so that emission is repeatable.
167
+ */
161
168
  function analyseLineRuleContext(context: LineRuleContext): void {
162
169
  if (context.gates.shouldRunTypeSafety) {
163
- analyseTypeSafetyLine(context.file, context.line, context.codeLine, context.lineNumber, context.findings);
170
+ analyseTypeSafetyLine(context.file, context.line, context.codeLine, context.lineNumber, context.findings, context.sourceLines, context.config.trackingTokens);
164
171
  }
165
172
  if (context.gates.shouldRunReliability) {
166
173
  analyseReliabilityLine(context.file, context.codeLine, context.lineNumber, context.findings);
167
174
  }
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
175
  if (context.gates.shouldRunStringTimer) {
187
176
  pushStringTimerFinding(context);
188
177
  }
@@ -195,42 +184,49 @@ function analyseLineRuleContext(context: LineRuleContext): void {
195
184
  }
196
185
  }
197
186
 
198
- // Code-shape rules: those that must match against the masked code (no comment or literal noise).
199
- // Targets the eval / new-Function / Math.random / innerHTML / proto-access family of security/waste signals.
187
+ // Each pattern check's advice is its catalogue remediation, carried on the finding so every output shows it.
188
+ const PATTERN_CHECK_REMEDIATION = new Map(ruleDescriptors().map((descriptor) => [descriptor.ruleId, descriptor.remediation]));
189
+
190
+ /**
191
+ * Code-shape rules that must match against the masked code without comment or literal noise.
192
+ *
193
+ * @returns The eval, Function-constructor, innerHTML, and document.write security checks.
194
+ */
200
195
  function codeLineChecks(): LineRuleCheck[] {
201
196
  return [
202
197
  { ruleId: "security.eval-call", pattern: /\beval\s*\(/, message: "eval() executes dynamic code.", severity: "error", pillar: "security" },
203
198
  { ruleId: "security.new-function", pattern: /\bnew\s+Function\s*\(|(?:^|[=(:,])\s*Function\s*\(/, message: "Function constructor executes dynamic code.", severity: "error", pillar: "security" },
204
- { ruleId: "security.insecure-random", pattern: /\bMath\.random\s*\(/, message: "Math.random() is not suitable for security-sensitive randomness.", severity: "warning", pillar: "security" },
205
199
  { ruleId: "security.inner-html", pattern: /\.innerHTML\s*=(?!\s*(?:""|''))|\bdangerouslySetInnerHTML\b/, message: "HTML injection sink can introduce XSS.", severity: "warning", pillar: "security" },
206
- { ruleId: "security.proto-access", pattern: /\.__proto__\b/, message: "Direct __proto__ access can enable prototype pollution.", severity: "warning", pillar: "security" },
207
200
  { ruleId: "security.document-write", pattern: /\bdocument\.write\s*\(/, message: "document.write() can introduce injection risks.", severity: "warning", pillar: "security" },
208
- { ruleId: "waste.redundant-boolean-cast", pattern: /\b(?:if|while)\s*\(\s*(?:!!\s*[A-Za-z_$][A-Za-z0-9_$.]*|Boolean\s*\()/, message: "Condition contains a redundant boolean cast.", severity: "advisory", pillar: "maintainability" },
209
201
  ];
210
202
  }
211
203
 
212
- // Rules that need to see the raw line including literals (e.g., `"javascript:"` URL detection,
213
- // `"md5"` weak-crypto match). Global patterns are auto-generated so global-match operations stay
214
- // safe - see `withGlobalPattern`.
204
+ /**
205
+ * Rules that need to see the raw line including literals, such as "javascript:" URLs and "md5" matches.
206
+ * Global patterns are generated via withGlobalPattern so global-match operations stay safe.
207
+ *
208
+ * @returns Security, maintainability, and modernisation line checks with global patterns attached.
209
+ */
215
210
  function literalLineChecks(): LineRuleCheck[] {
216
211
  const checks: LineRuleCheck[] = [
217
- { ruleId: "security.weak-crypto", pattern: /\b(?:createHash|createHmac)\s*\(\s*["'](?:md5|sha1)["']|\bcreateCipher\s*\(|\b(?:secureProtocol|minVersion|maxVersion)\s*:\s*["'](?:SSLv2_method|SSLv3_method|TLSv1(?:_method)?|TLSv1\.1)["']/i, message: "Weak cryptographic primitive is used.", severity: "warning", pillar: "security" },
212
+ { ruleId: "security.weak-crypto", pattern: /\bcreateHash\s*\(\s*["'](?:md5|sha1)["']|\bcreateHmac\s*\(\s*["']md5["']|\bcreateCipher\s*\(|\b(?:secureProtocol|minVersion|maxVersion)\s*:\s*["'](?:SSLv2_method|SSLv3_method|TLSv1(?:_method)?|TLSv1\.1)["']/i, message: "Weak cryptographic primitive is used.", severity: "warning", pillar: "security" },
218
213
  { 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" },
219
214
  { ruleId: "security.javascript-url", pattern: /["'`]\s*javascript\s*:(?!\s+URL\b)/i, message: "javascript: URL literal can execute script.", severity: "error", pillar: "security" },
220
- { ruleId: "security.proto-access", pattern: /\[\s*["']__proto__["']\s*\]/, message: "Direct __proto__ access can enable prototype pollution.", severity: "warning", pillar: "security" },
221
215
  { 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" },
222
216
  { 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" },
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" },
224
- { ruleId: "waste.console-log", pattern: /\bconsole\.(log|debug)\s*\(/, message: "console logging is committed in source.", severity: "advisory", pillar: "maintainability" },
225
217
  { ruleId: "waste.any-type", pattern: /:\s*any\b|as\s+any\b/, message: "any weakens TypeScript's type guarantees.", severity: "warning", pillar: "maintainability" },
226
218
  { ruleId: "modernisation.var-declaration", pattern: /\bvar\s+[A-Za-z_$]/, message: "var declaration should usually be let or const.", severity: "advisory", pillar: "modernisation" },
227
219
  ];
228
220
  return checks.map(withGlobalPattern);
229
221
  }
230
222
 
231
- // Returns a new check whose `globalPattern` has the `g` flag, leaving the original `pattern`
232
- // untouched. Required because `pattern.exec` stateful iteration would corrupt callers that share
233
- // a check across multiple files.
223
+ /**
224
+ * Copies the supplied line check with a global pattern so that scans can advance past rejected matches.
225
+ * Reuses an already-global pattern; otherwise adds the g flag to a copy and keeps the original pattern on the check.
226
+ *
227
+ * @param check - Line rule descriptor whose pattern is copied or reused as a global regular expression.
228
+ * @returns Copy of the check with `globalPattern` populated.
229
+ */
234
230
  function withGlobalPattern(check: LineRuleCheck): LineRuleCheck {
235
231
  return {
236
232
  ...check,
@@ -238,162 +234,231 @@ function withGlobalPattern(check: LineRuleCheck): LineRuleCheck {
238
234
  };
239
235
  }
240
236
 
241
- /*
242
- * Targets `// const x = …;`-style commented-out code. The detector is intentionally conservative
243
- * because clever false positives drown the rule. Reports the stable `waste.commented-out-code` finding.
237
+ /**
238
+ * Flags candidate browser timer calls with string callbacks and execScript calls with string arguments.
239
+ *
240
+ * @param context - supplies the masked line to check, its report location, and the findings array to update
241
+ * @returns - returns nothing. Appends a stable security.string-timer finding when the line matches.
244
242
  */
245
- function pushCommentedOutCodeFinding(context: LineRuleContext): void {
246
- if (isCommentedOutCode(context.line)) {
247
- context.findings.push(finding({ ruleId: "waste.commented-out-code", message: "Comment appears to contain disabled source code.", file: context.file, line: context.lineNumber, severity: "advisory", pillar: "maintainability" }));
243
+ function pushStringTimerFinding(context: LineRuleContext): void {
244
+ if (stringTimerCandidate(context.codeLine)) {
245
+ context.findings.push(finding({ ruleId: "security.string-timer", message: "Timer callback is provided as a string.", file: context.file, line: context.lineNumber, severity: "warning", pillar: "security" }));
248
246
  }
249
247
  }
250
248
 
251
- // Detects typed boolean declarations (or those with a literal true/false initializer) and runs
252
- // the boolean-prefix and negative-boolean checks. Surface is fixed to "declaration".
253
- function pushBooleanPrefixFinding(context: LineRuleContext): void {
254
- const booleanDeclaration = context.codeLine.match(/\b(?:const|let|var|public|private|protected)\s+([A-Za-z_$][A-Za-z0-9_$]*)\??(?:\s*:\s*boolean|\s*=\s*(?:true|false)\b)/);
255
- const name = booleanDeclaration?.[1] ?? "";
256
- if (!name) {
257
- return;
249
+ /**
250
+ * Runs enabled code and literal checks for the current line, skipping exempt eval, innerHTML, and literal matches.
251
+ * Literal checks reset and advance shared regex state so that scanning can continue past masked or exempt match starts.
252
+ *
253
+ * @param context - Per-line state providing enabled checks, the raw and masked lines, and the findings target.
254
+ * @returns Nothing. Appends one stable finding per matched rule to `context.findings` using configured or default severity.
255
+ */
256
+ function pushPatternCheckFindings(context: LineRuleContext): void {
257
+ for (const check of context.codeChecks) {
258
+ if (check.ruleId === "security.eval-call" && context.fixedEvalLines.has(context.lineNumber)) {
259
+ continue;
260
+ }
261
+ if (check.ruleId === "security.inner-html" && isFixedInnerHtmlLine(context)) {
262
+ continue;
263
+ }
264
+ if (check.pattern.test(context.codeLine)) {
265
+ context.findings.push(finding({ ruleId: check.ruleId, message: check.message, file: context.file, line: context.lineNumber, severity: ruleSeverity(context.config, check.ruleId, check.severity), pillar: check.pillar, remediation: PATTERN_CHECK_REMEDIATION.get(check.ruleId) }));
266
+ }
267
+ }
268
+ for (const check of context.literalChecks) {
269
+ const isExemptMatch = literalCheckExemption(check.ruleId, context);
270
+ if (rawPatternStartsInCode(context.line, context.codeLine, check.globalPattern ?? check.pattern, isExemptMatch)) {
271
+ context.findings.push(finding({ ruleId: check.ruleId, message: check.message, file: context.file, line: context.lineNumber, severity: ruleSeverity(context.config, check.ruleId, check.severity), pillar: check.pillar, remediation: PATTERN_CHECK_REMEDIATION.get(check.ruleId) }));
272
+ }
258
273
  }
259
- pushBooleanPrefixAt(context.file, context.lineNumber, name, context.config, context.findings, "declaration");
260
- pushNegativeBooleanAt(context.file, context.lineNumber, name, context.config, context.findings, "declaration");
261
274
  }
262
275
 
263
-
264
-
265
- // Walks all `strFoo` / `intBar` / `arrBaz` identifiers on the line. The prefix regex is
266
- // auto-generated from `config.hungarianPrefixes`. Reports `naming.hungarian-notation`.
267
- function pushHungarianNotationFindings(context: LineRuleContext): void {
268
- const regex = hungarianPrefixRegex(context.config.hungarianPrefixes);
269
- if (regex === null) {
270
- return;
276
+ /**
277
+ * Selects a match-index exemption predicate for the current line when the rule supports exemptions.
278
+ * TLS matches are exempt inside recognized deep-equality assertions; JavaScript URL literals next to equality operators are exempt.
279
+ *
280
+ * @param ruleId - Rule identifier being evaluated on the current line.
281
+ * @param context - Per-line state supplying masked lines, raw line text, and line number.
282
+ * @returns Predicate testing whether a match at a column index is exempt, or undefined when the rule has no exemption.
283
+ */
284
+ function literalCheckExemption(ruleId: string, context: LineRuleContext): ((index: number) => boolean) | undefined {
285
+ // Only inert `rejectUnauthorized: false` config literals inside deep-equality assertions are exempt; live env assignments stay flagged.
286
+ if (ruleId === "security.disabled-tls-verification") {
287
+ return (index: number) => /^rejectUnauthorized\s*:\s*false\b/i.test(context.line.slice(index))
288
+ && isInsideDeepEqualityAssertion(context.codeLines, context.lineNumber - 1, index);
271
289
  }
272
- for (const hungarian of context.codeLine.matchAll(regex)) {
273
- const name = hungarian[1] ?? "";
274
- context.findings.push(
275
- makeFinding({
276
- ruleId: "naming.hungarian-notation",
277
- message: `Identifier \`${name}\` uses type-style Hungarian notation.`,
278
- filePath: context.file.displayPath,
279
- line: context.lineNumber,
280
- severity: "advisory",
281
- pillar: "naming",
282
- confidence: "medium",
283
- symbol: name,
284
- remediation: "Name the domain concept instead of the storage type.",
285
- metadata: { identifierName: name },
286
- }),
287
- );
290
+ if (ruleId === "security.javascript-url") {
291
+ return (index: number) => isComparisonOperandLiteral(context.line, index);
288
292
  }
293
+ return undefined;
289
294
  }
290
295
 
291
- // Detects `foo && foo.bar` patterns where `foo?.bar` would say the same thing. Backreference
292
- // in the regex enforces identical identifiers on both sides. Reports `modernisation.optional-chaining-candidate`.
293
- function pushOptionalChainingFindings(context: LineRuleContext): void {
294
- for (const optional of context.codeLine.matchAll(/\b([A-Za-z_$][A-Za-z0-9_$]*)\s*&&\s*\1\.[A-Za-z_$][A-Za-z0-9_$]*/g)) {
295
- const name = optional[1] ?? "";
296
- context.findings.push(
297
- makeFinding({
298
- ruleId: "modernisation.optional-chaining-candidate",
299
- message: `Guarded property access on \`${name}\` can usually use optional chaining.`,
300
- filePath: context.file.displayPath,
301
- line: context.lineNumber,
302
- severity: "advisory",
303
- pillar: "modernisation",
304
- confidence: "medium",
305
- symbol: name,
306
- remediation: "Use optional chaining for the guarded property access.",
307
- }),
308
- );
296
+ /**
297
+ * Checks whether the raw source line has an equality or inequality operator beside the literal starting at index.
298
+ * This lets the URL rule exempt defensive checks such as `href === 'javascript:void(0)'`.
299
+ *
300
+ * @param rawLine - Unmasked source line containing the matched literal.
301
+ * @param index - Zero-based column where the opening quote of the literal starts.
302
+ * @returns True when an equality or inequality operator precedes or follows the literal; otherwise false.
303
+ */
304
+ function isComparisonOperandLiteral(rawLine: string, index: number): boolean {
305
+ if (/[=!]==?\s*$/.test(rawLine.slice(0, index))) {
306
+ return true;
309
307
  }
310
- }
311
-
312
- // Targets `x || defaultValue` patterns where the fallback is a literal - `??` would preserve
313
- // legitimately-falsy values (0, "", false). Reports `modernisation.nullish-coalescing-candidate`.
314
- function pushNullishCoalescingFindings(context: LineRuleContext): void {
315
- for (const fallback of context.codeLine.matchAll(/=\s*([A-Za-z_$][A-Za-z0-9_$.]*)\s*\|\|\s*(["'`]\s*["'`]|\d+|true|false)/g)) {
316
- const name = fallback[1] ?? "";
317
- context.findings.push(
318
- makeFinding({
319
- ruleId: "modernisation.nullish-coalescing-candidate",
320
- message: `Fallback for \`${name}\` can usually use nullish coalescing to preserve falsy values.`,
321
- filePath: context.file.displayPath,
322
- line: context.lineNumber,
323
- severity: "advisory",
324
- pillar: "modernisation",
325
- confidence: "medium",
326
- symbol: name,
327
- remediation: "Use ?? when only null or undefined should trigger the fallback.",
328
- }),
329
- );
308
+ const quote = rawLine[index] ?? "";
309
+ let position = index + 1;
310
+ // Skip escaped quotes so the operator check on the right starts after the whole literal.
311
+ while (position < rawLine.length && rawLine[position] !== quote) {
312
+ position += rawLine[position] === "\\" ? 2 : 1;
330
313
  }
314
+ return /^\s*[=!]==?(?!=)/.test(rawLine.slice(position + 1));
331
315
  }
332
316
 
333
- /*
334
- * Loose `==` / `!=` against non-null operands. The `looseEqualityOperator` helper excludes intentional
335
- * `x == null` checks (which legitimately match null and undefined). Reports the stable
336
- * `modernisation.loose-equality` finding.
317
+ /**
318
+ * Collects 1-based lines where every identifier or dot-property eval call has one string or substitution-free template argument.
319
+ * A recognized eval call with any other argument shape prevents the line exemption even when a fixed call shares that line.
320
+ *
321
+ * @param syntax - Clean TypeScript syntax tree, or undefined to preserve text-based checks on missing or incompatible parses.
322
+ * @returns 1-based line numbers eligible for eval exemption, or empty when syntax is undefined or uses non-LF line breaks.
337
323
  */
338
- function pushLooseEqualityFinding(context: LineRuleContext): void {
339
- const looseOperator = looseEqualityOperator(context.codeLine);
340
- if (looseOperator) {
341
- context.findings.push(finding({ ruleId: "modernisation.loose-equality", message: `Loose equality operator ${looseOperator} may coerce values.`, file: context.file, line: context.lineNumber, severity: "advisory", pillar: "modernisation" }));
342
- }
324
+ function fixedEvalCallLines(syntax: TsSourceFile | undefined): Set<number> {
325
+ const fixed = new Set<number>();
326
+ const dynamic = new Set<number>();
327
+ // Keep text fallback when parser line boundaries differ from the LF-based finding locations.
328
+ if (syntax === undefined || /\r(?!\n)|[\u2028\u2029]/.test(syntax.text)) {
329
+ return fixed;
330
+ }
331
+ /**
332
+ * Records fixed and dynamic eval calls in the supplied syntax subtree so a literal call cannot hide a dynamic call on the same line.
333
+ *
334
+ * @param node - AST node to inspect and traverse recursively.
335
+ * @returns Nothing. Adds each matching line number to the applicable enclosing `fixed` or `dynamic` set.
336
+ */
337
+ const visit = (node: TsNode): void => {
338
+ if (typescriptSyntax.isCallExpression(node)) {
339
+ const callee = node.expression;
340
+ const name = typescriptSyntax.isIdentifier(callee) ? callee
341
+ : typescriptSyntax.isPropertyAccessExpression(callee) ? callee.name : undefined;
342
+ if (name?.text === "eval") {
343
+ const line = syntax.getLineAndCharacterOfPosition(name.getStart(syntax)).line + 1;
344
+ const argument = node.arguments[0];
345
+ const isFixed = node.arguments.length === 1 && argument !== undefined
346
+ && (typescriptSyntax.isStringLiteral(argument) || typescriptSyntax.isNoSubstitutionTemplateLiteral(argument));
347
+ (isFixed ? fixed : dynamic).add(line);
348
+ }
349
+ }
350
+ node.forEachChild(visit);
351
+ };
352
+ syntax.forEachChild(visit);
353
+ return new Set([...fixed].filter((line) => !dynamic.has(line)));
343
354
  }
344
355
 
345
- /*
346
- * `setTimeout("alert(1)", …)` and friends evaluate the string as code, an `eval`-equivalent.
347
- * Reports the stable `security.string-timer` finding when a literal string callback is detected.
356
+ /**
357
+ * Determines whether the current line in context can skip security.inner-html.
358
+ * The line must be in the fixed-assignment set, and any `dangerouslySetInnerHTML` in the masked line keeps the rule active.
359
+ *
360
+ * @param context - Per-line state supplying the line number, masked code line, and precomputed fixed innerHTML lines.
361
+ * @returns True when the line is in `fixedInnerHtmlLines` and does not mention `dangerouslySetInnerHTML`.
348
362
  */
349
- function pushStringTimerFinding(context: LineRuleContext): void {
350
- if (stringTimerCandidate(context.codeLine)) {
351
- context.findings.push(finding({ ruleId: "security.string-timer", message: "Timer callback is provided as a string.", file: context.file, line: context.lineNumber, severity: "warning", pillar: "security" }));
352
- }
363
+ function isFixedInnerHtmlLine(context: LineRuleContext): boolean {
364
+ return context.fixedInnerHtmlLines.has(context.lineNumber) && !context.codeLine.includes("dangerouslySetInnerHTML");
353
365
  }
354
366
 
355
- // Runs the descriptor-driven line checks split into code-shape vs literal-aware. Literal checks use
356
- // `rawPatternStartsInCode` to confirm a match starts in real code, not inside a comment. Each finding's
357
- // severity is resolved through `ruleSeverity`, so a project's per-rule `severity:` override applies.
358
- // Reports each matching rule's stable, line-anchored finding; the descriptor severity is the default.
359
- function pushPatternCheckFindings(context: LineRuleContext): void {
360
- for (const check of context.codeChecks) {
361
- if (check.pattern.test(context.codeLine)) {
362
- context.findings.push(finding({ ruleId: check.ruleId, message: check.message, file: context.file, line: context.lineNumber, severity: ruleSeverity(context.config, check.ruleId, check.severity), pillar: check.pillar }));
363
- }
364
- }
365
- for (const check of context.literalChecks) {
366
- if (isSuppressedByPathContext(check.ruleId, context.file.displayPath)) {
367
- continue;
367
+ /**
368
+ * Finds 1-based lines of fixed innerHTML writes using plain equals and a string or substitution-free template literal.
369
+ * Compound writes prevent the exemption; without syntax, falls back to sourceLines because masking would hide the literal text.
370
+ *
371
+ * @param sourceLines - Raw source lines inspected when no clean syntax tree is available.
372
+ * @param syntax - Clean TypeScript syntax tree, or undefined when falling back to single-line literal matching.
373
+ * @returns 1-based line numbers whose only recognized innerHTML writes assign fixed literals.
374
+ */
375
+ function fixedInnerHtmlAssignmentLines(sourceLines: readonly string[], syntax: TsSourceFile | undefined): Set<number> {
376
+ const fixed = new Set<number>();
377
+ // Keep text fallback when no clean parse exists or parser line boundaries differ from LF-split finding locations.
378
+ if (syntax === undefined || /\r(?!\n)|[\u2028\u2029]/.test(syntax.text)) {
379
+ sourceLines.forEach((line, index) => {
380
+ if (/^[^]*?\.innerHTML\s*=\s*(?:"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\$]|\\.|\$(?!\{))*`)\s*;?\s*(?:\/\/.*)?$/.test(line)
381
+ && line.split(".innerHTML").length === 2) {
382
+ fixed.add(index + 1);
383
+ }
384
+ });
385
+ return fixed;
386
+ }
387
+ const dynamic = new Set<number>();
388
+ const { EqualsToken, FirstCompoundAssignment, LastCompoundAssignment } = typescriptSyntax.SyntaxKind;
389
+ /**
390
+ * Visits a syntax node and its descendants to record innerHTML assignment lines in the shared fixed or dynamic sets.
391
+ * Compound assignments remain dynamic because they depend on existing markup or an unmodelled operation.
392
+ *
393
+ * @param node - AST node to inspect and traverse recursively.
394
+ * @returns Nothing. Adds each innerHTML assignment line number to `fixed` or `dynamic`.
395
+ */
396
+ const visit = (node: TsNode): void => {
397
+ const operator = typescriptSyntax.isBinaryExpression(node) ? node.operatorToken.kind : undefined;
398
+ const isAssignment = operator === EqualsToken
399
+ || (operator !== undefined && operator >= FirstCompoundAssignment && operator <= LastCompoundAssignment);
400
+ if (isAssignment && typescriptSyntax.isBinaryExpression(node)
401
+ && typescriptSyntax.isPropertyAccessExpression(node.left) && node.left.name.text === "innerHTML") {
402
+ const line = syntax.getLineAndCharacterOfPosition(node.left.name.getStart(syntax)).line + 1;
403
+ const isFixed = operator === EqualsToken
404
+ && (typescriptSyntax.isStringLiteral(node.right) || typescriptSyntax.isNoSubstitutionTemplateLiteral(node.right));
405
+ (isFixed ? fixed : dynamic).add(line);
368
406
  }
369
- if (rawPatternStartsInCode(context.line, context.codeLine, check.globalPattern ?? check.pattern)) {
370
- context.findings.push(finding({ ruleId: check.ruleId, message: check.message, file: context.file, line: context.lineNumber, severity: ruleSeverity(context.config, check.ruleId, check.severity), pillar: check.pillar }));
407
+ node.forEachChild(visit);
408
+ };
409
+ syntax.forEachChild(visit);
410
+ return new Set([...fixed].filter((line) => !dynamic.has(line)));
411
+ }
412
+
413
+ // Deep-equality assertions whose arguments are expected values: chai's `.to.deep.equal`, jest and vitest's `toEqual`,
414
+ // and node's `assert.deepStrictEqual`. The named set is deliberately closed; any other call stays reportable.
415
+ const DEEP_EQUALITY_ASSERTION_CALLEE = /(?:\.to\.deep\.equal|\.toEqual|\bassert\.deepStrictEqual)\s*$/;
416
+ // How far back the enclosing-call search walks. An expected object literal longer than this is reported, not guessed.
417
+ const ENCLOSING_CALL_SEARCH_LINES = 200;
418
+
419
+ /**
420
+ * Check call context for expected values because rejectUnauthorized: false in an assertion configures nothing.
421
+ * The check applies in any file, and a real agent call nested inside an assertion remains reportable.
422
+ *
423
+ * @param codeLines - Masked source lines searched backward for the enclosing call.
424
+ * @param lineIndex - Zero-based line containing the value under review.
425
+ * @param column - Zero-based position where the backward search begins on that line.
426
+ * @returns True if the first unmatched opening parenthesis in the search window belongs to a recognized assertion, otherwise false.
427
+ */
428
+ function isInsideDeepEqualityAssertion(codeLines: readonly string[], lineIndex: number, column: number): boolean {
429
+ let unclosedCalls = 0;
430
+ const firstLine = Math.max(0, lineIndex - ENCLOSING_CALL_SEARCH_LINES);
431
+ for (let index = lineIndex; index >= firstLine; index -= 1) {
432
+ const codeLine = codeLines[index] ?? "";
433
+ for (let position = (index === lineIndex ? column : codeLine.length) - 1; position >= 0; position -= 1) {
434
+ if (codeLine[position] === ")") {
435
+ unclosedCalls += 1;
436
+ } else if (codeLine[position] === "(") {
437
+ if (unclosedCalls === 0) {
438
+ const calleeText = codeLine.slice(0, position).trim() === "" ? (codeLines[index - 1] ?? "") : codeLine.slice(0, position);
439
+ return DEEP_EQUALITY_ASSERTION_CALLEE.test(calleeText);
440
+ }
441
+ unclosedCalls -= 1;
442
+ }
371
443
  }
372
444
  }
445
+ return false;
373
446
  }
374
447
 
375
- // Per-rule path-context allowlist. CLI entry points, build scripts, and server diagnostic modules
376
- // are expected to write to stdout; the console-log rule would otherwise drown them in advisories.
377
- function isSuppressedByPathContext(ruleId: string, displayPath: string): boolean {
378
- if (ruleId !== "waste.console-log") {
379
- return false;
380
- }
381
- return /(?:^|\/)(?:scripts|bin)\//.test(displayPath) || /(?:^|\/)cli[/.]/i.test(displayPath) || /(?:^|\/)server[/.]/i.test(displayPath);
382
- }
383
-
384
- // Per-line variable-name pass that runs short/identifier-quality checks on both
385
- // regular `const`/`let` declarations and destructured names. Reports any findings produced.
386
- // Single-character for-of bindings whose body is ≤ 10 lines are idiomatic (e.g. `for (const f of
387
- // files) { write(f); }`) and skip the short-variable check; longer bodies still flag. The
388
- // exemption is gated on a real `of` token after the binding so C-style `for (let i = 0; …)` and
389
- // `for (const k in obj)` headers stay covered by the rule.
448
+ /**
449
+ * Checks the current code line for short or generic variable names in declarations and destructuring.
450
+ * A for-of binding skips the short-name check when its body scan counts at most 10 code lines because compact loop names are idiomatic.
451
+ *
452
+ * @param context - Per-line state holding the current masked line, line array, code-line flags, and findings array.
453
+ * @returns Nothing. Appends variable naming findings to `context.findings`.
454
+ */
390
455
  function pushVariableNameFindings(context: LineRuleContext): void {
391
456
  for (const match of context.codeLine.matchAll(context.variables)) {
392
457
  const name = match[1] ?? "";
393
458
  const matchText = match[0] ?? "";
394
459
  const headerTail = context.codeLine.slice((match.index ?? 0) + matchText.length);
395
460
  const isForOfHeader = matchText.startsWith("for") && /^\s+of\b/.test(headerTail);
396
- const loopBodyLineCount = isForOfHeader ? forOfBodyLineSpan(context.codeLines, context.lineNumber - 1) : undefined;
461
+ const loopBodyLineCount = isForOfHeader ? forOfBodyLineSpan(context.codeLines, context.isCodeLine, context.lineNumber - 1) : undefined;
397
462
  pushShortVariableFinding(context, name, loopBodyLineCount);
398
463
  pushIdentifierQualityFinding(context, name);
399
464
  }
@@ -403,24 +468,23 @@ function pushVariableNameFindings(context: LineRuleContext): void {
403
468
  }
404
469
  }
405
470
 
406
- /*
407
- * Counts the line span of a for-of body starting at the opener line index. Brace-less
408
- * single-statement bodies return 1 because the body is trivially short. When the opener has `{`,
409
- * brace-balance tracking finds the matching `}` and returns the line count from `{` to `}`
410
- * inclusive. The walker uses the masked codeLines so braces inside string literals are blanked
411
- * out; this avoids the false "balanced" claim a raw-source walker would make on template strings.
412
- * A 50-line scan window guards against unterminated scans because malformed input must not stall
413
- * the whole-file walker; an unbalanced result returns Infinity so a long-but-unclosed for-of
414
- * still fires the rule rather than getting silently exempted.
471
+ /**
472
+ * Counts the code-line span of a for-of body starting at the opener line using masked lines so string braces are ignored.
473
+ * Capped at a 50-line scan window because malformed input must not stall the walker and avoid false exemptions on unclosed loops.
474
+ *
475
+ * @param codeLines - Comment-and-literal-masked source lines scanned for brace balance.
476
+ * @param isCodeLine - Per-line flags counting only non-empty code lines inside the brace span.
477
+ * @param openerLineIndex - Zero-based index of the line containing the for-of header.
478
+ * @returns 1 for brace-less single statements, the inclusive code-line count from `{` to `}`, or Infinity if unclosed within 50 lines.
415
479
  */
416
- function forOfBodyLineSpan(codeLines: readonly string[], openerLineIndex: number): number {
480
+ function forOfBodyLineSpan(codeLines: readonly string[], isCodeLine: readonly boolean[], openerLineIndex: number): number {
417
481
  const maxLines = 50;
418
482
  const end = Math.min(codeLines.length, openerLineIndex + maxLines);
419
483
  let state: ForOfBraceScanState = { depth: 0, bodyOpenerLine: -1 };
420
484
  for (let i = openerLineIndex; i < end; i += 1) {
421
485
  state = advanceForOfBraceScan(state, codeLines[i] ?? "", i);
422
486
  if (state.bodyOpenerLine !== -1 && state.depth <= 0) {
423
- return i - state.bodyOpenerLine + 1;
487
+ return isCodeLine.slice(state.bodyOpenerLine, i + 1).filter(Boolean).length;
424
488
  }
425
489
  }
426
490
  return state.bodyOpenerLine === -1 ? 1 : Infinity;
@@ -433,8 +497,15 @@ interface ForOfBraceScanState {
433
497
  bodyOpenerLine: number;
434
498
  }
435
499
 
436
- // Per-line brace-balance update. Records the first line that introduced a `{` so the caller can
437
- // compute the body span when the balancing `}` lands.
500
+ /**
501
+ * Computes the next brace-scan state from the current line and prior state so the caller can measure the loop body.
502
+ * Does not mutate the supplied state; `bodyOpenerLine` stays -1 until the first opening brace is seen.
503
+ *
504
+ * @param state - Prior brace-nesting depth and opener line index.
505
+ * @param line - Masked source line scanned for opening and closing braces.
506
+ * @param lineIndex - Zero-based index of the current line.
507
+ * @returns Fresh brace-scan state with updated depth and opener line index.
508
+ */
438
509
  function advanceForOfBraceScan(state: ForOfBraceScanState, line: string, lineIndex: number): ForOfBraceScanState {
439
510
  const opens = (line.match(/\{/g) ?? []).length;
440
511
  const closes = (line.match(/\}/g) ?? []).length;
@@ -442,8 +513,13 @@ function advanceForOfBraceScan(state: ForOfBraceScanState, line: string, lineInd
442
513
  return { depth: state.depth + opens - closes, bodyOpenerLine };
443
514
  }
444
515
 
445
- // Walks `const { foo, bar: alias } = ...` patterns. Aliased names (the part after `:`) become the
446
- // local binding; defaults are stripped. Required because the naming rules check the local name only.
516
+ /**
517
+ * Extracts candidate local names from a shallow scan of const or let object destructuring for naming rules.
518
+ * Splits at every comma, strips any default suffix, and yields the alias or plain identifier for each matching fragment.
519
+ *
520
+ * @param codeLine - Masked source line inspected for object destructuring bindings.
521
+ * @returns Candidate bound local identifier names, or empty when no bindings match.
522
+ */
447
523
  function destructuredLocalNames(codeLine: string): string[] {
448
524
  const names: string[] = [];
449
525
  for (const block of codeLine.matchAll(/\b(?:const|let)\s+\{([^}]+)\}\s*=/g)) {
@@ -461,33 +537,46 @@ function destructuredLocalNames(codeLine: string): string[] {
461
537
  return names;
462
538
  }
463
539
 
464
- // Thin wrapper that fills in `"declaration"` for the surface field. Same back-end as parameter
465
- // and destructure callers, which use their own surface labels. `loopBodyLineCount` is forwarded so
466
- // the underlying rule can apply the for-of short-body exemption when the declaration came from a
467
- // `for (const X of …)` head.
540
+ /**
541
+ * Checks a declared identifier against the short-variable rule using the current context's file, line, and configuration.
542
+ *
543
+ * @param context - Per-line state supplying file metadata, line number, config, and findings array.
544
+ * @param name - Declared variable identifier to evaluate.
545
+ * @param loopBodyLineCount - Optional for-of body code-line count; undefined disables the short-body exemption.
546
+ * @returns Nothing. Appends any stable finding to `context.findings` with the declaration surface.
547
+ */
468
548
  function pushShortVariableFinding(context: LineRuleContext, name: string, loopBodyLineCount?: number): void {
469
549
  pushShortVariableAt(context.file, context.lineNumber, name, context.config, context.findings, "declaration", loopBodyLineCount);
470
550
  }
471
551
 
472
-
473
- // Thin wrapper that fills in `"declaration"` for the surface field; parameter and destructure
474
- // callers use their own surface labels via the underlying `pushIdentifierQualityAt`.
552
+ /**
553
+ * Checks a declared identifier for low-information names using the current context's file, line, and configuration.
554
+ *
555
+ * @param context - Per-line state supplying file metadata, line number, config, and findings array.
556
+ * @param name - Declared variable identifier to evaluate.
557
+ * @returns Nothing. Appends any stable `naming.identifier-quality` finding to `context.findings` with the declaration surface.
558
+ */
475
559
  function pushIdentifierQualityFinding(context: LineRuleContext, name: string): void {
476
560
  pushIdentifierQualityAt(context.file, context.lineNumber, name, context.config, context.findings, "declaration");
477
561
  }
478
562
 
479
-
480
-
481
- // True iff the pattern matches somewhere on the raw line *and* the match's start position falls on
482
- // a code character in `codeLine`. Required for literal-rule checks where the raw line is needed to
483
- // see the literal content, but the match must still begin in executable code (not inside a comment).
484
- function rawPatternStartsInCode(rawLine: string, codeLine: string, pattern: RegExp): boolean {
563
+ /**
564
+ * Tests whether a global pattern matches rawLine at a non-whitespace character in codeLine unless exempted.
565
+ * Resets and mutates `pattern.lastIndex`, and advances past rejected empty matches to avoid repeating the same match.
566
+ *
567
+ * @param rawLine - Unmasked source line searched for pattern matches.
568
+ * @param codeLine - Masked source line used to verify the match start is not blanked out.
569
+ * @param pattern - Regular expression that must have the global flag for stateful scanning.
570
+ * @param isExemptMatch - Optional predicate taking match index to exempt rule-specific hits; omitting it disables exemptions.
571
+ * @returns True on the first non-exempt match starting on a non-whitespace `codeLine` character; otherwise false.
572
+ */
573
+ function rawPatternStartsInCode(rawLine: string, codeLine: string, pattern: RegExp, isExemptMatch?: (index: number) => boolean): boolean {
485
574
  const globalPattern = pattern;
486
575
  let match: RegExpExecArray | null;
487
576
  globalPattern.lastIndex = 0;
488
577
  while ((match = globalPattern["exec"](rawLine)) !== null) {
489
578
  const index = match.index ?? 0;
490
- if (isNonWhitespaceCharacter(codeLine[index] ?? "")) {
579
+ if (isNonWhitespaceCharacter(codeLine[index] ?? "") && !isExemptMatch?.(index)) {
491
580
  return true;
492
581
  }
493
582
  if (match[0] === "") {
@@ -497,203 +586,26 @@ function rawPatternStartsInCode(rawLine: string, codeLine: string, pattern: RegE
497
586
  return false;
498
587
  }
499
588
 
500
- // Used by `rawPatternStartsInCode` to confirm a position holds executable code rather than the
501
- // space character produced by `maskNonCode`.
589
+ /**
590
+ * Checks whether a single character is non-empty and not a space, tab, carriage return, or newline for masked match-start checks.
591
+ *
592
+ * @param character - Single character or empty value from the masked code line at a match start.
593
+ * @returns True when `character` is non-empty and not space, tab, CR, or LF; otherwise false.
594
+ */
502
595
  function isNonWhitespaceCharacter(character: string): boolean {
503
596
  return character !== "" && character !== " " && character !== "\t" && character !== "\r" && character !== "\n";
504
597
  }
505
598
 
506
- // Returns the loose operator (`==` or `!=`) when present and not part of `===`/`!==`/null check.
507
- // Used by the modernisation rule; sufficient context lookback keeps `x == null` quiet.
508
- function looseEqualityOperator(codeLine: string): string | undefined {
509
- for (const match of codeLine.matchAll(/[=!]=/g)) {
510
- const index = match.index ?? 0;
511
- const operator = match[0] ?? "";
512
- if (!isLooseEqualityCandidate(codeLine, index, operator)) {
513
- continue;
514
- }
515
- return operator;
516
- }
517
- return undefined;
518
- }
519
-
520
- // Two-pass filter: reject `===`/`!==` (strict equality) and reject `x == null` (intentional double-test).
521
- function isLooseEqualityCandidate(codeLine: string, index: number, operator: string): boolean {
522
- return !isStrictEqualityOperator(codeLine, index, operator) && !isNullEqualityComparison(codeLine, index, operator);
523
- }
524
-
525
- // Looks one char before and after - `===` shows up as `==` plus a trailing `=`. The leading `!` /
526
- // `=` check catches `!==` and `===` from either side.
527
- function isStrictEqualityOperator(codeLine: string, index: number, operator: string): boolean {
528
- const before = codeLine[index - 1] ?? "";
529
- const after = codeLine[index + operator.length] ?? "";
530
- return before === "=" || before === "!" || after === "=";
531
- }
532
-
533
- // `x == null` matches both null and undefined and is a documented idiom - exempting it is the
534
- // rule's intentional false-positive escape hatch. 24-character lookback window is large enough to
535
- // span `someObject.field == null` without matching unrelated tokens.
536
- function isNullEqualityComparison(codeLine: string, index: number, operator: string): boolean {
537
- const left = codeLine.slice(Math.max(0, index - 24), index).trimEnd();
538
- const right = codeLine.slice(index + operator.length, Math.min(codeLine.length, index + operator.length + 24)).trimStart();
539
- return /\bnull$/.test(left) || /^null\b/.test(right);
540
- }
541
-
542
- // Two cases: a bare `setTimeout("…")` call, or one accessed via window/self/globalThis. Both
543
- // invoke `eval`-equivalent string-to-code semantics in browsers.
599
+ /**
600
+ * Checks whether codeLine contains a call prefix for setTimeout, setInterval, or execScript followed by an opening quote or backtick.
601
+ * Matches bare calls and calls through window, self, or globalThis so browser string-to-code evaluation can be reported.
602
+ *
603
+ * @param codeLine - Masked source line inspected for string-callback timer or execScript calls.
604
+ * @returns True when a bare or global-object timer or execScript call starts with a quote or backtick; otherwise false.
605
+ */
544
606
  function stringTimerCandidate(codeLine: string): boolean {
545
607
  return (
546
608
  /(?:^|[^.\w$])(?:setTimeout|setInterval|execScript)\s*\(\s*["'`]/.test(codeLine) ||
547
609
  /\b(?:window|self|globalThis)\.(?:setTimeout|setInterval|execScript)\s*\(\s*["'`]/.test(codeLine)
548
610
  );
549
611
  }
550
-
551
- /*
552
- * Targets child_process-style calls across single- and multi-line expressions. Stable invariant:
553
- * masked-source matching keeps fixture strings quiet. Unmatched calls recover by being skipped
554
- * rather than guessed, while fixed literal-command argv calls stay quiet.
555
- */
556
- function analyseProcessExecCalls(file: SourceFile, rawSource: string, codeSource: string, findings: Finding[]): void {
557
- const processCallPattern = /\b(?:(child_process|childProcess|cp)\.)?(exec|spawn|execFile|execSync|execFileSync|spawnSync|fork)\s*\(/g;
558
- for (const match of codeSource.matchAll(processCallPattern)) {
559
- const start = match.index ?? 0;
560
- const callName = match[2] ?? "";
561
- if (!callName || isMemberProcessExecFalsePositive(codeSource, start, Boolean(match[1]))) {
562
- continue;
563
- }
564
- const openParen = start + match[0].length - 1;
565
- const closeParen = matchingCloseParen(codeSource, openParen);
566
- if (closeParen === undefined) {
567
- continue;
568
- }
569
- const codeSegment = codeSource.slice(start, closeParen + 1);
570
- const rawSegment = rawSource.slice(start, closeParen + 1);
571
- if (isSafeProcessExecCall(file, callName, rawSource, start, rawSegment, codeSegment)) {
572
- continue;
573
- }
574
- findings.push(
575
- makeFinding({
576
- ruleId: "security.process-exec",
577
- message: "Child-process execution is used; validate arguments are not user-controlled.",
578
- filePath: file.displayPath,
579
- line: byteLine(codeSource, start),
580
- severity: "warning",
581
- pillar: "security",
582
- confidence: "high",
583
- remediation: "Review the command source and shell mode; prefer fixed command vectors with shell disabled.",
584
- metadata: processExecMetadata(callName, rawSource, start, rawSegment, codeSegment),
585
- }),
586
- );
587
- }
588
- }
589
-
590
- // Excludes ordinary member calls such as `pattern.exec(...)`; module receivers like `cp.exec(...)`
591
- // remain valid process-exec candidates.
592
- function isMemberProcessExecFalsePositive(codeSource: string, start: number, hasProcessReceiver: boolean): boolean {
593
- return !hasProcessReceiver && codeSource[start - 1] === ".";
594
- }
595
-
596
- // Tiny parenthesis matcher over masked source. Strings and comments are already blanked by
597
- // `maskNonCode`, so nested call parentheses are the only structure this needs to balance.
598
- function matchingCloseParen(source: string, openParen: number): number | undefined {
599
- let depth = 0;
600
- for (let index = openParen; index < source.length; index += 1) {
601
- const character = source[index];
602
- if (character === "(") {
603
- depth += 1;
604
- } else if (character === ")") {
605
- depth -= 1;
606
- if (depth === 0) {
607
- return index;
608
- }
609
- }
610
- }
611
- return undefined;
612
- }
613
-
614
- // Fixed command vectors and known safe wrappers are intentionally not shell-interpolated, so this
615
- // rule stays focused on dynamic commands and shell-enabled process calls.
616
- function isSafeProcessExecCall(file: SourceFile, callName: string, rawSource: string, callStart: number, rawSegment: string, codeSegment: string): boolean {
617
- return (
618
- isFixedArgvProcessCallSegment(callName, rawSource, callStart, rawSegment, codeSegment) ||
619
- isSafeExecWrapperCall(file, callName, codeSegment) ||
620
- isFixedTestHarnessProcessCall(file, callName, rawSegment, codeSegment)
621
- );
622
- }
623
-
624
- // Suppresses argv-form process calls where the command is fixed by a literal, `process.execPath`,
625
- // a local const literal selector, or a terminal-binary version probe.
626
- function isFixedArgvProcessCallSegment(callName: string, rawSource: string, callStart: number, rawSegment: string, codeSegment: string): boolean {
627
- if (/\bshell\s*:\s*true\b/.test(codeSegment)) {
628
- return false;
629
- }
630
- if (!["spawn", "spawnSync", "execFile", "execFileSync"].includes(callName)) {
631
- return false;
632
- }
633
- const argsText = rawSegment.slice(rawSegment.indexOf("(") + 1, rawSegment.lastIndexOf(")"));
634
- return (
635
- /^\s*(?:["'][^"']+["']|process\.execPath)\s*(?:,\s*(?:\[|[A-Za-z_$][A-Za-z0-9_$]*)|$)/s.test(argsText) ||
636
- isFixedTerminalVersionProbe(argsText) ||
637
- hasConstLiteralCommandVector(rawSource, callStart, argsText)
638
- );
639
- }
640
-
641
- // Agent/tool discovery commonly runs a manifest-backed terminal binary with `--version`. The
642
- // argument vector is fixed, and the binary field is a known capability slot rather than request data.
643
- function isFixedTerminalVersionProbe(argsText: string): boolean {
644
- return /^\s*[A-Za-z_$][A-Za-z0-9_$]*(?:\.[A-Za-z_$][A-Za-z0-9_$]*)*\.terminalBinary\s*,\s*\[\s*["']--version["']\s*\]/s.test(argsText);
645
- }
646
-
647
- // The safe-exec module is the wrapper implementation: it validates against an allow-list, rejects
648
- // unsafe args, sets `shell: false`, and bounds execution. Flagging its one spawn call is noise.
649
- function isSafeExecWrapperCall(file: SourceFile, callName: string, codeSegment: string): boolean {
650
- return /(?:^|\/)safe-exec\.ts$/.test(file.displayPath) && ["spawn", "spawnSync"].includes(callName) && /\bshell\s*:\s*false\b/.test(codeSegment);
651
- }
652
-
653
- // Test harnesses often launch the current Node process or syntax-check a local shell script. Keep
654
- // dynamic production process calls visible while suppressing those fixed test-driver invocations.
655
- function isFixedTestHarnessProcessCall(file: SourceFile, callName: string, rawSegment: string, codeSegment: string): boolean {
656
- if (!isTestLikeProcessExecPath(file.displayPath) || /\bshell\s*:\s*true\b/.test(codeSegment)) {
657
- return false;
658
- }
659
- const argsText = rawSegment.slice(rawSegment.indexOf("(") + 1, rawSegment.lastIndexOf(")"));
660
- if (/^\s*process\.execPath\s*,\s*\[/.test(argsText)) {
661
- return true;
662
- }
663
- return ["exec", "execSync"].includes(callName) && /^\s*(?:"node scripts\/[^"]+"|'node scripts\/[^']+'|`(?:bash -n|wc -l\b)[^`]*`)/s.test(argsText);
664
- }
665
-
666
- // Test-only paths get a few extra fixed-harness exemptions; production paths still report them.
667
- function isTestLikeProcessExecPath(path: string): boolean {
668
- return /(?:^|\/)(?:test|tests)\/|(?:^|\/)[^/]+\.(?:test|spec)\.[cm]?[jt]sx?$/.test(path);
669
- }
670
-
671
- // Handles local command variables such as `const whichCmd = platform ? "where" : "which"` when
672
- // the call still uses an argv array. Calls or templates in the declaration remain reportable.
673
- function hasConstLiteralCommandVector(rawSource: string, callStart: number, argsText: string): boolean {
674
- const firstArg = argsText.match(/^\s*([A-Za-z_$][A-Za-z0-9_$]*)\s*,\s*(?:\[|[A-Za-z_$][A-Za-z0-9_$]*)/s)?.[1];
675
- if (!firstArg) {
676
- return false;
677
- }
678
- const declaration = rawSource.slice(0, callStart).match(new RegExp(`\\bconst\\s+${escapeRegex(firstArg)}\\s*=\\s*([^;]+);\\s*$`, "s"));
679
- const initializer = declaration?.[1] ?? "";
680
- return /["'][^"']+["']/.test(initializer) && !/[`$()[\]{}]/.test(initializer);
681
- }
682
-
683
-
684
-
685
- const HUNGARIAN_PREFIX_REGEX_CACHE = new WeakMap<Set<string>, RegExp | null>();
686
-
687
-
688
- // Counterpart to `booleanPrefixRegex` for the `naming.hungarian-notation` rule. Returns a global
689
- // regex (callers iterate matches) anchored to declaration keywords + visibility modifiers, so a
690
- // reference to `IUser` inside a comment is not flagged - the regex is part of the stable contract.
691
- function hungarianPrefixRegex(prefixes: Set<string>): RegExp | null {
692
- if (HUNGARIAN_PREFIX_REGEX_CACHE.has(prefixes)) {
693
- return HUNGARIAN_PREFIX_REGEX_CACHE.get(prefixes) ?? null;
694
- }
695
- const escapedPrefixes = [...prefixes].map(escapeRegex);
696
- const regex = prefixes.size === 0 ? null : new RegExp(`\\b(?:const|let|var|public|private|protected)\\s+((?:${escapedPrefixes.join("|")})[A-Z][A-Za-z0-9_$]*)`, "g");
697
- HUNGARIAN_PREFIX_REGEX_CACHE.set(prefixes, regex);
698
- return regex;
699
- }