@blundergoat/gruff-ts 0.4.0 → 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.
- package/CHANGELOG.md +41 -1
- package/README.md +16 -6
- package/SECURITY.md +2 -1
- package/docs/README.md +1 -4
- package/docs/agent-hook.md +14 -2
- package/docs/configuration.md +32 -1
- package/docs/dashboard.md +3 -3
- package/docs/reports-and-ci.md +15 -0
- package/docs/rules.md +35 -29
- package/package.json +1 -1
- package/src/analyser.ts +163 -53
- package/src/baseline.ts +39 -3
- package/src/blocks.ts +116 -77
- package/src/changed-regions.ts +59 -11
- package/src/class-rules.ts +226 -76
- package/src/cli-program.ts +61 -14
- package/src/cli.ts +1 -0
- package/src/comment-rules.ts +58 -13
- package/src/comment-scanner.ts +27 -0
- package/src/complexity-metrics.ts +244 -0
- package/src/config.ts +56 -16
- package/src/constants.ts +1 -1
- package/src/context-doc-rules.ts +9 -10
- package/src/discovery.ts +39 -19
- package/src/doc-rules.ts +22 -53
- package/src/findings-helpers.ts +127 -1
- package/src/findings.ts +4 -0
- package/src/fixture-purpose-rules.ts +39 -5
- package/src/github-actions-rules.ts +24 -1
- package/src/hook-contract.ts +85 -14
- package/src/init-config.ts +15 -5
- package/src/line-rules.ts +54 -5
- package/src/naming-pushers.ts +26 -5
- package/src/parsed-script.ts +652 -0
- package/src/process-exec-metadata.ts +16 -6
- package/src/profiles.ts +14 -0
- package/src/project-config-rules.ts +15 -10
- package/src/public-exports.ts +220 -0
- package/src/report-renderers.ts +55 -4
- package/src/rules.ts +11 -11
- package/src/scoring.ts +13 -4
- package/src/security-flow-rules.ts +169 -24
- package/src/sensitive-data-rules.ts +132 -78
- package/src/source-text.ts +4 -46
- package/src/test-block-rules.ts +118 -14
- package/src/test-fixtures.ts +4 -1
- package/src/text-scans.ts +8 -1
- package/src/types.ts +5 -3
package/src/analyser.ts
CHANGED
|
@@ -1,21 +1,21 @@
|
|
|
1
1
|
// Analyser pipeline: walks discovered sources, runs every rule pass (complexity, dead-code, design,
|
|
2
2
|
// documentation, maintainability, modernisation, naming, security, sensitive-data, size, test-quality),
|
|
3
3
|
// aggregates findings into the `gruff.analysis.v2` schema, and exposes `analyse` to the CLI shell.
|
|
4
|
-
import { Buffer } from "node:buffer";
|
|
4
|
+
import { Buffer, isUtf8 } from "node:buffer";
|
|
5
5
|
import { readFileSync } from "node:fs";
|
|
6
6
|
import { cwd } from "node:process";
|
|
7
|
-
import { basename } from "node:path";
|
|
8
|
-
import {
|
|
7
|
+
import { basename, extname } from "node:path";
|
|
8
|
+
import { recordHistory, sortedUniqueFindings } from "./baseline.ts";
|
|
9
9
|
import { applyBaselineOptions, type BaselineApplication } from "./baseline-options.ts";
|
|
10
|
-
import { changedRegionScope, filterChangedFindings } from "./changed-regions.ts";
|
|
10
|
+
import { changedRegionScope, filterChangedFindings, filterScopedDiagnostics } from "./changed-regions.ts";
|
|
11
11
|
import { loadConfig, optionNumber, ruleEnabled, ruleSeverity, threshold } from "./config.ts";
|
|
12
12
|
import { VERSION } from "./constants.ts";
|
|
13
13
|
import { absolutize, discoverSources, displayPath, type SourceFile } from "./discovery.ts";
|
|
14
14
|
import { makeFinding } from "./findings.ts";
|
|
15
|
-
import { finding } from "./findings-helpers.ts";
|
|
16
|
-
import { commentRecords } from "./comment-scanner.ts";
|
|
15
|
+
import { applyConfiguredSeverity, finding, parameterNames } from "./findings-helpers.ts";
|
|
16
|
+
import { commentRecords, type CommentRecord } from "./comment-scanner.ts";
|
|
17
17
|
import { analyseArchitectureRules, analyseCircularImportRule, buildProjectIndex, CIRCULAR_IMPORT_RULE_ID, isProductionSourcePath, isTestPath, type ProjectSource } from "./project-rules.ts";
|
|
18
|
-
import { analyseBlockRules, type BlockRuleContext, blockRuleContext, type FunctionBlock, functionBlocks
|
|
18
|
+
import { analyseBlockRules, type BlockRuleContext, blockRuleContext, type FunctionBlock, functionBlocks } from "./blocks.ts";
|
|
19
19
|
import { analyseClassRules, analyseAcronymCase, analyseInconsistentCasing, analyseInterfaceFields, collectDeclaredIdentifiers } from "./class-rules.ts";
|
|
20
20
|
import { analyseDeadCode, analyseUnreachable, analyseUnusedImports } from "./dead-code-rules.ts";
|
|
21
21
|
import { analyseCommentQualityRules } from "./comment-rules.ts";
|
|
@@ -29,7 +29,8 @@ import { analyseProjectConfigRules } from "./project-config-rules.ts";
|
|
|
29
29
|
import { ruleDescriptors } from "./rules.ts";
|
|
30
30
|
import { scoreReport, summarize } from "./scoring.ts";
|
|
31
31
|
import { analyseSensitiveData } from "./sensitive-data-rules.ts";
|
|
32
|
-
import {
|
|
32
|
+
import { parseScript, type ParsedScript } from "./parsed-script.ts";
|
|
33
|
+
import { maskNonCode, maskTemplateLiteralBodies } from "./source-text.ts";
|
|
33
34
|
import type { AnalysisOptions, AnalysisReport, Config, Finding, Pillar, RunDiagnostic, ScanSurfaceNote, SkippedPath } from "./types.ts";
|
|
34
35
|
|
|
35
36
|
/*
|
|
@@ -57,7 +58,8 @@ export function analyse(options: AnalysisOptions): AnalysisReport {
|
|
|
57
58
|
recordHistory(run.projectRoot, options.historyFile, changedResult.findings, run.diagnostics);
|
|
58
59
|
}
|
|
59
60
|
|
|
60
|
-
|
|
61
|
+
// File-scoped policy: diff runs report and fail on diagnostics from changed target files only.
|
|
62
|
+
return reportFromRun({ ...run, diagnostics: filterScopedDiagnostics(run.diagnostics, changedScope) }, options, { ...run.baselineResult, findings: changedResult.findings }, changedResult.suppressedCount);
|
|
61
63
|
}
|
|
62
64
|
|
|
63
65
|
// Builds the hook's full and changed-region reports from one scan. The diff-base replay still uses
|
|
@@ -70,7 +72,8 @@ export function analyseHookReports(currentOptions: AnalysisOptions, scopedOption
|
|
|
70
72
|
}
|
|
71
73
|
const scopedChangedScope = changedRegionScope(scopedOptions);
|
|
72
74
|
const scopedChangedResult = filterChangedFindings(run.baselineResult.findings, scopedChangedScope, run.scanned.sources);
|
|
73
|
-
|
|
75
|
+
// Same file-scoped diagnostics policy as diff-scoped analyse, so both surfaces agree.
|
|
76
|
+
const scopedReport = reportFromRun({ ...run, diagnostics: filterScopedDiagnostics(run.diagnostics, scopedChangedScope) }, scopedOptions, { ...run.baselineResult, findings: scopedChangedResult.findings }, scopedChangedResult.suppressedCount);
|
|
74
77
|
return { currentReport, scopedReport };
|
|
75
78
|
}
|
|
76
79
|
|
|
@@ -92,7 +95,7 @@ function completeAnalysis(preparation: AnalysisPreparation, options: AnalysisOpt
|
|
|
92
95
|
const allFindings = sortedUniqueFindings([
|
|
93
96
|
...scanned.findings,
|
|
94
97
|
...analyseProjectIndex(projectRoot, options, discovery.files, scanned.projectSources, config).filter((finding) => ruleEnabled(config, finding.ruleId)),
|
|
95
|
-
]);
|
|
98
|
+
].map((finding) => applyConfiguredSeverity(config, finding)));
|
|
96
99
|
const baselineResult = applyBaselineOptions(projectRoot, options, allFindings);
|
|
97
100
|
const notes = [...discovery.notes, ...scanned.notes];
|
|
98
101
|
return { projectRoot, discovery, diagnostics, scanned, baselineResult, notes };
|
|
@@ -103,6 +106,7 @@ function reportFromRun(run: AnalysisRun, options: AnalysisOptions, baselineResul
|
|
|
103
106
|
return buildAnalysisReport(run.projectRoot, options, run.discovery, run.diagnostics, baselineResult, run.notes, suppressedCount);
|
|
104
107
|
}
|
|
105
108
|
|
|
109
|
+
// Assembles the run's payload; the field shape is the stable gruff.analysis.v2 schema contract.
|
|
106
110
|
function buildAnalysisReport(
|
|
107
111
|
projectRoot: string,
|
|
108
112
|
options: AnalysisOptions,
|
|
@@ -154,7 +158,7 @@ interface DiscoverySummary {
|
|
|
154
158
|
interface SourceScanResult {
|
|
155
159
|
findings: Finding[];
|
|
156
160
|
projectSources: ProjectSource[];
|
|
157
|
-
sources: Map<string, { file: SourceFile; source: string }>;
|
|
161
|
+
sources: Map<string, { file: SourceFile; source: string; parsed?: ParsedScript }>;
|
|
158
162
|
notes: ScanSurfaceNote[];
|
|
159
163
|
}
|
|
160
164
|
|
|
@@ -198,22 +202,34 @@ function pushMissingPathDiagnostics(missingPaths: string[], diagnostics: RunDiag
|
|
|
198
202
|
function scanDiscoveredSources(files: SourceFile[], config: Config, diagnostics: RunDiagnostic[]): SourceScanResult {
|
|
199
203
|
const findings: Finding[] = [];
|
|
200
204
|
const projectSources: ProjectSource[] = [];
|
|
201
|
-
const sources = new Map<string, { file: SourceFile; source: string }>();
|
|
205
|
+
const sources = new Map<string, { file: SourceFile; source: string; parsed?: ParsedScript }>();
|
|
202
206
|
const notes: ScanSurfaceNote[] = [];
|
|
203
207
|
for (const file of files) {
|
|
204
208
|
try {
|
|
205
|
-
const
|
|
206
|
-
|
|
209
|
+
const fileBytes = readFileSync(file.absolutePath);
|
|
210
|
+
// Non-text bytes cannot produce trustworthy findings; the note explains why the file was skipped.
|
|
211
|
+
if (!isUtf8(fileBytes) || fileBytes.includes(0)) {
|
|
212
|
+
notes.push({
|
|
213
|
+
noteType: "non-text-file",
|
|
214
|
+
path: file.displayPath,
|
|
215
|
+
message: "File was skipped before parsing because it contains invalid UTF-8 or NUL bytes.",
|
|
216
|
+
});
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
219
|
+
const source = fileBytes.toString("utf8");
|
|
207
220
|
const budgetNote = deepScanBudgetNote(file, source);
|
|
221
|
+
// One parse per script per run: every deep consumer shares this result; over-budget files skip it.
|
|
222
|
+
const parsed = budgetNote ? undefined : parseScript(file, source);
|
|
223
|
+
sources.set(file.displayPath, { file, source, ...(parsed ? { parsed } : {}) });
|
|
208
224
|
if (budgetNote) {
|
|
209
225
|
notes.push(budgetNote);
|
|
210
226
|
} else {
|
|
211
227
|
if (shouldRetainProjectSource(file, source)) {
|
|
212
228
|
projectSources.push(projectSource(file, source));
|
|
213
229
|
}
|
|
214
|
-
diagnostics.push(...
|
|
230
|
+
diagnostics.push(...(parsed?.diagnostics ?? []));
|
|
215
231
|
}
|
|
216
|
-
findings.push(...analyseSource(file, source, config, budgetNote === undefined));
|
|
232
|
+
findings.push(...analyseSource(file, source, config, budgetNote === undefined, parsed));
|
|
217
233
|
} catch (error) {
|
|
218
234
|
diagnostics.push({
|
|
219
235
|
diagnosticType: "read-error",
|
|
@@ -269,30 +285,19 @@ function hasImportSyntaxCandidate(source: string): boolean {
|
|
|
269
285
|
return source.includes("import") || source.includes("from");
|
|
270
286
|
}
|
|
271
287
|
|
|
272
|
-
// Canonical finding ordering: (filePath, line, ruleId, message). The same tuple is part of the
|
|
273
|
-
// stable baseline matching contract, so changing the comparator would churn every existing baseline.
|
|
274
|
-
function sortedUniqueFindings(findings: Finding[]): Finding[] {
|
|
275
|
-
findings.sort(
|
|
276
|
-
(left, right) =>
|
|
277
|
-
left.filePath.localeCompare(right.filePath) ||
|
|
278
|
-
(left.line ?? 0) - (right.line ?? 0) ||
|
|
279
|
-
left.ruleId.localeCompare(right.ruleId) ||
|
|
280
|
-
left.message.localeCompare(right.message),
|
|
281
|
-
);
|
|
282
|
-
return dedupeFindings(findings);
|
|
283
|
-
}
|
|
284
|
-
|
|
285
288
|
// Per-file rule pipeline. Text rules run on every file (including config/yaml); TypeScript rules
|
|
286
289
|
// run only on scripts within the deep-scan budget. Fixed order is part of the stable fingerprint
|
|
287
290
|
// contract. Generated/copied files keep every security and sensitive-data finding but drop
|
|
288
291
|
// documentation and naming findings - generated code is not maintainer-authored source, so pushing
|
|
289
292
|
// doc/naming work at a human reviewer is unactionable noise.
|
|
290
293
|
// Contract invariant: doc/naming skips must not suppress safety pillars or change rule order.
|
|
291
|
-
function analyseSource(file: SourceFile, source: string, config: Config, isWithinDeepScanBudget: boolean): Finding[] {
|
|
294
|
+
function analyseSource(file: SourceFile, source: string, config: Config, isWithinDeepScanBudget: boolean, parsed?: ParsedScript): Finding[] {
|
|
292
295
|
const findings: Finding[] = [];
|
|
293
|
-
|
|
296
|
+
// Size and documentation rules share one comment scan so code-only line counts do not add a second pass.
|
|
297
|
+
const comments = (ruleEnabled(config, "size.file-length") && usesCStyleComments(file)) || (file.isScript && isAnyRuleEnabled(config, COMMENT_QUALITY_RULE_IDS)) ? commentRecords(source) : [];
|
|
298
|
+
analyseTextRules(file, source, comments, config, findings);
|
|
294
299
|
if (file.isScript && isWithinDeepScanBudget) {
|
|
295
|
-
analyseTypeScriptRules(file, source, config, findings);
|
|
300
|
+
analyseTypeScriptRules(file, source, comments, config, findings, parsed);
|
|
296
301
|
}
|
|
297
302
|
const isGenerated = isGeneratedSource(source);
|
|
298
303
|
return findings.filter((finding) => ruleEnabled(config, finding.ruleId) && !(isGenerated && GENERATED_SKIPPED_PILLARS.has(finding.pillar)));
|
|
@@ -395,6 +400,17 @@ const SENSITIVE_DATA_RULE_IDS = ruleIdsForPillar("sensitive-data");
|
|
|
395
400
|
const SIZE_RULE_IDS = ruleIdsForPillar("size");
|
|
396
401
|
const TEST_QUALITY_RULE_IDS = ruleIdsForPillar("test-quality");
|
|
397
402
|
|
|
403
|
+
/*
|
|
404
|
+
* Sensitive-data rules that infer a secret from shape rather than value, so generated
|
|
405
|
+
* dependency metadata defeats them: every integrity digest looks high-entropy, and a package
|
|
406
|
+
* named `gtoken` turns `gtoken: 8.0.0(supports-color@11.0.0)` into a credential assignment.
|
|
407
|
+
* Suppressed for lockfiles only. Every value-shaped detector still runs there.
|
|
408
|
+
*/
|
|
409
|
+
const LOCKFILE_SUPPRESSED_SENSITIVE_RULE_IDS = new Set([
|
|
410
|
+
"sensitive-data.high-entropy-string",
|
|
411
|
+
"sensitive-data.hardcoded-env-value",
|
|
412
|
+
]);
|
|
413
|
+
|
|
398
414
|
const GITHUB_ACTIONS_RULE_IDS = [
|
|
399
415
|
"security.github-actions-broad-permissions",
|
|
400
416
|
"security.github-actions-pull-request-target",
|
|
@@ -535,18 +551,18 @@ function isAnyRuleEnabled(config: Config, ruleIds: readonly string[]): boolean {
|
|
|
535
551
|
* secret surfaces are not TypeScript. The order is a stable baseline contract: reshuffling these
|
|
536
552
|
* checks changes same-line finding order for machine reports.
|
|
537
553
|
*/
|
|
538
|
-
function analyseTextRules(file: SourceFile, source: string, config: Config, findings: Finding[]): void {
|
|
539
|
-
const lines = lineCount(source);
|
|
554
|
+
function analyseTextRules(file: SourceFile, source: string, comments: CommentRecord[], config: Config, findings: Finding[]): void {
|
|
540
555
|
if (ruleEnabled(config, "size.file-length") && !isGeneratedLockfile(file.displayPath)) {
|
|
541
|
-
const
|
|
556
|
+
const lines = substantiveLineCount(file, source, comments);
|
|
557
|
+
const fileLengthThreshold = threshold(config, "size.file-length", 1000);
|
|
542
558
|
if (lines > fileLengthThreshold) {
|
|
543
559
|
findings.push(
|
|
544
560
|
makeFinding({
|
|
545
561
|
ruleId: "size.file-length",
|
|
546
|
-
message: `File has ${lines} lines, above the threshold of ${fileLengthThreshold}.`,
|
|
562
|
+
message: `File has ${lines} substantive lines, above the threshold of ${fileLengthThreshold}.`,
|
|
547
563
|
filePath: file.displayPath,
|
|
548
564
|
line: 1,
|
|
549
|
-
severity: ruleSeverity(config, "size.file-length", "
|
|
565
|
+
severity: ruleSeverity(config, "size.file-length", "error"),
|
|
550
566
|
pillar: "size",
|
|
551
567
|
confidence: "high",
|
|
552
568
|
remediation: "Split unrelated responsibilities into smaller files. Or raise rules.size.file-length.threshold in .gruff-ts.yaml if the bound is wrong for this project.",
|
|
@@ -557,7 +573,18 @@ function analyseTextRules(file: SourceFile, source: string, config: Config, find
|
|
|
557
573
|
}
|
|
558
574
|
|
|
559
575
|
if (isAnyRuleEnabled(config, SENSITIVE_DATA_RULE_IDS)) {
|
|
560
|
-
|
|
576
|
+
const sensitiveFindings: Finding[] = [];
|
|
577
|
+
analyseSensitiveData(file, source, config, sensitiveFindings);
|
|
578
|
+
// Generated dependency metadata defeats the two shape-based detectors: integrity digests
|
|
579
|
+
// look high-entropy, and a package whose name contains `token`/`key`/`secret` makes its
|
|
580
|
+
// version spec look like a credential assignment. The value-shaped detectors still run,
|
|
581
|
+
// because a credential in a `resolved` URL is the real leak vector for this file family.
|
|
582
|
+
const isLockfile = isGeneratedLockfile(file.displayPath);
|
|
583
|
+
for (const sensitiveFinding of sensitiveFindings) {
|
|
584
|
+
if (!isLockfile || !LOCKFILE_SUPPRESSED_SENSITIVE_RULE_IDS.has(sensitiveFinding.ruleId)) {
|
|
585
|
+
findings.push(sensitiveFinding);
|
|
586
|
+
}
|
|
587
|
+
}
|
|
561
588
|
}
|
|
562
589
|
if (isAnyRuleEnabled(config, GITHUB_ACTIONS_RULE_IDS)) {
|
|
563
590
|
analyseGithubActionsRules(file, source, findings);
|
|
@@ -567,6 +594,59 @@ function analyseTextRules(file: SourceFile, source: string, config: Config, find
|
|
|
567
594
|
}
|
|
568
595
|
}
|
|
569
596
|
|
|
597
|
+
// Counts nonblank lines after removing C-style and XML comments, then applies config-format
|
|
598
|
+
// full-line markers. Strings remain intact, so a line containing only a string literal still counts.
|
|
599
|
+
function substantiveLineCount(file: SourceFile, source: string, comments: CommentRecord[]): number {
|
|
600
|
+
const withoutCStyleComments = maskRecordedComments(source, comments);
|
|
601
|
+
const withoutComments = extname(file.displayPath).toLowerCase() === ".xml" ? maskXmlComments(withoutCStyleComments) : withoutCStyleComments;
|
|
602
|
+
return withoutComments
|
|
603
|
+
.split(/\r?\n/)
|
|
604
|
+
.filter((line) => isSubstantiveLine(file, line))
|
|
605
|
+
.length;
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
// C-style comments are valid on script/CSS surfaces and common in JSON-with-comments configs.
|
|
609
|
+
// Other supported text formats use their own full-line markers and must keep literal slash pairs.
|
|
610
|
+
function usesCStyleComments(file: SourceFile): boolean {
|
|
611
|
+
const extension = extname(file.displayPath).toLowerCase();
|
|
612
|
+
return file.isScript || extension === ".css" || extension === ".json";
|
|
613
|
+
}
|
|
614
|
+
|
|
615
|
+
// Replaces comment text with spaces while retaining newlines and UTF-16 offsets from CommentRecord.
|
|
616
|
+
function maskRecordedComments(source: string, comments: CommentRecord[]): string {
|
|
617
|
+
let cursor = 0;
|
|
618
|
+
let masked = "";
|
|
619
|
+
for (const comment of comments) {
|
|
620
|
+
const end = comment.kind === "block" ? Math.min(source.length, comment.endIndex + 1) : comment.endIndex;
|
|
621
|
+
masked += source.slice(cursor, comment.startIndex);
|
|
622
|
+
masked += source.slice(comment.startIndex, end).replace(/[^\r\n]/g, " ");
|
|
623
|
+
cursor = end;
|
|
624
|
+
}
|
|
625
|
+
return masked + source.slice(cursor);
|
|
626
|
+
}
|
|
627
|
+
|
|
628
|
+
// XML comments are outside the JavaScript lexer; preserving their newlines keeps line accounting stable.
|
|
629
|
+
function maskXmlComments(source: string): string {
|
|
630
|
+
return source.replace(/<!--[\s\S]*?(?:-->|$)/g, (comment) => comment.replace(/[^\r\n]/g, " "));
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
// Hash and semicolon markers are restricted to formats where they are comments, so TypeScript
|
|
634
|
+
// private fields and ordinary semicolon statements remain substantive.
|
|
635
|
+
function isSubstantiveLine(file: SourceFile, line: string): boolean {
|
|
636
|
+
const trimmed = line.trim();
|
|
637
|
+
if (!trimmed) {
|
|
638
|
+
return false;
|
|
639
|
+
}
|
|
640
|
+
const name = basename(file.displayPath).toLowerCase();
|
|
641
|
+
const extension = extname(name);
|
|
642
|
+
const usesHashComments = [".yaml", ".yml", ".toml"].includes(extension) || name === ".npmrc" || name.startsWith(".env");
|
|
643
|
+
if ((usesHashComments || (file.isScript && trimmed.startsWith("#!"))) && trimmed.startsWith("#")) {
|
|
644
|
+
return false;
|
|
645
|
+
}
|
|
646
|
+
const usesSemicolonComments = extension === ".ini" || name === ".npmrc";
|
|
647
|
+
return !(usesSemicolonComments && trimmed.startsWith(";"));
|
|
648
|
+
}
|
|
649
|
+
|
|
570
650
|
// Counts the same logical lines as `source.split(/\r?\n/)` without allocating the full line array.
|
|
571
651
|
function lineCount(source: string): number {
|
|
572
652
|
let count = 1;
|
|
@@ -578,38 +658,49 @@ function lineCount(source: string): number {
|
|
|
578
658
|
return count;
|
|
579
659
|
}
|
|
580
660
|
|
|
581
|
-
//
|
|
582
|
-
//
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
661
|
+
// Package-manager lockfiles contain generated dependency metadata, including public integrity digests.
|
|
662
|
+
// Discovery retains them; `size.file-length` skips them outright and the sensitive-data pass uses this
|
|
663
|
+
// predicate to drop only `sensitive-data.high-entropy-string`, so lockfile credentials still report.
|
|
664
|
+
function isGeneratedLockfile(filePath: string): boolean {
|
|
665
|
+
const fileName = basename(filePath);
|
|
666
|
+
return fileName === "package-lock.json" || fileName === "npm-shrinkwrap.json" || fileName === "yarn.lock" || fileName === "pnpm-lock.yaml" || fileName === "bun.lockb";
|
|
586
667
|
}
|
|
587
668
|
|
|
588
669
|
/*
|
|
589
670
|
* TypeScript-only rule pipeline. Masks comments and literals once, parses callable blocks once,
|
|
590
671
|
* then walks every rule pack in a stable, deterministic order so reports and baselines remain reproducible.
|
|
591
672
|
*/
|
|
592
|
-
function analyseTypeScriptRules(file: SourceFile, source: string, config: Config, findings: Finding[]): void {
|
|
673
|
+
function analyseTypeScriptRules(file: SourceFile, source: string, comments: CommentRecord[], config: Config, findings: Finding[], parsed?: ParsedScript): void {
|
|
593
674
|
if (!isAnyRuleEnabled(config, TYPESCRIPT_RULE_IDS)) {
|
|
594
675
|
return;
|
|
595
676
|
}
|
|
596
677
|
const codeSource = maskNonCode(source);
|
|
597
|
-
const blocks = isAnyRuleEnabled(config, BLOCK_DEPENDENT_RULE_IDS) ? functionBlocks(source, codeSource) : [];
|
|
678
|
+
const blocks = isAnyRuleEnabled(config, BLOCK_DEPENDENT_RULE_IDS) ? functionBlocks(source, codeSource, parsed) : [];
|
|
598
679
|
runRulePass(config, "docs.missing-file-overview", () => analyseFileOverviewDoc(file, source, findings));
|
|
599
680
|
analyseBlocks(file, source, codeSource, blocks, config, findings);
|
|
600
681
|
runRulePass(config, "waste.unused-import", () => analyseUnusedImports(file, codeSource, source, findings));
|
|
601
682
|
runRuleGroupPass(config, LINE_RULE_IDS, () => analyseLineRules(file, source, codeSource, config, findings));
|
|
602
|
-
runRuleGroupPass(config, SECURITY_FLOW_RULE_IDS, () => analyseSecurityFlow(file, source, findings));
|
|
683
|
+
runRuleGroupPass(config, SECURITY_FLOW_RULE_IDS, () => analyseSecurityFlow(file, source, findings, parsed?.sourceFile));
|
|
603
684
|
runRulePass(config, "waste.unreachable-code", () => analyseUnreachable(file, codeSource, findings));
|
|
604
|
-
|
|
685
|
+
// Docblock rules read real AST signatures; a bounded-deep-scan file without a parse skips them
|
|
686
|
+
// like the other syntax-backed passes instead of falling back to a lossy regex walk.
|
|
687
|
+
runRuleGroupPass(config, DOCBLOCK_RULE_IDS, () => {
|
|
688
|
+
if (parsed) {
|
|
689
|
+
analyseDocRules(file, findings, parsed);
|
|
690
|
+
}
|
|
691
|
+
});
|
|
605
692
|
runRulePass(config, "docs.missing-interface-doc", () => analyseInterfaceDocs(file, source, codeSource, findings));
|
|
606
693
|
runRuleGroupPass(config, INTERFACE_FIELD_RULE_IDS, () => analyseInterfaceFields(file, source, codeSource, config, findings));
|
|
607
|
-
runRuleGroupPass(config, COMMENT_QUALITY_RULE_IDS, () => analyseCommentQualityRules({ file, source, codeSource, blocks, comments
|
|
608
|
-
runRuleGroupPass(config, CLASS_RULE_IDS, () => analyseClassRules(file, source, codeSource, findings));
|
|
694
|
+
runRuleGroupPass(config, COMMENT_QUALITY_RULE_IDS, () => analyseCommentQualityRules({ file, source, codeSource, blocks, comments, config, findings }));
|
|
695
|
+
runRuleGroupPass(config, CLASS_RULE_IDS, () => analyseClassRules(file, source, codeSource, config, findings, parsed));
|
|
609
696
|
runRulePass(config, "dead-code.unused-private-method", () => analyseDeadCode(file, codeSource, findings));
|
|
610
697
|
runRuleGroupPass(config, IDENTIFIER_INVENTORY_RULE_IDS, () => {
|
|
611
|
-
|
|
612
|
-
|
|
698
|
+
// A normal deep script scan always supplies the shared parse; a missing result must not reparse.
|
|
699
|
+
if (!parsed) {
|
|
700
|
+
return;
|
|
701
|
+
}
|
|
702
|
+
const inventory = collectDeclaredIdentifiers(source, codeSource, parsed);
|
|
703
|
+
runRulePass(config, "naming.inconsistent-casing", () => analyseInconsistentCasing(file, inventory, config, findings));
|
|
613
704
|
runRulePass(config, "naming.acronym-case", () => analyseAcronymCase(file, inventory, config, findings));
|
|
614
705
|
});
|
|
615
706
|
}
|
|
@@ -659,8 +750,9 @@ function analyseBlocks(file: SourceFile, source: string, codeSource: string, blo
|
|
|
659
750
|
function pushParameterNamingFindings(context: BlockRuleContext): void {
|
|
660
751
|
const line = context.block.declarationLine;
|
|
661
752
|
const params = parameterNames(context.block.params);
|
|
753
|
+
const hasLocallyBoundParameters = isLocallyBoundParameterOwner(context.block);
|
|
662
754
|
for (const parameter of params) {
|
|
663
|
-
if (!isComparatorShortParameter(context, params, parameter.name)) {
|
|
755
|
+
if (!hasLocallyBoundParameters && !isComparatorShortParameter(context, params, parameter.name)) {
|
|
664
756
|
pushShortVariableAt(context.file, line, parameter.name, context.config, context.findings, "parameter");
|
|
665
757
|
}
|
|
666
758
|
pushIdentifierQualityAt(context.file, line, parameter.name, context.config, context.findings, "parameter");
|
|
@@ -674,6 +766,24 @@ function pushParameterNamingFindings(context: BlockRuleContext): void {
|
|
|
674
766
|
}
|
|
675
767
|
}
|
|
676
768
|
|
|
769
|
+
// Variable-bound callables and test callbacks keep their parameters beside the implementation,
|
|
770
|
+
// so short closure names do not create the cross-file review cost this rule is meant to surface.
|
|
771
|
+
// Declared functions and methods remain covered. Other parameter naming rules still run here.
|
|
772
|
+
function isLocallyBoundParameterOwner(block: FunctionBlock): boolean {
|
|
773
|
+
if (block.isTest) {
|
|
774
|
+
return true;
|
|
775
|
+
}
|
|
776
|
+
// An exported binding is the cross-file API this exemption exists to keep covered, so
|
|
777
|
+
// `export const transform = (x) => ...` is judged like `export function transform(x)`.
|
|
778
|
+
if (block.isExported) {
|
|
779
|
+
return false;
|
|
780
|
+
}
|
|
781
|
+
const declarationOffset = block.declarationLine - block.startLine;
|
|
782
|
+
const declarationLine = block.codeBody.split(/\r?\n/)[declarationOffset] ?? "";
|
|
783
|
+
const bindingName = declarationLine.match(/\b(?:const|let)\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=/)?.[1];
|
|
784
|
+
return bindingName === block.name;
|
|
785
|
+
}
|
|
786
|
+
|
|
677
787
|
// `(a, b)` is a conventional comparator pair when the callable is explicitly shaped like sorting.
|
|
678
788
|
// Keep the exemption narrow so arbitrary two-parameter helpers still need domain names.
|
|
679
789
|
function isComparatorShortParameter(context: BlockRuleContext, params: Array<{ name: string; raw: string }>, name: string): boolean {
|
package/src/baseline.ts
CHANGED
|
@@ -74,11 +74,14 @@ function recordHistory(projectRoot: string, historyFile: string, findings: Findi
|
|
|
74
74
|
|
|
75
75
|
// `docs.missing-public-doc` is keyed by (ruleId, filePath, symbol) instead of fingerprint because one
|
|
76
76
|
// file can legitimately surface multiple undocumented public symbols and they must each survive dedupe.
|
|
77
|
-
// All other rules collapse on their fingerprint,
|
|
77
|
+
// All other rules collapse on their fingerprint, extended by the match column when one is present
|
|
78
|
+
// (ADR-017): two distinct secrets on one line share a line-keyed fingerprint, and without the column
|
|
79
|
+
// discriminator the second occurrence would be silently dropped from every report and the hook.
|
|
80
|
+
// The extended key is in-memory only - fingerprint values and `gruff.baseline.v1` matching are unchanged.
|
|
78
81
|
function dedupeFindings(findings: Finding[]): Finding[] {
|
|
79
82
|
const seen = new Set<string>();
|
|
80
83
|
return findings.filter((finding) => {
|
|
81
|
-
const key = finding
|
|
84
|
+
const key = dedupeKey(finding);
|
|
82
85
|
if (seen.has(key)) {
|
|
83
86
|
return false;
|
|
84
87
|
}
|
|
@@ -87,4 +90,37 @@ function dedupeFindings(findings: Finding[]): Finding[] {
|
|
|
87
90
|
});
|
|
88
91
|
}
|
|
89
92
|
|
|
90
|
-
|
|
93
|
+
// Derives the in-memory dedupe key for one finding, so same-line occurrences with distinct
|
|
94
|
+
// columns survive dedupe as separate findings (ADR-017). Invariant: the key is never serialized
|
|
95
|
+
// and never feeds `applyBaseline` - fingerprint values and baseline matching stay byte-identical.
|
|
96
|
+
function dedupeKey(finding: Finding): string {
|
|
97
|
+
// One file legitimately surfaces many undocumented public symbols; keep each per-symbol entry.
|
|
98
|
+
if (finding.ruleId === "docs.missing-public-doc" && finding.symbol) {
|
|
99
|
+
return [finding.ruleId, finding.filePath, finding.symbol].join("\0");
|
|
100
|
+
}
|
|
101
|
+
// Casing drift is scoped to a lexical owner. Preserve owner-distinct diagnostics in memory
|
|
102
|
+
// without changing their public line-keyed fingerprints or baseline matching contract.
|
|
103
|
+
if (finding.ruleId === "naming.inconsistent-casing" && typeof finding.metadata.ownerId === "string") {
|
|
104
|
+
return [finding.fingerprint, finding.metadata.ownerId].join("\0");
|
|
105
|
+
}
|
|
106
|
+
// A column means the scanner pinpointed the occurrence; same-line occurrences stay distinct.
|
|
107
|
+
if (finding.column !== undefined) {
|
|
108
|
+
return [finding.fingerprint, String(finding.column)].join("\0");
|
|
109
|
+
}
|
|
110
|
+
return finding.fingerprint;
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
// Canonical finding ordering: (filePath, line, ruleId, message). The same tuple is part of the
|
|
114
|
+
// stable baseline matching contract, so changing the comparator would churn every existing baseline.
|
|
115
|
+
function sortedUniqueFindings(findings: Finding[]): Finding[] {
|
|
116
|
+
findings.sort(
|
|
117
|
+
(left, right) =>
|
|
118
|
+
left.filePath.localeCompare(right.filePath) ||
|
|
119
|
+
(left.line ?? 0) - (right.line ?? 0) ||
|
|
120
|
+
left.ruleId.localeCompare(right.ruleId) ||
|
|
121
|
+
left.message.localeCompare(right.message),
|
|
122
|
+
);
|
|
123
|
+
return dedupeFindings(findings);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
export { DEFAULT_BASELINE, writeBaseline, applyBaseline, recordHistory, dedupeFindings, sortedUniqueFindings };
|