@blundergoat/gruff-ts 0.3.1 → 0.3.2
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 +6 -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/rules.md +4 -3
- package/package.json +17 -2
- package/src/analyser.ts +13 -1
- package/src/blocks.ts +56 -9
- package/src/changed-regions.ts +25 -17
- package/src/cli-program.ts +99 -3
- package/src/constants.ts +1 -1
- package/src/dashboard.ts +1 -1
- package/src/findings.ts +2 -0
- package/src/hook-contract.ts +435 -0
- package/src/rule-list.ts +1 -0
- package/src/sensitive-data-rules.ts +2 -2
- package/src/types.ts +1 -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,435 @@
|
|
|
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 HookAnalysisRunner = (options: AnalysisOptions) => AnalysisReport;
|
|
16
|
+
|
|
17
|
+
// Inputs for one hook render: full-scan options, changed-region options, and optional baseline/diff
|
|
18
|
+
// bases used for new-only filtering.
|
|
19
|
+
interface HookReportInput {
|
|
20
|
+
currentOptions: AnalysisOptions;
|
|
21
|
+
scopedOptions: AnalysisOptions;
|
|
22
|
+
baselinePath?: string;
|
|
23
|
+
diffBase?: string;
|
|
24
|
+
hasChangedRegion: boolean;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// The gruff.hook.v1 envelope written to stdout; field names are the cross-analyzer contract.
|
|
28
|
+
interface HookReport {
|
|
29
|
+
contractVersion: "gruff.hook.v1";
|
|
30
|
+
analyzer: { name: "gruff-ts"; version: string };
|
|
31
|
+
findings: HookFinding[];
|
|
32
|
+
suppressed: { count: number };
|
|
33
|
+
ignored: { paths: SkippedPath[] };
|
|
34
|
+
config: { schemaOk: boolean; error: string | null };
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
// A finding projected into the hook contract, with enum scope and non-null remediation, keyed for
|
|
38
|
+
// new-only tracking by the stable identity and fingerprint.
|
|
39
|
+
interface HookFinding {
|
|
40
|
+
ruleId: string;
|
|
41
|
+
pillar: string;
|
|
42
|
+
severity: Severity;
|
|
43
|
+
scope: HookScope;
|
|
44
|
+
file: string;
|
|
45
|
+
line?: number;
|
|
46
|
+
endLine?: number;
|
|
47
|
+
symbol: string | null;
|
|
48
|
+
message: string;
|
|
49
|
+
remediation: string;
|
|
50
|
+
metadata: Record<string, unknown>;
|
|
51
|
+
stableIdentity: string;
|
|
52
|
+
fingerprint: string;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// A gruff.baseline.v1 entry as read for new-only comparison; every field is optional because older
|
|
56
|
+
// baselines predate stableIdentity.
|
|
57
|
+
interface BaselineEntry {
|
|
58
|
+
stableIdentity?: string;
|
|
59
|
+
ruleId?: string;
|
|
60
|
+
filePath?: string;
|
|
61
|
+
symbol?: string;
|
|
62
|
+
message?: string;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
const HOOK_CONTRACT_VERSION = "gruff.hook.v1";
|
|
66
|
+
const FILE_SCOPE_RULE_IDS = new Set(["design.large-module-concentration", "docs.missing-file-overview", "size.file-length"]);
|
|
67
|
+
const PROJECT_SCOPE_RULE_IDS = new Set(["design.circular-import"]);
|
|
68
|
+
const SEVERITY_RANK: Record<Severity, number> = { error: 0, warning: 1, advisory: 2 };
|
|
69
|
+
const DESCRIPTORS = new Map(ruleDescriptors().map((descriptor) => [descriptor.ruleId, descriptor]));
|
|
70
|
+
|
|
71
|
+
// Emits the gruff.hook.v1 capability handshake so a consumer can resolve flag names before a real
|
|
72
|
+
// request; the advertised supports/flags object is the stable gruff.hook.v1 contract.
|
|
73
|
+
export function renderHookCapabilities(): string {
|
|
74
|
+
return JSON.stringify({
|
|
75
|
+
contractVersion: HOOK_CONTRACT_VERSION,
|
|
76
|
+
analyzer: analyzerInfo(),
|
|
77
|
+
supports: {
|
|
78
|
+
changedRanges: true,
|
|
79
|
+
diff: true,
|
|
80
|
+
baseline: true,
|
|
81
|
+
scopeField: true,
|
|
82
|
+
metadata: true,
|
|
83
|
+
stableIdentity: true,
|
|
84
|
+
ignoreReport: true,
|
|
85
|
+
newOnly: true,
|
|
86
|
+
},
|
|
87
|
+
flags: { changedRanges: "--changed-ranges", diff: "--diff", baseline: "--baseline" },
|
|
88
|
+
flagOrder: "any" satisfies FlagOrder,
|
|
89
|
+
}, null, 2) + "\n";
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
// Runs the analysis (twice when a changed region is requested) and projects it into the gruff.hook.v1
|
|
93
|
+
// envelope: scoped findings, suppressed count, ignored paths, and a schema-ok config block.
|
|
94
|
+
export function renderHookReport(runAnalyse: HookAnalysisRunner, input: HookReportInput): string {
|
|
95
|
+
const currentReport = runAnalyse(input.currentOptions);
|
|
96
|
+
const scopedReport = input.hasChangedRegion ? runAnalyse(input.scopedOptions) : currentReport;
|
|
97
|
+
const baseIdentities = hookBaseIdentities(runAnalyse, input, currentReport);
|
|
98
|
+
const findings = hookFindings(currentReport, scopedReport, input.hasChangedRegion, baseIdentities);
|
|
99
|
+
const suppressedCount = hookSuppressedCount(scopedReport, findings, input.hasChangedRegion);
|
|
100
|
+
return JSON.stringify(hookReport(scopedReport, findings, suppressedCount, true, null), null, 2) + "\n";
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// Emits a gruff.hook.v1 envelope for an operational failure (config rejected, bad baseline, git
|
|
104
|
+
// error) so the consumer always receives JSON with config.error set instead of a crash.
|
|
105
|
+
export function renderHookConfigError(message: string, remediation: string): string {
|
|
106
|
+
const error = `${message}\nSuggested fix: ${remediation}`;
|
|
107
|
+
return JSON.stringify(hookReport(undefined, [], 0, false, error), null, 2) + "\n";
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
// Assembles the gruff.hook.v1 envelope (sorted findings, suppressed count, ignored paths, config)
|
|
111
|
+
// as the stable gruff.hook.v1 output contract.
|
|
112
|
+
function hookReport(report: AnalysisReport | undefined, findings: HookFinding[], suppressedCount: number, isSchemaOk: boolean, error: string | null): HookReport {
|
|
113
|
+
return {
|
|
114
|
+
contractVersion: HOOK_CONTRACT_VERSION,
|
|
115
|
+
analyzer: analyzerInfo(),
|
|
116
|
+
findings: sortHookFindings(findings),
|
|
117
|
+
suppressed: { count: suppressedCount },
|
|
118
|
+
ignored: { paths: report?.paths.skipped ?? [] },
|
|
119
|
+
config: { schemaOk: isSchemaOk, error },
|
|
120
|
+
};
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
// Analyzer identity block shared by the capability and report envelopes.
|
|
124
|
+
function analyzerInfo(): { name: "gruff-ts"; version: string } {
|
|
125
|
+
return { name: "gruff-ts", version: VERSION };
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function hookFindings(
|
|
129
|
+
currentReport: AnalysisReport,
|
|
130
|
+
scopedReport: AnalysisReport,
|
|
131
|
+
hasChangedRegion: boolean,
|
|
132
|
+
baseIdentities: Set<string> | undefined,
|
|
133
|
+
): HookFinding[] {
|
|
134
|
+
const scopedFindings = scopedReport.findings
|
|
135
|
+
.map(toHookFinding)
|
|
136
|
+
.filter((finding) => !hasChangedRegion || (finding.scope !== "file" && finding.scope !== "project"));
|
|
137
|
+
const withNewFileAndProject = hasChangedRegion && baseIdentities
|
|
138
|
+
? [...scopedFindings, ...newFileAndProjectFindings(currentReport, scopedFindings, baseIdentities)]
|
|
139
|
+
: scopedFindings;
|
|
140
|
+
return baseIdentities ? withNewFileAndProject.filter((finding) => !baseIdentities.has(finding.stableIdentity)) : withNewFileAndProject;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// Collects file- and project-scope findings that are new since the base, excluding any already
|
|
144
|
+
// emitted, deduped by fingerprint.
|
|
145
|
+
function newFileAndProjectFindings(currentReport: AnalysisReport, scopedFindings: HookFinding[], baseIdentities: Set<string>): HookFinding[] {
|
|
146
|
+
const alreadyIncluded = new Set(scopedFindings.map((finding) => finding.fingerprint));
|
|
147
|
+
return currentReport.findings
|
|
148
|
+
.map(toHookFinding)
|
|
149
|
+
.filter((finding) => (finding.scope === "file" || finding.scope === "project") && !baseIdentities.has(finding.stableIdentity) && !alreadyIncluded.has(finding.fingerprint));
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// Counts the file/project findings the hook drops under changed-region attribution, excluding any
|
|
153
|
+
// re-emitted as new, so the stable suppressed.count contract is never double-counted.
|
|
154
|
+
function hookSuppressedCount(scopedReport: AnalysisReport, emittedFindings: HookFinding[], hasChangedRegion: boolean): number {
|
|
155
|
+
if (!hasChangedRegion) {
|
|
156
|
+
return 0;
|
|
157
|
+
}
|
|
158
|
+
const emittedFingerprints = new Set(emittedFindings.map((finding) => finding.fingerprint));
|
|
159
|
+
const fileOrProjectAnchorResiduals = scopedReport.findings.filter((finding) => {
|
|
160
|
+
const scope = scopeForFinding(finding);
|
|
161
|
+
return (scope === "file" || scope === "project") && !emittedFingerprints.has(finding.fingerprint);
|
|
162
|
+
}).length;
|
|
163
|
+
return (scopedReport.suppressedCount ?? 0) + fileOrProjectAnchorResiduals;
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
// Projects an analyser Finding into the hook shape, attaching scope, remediation, and the stable
|
|
167
|
+
// identity plus fingerprint.
|
|
168
|
+
function toHookFinding(finding: Finding): HookFinding {
|
|
169
|
+
const scope = scopeForFinding(finding);
|
|
170
|
+
return {
|
|
171
|
+
ruleId: finding.ruleId,
|
|
172
|
+
pillar: finding.pillar,
|
|
173
|
+
severity: finding.severity,
|
|
174
|
+
scope,
|
|
175
|
+
file: finding.filePath,
|
|
176
|
+
...(finding.line === undefined ? {} : { line: finding.line }),
|
|
177
|
+
...(finding.endLine === undefined ? {} : { endLine: finding.endLine }),
|
|
178
|
+
symbol: finding.symbol ?? null,
|
|
179
|
+
message: finding.message,
|
|
180
|
+
remediation: finding.remediation ?? DESCRIPTORS.get(finding.ruleId)?.remediation ?? "Review and address this finding.",
|
|
181
|
+
metadata: hookMetadata(finding),
|
|
182
|
+
stableIdentity: hookStableIdentity(finding, scope),
|
|
183
|
+
fingerprint: finding.fingerprint,
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// Classifies a finding as line/symbol/file/project scope; this choice drives changed-region
|
|
188
|
+
// attribution and the stable hook identity.
|
|
189
|
+
function scopeForFinding(finding: Finding): HookScope {
|
|
190
|
+
if (PROJECT_SCOPE_RULE_IDS.has(finding.ruleId)) {
|
|
191
|
+
return "project";
|
|
192
|
+
}
|
|
193
|
+
if (FILE_SCOPE_RULE_IDS.has(finding.ruleId)) {
|
|
194
|
+
return "file";
|
|
195
|
+
}
|
|
196
|
+
if (finding.symbol || (finding.endLine !== undefined && finding.line !== undefined && finding.endLine > finding.line)) {
|
|
197
|
+
return "symbol";
|
|
198
|
+
}
|
|
199
|
+
return "line";
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// Returns normalized threshold metadata when the rule has one, else the finding's own metadata,
|
|
203
|
+
// keeping the contract's metadata shape stable.
|
|
204
|
+
function hookMetadata(finding: Finding): Record<string, unknown> {
|
|
205
|
+
const thresholdMetadata = thresholdMetadataFor(finding);
|
|
206
|
+
return thresholdMetadata ?? finding.metadata;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
// Maps known threshold rules to a measured/threshold/unit triple so the hook exposes a stable,
|
|
210
|
+
// machine-readable measurement contract.
|
|
211
|
+
function thresholdMetadataFor(finding: Finding): Record<string, unknown> | undefined {
|
|
212
|
+
const metadata = finding.metadata;
|
|
213
|
+
switch (finding.ruleId) {
|
|
214
|
+
case "complexity.cognitive":
|
|
215
|
+
case "complexity.cyclomatic":
|
|
216
|
+
return metricMetadata(metadata.complexity, metadata.threshold, "points");
|
|
217
|
+
case "design.deep-relative-import":
|
|
218
|
+
return metricMetadata(metadata.parentSegments, metadata.maxParentSegments, "segments");
|
|
219
|
+
case "design.large-module-concentration":
|
|
220
|
+
return metricMetadata(metadata.sharePercent, metadata.maxSharePercent, "percent");
|
|
221
|
+
case "sensitive-data.hardcoded-env-value":
|
|
222
|
+
case "sensitive-data.high-entropy-string":
|
|
223
|
+
return metricMetadata(metadata.length, metadata.threshold, "characters");
|
|
224
|
+
case "size.file-length":
|
|
225
|
+
case "size.function-length":
|
|
226
|
+
return metricMetadata(metadata.lines, metadata.threshold, "lines");
|
|
227
|
+
case "size.parameter-count":
|
|
228
|
+
return metricMetadata(metadata.parameters, metadata.threshold, "parameters");
|
|
229
|
+
}
|
|
230
|
+
return undefined;
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
// Builds the normalized measurement object, or undefined when the measured/threshold pair is not
|
|
234
|
+
// numeric.
|
|
235
|
+
function metricMetadata(measured: unknown, threshold: unknown, unit: string): Record<string, unknown> | undefined {
|
|
236
|
+
return typeof measured === "number" && typeof threshold === "number"
|
|
237
|
+
? { measured, threshold, unit, direction: "above" }
|
|
238
|
+
: undefined;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
// Hashes (ruleId, filePath, scope component) into the 16-hex hook identity; line-insensitive so it
|
|
242
|
+
// stays the stable cross-edit key for new-only filtering.
|
|
243
|
+
function hookStableIdentity(finding: Finding, scope: HookScope): string {
|
|
244
|
+
const component = stableIdentityComponent(finding, scope);
|
|
245
|
+
return createHash("sha256")
|
|
246
|
+
.update([finding.ruleId, finding.filePath, component].join("\0"))
|
|
247
|
+
.digest("hex")
|
|
248
|
+
.slice(0, 16);
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
// Derives the per-occurrence component of the stable hook identity: scope token, symbol, or message.
|
|
252
|
+
function stableIdentityComponent(finding: { message: string; ruleId: string; symbol?: string }, scope: HookScope): string {
|
|
253
|
+
if (scope === "file") {
|
|
254
|
+
return scope;
|
|
255
|
+
}
|
|
256
|
+
if (scope === "project") {
|
|
257
|
+
// Project rules are value-insensitive on their measurement, but one file can anchor several
|
|
258
|
+
// distinct project findings: design.circular-import emits one finding per cycle and sorts each
|
|
259
|
+
// cycle to its alphabetically-first member, so `a -> b` and `a -> c` both anchor `a.ts`. The
|
|
260
|
+
// cycle path (carried in `symbol`) is the only discriminator; folding it in keeps distinct
|
|
261
|
+
// cycles distinct so baselining one never suppresses a genuinely new one. A project finding with
|
|
262
|
+
// no symbol falls back to the bare scope token, preserving its value-insensitive identity.
|
|
263
|
+
return finding.symbol && finding.symbol.length > 0 ? `project:${finding.symbol}` : scope;
|
|
264
|
+
}
|
|
265
|
+
if (finding.symbol && finding.symbol.length > 0) {
|
|
266
|
+
return `symbol:${finding.symbol}`;
|
|
267
|
+
}
|
|
268
|
+
// Symbol-less line findings (e.g. each hardcoded secret) key on the message so several same-rule
|
|
269
|
+
// findings in one file get distinct identities. A value-insensitive `metric:${scope}` token
|
|
270
|
+
// collapsed them all, letting one baselined finding suppress later new ones in the same file. The
|
|
271
|
+
// message carries the per-occurrence discriminator (redacted preview) and no line number, so it
|
|
272
|
+
// stays stable across surrounding edits. file scope above stays fully value-insensitive; project
|
|
273
|
+
// scope folds in the cycle symbol when one is present.
|
|
274
|
+
return `message:${finding.message}`;
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
// Builds the base identity set (from a baseline file and/or a diff base) that new-only filtering
|
|
278
|
+
// compares against by stable hook identity; undefined when neither source is requested.
|
|
279
|
+
function hookBaseIdentities(runAnalyse: HookAnalysisRunner, input: HookReportInput, currentReport: AnalysisReport): Set<string> | undefined {
|
|
280
|
+
const identities = new Set<string>();
|
|
281
|
+
if (input.baselinePath) {
|
|
282
|
+
for (const identity of stableIdentitiesFromBaseline(input.baselinePath)) {
|
|
283
|
+
identities.add(identity);
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
if (input.diffBase) {
|
|
287
|
+
for (const identity of stableIdentitiesFromDiffBase(runAnalyse, input.currentOptions, input.diffBase, currentReport)) {
|
|
288
|
+
identities.add(identity);
|
|
289
|
+
}
|
|
290
|
+
}
|
|
291
|
+
return identities.size > 0 || input.baselinePath || input.diffBase ? identities : undefined;
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
// Reads stable identities from a gruff.baseline.v1 file; the schema is the gruff.baseline.v1
|
|
295
|
+
// contract and the reader throws on any schemaVersion mismatch.
|
|
296
|
+
function stableIdentitiesFromBaseline(path: string): Set<string> {
|
|
297
|
+
const baselinePath = absolutize(cwd(), path);
|
|
298
|
+
const baseline = JSON.parse(readFileSync(baselinePath, "utf8")) as { schemaVersion?: string; entries?: BaselineEntry[] };
|
|
299
|
+
if (baseline.schemaVersion !== "gruff.baseline.v1") {
|
|
300
|
+
throw new Error(`unsupported baseline schema in ${path}`);
|
|
301
|
+
}
|
|
302
|
+
return new Set((baseline.entries ?? []).flatMap(stableIdentityFromBaselineEntry));
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
// Resolves one baseline entry to hook identities: its stored identity, or a recomputed one from
|
|
306
|
+
// ruleId, filePath, and scope.
|
|
307
|
+
function stableIdentityFromBaselineEntry(entry: BaselineEntry): string[] {
|
|
308
|
+
if (typeof entry.stableIdentity === "string") {
|
|
309
|
+
return [entry.stableIdentity];
|
|
310
|
+
}
|
|
311
|
+
if (typeof entry.ruleId !== "string" || typeof entry.filePath !== "string") {
|
|
312
|
+
return [];
|
|
313
|
+
}
|
|
314
|
+
const scope = baselineScopeForRule(entry.ruleId);
|
|
315
|
+
const component = stableIdentityComponent({
|
|
316
|
+
ruleId: entry.ruleId,
|
|
317
|
+
message: entry.message ?? "",
|
|
318
|
+
...(typeof entry.symbol === "string" ? { symbol: entry.symbol } : {}),
|
|
319
|
+
}, scope);
|
|
320
|
+
return [
|
|
321
|
+
createHash("sha256")
|
|
322
|
+
.update([entry.ruleId, entry.filePath, component].join("\0"))
|
|
323
|
+
.digest("hex")
|
|
324
|
+
.slice(0, 16),
|
|
325
|
+
];
|
|
326
|
+
}
|
|
327
|
+
|
|
328
|
+
// Maps a rule id to its baseline scope so entries without a stored identity recompute the right
|
|
329
|
+
// component.
|
|
330
|
+
function baselineScopeForRule(ruleId: string): HookScope {
|
|
331
|
+
if (PROJECT_SCOPE_RULE_IDS.has(ruleId)) {
|
|
332
|
+
return "project";
|
|
333
|
+
}
|
|
334
|
+
if (FILE_SCOPE_RULE_IDS.has(ruleId)) {
|
|
335
|
+
return "file";
|
|
336
|
+
}
|
|
337
|
+
return "line";
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
function stableIdentitiesFromDiffBase(
|
|
341
|
+
runAnalyse: HookAnalysisRunner,
|
|
342
|
+
options: AnalysisOptions,
|
|
343
|
+
diffBase: string,
|
|
344
|
+
currentReport: AnalysisReport,
|
|
345
|
+
): Set<string> {
|
|
346
|
+
const ref = diffBaseRef(diffBase);
|
|
347
|
+
if (ref === undefined) {
|
|
348
|
+
return new Set();
|
|
349
|
+
}
|
|
350
|
+
const files = [...new Set(currentReport.findings.map((finding) => finding.filePath))];
|
|
351
|
+
if (files.length === 0) {
|
|
352
|
+
return new Set();
|
|
353
|
+
}
|
|
354
|
+
const tempRoot = mkdtempSync(join(tmpdir(), "gruff-ts-hook-base-"));
|
|
355
|
+
const previous = cwd();
|
|
356
|
+
try {
|
|
357
|
+
const baseFiles = materializeBaseFiles(ref, files, tempRoot);
|
|
358
|
+
if (baseFiles.length === 0) {
|
|
359
|
+
return new Set();
|
|
360
|
+
}
|
|
361
|
+
chdir(tempRoot);
|
|
362
|
+
const baseReport = runAnalyse(baseAnalysisOptions(options, baseFiles, previous));
|
|
363
|
+
return new Set(baseReport.findings.map((finding) => hookStableIdentity(finding, scopeForFinding(finding))));
|
|
364
|
+
} finally {
|
|
365
|
+
chdir(previous);
|
|
366
|
+
rmSync(tempRoot, { recursive: true, force: true });
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
// Resolves a diff-base selector to the git rev whose blobs are the new-only base. "unstaged" diffs
|
|
371
|
+
// the worktree against the index, so its base is the index ("" rev -> `git show :path`); "-" (stdin
|
|
372
|
+
// patch) has no materializable base. Returns undefined only when no base can be replayed.
|
|
373
|
+
function diffBaseRef(diffBase: string): string | undefined {
|
|
374
|
+
if (diffBase === "-") {
|
|
375
|
+
return undefined;
|
|
376
|
+
}
|
|
377
|
+
if (diffBase === "unstaged") {
|
|
378
|
+
return "";
|
|
379
|
+
}
|
|
380
|
+
return diffBase === "working-tree" || diffBase === "staged" ? "HEAD" : diffBase;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
// Writes each file's blob at the base ref into the temp dir via git; a blob missing at the ref is a
|
|
384
|
+
// recover path so that file's findings count as new (filesystem writes).
|
|
385
|
+
function materializeBaseFiles(ref: string, files: string[], root: string): string[] {
|
|
386
|
+
const materialized: string[] = [];
|
|
387
|
+
for (const file of files) {
|
|
388
|
+
try {
|
|
389
|
+
const source = execFileSync("git", ["show", `${ref}:${file}`], { encoding: "utf8" });
|
|
390
|
+
const target = join(root, file);
|
|
391
|
+
mkdirSync(dirname(target), { recursive: true });
|
|
392
|
+
writeFileSync(target, source);
|
|
393
|
+
materialized.push(file);
|
|
394
|
+
} catch {
|
|
395
|
+
// File is missing at the base ref, so every current finding in it is new.
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
return materialized;
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
// Builds the analysis options for the base-ref scan: drops changed-region flags and resolves the
|
|
402
|
+
// config path against the original root.
|
|
403
|
+
function baseAnalysisOptions(options: AnalysisOptions, paths: string[], originalRoot: string): AnalysisOptions {
|
|
404
|
+
return {
|
|
405
|
+
...withoutChangedRegion(options),
|
|
406
|
+
paths,
|
|
407
|
+
...(options.config ? { config: absolutize(originalRoot, options.config) } : defaultConfigPathOption(originalRoot, options)),
|
|
408
|
+
};
|
|
409
|
+
}
|
|
410
|
+
|
|
411
|
+
// Falls back to the project's default .gruff-ts.yaml for the base scan when one exists and config is
|
|
412
|
+
// not skipped.
|
|
413
|
+
function defaultConfigPathOption(originalRoot: string, options: AnalysisOptions): Partial<Pick<AnalysisOptions, "config">> {
|
|
414
|
+
const defaultConfigPath = join(originalRoot, ".gruff-ts.yaml");
|
|
415
|
+
return !options.shouldSkipConfig && existsSync(defaultConfigPath) ? { config: defaultConfigPath } : {};
|
|
416
|
+
}
|
|
417
|
+
|
|
418
|
+
// Strips every changed-region and baseline flag so the base-ref scan runs as a plain full scan,
|
|
419
|
+
// deterministic regardless of the original changed-region request.
|
|
420
|
+
function withoutChangedRegion(options: AnalysisOptions): AnalysisOptions {
|
|
421
|
+
const { baseline: _baseline, changedRanges: _changedRanges, diff: _diff, diffPatch: _diffPatch, generateBaseline: _generateBaseline, since: _since, ...rest } = options;
|
|
422
|
+
return { ...rest, shouldSkipBaseline: true };
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
// Orders findings by severity, then file, line, and rule id, giving the contract a deterministic,
|
|
426
|
+
// stable finding order.
|
|
427
|
+
function sortHookFindings(findings: HookFinding[]): HookFinding[] {
|
|
428
|
+
return [...findings].sort(
|
|
429
|
+
(left, right) =>
|
|
430
|
+
SEVERITY_RANK[left.severity] - SEVERITY_RANK[right.severity] ||
|
|
431
|
+
left.file.localeCompare(right.file) ||
|
|
432
|
+
(left.line ?? 0) - (right.line ?? 0) ||
|
|
433
|
+
left.ruleId.localeCompare(right.ruleId),
|
|
434
|
+
);
|
|
435
|
+
}
|
package/src/rule-list.ts
CHANGED
|
@@ -23,6 +23,7 @@ const CONSOLE_COMMANDS = [
|
|
|
23
23
|
{ name: "completion", description: "Dump the shell completion script" },
|
|
24
24
|
{ name: "dashboard", description: "Serve the local gruff dashboard." },
|
|
25
25
|
{ name: "help", description: "Display help for a command" },
|
|
26
|
+
{ name: "hook", description: "Run the gruff agent-hook contract." },
|
|
26
27
|
{ name: "init", description: "Write the default .gruff-ts.yaml to the current directory." },
|
|
27
28
|
{ name: "list", description: "List commands" },
|
|
28
29
|
{ name: "list-profiles", description: "List the built-in gruff profiles." },
|
|
@@ -140,7 +140,7 @@ function analyseHardcodedEnvironmentValues(file: SensitiveSourceFile, source: st
|
|
|
140
140
|
index + 1,
|
|
141
141
|
envValue.value,
|
|
142
142
|
"medium",
|
|
143
|
-
{ keyName: envValue.keyName, length: envValue.value.length },
|
|
143
|
+
{ keyName: envValue.keyName, length: envValue.value.length, threshold: minLength },
|
|
144
144
|
ruleSeverity(config, "sensitive-data.hardcoded-env-value", "error"),
|
|
145
145
|
);
|
|
146
146
|
}
|
|
@@ -165,7 +165,7 @@ function analyseHighEntropyStrings(file: SensitiveSourceFile, source: string, co
|
|
|
165
165
|
byteLine(source, match.index ?? 0),
|
|
166
166
|
raw,
|
|
167
167
|
"medium",
|
|
168
|
-
{ length: raw.length, detector: "high-entropy-string" },
|
|
168
|
+
{ length: raw.length, detector: "high-entropy-string", threshold: minLength },
|
|
169
169
|
ruleSeverity(config, "sensitive-data.high-entropy-string", "error"),
|
|
170
170
|
);
|
|
171
171
|
}
|
package/src/types.ts
CHANGED
|
@@ -25,7 +25,7 @@ export type OutputFormat = "text" | "json" | "html" | "markdown" | "github" | "h
|
|
|
25
25
|
export type FailThreshold = "none" | "advisory" | "warning" | "error";
|
|
26
26
|
|
|
27
27
|
/** Changed-region filter precision for diff-aware analysis. */
|
|
28
|
-
export type ChangedScopeMode = "symbol" | "hunk";
|
|
28
|
+
export type ChangedScopeMode = "symbol" | "hunk" | "file";
|
|
29
29
|
|
|
30
30
|
/** Public options contract consumed by the analyzer core and CLI. */
|
|
31
31
|
export interface AnalysisOptions {
|
package/docs/releasing.md
DELETED
|
@@ -1,106 +0,0 @@
|
|
|
1
|
-
# Releasing
|
|
2
|
-
|
|
3
|
-
This checklist prepares public `@blundergoat/gruff-ts@0.3.x` patch releases.
|
|
4
|
-
Current release line: `0.3.0`.
|
|
5
|
-
|
|
6
|
-
## Bump The Version
|
|
7
|
-
|
|
8
|
-
`scripts/bump-version.sh <semver>` updates `package.json`,
|
|
9
|
-
`package-lock.json`, and `src/constants.ts` together so the CLI `--version`
|
|
10
|
-
output and the published `@blundergoat/gruff-ts` package version cannot drift
|
|
11
|
-
apart. For a no-op release (e.g. fixes folded into the current dated version),
|
|
12
|
-
the version should already match; use `--check` instead of bumping unless the
|
|
13
|
-
release version changes.
|
|
14
|
-
|
|
15
|
-
```bash
|
|
16
|
-
scripts/bump-version.sh --check
|
|
17
|
-
scripts/bump-version.sh 0.3.1
|
|
18
|
-
scripts/bump-version.sh --check
|
|
19
|
-
```
|
|
20
|
-
|
|
21
|
-
The script edits files in place and does not commit or tag. After running it,
|
|
22
|
-
update `CHANGELOG.md` and run `npm run check`.
|
|
23
|
-
|
|
24
|
-
## Before Publishing
|
|
25
|
-
|
|
26
|
-
- [ ] `scripts/bump-version.sh --check` reports the intended version.
|
|
27
|
-
- [ ] `CHANGELOG.md` has an entry for the new version with today's date.
|
|
28
|
-
- [ ] `README.md`, `CONTRIBUTING.md`, `SECURITY.md`, and docs under `docs/`
|
|
29
|
-
reflect any user-visible changes.
|
|
30
|
-
- [ ] `.goat-flow/tasks/0.3.0/` has no unresolved release blockers beyond
|
|
31
|
-
explicitly accepted `human-verification-pending` milestones.
|
|
32
|
-
- [ ] `LICENSE` is present and `package.json` `license` field matches.
|
|
33
|
-
- [ ] `npm run check` passes.
|
|
34
|
-
- [ ] `scripts/preflight-checks.sh` passes (checks version lockstep, runs
|
|
35
|
-
`npm audit --audit-level=moderate`, `npm run check`, a full `gruff-ts`
|
|
36
|
-
self-scan, and `shellcheck` on `scripts/*.sh` when `shellcheck` is
|
|
37
|
-
installed).
|
|
38
|
-
- [ ] `npm pack --dry-run` shows only publishable runtime, docs, scripts, and
|
|
39
|
-
metadata files.
|
|
40
|
-
- [ ] Local smoke scan succeeds:
|
|
41
|
-
|
|
42
|
-
```bash
|
|
43
|
-
./bin/gruff-ts
|
|
44
|
-
./bin/gruff-ts analyse fixtures/sample.ts --fail-on=none
|
|
45
|
-
./bin/gruff-ts summary fixtures/sample.ts --fail-on=none
|
|
46
|
-
./bin/gruff-ts report fixtures/sample.ts --output /tmp/gruff-ts-report.html
|
|
47
|
-
./bin/gruff-ts list-rules
|
|
48
|
-
```
|
|
49
|
-
|
|
50
|
-
## Package Review
|
|
51
|
-
|
|
52
|
-
Preview `@blundergoat/gruff-ts` package contents:
|
|
53
|
-
|
|
54
|
-
```bash
|
|
55
|
-
npm pack --dry-run
|
|
56
|
-
```
|
|
57
|
-
|
|
58
|
-
The package should include:
|
|
59
|
-
|
|
60
|
-
- `bin/gruff-ts`
|
|
61
|
-
- `src/` (all runtime `.ts` files; `src/**/*.test.ts` files are excluded by
|
|
62
|
-
`.npmignore`)
|
|
63
|
-
- `scripts/` (`bump-version.sh`, `check.sh`, `dependency-install.sh`,
|
|
64
|
-
`dependency-update.sh`, `preflight-checks.sh`, `npm-publish.sh`,
|
|
65
|
-
`start-dev.sh`, `test-performance.sh`)
|
|
66
|
-
- `fixtures/sample.ts`
|
|
67
|
-
- `README.md`
|
|
68
|
-
- `CHANGELOG.md`
|
|
69
|
-
- `CONTRIBUTING.md`
|
|
70
|
-
- `SECURITY.md`
|
|
71
|
-
- `LICENSE`
|
|
72
|
-
- `docs/`
|
|
73
|
-
- `package.json`
|
|
74
|
-
- `tsconfig.json`
|
|
75
|
-
|
|
76
|
-
The package must exclude:
|
|
77
|
-
|
|
78
|
-
- `node_modules/`
|
|
79
|
-
- `coverage/`
|
|
80
|
-
- `.agents/`, `.claude/`, `.codex/`, `.github/`, and `.goat-flow/`
|
|
81
|
-
- `AGENTS.md` and `CLAUDE.md`
|
|
82
|
-
- `.gruff-ts.yaml` (this repo's local config)
|
|
83
|
-
- env and secret files (`.env`, `.env.*` except `.env.example`)
|
|
84
|
-
- local scratchpad or log artifacts
|
|
85
|
-
- `src/**/*.test.ts`
|
|
86
|
-
|
|
87
|
-
## Publish
|
|
88
|
-
|
|
89
|
-
```bash
|
|
90
|
-
bash scripts/npm-publish.sh
|
|
91
|
-
```
|
|
92
|
-
|
|
93
|
-
The script verifies npm auth, checks version lockstep, runs
|
|
94
|
-
`scripts/preflight-checks.sh`, prints an `npm publish --dry-run` summary, and
|
|
95
|
-
prompts before publishing.
|
|
96
|
-
|
|
97
|
-
## After Publishing
|
|
98
|
-
|
|
99
|
-
- [ ] Install `@blundergoat/gruff-ts` in a temporary project.
|
|
100
|
-
- [ ] Run `gruff-ts --help`.
|
|
101
|
-
- [ ] Run `gruff-ts analyse . --fail-on=none`.
|
|
102
|
-
- [ ] Run `gruff-ts summary . --fail-on=none`.
|
|
103
|
-
- [ ] Run `gruff-ts list-rules`.
|
|
104
|
-
- [ ] Verify `README.md` install instructions from a clean checkout.
|
|
105
|
-
- [ ] Tag the release in git (`git tag v0.3.0 && git push --tags`) and create
|
|
106
|
-
or update public release notes from `CHANGELOG.md`.
|
package/fixtures/sample.ts
DELETED
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
export class SampleAnalyzer {
|
|
2
|
-
public name = "demo";
|
|
3
|
-
private secretUrl = "mysql://demo:password123@example.test/app";
|
|
4
|
-
|
|
5
|
-
public process(a: boolean, b: string[], c: string, d: string, e: string, f: string): void {
|
|
6
|
-
if (a) {
|
|
7
|
-
for (const item of b) {
|
|
8
|
-
if (item === c) {
|
|
9
|
-
eval(item);
|
|
10
|
-
}
|
|
11
|
-
}
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
const apiKey = "AKIA1111111111111111";
|
|
15
|
-
console.log(apiKey, this.secretUrl, d, e, f);
|
|
16
|
-
}
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
test("sleeps without assertion", async () => {
|
|
20
|
-
await new Promise((resolve) => setTimeout(resolve, 1));
|
|
21
|
-
});
|