@blundergoat/gruff-ts 0.3.1 → 0.4.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 +19 -0
- package/CONTRIBUTING.md +1 -1
- package/README.md +20 -5
- package/SECURITY.md +1 -1
- package/docs/README.md +0 -1
- package/docs/agent-hook.md +14 -2
- package/docs/configuration.md +15 -0
- package/docs/reports-and-ci.md +21 -0
- package/docs/rules.md +22 -12
- package/package.json +17 -2
- package/src/analyser.ts +410 -122
- package/src/baseline-options.ts +90 -0
- package/src/blocks.ts +56 -9
- package/src/changed-regions.ts +46 -17
- package/src/cli-program.ts +103 -4
- package/src/cli.ts +3 -2
- package/src/constants.ts +1 -1
- package/src/dashboard.ts +1 -1
- package/src/dead-code-rules.ts +10 -3
- package/src/discovery.ts +27 -3
- package/src/findings.ts +2 -0
- package/src/hook-contract.ts +457 -0
- package/src/line-rules.ts +126 -19
- package/src/process-exec-metadata.ts +153 -0
- package/src/project-config-rules.ts +21 -8
- package/src/project-rules.ts +159 -42
- package/src/report-renderers.ts +3 -0
- package/src/rule-list.ts +1 -0
- package/src/rules.ts +5 -5
- package/src/sensitive-data-rules.ts +134 -12
- package/src/source-text.ts +47 -22
- package/src/static-analysis-redundant-rules.ts +46 -2
- package/src/types.ts +16 -1
- package/docs/releasing.md +0 -106
- package/fixtures/sample.ts +0 -21
- package/scripts/bump-version.sh +0 -210
- package/scripts/check.sh +0 -4
- package/scripts/dependency-install.sh +0 -96
- package/scripts/dependency-update.sh +0 -177
- package/scripts/npm-publish.sh +0 -258
- package/scripts/preflight-checks.sh +0 -395
- package/scripts/start-dev.sh +0 -8
- package/scripts/test-performance.sh +0 -695
- package/src/fixtures/rule-catalogue-security-doctrine.ts +0 -160
|
@@ -0,0 +1,457 @@
|
|
|
1
|
+
// gruff.hook.v1 adapter: owns the agent-hook JSON shape without changing gruff.analysis.v2.
|
|
2
|
+
import { execFileSync } from "node:child_process";
|
|
3
|
+
import { createHash } from "node:crypto";
|
|
4
|
+
import { existsSync, mkdirSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "node:fs";
|
|
5
|
+
import { dirname, join } from "node:path";
|
|
6
|
+
import { chdir, cwd } from "node:process";
|
|
7
|
+
import { tmpdir } from "node:os";
|
|
8
|
+
import { absolutize } from "./discovery.ts";
|
|
9
|
+
import { VERSION } from "./constants.ts";
|
|
10
|
+
import { ruleDescriptors } from "./rules.ts";
|
|
11
|
+
import type { AnalysisOptions, AnalysisReport, Finding, Severity, SkippedPath } from "./types.ts";
|
|
12
|
+
|
|
13
|
+
type HookScope = "line" | "symbol" | "file" | "project";
|
|
14
|
+
type FlagOrder = "any" | "flags-before-path";
|
|
15
|
+
type HookAnalysisViews = { currentReport: AnalysisReport; scopedReport: AnalysisReport };
|
|
16
|
+
type HookAnalysisRunner = ((options: AnalysisOptions) => AnalysisReport) & {
|
|
17
|
+
hookViews?: (currentOptions: AnalysisOptions, scopedOptions: AnalysisOptions, hasChangedRegion: boolean) => HookAnalysisViews;
|
|
18
|
+
};
|
|
19
|
+
|
|
20
|
+
// Inputs for one hook render: full-scan options, changed-region options, and optional baseline/diff
|
|
21
|
+
// bases used for new-only filtering.
|
|
22
|
+
interface HookReportInput {
|
|
23
|
+
currentOptions: AnalysisOptions;
|
|
24
|
+
scopedOptions: AnalysisOptions;
|
|
25
|
+
baselinePath?: string;
|
|
26
|
+
diffBase?: string;
|
|
27
|
+
hasChangedRegion: boolean;
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// The gruff.hook.v1 envelope written to stdout; field names are the cross-analyzer contract.
|
|
31
|
+
interface HookReport {
|
|
32
|
+
contractVersion: "gruff.hook.v1";
|
|
33
|
+
analyzer: { name: "gruff-ts"; version: string };
|
|
34
|
+
findings: HookFinding[];
|
|
35
|
+
suppressed: { count: number };
|
|
36
|
+
ignored: { paths: SkippedPath[] };
|
|
37
|
+
config: { schemaOk: boolean; error: string | null };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// A finding projected into the hook contract, with enum scope and non-null remediation, keyed for
|
|
41
|
+
// new-only tracking by the stable identity and fingerprint.
|
|
42
|
+
interface HookFinding {
|
|
43
|
+
ruleId: string;
|
|
44
|
+
pillar: string;
|
|
45
|
+
severity: Severity;
|
|
46
|
+
scope: HookScope;
|
|
47
|
+
file: string;
|
|
48
|
+
line?: number;
|
|
49
|
+
endLine?: number;
|
|
50
|
+
symbol: string | null;
|
|
51
|
+
message: string;
|
|
52
|
+
remediation: string;
|
|
53
|
+
metadata: Record<string, unknown>;
|
|
54
|
+
stableIdentity: string;
|
|
55
|
+
fingerprint: string;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// A gruff.baseline.v1 entry as read for new-only comparison; every field is optional because older
|
|
59
|
+
// baselines predate stableIdentity.
|
|
60
|
+
interface BaselineEntry {
|
|
61
|
+
stableIdentity?: string;
|
|
62
|
+
ruleId?: string;
|
|
63
|
+
filePath?: string;
|
|
64
|
+
symbol?: string;
|
|
65
|
+
message?: string;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
const HOOK_CONTRACT_VERSION = "gruff.hook.v1";
|
|
69
|
+
const FILE_SCOPE_RULE_IDS = new Set(["design.large-module-concentration", "docs.missing-file-overview", "size.file-length"]);
|
|
70
|
+
const PROJECT_SCOPE_RULE_IDS = new Set(["design.circular-import"]);
|
|
71
|
+
const SEVERITY_RANK: Record<Severity, number> = { error: 0, warning: 1, advisory: 2 };
|
|
72
|
+
const DESCRIPTORS = new Map(ruleDescriptors().map((descriptor) => [descriptor.ruleId, descriptor]));
|
|
73
|
+
|
|
74
|
+
// Emits the gruff.hook.v1 capability handshake so a consumer can resolve flag names before a real
|
|
75
|
+
// request; the advertised supports/flags object is the stable gruff.hook.v1 contract.
|
|
76
|
+
export function renderHookCapabilities(): string {
|
|
77
|
+
return JSON.stringify({
|
|
78
|
+
contractVersion: HOOK_CONTRACT_VERSION,
|
|
79
|
+
analyzer: analyzerInfo(),
|
|
80
|
+
supports: {
|
|
81
|
+
changedRanges: true,
|
|
82
|
+
diff: true,
|
|
83
|
+
baseline: true,
|
|
84
|
+
scopeField: true,
|
|
85
|
+
metadata: true,
|
|
86
|
+
stableIdentity: true,
|
|
87
|
+
ignoreReport: true,
|
|
88
|
+
newOnly: true,
|
|
89
|
+
},
|
|
90
|
+
flags: { changedRanges: "--changed-ranges", diff: "--diff", baseline: "--baseline" },
|
|
91
|
+
flagOrder: "any" satisfies FlagOrder,
|
|
92
|
+
}, null, 2) + "\n";
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// Runs the analysis and projects it into the gruff.hook.v1 envelope: scoped findings, suppressed
|
|
96
|
+
// count, ignored paths, and a schema-ok config block.
|
|
97
|
+
export function renderHookReport(runAnalyse: HookAnalysisRunner, input: HookReportInput): string {
|
|
98
|
+
const { currentReport, scopedReport } = hookAnalysisViews(runAnalyse, input);
|
|
99
|
+
const baseIdentities = hookBaseIdentities(runAnalyse, input, currentReport);
|
|
100
|
+
const findings = hookFindings(currentReport, scopedReport, input.hasChangedRegion, baseIdentities);
|
|
101
|
+
const suppressedCount = hookSuppressedCount(scopedReport, findings, input.hasChangedRegion);
|
|
102
|
+
return JSON.stringify(hookReport(scopedReport, findings, suppressedCount, true, null), null, 2) + "\n";
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
// Selects the optimized hook view when available, otherwise falls back to one or two analyse calls.
|
|
106
|
+
function hookAnalysisViews(runAnalyse: HookAnalysisRunner, input: HookReportInput): HookAnalysisViews {
|
|
107
|
+
if (runAnalyse.hookViews) {
|
|
108
|
+
return runAnalyse.hookViews(input.currentOptions, input.scopedOptions, input.hasChangedRegion);
|
|
109
|
+
}
|
|
110
|
+
const currentReport = runAnalyse(input.currentOptions);
|
|
111
|
+
const scopedReport = input.hasChangedRegion ? runAnalyse(input.scopedOptions) : currentReport;
|
|
112
|
+
return { currentReport, scopedReport };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// Emits a gruff.hook.v1 envelope for an operational failure (config rejected, bad baseline, git
|
|
116
|
+
// error) so the consumer always receives JSON with config.error set instead of a crash.
|
|
117
|
+
export function renderHookConfigError(message: string, remediation: string): string {
|
|
118
|
+
const error = `${message}\nSuggested fix: ${remediation}`;
|
|
119
|
+
return JSON.stringify(hookReport(undefined, [], 0, false, error), null, 2) + "\n";
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// Assembles the gruff.hook.v1 envelope (sorted findings, suppressed count, ignored paths, config)
|
|
123
|
+
// as the stable gruff.hook.v1 output contract.
|
|
124
|
+
function hookReport(report: AnalysisReport | undefined, findings: HookFinding[], suppressedCount: number, isSchemaOk: boolean, error: string | null): HookReport {
|
|
125
|
+
return {
|
|
126
|
+
contractVersion: HOOK_CONTRACT_VERSION,
|
|
127
|
+
analyzer: analyzerInfo(),
|
|
128
|
+
findings: sortHookFindings(findings),
|
|
129
|
+
suppressed: { count: suppressedCount },
|
|
130
|
+
ignored: { paths: report?.paths.skipped ?? [] },
|
|
131
|
+
config: { schemaOk: isSchemaOk, error },
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// Analyzer identity block shared by the capability and report envelopes.
|
|
136
|
+
function analyzerInfo(): { name: "gruff-ts"; version: string } {
|
|
137
|
+
return { name: "gruff-ts", version: VERSION };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
function hookFindings(
|
|
141
|
+
currentReport: AnalysisReport,
|
|
142
|
+
scopedReport: AnalysisReport,
|
|
143
|
+
hasChangedRegion: boolean,
|
|
144
|
+
baseIdentities: Set<string> | undefined,
|
|
145
|
+
): HookFinding[] {
|
|
146
|
+
const scopedFindings = scopedReport.findings
|
|
147
|
+
.map(toHookFinding)
|
|
148
|
+
.filter((finding) => !hasChangedRegion || finding.scope !== "file");
|
|
149
|
+
const withNewFileAndProject = hasChangedRegion && baseIdentities
|
|
150
|
+
? [...scopedFindings, ...newFileAndProjectFindings(currentReport, scopedFindings, baseIdentities)]
|
|
151
|
+
: scopedFindings;
|
|
152
|
+
return baseIdentities ? withNewFileAndProject.filter((finding) => !baseIdentities.has(finding.stableIdentity)) : withNewFileAndProject;
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// Collects file- and project-scope findings that are new since the base, excluding any already
|
|
156
|
+
// emitted, deduped by fingerprint.
|
|
157
|
+
function newFileAndProjectFindings(currentReport: AnalysisReport, scopedFindings: HookFinding[], baseIdentities: Set<string>): HookFinding[] {
|
|
158
|
+
const alreadyIncluded = new Set(scopedFindings.map((finding) => finding.fingerprint));
|
|
159
|
+
return currentReport.findings
|
|
160
|
+
.map(toHookFinding)
|
|
161
|
+
.filter((finding) => (finding.scope === "file" || finding.scope === "project") && !baseIdentities.has(finding.stableIdentity) && !alreadyIncluded.has(finding.fingerprint));
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// Counts the file/project findings the hook drops under changed-region attribution, excluding any
|
|
165
|
+
// re-emitted as new, so the stable suppressed.count contract is never double-counted.
|
|
166
|
+
function hookSuppressedCount(scopedReport: AnalysisReport, emittedFindings: HookFinding[], hasChangedRegion: boolean): number {
|
|
167
|
+
if (!hasChangedRegion) {
|
|
168
|
+
return 0;
|
|
169
|
+
}
|
|
170
|
+
const emittedFingerprints = new Set(emittedFindings.map((finding) => finding.fingerprint));
|
|
171
|
+
const fileOrProjectAnchorResiduals = scopedReport.findings.filter((finding) => {
|
|
172
|
+
const scope = scopeForFinding(finding);
|
|
173
|
+
return (scope === "file" || scope === "project") && !emittedFingerprints.has(finding.fingerprint);
|
|
174
|
+
}).length;
|
|
175
|
+
return (scopedReport.suppressedCount ?? 0) + fileOrProjectAnchorResiduals;
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// Projects an analyser Finding into the hook shape, attaching scope, remediation, and the stable
|
|
179
|
+
// identity plus fingerprint.
|
|
180
|
+
function toHookFinding(finding: Finding): HookFinding {
|
|
181
|
+
const scope = scopeForFinding(finding);
|
|
182
|
+
return {
|
|
183
|
+
ruleId: finding.ruleId,
|
|
184
|
+
pillar: finding.pillar,
|
|
185
|
+
severity: finding.severity,
|
|
186
|
+
scope,
|
|
187
|
+
file: finding.filePath,
|
|
188
|
+
...(finding.line === undefined ? {} : { line: finding.line }),
|
|
189
|
+
...(finding.endLine === undefined ? {} : { endLine: finding.endLine }),
|
|
190
|
+
symbol: finding.symbol ?? null,
|
|
191
|
+
message: finding.message,
|
|
192
|
+
remediation: finding.remediation ?? DESCRIPTORS.get(finding.ruleId)?.remediation ?? "Review and address this finding.",
|
|
193
|
+
metadata: hookMetadata(finding),
|
|
194
|
+
stableIdentity: hookStableIdentity(finding, scope),
|
|
195
|
+
fingerprint: finding.fingerprint,
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
// Classifies a finding as line/symbol/file/project scope; this choice drives changed-region
|
|
200
|
+
// attribution and the stable hook identity.
|
|
201
|
+
function scopeForFinding(finding: Finding): HookScope {
|
|
202
|
+
if (PROJECT_SCOPE_RULE_IDS.has(finding.ruleId)) {
|
|
203
|
+
return "project";
|
|
204
|
+
}
|
|
205
|
+
if (FILE_SCOPE_RULE_IDS.has(finding.ruleId)) {
|
|
206
|
+
return "file";
|
|
207
|
+
}
|
|
208
|
+
if (finding.symbol || (finding.endLine !== undefined && finding.line !== undefined && finding.endLine > finding.line)) {
|
|
209
|
+
return "symbol";
|
|
210
|
+
}
|
|
211
|
+
return "line";
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
// Returns normalized threshold metadata when the rule has one, else the finding's own metadata,
|
|
215
|
+
// keeping the contract's metadata shape stable.
|
|
216
|
+
function hookMetadata(finding: Finding): Record<string, unknown> {
|
|
217
|
+
const thresholdMetadata = thresholdMetadataFor(finding);
|
|
218
|
+
return thresholdMetadata ?? finding.metadata;
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
// Maps known threshold rules to a measured/threshold/unit triple so the hook exposes a stable,
|
|
222
|
+
// machine-readable measurement contract.
|
|
223
|
+
function thresholdMetadataFor(finding: Finding): Record<string, unknown> | undefined {
|
|
224
|
+
const metadata = finding.metadata;
|
|
225
|
+
switch (finding.ruleId) {
|
|
226
|
+
case "complexity.cognitive":
|
|
227
|
+
case "complexity.cyclomatic":
|
|
228
|
+
return metricMetadata(metadata.complexity, metadata.threshold, "points");
|
|
229
|
+
case "design.deep-relative-import":
|
|
230
|
+
return metricMetadata(metadata.parentSegments, metadata.maxParentSegments, "segments");
|
|
231
|
+
case "design.large-module-concentration":
|
|
232
|
+
return metricMetadata(metadata.sharePercent, metadata.maxSharePercent, "percent");
|
|
233
|
+
case "sensitive-data.hardcoded-env-value":
|
|
234
|
+
case "sensitive-data.high-entropy-string":
|
|
235
|
+
return metricMetadata(metadata.length, metadata.threshold, "characters");
|
|
236
|
+
case "size.file-length":
|
|
237
|
+
case "size.function-length":
|
|
238
|
+
return metricMetadata(metadata.lines, metadata.threshold, "lines");
|
|
239
|
+
case "size.parameter-count":
|
|
240
|
+
return metricMetadata(metadata.parameters, metadata.threshold, "parameters");
|
|
241
|
+
}
|
|
242
|
+
return undefined;
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
// Builds the normalized measurement object, or undefined when the measured/threshold pair is not
|
|
246
|
+
// numeric.
|
|
247
|
+
function metricMetadata(measured: unknown, threshold: unknown, unit: string): Record<string, unknown> | undefined {
|
|
248
|
+
return typeof measured === "number" && typeof threshold === "number"
|
|
249
|
+
? { measured, threshold, unit, direction: "above" }
|
|
250
|
+
: undefined;
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
// Hashes (ruleId, filePath, scope component) into the 16-hex hook identity; line-insensitive so it
|
|
254
|
+
// stays the stable cross-edit key for new-only filtering.
|
|
255
|
+
function hookStableIdentity(finding: Finding, scope: HookScope): string {
|
|
256
|
+
const component = stableIdentityComponent(finding, scope);
|
|
257
|
+
return createHash("sha256")
|
|
258
|
+
.update([finding.ruleId, finding.filePath, component].join("\0"))
|
|
259
|
+
.digest("hex")
|
|
260
|
+
.slice(0, 16);
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// Derives the per-occurrence component of the stable hook identity: scope token, symbol, or message.
|
|
264
|
+
function stableIdentityComponent(finding: { message: string; ruleId: string; symbol?: string }, scope: HookScope): string {
|
|
265
|
+
if (scope === "file") {
|
|
266
|
+
return scope;
|
|
267
|
+
}
|
|
268
|
+
if (scope === "project") {
|
|
269
|
+
// Project rules are value-insensitive on their measurement, but component-level findings still
|
|
270
|
+
// need a stable occurrence key. design.circular-import carries the canonical sorted SCC member
|
|
271
|
+
// list in `symbol`; folding it in keeps independent components distinct without line sensitivity.
|
|
272
|
+
return finding.symbol && finding.symbol.length > 0 ? `project:${finding.symbol}` : scope;
|
|
273
|
+
}
|
|
274
|
+
if (finding.symbol && finding.symbol.length > 0) {
|
|
275
|
+
return `symbol:${finding.symbol}`;
|
|
276
|
+
}
|
|
277
|
+
// Symbol-less line findings (e.g. each hardcoded secret) key on the message so several same-rule
|
|
278
|
+
// findings in one file get distinct identities. A value-insensitive `metric:${scope}` token
|
|
279
|
+
// collapsed them all, letting one baselined finding suppress later new ones in the same file. The
|
|
280
|
+
// message carries the per-occurrence discriminator (redacted preview) and no line number, so it
|
|
281
|
+
// stays stable across surrounding edits. file scope above stays fully value-insensitive; project
|
|
282
|
+
// scope folds in a canonical symbol when one is present.
|
|
283
|
+
return `message:${finding.message}`;
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
// Builds the base identity set (from a baseline file and/or a diff base) that new-only filtering
|
|
287
|
+
// compares against by stable hook identity; undefined when neither source is requested.
|
|
288
|
+
function hookBaseIdentities(runAnalyse: HookAnalysisRunner, input: HookReportInput, currentReport: AnalysisReport): Set<string> | undefined {
|
|
289
|
+
const identities = new Set<string>();
|
|
290
|
+
if (input.baselinePath) {
|
|
291
|
+
for (const identity of stableIdentitiesFromBaseline(input.baselinePath)) {
|
|
292
|
+
identities.add(identity);
|
|
293
|
+
}
|
|
294
|
+
}
|
|
295
|
+
if (input.diffBase) {
|
|
296
|
+
for (const identity of stableIdentitiesFromDiffBase(runAnalyse, input.currentOptions, input.diffBase, currentReport)) {
|
|
297
|
+
identities.add(identity);
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
return identities.size > 0 || input.baselinePath || input.diffBase ? identities : undefined;
|
|
301
|
+
}
|
|
302
|
+
|
|
303
|
+
// Reads stable identities from a gruff.baseline.v1 file; the schema is the gruff.baseline.v1
|
|
304
|
+
// contract and the reader throws on any schemaVersion mismatch.
|
|
305
|
+
function stableIdentitiesFromBaseline(path: string): Set<string> {
|
|
306
|
+
const baselinePath = absolutize(cwd(), path);
|
|
307
|
+
const baseline = JSON.parse(readFileSync(baselinePath, "utf8")) as { schemaVersion?: string; entries?: BaselineEntry[] };
|
|
308
|
+
if (baseline.schemaVersion !== "gruff.baseline.v1") {
|
|
309
|
+
throw new Error(`unsupported baseline schema in ${path}`);
|
|
310
|
+
}
|
|
311
|
+
return new Set((baseline.entries ?? []).flatMap(stableIdentityFromBaselineEntry));
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
// Resolves one baseline entry to hook identities: its stored identity, or a recomputed one from
|
|
315
|
+
// ruleId, filePath, and scope.
|
|
316
|
+
function stableIdentityFromBaselineEntry(entry: BaselineEntry): string[] {
|
|
317
|
+
if (typeof entry.stableIdentity === "string") {
|
|
318
|
+
return [entry.stableIdentity];
|
|
319
|
+
}
|
|
320
|
+
if (typeof entry.ruleId !== "string" || typeof entry.filePath !== "string") {
|
|
321
|
+
return [];
|
|
322
|
+
}
|
|
323
|
+
const scope = baselineScopeForRule(entry.ruleId);
|
|
324
|
+
const component = stableIdentityComponent({
|
|
325
|
+
ruleId: entry.ruleId,
|
|
326
|
+
message: entry.message ?? "",
|
|
327
|
+
...(typeof entry.symbol === "string" ? { symbol: entry.symbol } : {}),
|
|
328
|
+
}, scope);
|
|
329
|
+
return [
|
|
330
|
+
createHash("sha256")
|
|
331
|
+
.update([entry.ruleId, entry.filePath, component].join("\0"))
|
|
332
|
+
.digest("hex")
|
|
333
|
+
.slice(0, 16),
|
|
334
|
+
];
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
// Maps a rule id to its baseline scope so entries without a stored identity recompute the right
|
|
338
|
+
// component.
|
|
339
|
+
function baselineScopeForRule(ruleId: string): HookScope {
|
|
340
|
+
if (PROJECT_SCOPE_RULE_IDS.has(ruleId)) {
|
|
341
|
+
return "project";
|
|
342
|
+
}
|
|
343
|
+
if (FILE_SCOPE_RULE_IDS.has(ruleId)) {
|
|
344
|
+
return "file";
|
|
345
|
+
}
|
|
346
|
+
return "line";
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
function stableIdentitiesFromDiffBase(
|
|
350
|
+
runAnalyse: HookAnalysisRunner,
|
|
351
|
+
options: AnalysisOptions,
|
|
352
|
+
diffBase: string,
|
|
353
|
+
currentReport: AnalysisReport,
|
|
354
|
+
): Set<string> {
|
|
355
|
+
const ref = diffBaseRef(diffBase);
|
|
356
|
+
if (ref === undefined) {
|
|
357
|
+
return new Set();
|
|
358
|
+
}
|
|
359
|
+
const files = [...new Set(currentReport.findings.flatMap(findingBasePaths))];
|
|
360
|
+
if (files.length === 0) {
|
|
361
|
+
return new Set();
|
|
362
|
+
}
|
|
363
|
+
const tempRoot = mkdtempSync(join(tmpdir(), "gruff-ts-hook-base-"));
|
|
364
|
+
const previous = cwd();
|
|
365
|
+
try {
|
|
366
|
+
const baseFiles = materializeBaseFiles(ref, files, tempRoot);
|
|
367
|
+
if (baseFiles.length === 0) {
|
|
368
|
+
return new Set();
|
|
369
|
+
}
|
|
370
|
+
chdir(tempRoot);
|
|
371
|
+
const baseReport = runAnalyse(baseAnalysisOptions(options, baseFiles, previous));
|
|
372
|
+
return new Set(baseReport.findings.map((finding) => hookStableIdentity(finding, scopeForFinding(finding))));
|
|
373
|
+
} finally {
|
|
374
|
+
chdir(previous);
|
|
375
|
+
rmSync(tempRoot, { recursive: true, force: true });
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
|
|
379
|
+
/*
|
|
380
|
+
* A finding's base context is its anchor plus any project-relationship members from
|
|
381
|
+
* `metadata.files`. Contract invariant: without every SCC member at the base ref, the replay
|
|
382
|
+
* cannot reconstruct the cycle identity and a pre-existing cycle would be reported as new.
|
|
383
|
+
*/
|
|
384
|
+
function findingBasePaths(finding: Finding): string[] {
|
|
385
|
+
const memberFiles = finding.metadata.files;
|
|
386
|
+
if (!Array.isArray(memberFiles)) {
|
|
387
|
+
return [finding.filePath];
|
|
388
|
+
}
|
|
389
|
+
return [finding.filePath, ...memberFiles.filter((file): file is string => typeof file === "string")];
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
// Resolves a diff-base selector to the git rev whose blobs are the new-only base. "unstaged" diffs
|
|
393
|
+
// the worktree against the index, so its base is the index ("" rev -> `git show :path`); "-" (stdin
|
|
394
|
+
// patch) has no materializable base. Returns undefined only when no base can be replayed.
|
|
395
|
+
function diffBaseRef(diffBase: string): string | undefined {
|
|
396
|
+
if (diffBase === "-") {
|
|
397
|
+
return undefined;
|
|
398
|
+
}
|
|
399
|
+
if (diffBase === "unstaged") {
|
|
400
|
+
return "";
|
|
401
|
+
}
|
|
402
|
+
return diffBase === "working-tree" || diffBase === "staged" ? "HEAD" : diffBase;
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
// Writes each file's blob at the base ref into the temp dir via git; a blob missing at the ref is a
|
|
406
|
+
// recover path so that file's findings count as new (filesystem writes).
|
|
407
|
+
function materializeBaseFiles(ref: string, files: string[], root: string): string[] {
|
|
408
|
+
const materialized: string[] = [];
|
|
409
|
+
for (const file of files) {
|
|
410
|
+
try {
|
|
411
|
+
const source = execFileSync("git", ["show", `${ref}:${file}`], { encoding: "utf8" });
|
|
412
|
+
const target = join(root, file);
|
|
413
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
414
|
+
writeFileSync(target, source);
|
|
415
|
+
materialized.push(file);
|
|
416
|
+
} catch {
|
|
417
|
+
// File is missing at the base ref, so every current finding in it is new.
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
return materialized;
|
|
421
|
+
}
|
|
422
|
+
|
|
423
|
+
// Builds the analysis options for the base-ref scan: drops changed-region flags and resolves the
|
|
424
|
+
// config path against the original root.
|
|
425
|
+
function baseAnalysisOptions(options: AnalysisOptions, paths: string[], originalRoot: string): AnalysisOptions {
|
|
426
|
+
return {
|
|
427
|
+
...withoutChangedRegion(options),
|
|
428
|
+
paths,
|
|
429
|
+
...(options.config ? { config: absolutize(originalRoot, options.config) } : defaultConfigPathOption(originalRoot, options)),
|
|
430
|
+
};
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
// Falls back to the project's default .gruff-ts.yaml for the base scan when one exists and config is
|
|
434
|
+
// not skipped.
|
|
435
|
+
function defaultConfigPathOption(originalRoot: string, options: AnalysisOptions): Partial<Pick<AnalysisOptions, "config">> {
|
|
436
|
+
const defaultConfigPath = join(originalRoot, ".gruff-ts.yaml");
|
|
437
|
+
return !options.shouldSkipConfig && existsSync(defaultConfigPath) ? { config: defaultConfigPath } : {};
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
// Strips every changed-region and baseline flag so the base-ref scan runs as a plain full scan,
|
|
441
|
+
// deterministic regardless of the original changed-region request.
|
|
442
|
+
function withoutChangedRegion(options: AnalysisOptions): AnalysisOptions {
|
|
443
|
+
const { baseline: _baseline, changedRanges: _changedRanges, diff: _diff, diffPatch: _diffPatch, generateBaseline: _generateBaseline, since: _since, ...rest } = options;
|
|
444
|
+
return { ...rest, shouldSkipBaseline: true };
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
// Orders findings by severity, then file, line, and rule id, giving the contract a deterministic,
|
|
448
|
+
// stable finding order.
|
|
449
|
+
function sortHookFindings(findings: HookFinding[]): HookFinding[] {
|
|
450
|
+
return [...findings].sort(
|
|
451
|
+
(left, right) =>
|
|
452
|
+
SEVERITY_RANK[left.severity] - SEVERITY_RANK[right.severity] ||
|
|
453
|
+
left.file.localeCompare(right.file) ||
|
|
454
|
+
(left.line ?? 0) - (right.line ?? 0) ||
|
|
455
|
+
left.ruleId.localeCompare(right.ruleId),
|
|
456
|
+
);
|
|
457
|
+
}
|
package/src/line-rules.ts
CHANGED
|
@@ -4,11 +4,12 @@
|
|
|
4
4
|
// detection and the block-rule parameter pass. Dead-code rules (unused imports, unreachable) are
|
|
5
5
|
// invoked by the cli orchestrator before/after this module so the stable per-line emission order
|
|
6
6
|
// stays a single contract.
|
|
7
|
-
import { ruleSeverity } from "./config.ts";
|
|
7
|
+
import { ruleEnabled, ruleSeverity } from "./config.ts";
|
|
8
8
|
import { type SourceFile } from "./discovery.ts";
|
|
9
9
|
import { makeFinding } from "./findings.ts";
|
|
10
10
|
import { escapeRegex, finding, isCommentedOutCode } from "./findings-helpers.ts";
|
|
11
11
|
import { type NamingSurface, pushBooleanPrefixAt, pushIdentifierQualityAt, pushNegativeBooleanAt, pushShortVariableAt } from "./naming-pushers.ts";
|
|
12
|
+
import { processExecMetadata } from "./process-exec-metadata.ts";
|
|
12
13
|
import { analyseReliabilityLine, analyseSwallowedCatches, analyseTypeSafetyLine, analyseUselessCatches } from "./safety-rules.ts";
|
|
13
14
|
import { analyseSecurityFlowLine } from "./security-flow-rules.ts";
|
|
14
15
|
import { codeLineForMatching } from "./source-text.ts";
|
|
@@ -44,12 +45,61 @@ interface LineRuleContext {
|
|
|
44
45
|
codeChecks: LineRuleCheck[];
|
|
45
46
|
literalChecks: LineRuleCheck[];
|
|
46
47
|
variables: RegExp;
|
|
48
|
+
gates: LineRuleGates;
|
|
47
49
|
}
|
|
48
50
|
|
|
49
51
|
const CODE_LINE_CHECKS = codeLineChecks();
|
|
50
52
|
const LITERAL_LINE_CHECKS = literalLineChecks();
|
|
51
53
|
const VARIABLE_DECLARATIONS = /\b(?:const|let|for\s*\(\s*const|for\s*\(\s*let)\s+([A-Za-z_$][A-Za-z0-9_$]*)/g;
|
|
52
54
|
|
|
55
|
+
// Per-file rule-family switches. They avoid re-running helpers when every rule they emit is disabled.
|
|
56
|
+
interface LineRuleGates {
|
|
57
|
+
shouldRunTypeSafety: boolean;
|
|
58
|
+
shouldRunReliability: boolean;
|
|
59
|
+
shouldRunCommentedOutCode: boolean;
|
|
60
|
+
shouldRunBooleanNaming: boolean;
|
|
61
|
+
shouldRunHungarianNotation: boolean;
|
|
62
|
+
shouldRunOptionalChaining: boolean;
|
|
63
|
+
shouldRunNullishCoalescing: boolean;
|
|
64
|
+
shouldRunLooseEquality: boolean;
|
|
65
|
+
shouldRunStringTimer: boolean;
|
|
66
|
+
shouldRunSecurityFlow: boolean;
|
|
67
|
+
shouldRunVariableNaming: boolean;
|
|
68
|
+
shouldRunProcessExec: boolean;
|
|
69
|
+
shouldRunUselessCatch: boolean;
|
|
70
|
+
shouldRunSwallowedCatch: boolean;
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const TYPE_SAFETY_RULE_IDS = [
|
|
74
|
+
"modernisation.double-cast",
|
|
75
|
+
"modernisation.non-null-assertion",
|
|
76
|
+
"modernisation.ts-comment-without-rationale",
|
|
77
|
+
"waste.exported-any",
|
|
78
|
+
] as const;
|
|
79
|
+
|
|
80
|
+
const RELIABILITY_RULE_IDS = [
|
|
81
|
+
"security.async-foreach",
|
|
82
|
+
"security.floating-promise",
|
|
83
|
+
"security.throw-non-error",
|
|
84
|
+
] as const;
|
|
85
|
+
|
|
86
|
+
const BOOLEAN_NAMING_RULE_IDS = [
|
|
87
|
+
"naming.boolean-prefix",
|
|
88
|
+
"naming.negative-boolean",
|
|
89
|
+
] as const;
|
|
90
|
+
|
|
91
|
+
const SECURITY_FLOW_LINE_RULE_IDS = [
|
|
92
|
+
"security.dynamic-regexp",
|
|
93
|
+
"security.open-redirect-candidate",
|
|
94
|
+
"security.path-traversal-candidate",
|
|
95
|
+
"security.ssrf-candidate",
|
|
96
|
+
] as const;
|
|
97
|
+
|
|
98
|
+
const VARIABLE_NAMING_RULE_IDS = [
|
|
99
|
+
"naming.identifier-quality",
|
|
100
|
+
"naming.short-variable",
|
|
101
|
+
] as const;
|
|
102
|
+
|
|
53
103
|
/*
|
|
54
104
|
* Per-line rule pipeline plus the two multi-line catch detectors. Excludes analyseUnusedImports
|
|
55
105
|
* and analyseUnreachable so the dead-code module can own them; the orchestrator in cli.ts wraps
|
|
@@ -58,6 +108,22 @@ const VARIABLE_DECLARATIONS = /\b(?:const|let|for\s*\(\s*const|for\s*\(\s*let)\s
|
|
|
58
108
|
export function analyseLineRules(file: SourceFile, source: string, codeSource: string, config: Config, findings: Finding[]): void {
|
|
59
109
|
const sourceLines = source.split(/\r?\n/);
|
|
60
110
|
const codeLines = codeSource.split(/\r?\n/);
|
|
111
|
+
const gates: LineRuleGates = {
|
|
112
|
+
shouldRunTypeSafety: TYPE_SAFETY_RULE_IDS.some((ruleId) => ruleEnabled(config, ruleId)),
|
|
113
|
+
shouldRunReliability: RELIABILITY_RULE_IDS.some((ruleId) => ruleEnabled(config, ruleId)),
|
|
114
|
+
shouldRunCommentedOutCode: ruleEnabled(config, "waste.commented-out-code"),
|
|
115
|
+
shouldRunBooleanNaming: BOOLEAN_NAMING_RULE_IDS.some((ruleId) => ruleEnabled(config, ruleId)),
|
|
116
|
+
shouldRunHungarianNotation: ruleEnabled(config, "naming.hungarian-notation"),
|
|
117
|
+
shouldRunOptionalChaining: ruleEnabled(config, "modernisation.optional-chaining-candidate"),
|
|
118
|
+
shouldRunNullishCoalescing: ruleEnabled(config, "modernisation.nullish-coalescing-candidate"),
|
|
119
|
+
shouldRunLooseEquality: ruleEnabled(config, "modernisation.loose-equality"),
|
|
120
|
+
shouldRunStringTimer: ruleEnabled(config, "security.string-timer"),
|
|
121
|
+
shouldRunSecurityFlow: SECURITY_FLOW_LINE_RULE_IDS.some((ruleId) => ruleEnabled(config, ruleId)),
|
|
122
|
+
shouldRunVariableNaming: VARIABLE_NAMING_RULE_IDS.some((ruleId) => ruleEnabled(config, ruleId)),
|
|
123
|
+
shouldRunProcessExec: ruleEnabled(config, "security.process-exec"),
|
|
124
|
+
shouldRunUselessCatch: ruleEnabled(config, "waste.useless-catch"),
|
|
125
|
+
shouldRunSwallowedCatch: ruleEnabled(config, "waste.swallowed-catch"),
|
|
126
|
+
};
|
|
61
127
|
const context: LineRuleContext = {
|
|
62
128
|
file,
|
|
63
129
|
line: "",
|
|
@@ -66,9 +132,10 @@ export function analyseLineRules(file: SourceFile, source: string, codeSource: s
|
|
|
66
132
|
lineNumber: 0,
|
|
67
133
|
config,
|
|
68
134
|
findings,
|
|
69
|
-
codeChecks: CODE_LINE_CHECKS,
|
|
70
|
-
literalChecks: LITERAL_LINE_CHECKS,
|
|
135
|
+
codeChecks: CODE_LINE_CHECKS.filter((check) => ruleEnabled(config, check.ruleId)),
|
|
136
|
+
literalChecks: LITERAL_LINE_CHECKS.filter((check) => ruleEnabled(config, check.ruleId)),
|
|
71
137
|
variables: VARIABLE_DECLARATIONS,
|
|
138
|
+
gates,
|
|
72
139
|
};
|
|
73
140
|
sourceLines.forEach((line, index) => {
|
|
74
141
|
context.line = line;
|
|
@@ -78,26 +145,54 @@ export function analyseLineRules(file: SourceFile, source: string, codeSource: s
|
|
|
78
145
|
analyseLineRuleContext(context);
|
|
79
146
|
});
|
|
80
147
|
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
148
|
+
if (gates.shouldRunProcessExec) {
|
|
149
|
+
analyseProcessExecCalls(file, source, codeSource, findings);
|
|
150
|
+
}
|
|
151
|
+
if (gates.shouldRunUselessCatch) {
|
|
152
|
+
analyseUselessCatches(file, codeSource, findings);
|
|
153
|
+
}
|
|
154
|
+
if (gates.shouldRunSwallowedCatch) {
|
|
155
|
+
analyseSwallowedCatches(file, source, codeSource, findings);
|
|
156
|
+
}
|
|
84
157
|
}
|
|
85
158
|
|
|
86
159
|
// All per-line checks for a single line in their stable, deterministic emission order. Each helper
|
|
87
160
|
// either no-ops (rule skipped or no match) or appends to `findings`.
|
|
88
161
|
function analyseLineRuleContext(context: LineRuleContext): void {
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
162
|
+
if (context.gates.shouldRunTypeSafety) {
|
|
163
|
+
analyseTypeSafetyLine(context.file, context.line, context.codeLine, context.lineNumber, context.findings);
|
|
164
|
+
}
|
|
165
|
+
if (context.gates.shouldRunReliability) {
|
|
166
|
+
analyseReliabilityLine(context.file, context.codeLine, context.lineNumber, context.findings);
|
|
167
|
+
}
|
|
168
|
+
if (context.gates.shouldRunCommentedOutCode) {
|
|
169
|
+
pushCommentedOutCodeFinding(context);
|
|
170
|
+
}
|
|
171
|
+
if (context.gates.shouldRunBooleanNaming) {
|
|
172
|
+
pushBooleanPrefixFinding(context);
|
|
173
|
+
}
|
|
174
|
+
if (context.gates.shouldRunHungarianNotation) {
|
|
175
|
+
pushHungarianNotationFindings(context);
|
|
176
|
+
}
|
|
177
|
+
if (context.gates.shouldRunOptionalChaining) {
|
|
178
|
+
pushOptionalChainingFindings(context);
|
|
179
|
+
}
|
|
180
|
+
if (context.gates.shouldRunNullishCoalescing) {
|
|
181
|
+
pushNullishCoalescingFindings(context);
|
|
182
|
+
}
|
|
183
|
+
if (context.gates.shouldRunLooseEquality) {
|
|
184
|
+
pushLooseEqualityFinding(context);
|
|
185
|
+
}
|
|
186
|
+
if (context.gates.shouldRunStringTimer) {
|
|
187
|
+
pushStringTimerFinding(context);
|
|
188
|
+
}
|
|
189
|
+
if (context.gates.shouldRunSecurityFlow) {
|
|
190
|
+
analyseSecurityFlowLine(context.file, context.codeLine, context.lineNumber, context.findings);
|
|
191
|
+
}
|
|
99
192
|
pushPatternCheckFindings(context);
|
|
100
|
-
|
|
193
|
+
if (context.gates.shouldRunVariableNaming) {
|
|
194
|
+
pushVariableNameFindings(context);
|
|
195
|
+
}
|
|
101
196
|
}
|
|
102
197
|
|
|
103
198
|
// Code-shape rules: those that must match against the masked code (no comment or literal noise).
|
|
@@ -123,7 +218,7 @@ function literalLineChecks(): LineRuleCheck[] {
|
|
|
123
218
|
{ ruleId: "security.disabled-tls-verification", pattern: /\b(?:process\.env\.)?NODE_TLS_REJECT_UNAUTHORIZED\b\s*=\s*["']0["']|\brejectUnauthorized\s*:\s*false\b/i, message: "TLS certificate verification is disabled.", severity: "error", pillar: "security" },
|
|
124
219
|
{ ruleId: "security.javascript-url", pattern: /["'`]\s*javascript\s*:(?!\s+URL\b)/i, message: "javascript: URL literal can execute script.", severity: "error", pillar: "security" },
|
|
125
220
|
{ ruleId: "security.proto-access", pattern: /\[\s*["']__proto__["']\s*\]/, message: "Direct __proto__ access can enable prototype pollution.", severity: "warning", pillar: "security" },
|
|
126
|
-
{ ruleId: "security.sql-concatenation", pattern: /\b(?:query|execute|raw)\s*\(\s*(?:`[^`]*(?:SELECT|INSERT|UPDATE|DELETE)[^`]*\$\{|["'][^"']*(?:SELECT|INSERT|UPDATE|DELETE)[^"']*["']\s*\+)/i, message: "SQL text is composed with runtime string interpolation.", severity: "warning", pillar: "security" },
|
|
221
|
+
{ ruleId: "security.sql-concatenation", pattern: /\b(?:query|execute|raw|prepare)\s*\(\s*(?:`[^`]*(?:SELECT|INSERT|UPDATE|DELETE)[^`]*\$\{|["'][^"']*(?:SELECT|INSERT|UPDATE|DELETE)[^"']*["']\s*\+)/i, message: "SQL text is composed with runtime string interpolation.", severity: "warning", pillar: "security" },
|
|
127
222
|
{ ruleId: "modernisation.date-now-candidate", pattern: /\bnew\s+Date\s*\(\s*\)\s*\.getTime\s*\(\s*\)|\bNumber\s*\(\s*new\s+Date\s*\(\s*\)\s*\)/, message: "Current-time expression can use Date.now().", severity: "advisory", pillar: "modernisation" },
|
|
128
223
|
{ ruleId: "modernisation.object-spread-candidate", pattern: /\bObject\.assign\s*\(\s*\{\s*\}\s*,/, message: "Object.assign clone can usually use object spread.", severity: "advisory", pillar: "modernisation" },
|
|
129
224
|
{ ruleId: "waste.console-log", pattern: /\bconsole\.(log|debug)\s*\(/, message: "console logging is committed in source.", severity: "advisory", pillar: "maintainability" },
|
|
@@ -476,7 +571,19 @@ function analyseProcessExecCalls(file: SourceFile, rawSource: string, codeSource
|
|
|
476
571
|
if (isSafeProcessExecCall(file, callName, rawSource, start, rawSegment, codeSegment)) {
|
|
477
572
|
continue;
|
|
478
573
|
}
|
|
479
|
-
findings.push(
|
|
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
|
+
);
|
|
480
587
|
}
|
|
481
588
|
}
|
|
482
589
|
|