@blundergoat/gruff-ts 0.2.0 → 0.3.1
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 +30 -0
- package/README.md +81 -13
- package/docs/README.md +2 -0
- package/docs/agent-hook.md +80 -0
- package/docs/ci-integration.md +16 -0
- package/docs/configuration.md +21 -5
- package/docs/output-formats.md +10 -0
- package/docs/philosophy.md +21 -0
- package/docs/releasing.md +5 -5
- package/docs/rules.md +26 -18
- package/package.json +5 -5
- package/scripts/bump-version.sh +1 -1
- package/src/analyser.ts +48 -37
- package/src/blocks.ts +23 -70
- package/src/changed-regions.ts +390 -0
- package/src/check-ignore.ts +49 -0
- package/src/class-rules.ts +80 -33
- package/src/cli-program.ts +106 -12
- package/src/comment-rules.ts +5 -1
- package/src/config-parse.ts +458 -0
- package/src/config-preservation.ts +1 -1
- package/src/config.ts +215 -460
- package/src/constants.ts +1 -1
- package/src/context-doc-rules.ts +2 -4
- package/src/dashboard.ts +7 -4
- package/src/discovery.ts +88 -32
- package/src/findings-helpers.ts +41 -5
- package/src/findings.ts +10 -0
- package/src/fixture-purpose-rules.ts +7 -9
- package/src/fixtures/rule-catalogue-security-doctrine.ts +28 -0
- package/src/init-config.ts +3 -0
- package/src/line-rules.ts +7 -5
- package/src/naming-pushers.ts +35 -6
- package/src/profiles.ts +231 -0
- package/src/project-config-rules.ts +5 -5
- package/src/project-rules.ts +6 -117
- package/src/report-html.ts +1 -1
- package/src/report-renderers.ts +98 -7
- package/src/rule-list.ts +23 -2
- package/src/rules.ts +11 -12
- package/src/safety-rules.ts +16 -6
- package/src/scoring.ts +43 -5
- package/src/security-flow-rules.ts +533 -0
- package/src/sensitive-data-rules.ts +138 -2
- package/src/static-analysis-redundant-rules.ts +411 -0
- package/src/test-block-rules.ts +115 -53
- package/src/test-fixtures.ts +50 -9
- package/src/types.ts +79 -2
package/src/test-block-rules.ts
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
// Per-test-block rule pass: assertion quality (no-assertions, trivial, snapshot-only,
|
|
2
2
|
// no-throw-only, exception-type-only, magic-number), mock quality (unused-mock, mock-only-test),
|
|
3
|
-
//
|
|
3
|
+
// global-state-mutation, and structural checks (sleep/loop/conditional/only-skip).
|
|
4
4
|
// Invoked from the analyseBlocks orchestrator when `block.isTest` is true.
|
|
5
|
-
import { blockFinding, blockFindingWithMetadata, type FunctionBlock, hasAssertion
|
|
6
|
-
import { ruleSeverity, threshold } from "./config.ts";
|
|
5
|
+
import { blockFinding, blockFindingWithMetadata, type FunctionBlock, hasAssertion } from "./blocks.ts";
|
|
7
6
|
import { type SourceFile } from "./discovery.ts";
|
|
8
7
|
import { escapeRegex } from "./findings-helpers.ts";
|
|
8
|
+
import { pushStaticAnalysisRedundantTestFindings, type StaticAnalysisSourceContext } from "./static-analysis-redundant-rules.ts";
|
|
9
9
|
import { countMatches } from "./text-scans.ts";
|
|
10
|
-
import type {
|
|
10
|
+
import type { Finding, Severity } from "./types.ts";
|
|
11
11
|
|
|
12
12
|
// Provisional rule output gathered during a test-block walk. Built before the surrounding context
|
|
13
13
|
// (file, line) is known, then promoted into a real Finding by the caller.
|
|
@@ -21,28 +21,31 @@ interface TestBlockCheck {
|
|
|
21
21
|
interface MagicNumberAssertionPattern {
|
|
22
22
|
pattern: RegExp;
|
|
23
23
|
expressionIndex: number;
|
|
24
|
+
matcherIndex?: number;
|
|
24
25
|
valueIndex: number;
|
|
25
26
|
}
|
|
26
27
|
|
|
27
28
|
/*
|
|
28
29
|
* Reached when `block.isTest` is true. Four sub-passes in a stable, deterministic order: assertion
|
|
29
|
-
* quality, mock quality,
|
|
30
|
+
* quality, mock quality, global-state-mutation, structural rules.
|
|
30
31
|
*/
|
|
31
|
-
export function analyseTestBlock(file: SourceFile, block: FunctionBlock,
|
|
32
|
+
export function analyseTestBlock(file: SourceFile, block: FunctionBlock, findings: Finding[], staticContext?: StaticAnalysisSourceContext): void {
|
|
32
33
|
const body = block.codeBody;
|
|
33
|
-
|
|
34
|
+
const sourceContext = staticContext ?? { source: block.body, codeSource: block.codeBody, startLine: block.startLine };
|
|
35
|
+
analyseAssertionQuality(file, block, body, sourceContext, findings);
|
|
34
36
|
analyseMockQuality(file, block, body, findings);
|
|
35
|
-
|
|
37
|
+
analyseGlobalStateMutation(file, block, body, findings);
|
|
36
38
|
analyseTestStructureChecks(file, block, body, findings);
|
|
37
39
|
}
|
|
38
40
|
|
|
39
41
|
// Five assertion-shape checks (no-assertions, trivial, snapshot-only, no-throw-only, exception-type-only)
|
|
40
42
|
// plus the magic-number sub-pass. Reports findings with stable test-block metadata.
|
|
41
|
-
function analyseAssertionQuality(file: SourceFile, block: FunctionBlock, body: string, findings: Finding[]): void {
|
|
43
|
+
function analyseAssertionQuality(file: SourceFile, block: FunctionBlock, body: string, staticContext: StaticAnalysisSourceContext, findings: Finding[]): void {
|
|
42
44
|
for (const check of assertionQualityChecks(block, body)) {
|
|
43
45
|
findings.push(blockFinding({ ruleId: check.ruleId, message: check.message, file, block, severity: check.severity, pillar: "test-quality" }));
|
|
44
46
|
}
|
|
45
47
|
pushMagicNumberAssertionFindings(file, block, body, findings);
|
|
48
|
+
pushStaticAnalysisRedundantTestFindings(file, block, block.body, body, staticContext, findings);
|
|
46
49
|
}
|
|
47
50
|
|
|
48
51
|
// Lazy evaluation: only checks whose `active` predicate fired are returned. The five rule IDs are
|
|
@@ -64,6 +67,9 @@ function assertionQualityChecks(block: FunctionBlock, body: string): TestBlockCh
|
|
|
64
67
|
* `test-quality.magic-number-assertion` with stable literal metadata for downstream review tools.
|
|
65
68
|
*/
|
|
66
69
|
function pushMagicNumberAssertionFindings(file: SourceFile, block: FunctionBlock, body: string, findings: Finding[]): void {
|
|
70
|
+
if (isConstantContractTestName(block.name)) {
|
|
71
|
+
return;
|
|
72
|
+
}
|
|
67
73
|
for (const assertion of magicNumberAssertions(body)) {
|
|
68
74
|
findings.push(
|
|
69
75
|
blockFindingWithMetadata({
|
|
@@ -101,30 +107,11 @@ function analyseMockQuality(file: SourceFile, block: FunctionBlock, body: string
|
|
|
101
107
|
}
|
|
102
108
|
}
|
|
103
109
|
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
* and `test-quality.setup-bloat` (threshold 12) for excessive arrange before the first assertion.
|
|
107
|
-
* Reports both with stable metadata so downstream tooling can track the setup-line counts.
|
|
108
|
-
*/
|
|
109
|
-
function analyseSetupBloat(file: SourceFile, block: FunctionBlock, body: string, config: Config, findings: Finding[]): void {
|
|
110
|
+
// Reports the stable `test-quality.global-state-mutation` finding contract for state leaks.
|
|
111
|
+
function analyseGlobalStateMutation(file: SourceFile, block: FunctionBlock, body: string, findings: Finding[]): void {
|
|
110
112
|
if (hasGlobalStateMutation(body)) {
|
|
111
113
|
findings.push(blockFinding({ ruleId: "test-quality.global-state-mutation", message: `Test \`${block.name}\` mutates global process or runtime state.`, file, block, severity: "warning", pillar: "test-quality" }));
|
|
112
114
|
}
|
|
113
|
-
const setupLines = setupLineCount(body);
|
|
114
|
-
const maxSetupLines = setupBloatThreshold(file, config);
|
|
115
|
-
if (setupLines > maxSetupLines) {
|
|
116
|
-
findings.push(
|
|
117
|
-
blockFindingWithMetadata({
|
|
118
|
-
ruleId: "test-quality.setup-bloat",
|
|
119
|
-
message: `Test \`${block.name}\` has ${setupLines} setup lines before its first assertion.`,
|
|
120
|
-
file,
|
|
121
|
-
block,
|
|
122
|
-
severity: ruleSeverity(config, "test-quality.setup-bloat", "advisory"),
|
|
123
|
-
pillar: "test-quality",
|
|
124
|
-
metadata: { setupLines, maxSetupLines },
|
|
125
|
-
}),
|
|
126
|
-
);
|
|
127
|
-
}
|
|
128
115
|
}
|
|
129
116
|
|
|
130
117
|
// Pattern-driven checks for sleep/loop/conditional logic plus the `.only`/`.skip` commit gate.
|
|
@@ -154,7 +141,7 @@ function controlFlowContainsNonFixtureLoop(source: string): boolean {
|
|
|
154
141
|
if (!hasAssertion(segment)) {
|
|
155
142
|
continue;
|
|
156
143
|
}
|
|
157
|
-
if (isFixtureLoop(segment)) {
|
|
144
|
+
if (isFixtureLoop(source, start, segment)) {
|
|
158
145
|
continue;
|
|
159
146
|
}
|
|
160
147
|
return true;
|
|
@@ -162,22 +149,20 @@ function controlFlowContainsNonFixtureLoop(source: string): boolean {
|
|
|
162
149
|
return false;
|
|
163
150
|
}
|
|
164
151
|
|
|
165
|
-
// A "fixture loop" is the table-test pattern: iterable is
|
|
166
|
-
//
|
|
167
|
-
//
|
|
168
|
-
|
|
169
|
-
// is not silently classified as a fixture loop.
|
|
170
|
-
function isFixtureLoop(segment: string): boolean {
|
|
152
|
+
// A "fixture loop" is the table-test pattern: iterable is an inline fixture OR a local const-bound
|
|
153
|
+
// fixture table, AND every path through the body terminates in an assertion call. Guard branches
|
|
154
|
+
// without assertions are allowed, but assertion-bearing branches still opt out.
|
|
155
|
+
function isFixtureLoop(source: string, start: number, segment: string): boolean {
|
|
171
156
|
const braceIndex = segment.indexOf("{");
|
|
172
157
|
const header = braceIndex === -1 ? segment : segment.slice(0, braceIndex);
|
|
173
|
-
if (
|
|
158
|
+
if (!hasFixtureIterable(source, start, header)) {
|
|
174
159
|
return false;
|
|
175
160
|
}
|
|
176
161
|
if (braceIndex === -1) {
|
|
177
162
|
return false;
|
|
178
163
|
}
|
|
179
164
|
const body = segment.slice(braceIndex + 1, segment.length - 1);
|
|
180
|
-
if (
|
|
165
|
+
if (hasUnsafeFixtureLoopBranch(source.slice(0, start + braceIndex + 1), body)) {
|
|
181
166
|
return false;
|
|
182
167
|
}
|
|
183
168
|
const statements = body.split(/[;\n]/).map((statement) => statement.trim()).filter((statement) => statement.length > 0 && statement !== "}" && !/^(?:break|continue)\b/.test(statement));
|
|
@@ -185,16 +170,58 @@ function isFixtureLoop(segment: string): boolean {
|
|
|
185
170
|
return /^(?:assert\.[a-z]+\s*\(|expect\s*\(|[a-z][A-Za-z0-9_]*\.should(?:Be|Equal)?\s*\()/i.test(lastStatement);
|
|
186
171
|
}
|
|
187
172
|
|
|
188
|
-
//
|
|
189
|
-
//
|
|
190
|
-
function
|
|
191
|
-
|
|
192
|
-
|
|
173
|
+
// Fixture sweeps may carry invariant guards such as `if (expectedIds.has(case.id))`; other branches
|
|
174
|
+
// still opt out because they can hide case-specific expectations inside the loop.
|
|
175
|
+
function hasUnsafeFixtureLoopBranch(sourceBeforeLoopBody: string, body: string): boolean {
|
|
176
|
+
if (/\bswitch\s*\(|\bcase\s|\bdefault\s*:/.test(body)) {
|
|
177
|
+
return true;
|
|
178
|
+
}
|
|
179
|
+
for (const match of body.matchAll(/\bif\b/g)) {
|
|
180
|
+
const start = match.index ?? 0;
|
|
181
|
+
const segment = controlFlowSegment(body, start);
|
|
182
|
+
const sourceBeforeCondition = `${sourceBeforeLoopBody}${body.slice(0, start)}`;
|
|
183
|
+
if (hasAssertion(segment) && !isInvariantAssertionConditional(sourceBeforeCondition, sourceBeforeCondition.length, segment)) {
|
|
184
|
+
return true;
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
return false;
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// Inline fixture tables cover `for (... of [...])` and `Object.entries({ ... })`. Const-bound
|
|
191
|
+
// tables cover the common contract-test shape where the named case table is declared immediately
|
|
192
|
+
// before the sweep for readability.
|
|
193
|
+
function hasFixtureIterable(source: string, start: number, header: string): boolean {
|
|
194
|
+
if (/\bof\s*\[/.test(header) || /\bof\s+Object\.(?:entries|keys|values)\s*\(/.test(header)) {
|
|
195
|
+
return true;
|
|
196
|
+
}
|
|
197
|
+
const iterableName = header.match(/\bof\s+([A-Za-z_$][A-Za-z0-9_$]*)\b/)?.[1] ?? "";
|
|
198
|
+
return iterableName !== "" && (isFixtureConstantIterableName(iterableName) || hasConstBoundFixtureIterable(source.slice(0, start), iterableName));
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
// Accepts const-bound fixture loops only when the iterable name and initializer both look like a
|
|
202
|
+
// deterministic case table or discovered fixture set.
|
|
203
|
+
function hasConstBoundFixtureIterable(sourceBeforeLoop: string, iterableName: string): boolean {
|
|
204
|
+
if (!isFixtureIterableName(iterableName)) {
|
|
205
|
+
return false;
|
|
206
|
+
}
|
|
207
|
+
const assignment = sourceBeforeLoop.match(new RegExp(`\\bconst\\s+${escapeRegex(iterableName)}\\s*=\\s*([\\s\\S]*?);\\s*$`));
|
|
208
|
+
const initializer = assignment?.[1]?.trim() ?? "";
|
|
209
|
+
return initializer.startsWith("[") || /^Object\.(?:entries|keys|values)\s*\(/.test(initializer) || isFixtureDiscoveryCall(initializer);
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
// Limits const-bound loop suppression to table/sweep vocabulary rather than arbitrary arrays.
|
|
213
|
+
function isFixtureIterableName(name: string): boolean {
|
|
214
|
+
return /(?:agents|cases|checks|entries|examples|fixtures|files|ids|paths|records|scenarios|scores|snapshots)$/i.test(name);
|
|
193
215
|
}
|
|
194
216
|
|
|
195
|
-
//
|
|
196
|
-
function
|
|
197
|
-
return
|
|
217
|
+
// UPPER_CASE fixture constants such as HARNESS_CHECKS are named case tables even when imported.
|
|
218
|
+
function isFixtureConstantIterableName(name: string): boolean {
|
|
219
|
+
return /^[A-Z0-9_]+$/.test(name) && isFixtureIterableName(name);
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// Recognises local fixture discovery calls used by contract sweeps without accepting unknown calls.
|
|
223
|
+
function isFixtureDiscoveryCall(initializer: string): boolean {
|
|
224
|
+
return /\b(?:glob|globSync|readdir|readdirSync|discover[A-Za-z0-9_$]*|find[A-Za-z0-9_$]*|list[A-Za-z0-9_$]*)\s*\(/.test(initializer);
|
|
198
225
|
}
|
|
199
226
|
|
|
200
227
|
// Structural loop/branch findings now require the control flow to wrap an assertion; setup-only
|
|
@@ -203,13 +230,28 @@ function controlFlowContainsAssertion(source: string, pattern: RegExp): boolean
|
|
|
203
230
|
for (const match of source.matchAll(pattern)) {
|
|
204
231
|
const start = match.index ?? 0;
|
|
205
232
|
const segment = controlFlowSegment(source, start);
|
|
206
|
-
if (hasAssertion(segment)) {
|
|
233
|
+
if (hasAssertion(segment) && !isInvariantAssertionConditional(source, start, segment)) {
|
|
207
234
|
return true;
|
|
208
235
|
}
|
|
209
236
|
}
|
|
210
237
|
return false;
|
|
211
238
|
}
|
|
212
239
|
|
|
240
|
+
// Accepts guard conditionals whose assertion proves a shared invariant rather than branch policy.
|
|
241
|
+
function isInvariantAssertionConditional(source: string, start: number, segment: string): boolean {
|
|
242
|
+
const condition = segment.slice(0, Math.max(0, segment.indexOf("{"))).trim();
|
|
243
|
+
return isFixtureMembershipGuard(source.slice(0, start), condition);
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// Membership guards over const-bound fixtures keep invariant sweeps readable.
|
|
247
|
+
function isFixtureMembershipGuard(sourceBeforeCondition: string, condition: string): boolean {
|
|
248
|
+
const guardTarget = condition.match(/\b([A-Za-z_$][A-Za-z0-9_$]*)\.(?:has|includes)\s*\(/)?.[1] ?? "";
|
|
249
|
+
if (!guardTarget) {
|
|
250
|
+
return false;
|
|
251
|
+
}
|
|
252
|
+
return new RegExp(`\\bconst\\s+${escapeRegex(guardTarget)}\\s*=\\s*(?:new\\s+Set\\s*\\(|\\[)`).test(sourceBeforeCondition);
|
|
253
|
+
}
|
|
254
|
+
|
|
213
255
|
// Captures the smallest control-flow segment so assertion detection does not scan the whole test.
|
|
214
256
|
function controlFlowSegment(source: string, start: number): string {
|
|
215
257
|
const lineEnd = source.indexOf("\n", start);
|
|
@@ -313,31 +355,51 @@ function isNoThrowOnlyTest(source: string): boolean {
|
|
|
313
355
|
}
|
|
314
356
|
|
|
315
357
|
// Pulls every numeric expected value out of `expect(...).toBe(n)` and `assert.equal(actual, n)`
|
|
316
|
-
// shapes.
|
|
317
|
-
//
|
|
358
|
+
// shapes. Small cardinalities and length/count matchers are excluded because the literal often is
|
|
359
|
+
// the test contract; larger opaque values still surface for naming or rationale.
|
|
318
360
|
function magicNumberAssertions(source: string): Array<{ value: number }> {
|
|
319
361
|
return MAGIC_NUMBER_ASSERTION_PATTERNS.flatMap((candidate) => magicNumberAssertionMatches(source, candidate));
|
|
320
362
|
}
|
|
321
363
|
|
|
322
364
|
const MAGIC_NUMBER_ASSERTION_PATTERNS: MagicNumberAssertionPattern[] = [
|
|
323
|
-
{ pattern: /\bexpect\s*\(\s*([^)]+?)\s*\)\s*\.\s*to(?:Be|Equal|HaveLength|HaveCount)\s*\(\s*(-?\d+(?:\.\d+)?)\s*\)/g, expressionIndex: 1,
|
|
365
|
+
{ pattern: /\bexpect\s*\(\s*([^)]+?)\s*\)\s*\.\s*(to(?:Be|Equal|HaveLength|HaveCount))\s*\(\s*(-?\d+(?:\.\d+)?)\s*\)/g, expressionIndex: 1, matcherIndex: 2, valueIndex: 3 },
|
|
324
366
|
{ pattern: /\bassert\.(?:equal|strictEqual|deepEqual)\s*\(\s*([^,\n]+?)\s*,\s*(-?\d+(?:\.\d+)?)(?:\s*,|\s*\))/g, expressionIndex: 1, valueIndex: 2 },
|
|
325
367
|
];
|
|
326
368
|
|
|
327
369
|
// Extracts reportable numeric literals for one assertion grammar while keeping HTTP statuses quiet.
|
|
328
370
|
function magicNumberAssertionMatches(source: string, candidate: MagicNumberAssertionPattern): Array<{ value: number }> {
|
|
329
|
-
const ignored = new Set([-1, 0, 1]);
|
|
330
371
|
const results: Array<{ value: number }> = [];
|
|
331
372
|
for (const match of source.matchAll(candidate.pattern)) {
|
|
332
373
|
const expression = match[candidate.expressionIndex] ?? "";
|
|
374
|
+
const matcher = candidate.matcherIndex === undefined ? "" : match[candidate.matcherIndex] ?? "";
|
|
333
375
|
const expectedNumber = Number(match[candidate.valueIndex] ?? "0");
|
|
334
|
-
if (!
|
|
376
|
+
if (!isIgnoredMagicNumberAssertion(expression, matcher, expectedNumber)) {
|
|
335
377
|
results.push({ value: expectedNumber });
|
|
336
378
|
}
|
|
337
379
|
}
|
|
338
380
|
return results;
|
|
339
381
|
}
|
|
340
382
|
|
|
383
|
+
// Centralises the rule's non-findings so cardinal, count, and HTTP-status exemptions stay aligned.
|
|
384
|
+
function isIgnoredMagicNumberAssertion(expression: string, matcher: string, expectedNumber: number): boolean {
|
|
385
|
+
return isSmallCardinal(expectedNumber) || isLengthOrCountMatcher(matcher) || isHttpStatusAssertion(expression, expectedNumber);
|
|
386
|
+
}
|
|
387
|
+
|
|
388
|
+
// Small integer cardinals usually express the expected case count directly.
|
|
389
|
+
function isSmallCardinal(cardinal: number): boolean {
|
|
390
|
+
return Number.isInteger(cardinal) && cardinal >= -1 && cardinal <= 3;
|
|
391
|
+
}
|
|
392
|
+
|
|
393
|
+
// Length/count matchers already name the measurement, so the numeric literal is the assertion.
|
|
394
|
+
function isLengthOrCountMatcher(matcher: string): boolean {
|
|
395
|
+
return matcher === "toHaveLength" || matcher === "toHaveCount";
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
// Contract-named tests may assert the documented number directly; the name supplies the rationale.
|
|
399
|
+
function isConstantContractTestName(name: string): boolean {
|
|
400
|
+
return /\b(?:constant|threshold|limit|budget|default|contract)\b/i.test(name);
|
|
401
|
+
}
|
|
402
|
+
|
|
341
403
|
// HTTP response status codes are intentionally numeric at assertion sites; naming every 200/404
|
|
342
404
|
// would add ceremony without making the test clearer.
|
|
343
405
|
function isHttpStatusAssertion(expression: string, expectedNumber: number): boolean {
|
package/src/test-fixtures.ts
CHANGED
|
@@ -7,12 +7,13 @@ import { tmpdir } from "node:os";
|
|
|
7
7
|
import { dirname, join } from "node:path";
|
|
8
8
|
import { chdir, cwd } from "node:process";
|
|
9
9
|
import { analyse } from "./cli.ts";
|
|
10
|
-
import type { AnalysisReport } from "./
|
|
10
|
+
import type { AnalysisReport, ChangedScopeMode } from "./types.ts";
|
|
11
11
|
|
|
12
12
|
export const REPO_ROOT = cwd();
|
|
13
13
|
export const HIGH_ENTROPY_FIXTURE_VALUE = ["Zx7pQ9vLm3N8sT2r", "Y6wK1dF4gH5jC0bR2"].join("");
|
|
14
14
|
export const API_TOKEN_FIXTURE_VALUE = ["rN7pQ4sV9xY2zA5b", "C8dG9hK2mN5pQ8sR1"].join("");
|
|
15
15
|
export const DATABASE_URL_FIXTURE_VALUE = ["postgres://app:superSecret", "Password@db.internal/app"].join("");
|
|
16
|
+
export const URL_CREDENTIAL_FIXTURE_VALUE = ["https://agent:", "clientSecret42", "@example.test/api"].join("");
|
|
16
17
|
export const OPENAI_KEY_FIXTURE_VALUE = ["sk-proj-AbCdEfGhIjKl", "MnOpQrStUvWxYz1234567890"].join("");
|
|
17
18
|
export const GOOGLE_API_KEY_FIXTURE_VALUE = ["AIzaSyD3moKeyValue", "1234567890AbCdEf"].join("");
|
|
18
19
|
export const SLACK_WEBHOOK_FIXTURE_VALUE = ["https://hooks.slack.com/services/T00000000", "B00000000", "abcdefghijklmnopqrstuvwx"].join("/");
|
|
@@ -22,6 +23,11 @@ export const DISCORD_WEBHOOK_FIXTURE_VALUE = [
|
|
|
22
23
|
].join("/");
|
|
23
24
|
export const NPM_AUTH_TOKEN_FIXTURE_VALUE = ["npmAuthToken", "AbCdEfGhIjKlMnOp", "QrStUvWxYz123456"].join("");
|
|
24
25
|
export const SSN_FIXTURE_VALUE = ["123", "45", "6789"].join("-");
|
|
26
|
+
export const CREDIT_CARD_FIXTURE_VALUE = ["4111", "1111", "1111", "1111"].join(" ");
|
|
27
|
+
export const INVALID_CREDIT_CARD_FIXTURE_VALUE = ["4111", "1111", "1111", "1112"].join(" ");
|
|
28
|
+
export const MBI_FIXTURE_VALUE = ["1EG4", "TE5", "MK73"].join("");
|
|
29
|
+
export const MRN_FIXTURE_VALUE = "00489912";
|
|
30
|
+
export const GCP_PRIVATE_KEY_ID_FIXTURE_VALUE = ["a1b2c3d4e5f6a7b8c9d0", "e1f2a3b4c5d6e7f8a9b0"].join("");
|
|
25
31
|
export const AWS_ACCESS_KEY_FIXTURE_VALUE = ["AKIAABCDEFGH", "IJKLMNOP"].join("");
|
|
26
32
|
export const PRIVATE_KEY_HEADER_FIXTURE_VALUE = ["-----BEGIN ", "PRIVATE KEY-----"].join("");
|
|
27
33
|
export const POSTGRES_URL_FIXTURE_VALUE = ["postgres://user:sec", "ret@example.test/db"].join("");
|
|
@@ -35,10 +41,16 @@ export const COMMENTED_OUT_LEGACY_CALL = ["const", " disabledLegacy = runLegacyP
|
|
|
35
41
|
export interface AnalyseProjectOptions {
|
|
36
42
|
config?: Record<string, unknown>;
|
|
37
43
|
configPath?: string;
|
|
44
|
+
profile?: string;
|
|
38
45
|
executableFiles?: string[];
|
|
39
46
|
shouldIncludeIgnored?: boolean;
|
|
40
47
|
shouldSkipConfig?: boolean;
|
|
41
48
|
paths?: string[];
|
|
49
|
+
diff?: string;
|
|
50
|
+
diffPatch?: string;
|
|
51
|
+
since?: string;
|
|
52
|
+
changedRanges?: string;
|
|
53
|
+
changedScope?: ChangedScopeMode;
|
|
42
54
|
}
|
|
43
55
|
|
|
44
56
|
// Adds a fixture filename override for single-source test scans.
|
|
@@ -58,7 +70,8 @@ export function analyseFixture(source: string, options: AnalyseFixtureOptions =
|
|
|
58
70
|
);
|
|
59
71
|
}
|
|
60
72
|
|
|
61
|
-
// Creates a temporary project, runs analysis inside it, and removes the fixture tree.
|
|
73
|
+
// Creates a temporary project, runs analysis inside it, and removes the fixture tree. It mutates the
|
|
74
|
+
// filesystem and process cwd; explicit options preserve absent-vs-undefined typing.
|
|
62
75
|
export function analyseProject(files: Record<string, string>, options: AnalyseProjectOptions = {}) {
|
|
63
76
|
const dir = mkdtempSync(join(tmpdir(), "gruff-ts-"));
|
|
64
77
|
const previous = cwd();
|
|
@@ -90,21 +103,36 @@ export function setupAnalyseProjectDirectory(dir: string, files: Record<string,
|
|
|
90
103
|
|
|
91
104
|
/**
|
|
92
105
|
* Runs analyse after the fixture helper has switched into the temp project root, returning a stable report.
|
|
106
|
+
* The explicit option assembly preserves exact optional property types because absent and undefined differ.
|
|
93
107
|
* @param options Normalized fixture scan options.
|
|
94
108
|
* @returns The analysis report produced from the current temporary project.
|
|
95
109
|
*/
|
|
96
110
|
export function analyseProjectInCurrentDirectory(options: AnalyseProjectOptions): AnalysisReport {
|
|
97
111
|
return analyse({
|
|
98
112
|
paths: options.paths ?? ["."],
|
|
99
|
-
...(typeof options.configPath === "string" ? { config: options.configPath } : {}),
|
|
100
113
|
shouldSkipConfig: options.shouldSkipConfig ?? !(options.config || options.configPath),
|
|
101
114
|
format: "json",
|
|
102
115
|
failOn: "none",
|
|
103
116
|
shouldIncludeIgnored: options.shouldIncludeIgnored ?? false,
|
|
117
|
+
changedScope: options.changedScope ?? "symbol",
|
|
104
118
|
shouldSkipBaseline: true,
|
|
119
|
+
...optionalFixtureScanFields(options),
|
|
105
120
|
});
|
|
106
121
|
}
|
|
107
122
|
|
|
123
|
+
// Assembles the optional scan fields with conditional spreads so each stays omitted (not undefined)
|
|
124
|
+
// under exactOptionalPropertyTypes, keeping analyseProjectInCurrentDirectory a flat literal.
|
|
125
|
+
function optionalFixtureScanFields(options: AnalyseProjectOptions): Partial<Pick<Parameters<typeof analyse>[0], "config" | "profile" | "diff" | "diffPatch" | "since" | "changedRanges">> {
|
|
126
|
+
return {
|
|
127
|
+
...(typeof options.configPath === "string" ? { config: options.configPath } : {}),
|
|
128
|
+
...(typeof options.profile === "string" ? { profile: options.profile } : {}),
|
|
129
|
+
...(typeof options.diff === "string" ? { diff: options.diff } : {}),
|
|
130
|
+
...(typeof options.diffPatch === "string" ? { diffPatch: options.diffPatch } : {}),
|
|
131
|
+
...(typeof options.since === "string" ? { since: options.since } : {}),
|
|
132
|
+
...(typeof options.changedRanges === "string" ? { changedRanges: options.changedRanges } : {}),
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
|
|
108
136
|
/*
|
|
109
137
|
* Serializes a test YAML config object from the root indentation level. Every fixture YAML is
|
|
110
138
|
* stamped with the required `schemaVersion: gruff-ts.config.v0.1` field at the top (per ADR-004)
|
|
@@ -321,8 +349,15 @@ DATABASE_URL=${POSTGRES_URL_FIXTURE_VALUE}
|
|
|
321
349
|
JWT_TOKEN=${JWT_FIXTURE_VALUE}
|
|
322
350
|
OPENAI_API_KEY=${OPENAI_KEY_FIXTURE_VALUE}
|
|
323
351
|
PATIENT_SSN=${SSN_FIXTURE_VALUE}
|
|
352
|
+
PATIENT_MBI=${MBI_FIXTURE_VALUE}
|
|
324
353
|
API_TOKEN=${API_TOKEN_FIXTURE_VALUE}
|
|
325
354
|
`,
|
|
355
|
+
"credentials/service-account.json": JSON.stringify({
|
|
356
|
+
type: "service_account",
|
|
357
|
+
private_key_id: GCP_PRIVATE_KEY_ID_FIXTURE_VALUE,
|
|
358
|
+
private_key: `${PRIVATE_KEY_HEADER_FIXTURE_VALUE}\nMIIfake\n-----END PRIVATE KEY-----\n`,
|
|
359
|
+
client_email: "svc@project.iam.gserviceaccount.com",
|
|
360
|
+
}),
|
|
326
361
|
"package.json": JSON.stringify({
|
|
327
362
|
scripts: {
|
|
328
363
|
postinstall: "node scripts/setup.js",
|
|
@@ -339,7 +374,6 @@ API_TOKEN=${API_TOKEN_FIXTURE_VALUE}
|
|
|
339
374
|
}),
|
|
340
375
|
".github/workflows/risky.yml": githubActionsCoverageWorkflowSource(),
|
|
341
376
|
"bin/bad.js": "#!/usr/bin/env node\nconsole.log('ok');\n",
|
|
342
|
-
"styles/component.css": ".one { color: red; }\n.two { color: blue; }\n.three { color: green; }\n.four { color: yellow; }\n",
|
|
343
377
|
"tsconfig.json": JSON.stringify({
|
|
344
378
|
compilerOptions: {
|
|
345
379
|
strict: false,
|
|
@@ -383,8 +417,10 @@ const active = true;
|
|
|
383
417
|
const xx = 1;
|
|
384
418
|
const ctx = { request: 1 };
|
|
385
419
|
const disableCache = true;
|
|
386
|
-
const
|
|
387
|
-
const
|
|
420
|
+
const DATABASE_URL = "/health";
|
|
421
|
+
const databaseUrl = "/healthz";
|
|
422
|
+
const project_path = "src";
|
|
423
|
+
const projectPath = "src/index.ts";
|
|
388
424
|
const unsafeAny: any = {};
|
|
389
425
|
const embeddedToken = "${HIGH_ENTROPY_FIXTURE_VALUE}";
|
|
390
426
|
const maxRetryLimit = 12;
|
|
@@ -434,6 +470,10 @@ export function process(flag: boolean, userInput: string, userId: string, userId
|
|
|
434
470
|
fetch(req.body.url);
|
|
435
471
|
res.redirect(req.query.next);
|
|
436
472
|
new RegExp(process.argv[2]);
|
|
473
|
+
const serializedPayload = req.body.serialized;
|
|
474
|
+
nodeSerialize.unserialize(serializedPayload);
|
|
475
|
+
const xmlPayload = req.body.xml;
|
|
476
|
+
libxmljs.parseXml(xmlPayload, { noent: true });
|
|
437
477
|
Math.random();
|
|
438
478
|
document.write(userInput);
|
|
439
479
|
element.innerHTML = userInput;
|
|
@@ -568,6 +608,10 @@ ${"test"}("magic assertion", () => {
|
|
|
568
608
|
expect(total).toBe(42);
|
|
569
609
|
});
|
|
570
610
|
|
|
611
|
+
${"test"}("static shape assertion", () => {
|
|
612
|
+
assert.equal(typeof renderCatalogue, "function");
|
|
613
|
+
});
|
|
614
|
+
|
|
571
615
|
${"test"}("unused mock", () => {
|
|
572
616
|
const unusedMock = jest.fn();
|
|
573
617
|
assert.ok(true);
|
|
@@ -614,13 +658,10 @@ function catalogueCoverageOptions(): AnalyseProjectOptions {
|
|
|
614
658
|
rules: {
|
|
615
659
|
"complexity.cognitive": { threshold: 3, severity: "warning" },
|
|
616
660
|
"complexity.cyclomatic": { threshold: 2, severity: "warning" },
|
|
617
|
-
"complexity.npath": { threshold: 2, severity: "warning" },
|
|
618
661
|
"design.large-module-concentration": { threshold: 35, severity: "advisory", options: { minFiles: 4, minLines: 8 } },
|
|
619
662
|
"size.file-length": { threshold: 8, severity: "warning" },
|
|
620
663
|
"size.function-length": { threshold: 8, severity: "warning" },
|
|
621
664
|
"size.parameter-count": { threshold: 3, severity: "warning" },
|
|
622
|
-
"size.stylesheet-length": { threshold: 3, severity: "warning" },
|
|
623
|
-
"test-quality.setup-bloat": { threshold: 2, severity: "advisory" },
|
|
624
665
|
},
|
|
625
666
|
},
|
|
626
667
|
};
|
package/src/types.ts
CHANGED
|
@@ -24,15 +24,28 @@ export type OutputFormat = "text" | "json" | "html" | "markdown" | "github" | "h
|
|
|
24
24
|
/** Minimum severity that causes a non-zero CLI exit. */
|
|
25
25
|
export type FailThreshold = "none" | "advisory" | "warning" | "error";
|
|
26
26
|
|
|
27
|
+
/** Changed-region filter precision for diff-aware analysis. */
|
|
28
|
+
export type ChangedScopeMode = "symbol" | "hunk";
|
|
29
|
+
|
|
27
30
|
/** Public options contract consumed by the analyzer core and CLI. */
|
|
28
31
|
export interface AnalysisOptions {
|
|
29
32
|
paths: string[];
|
|
30
33
|
config?: string;
|
|
34
|
+
/**
|
|
35
|
+
* Named built-in profile (`gruff.minimal` / `gruff.recommended` / `gruff.strict`) or a path to a
|
|
36
|
+
* profile file, from the `--profile` CLI flag. Wins over a config-file `profile:` block. Absent
|
|
37
|
+
* means "fall back to the config-file profile, else the default `recommended` (a no-op delta)".
|
|
38
|
+
*/
|
|
39
|
+
profile?: string;
|
|
31
40
|
shouldSkipConfig: boolean;
|
|
32
41
|
format: OutputFormat;
|
|
33
42
|
failOn: FailThreshold;
|
|
34
43
|
shouldIncludeIgnored: boolean;
|
|
35
44
|
diff?: string;
|
|
45
|
+
since?: string;
|
|
46
|
+
changedRanges?: string;
|
|
47
|
+
changedScope: ChangedScopeMode;
|
|
48
|
+
diffPatch?: string;
|
|
36
49
|
historyFile?: string;
|
|
37
50
|
baseline?: string;
|
|
38
51
|
generateBaseline?: string;
|
|
@@ -58,6 +71,7 @@ export interface Config {
|
|
|
58
71
|
acceptedAbbreviations: Set<string>;
|
|
59
72
|
secretPreviews: Set<string>;
|
|
60
73
|
bannedGenericNames: Set<string>;
|
|
74
|
+
acceptedBooleanNames: Set<string>;
|
|
61
75
|
booleanPrefixes: Set<string>;
|
|
62
76
|
hungarianPrefixes: Set<string>;
|
|
63
77
|
placeholderNames: Set<string>;
|
|
@@ -72,6 +86,46 @@ export interface Config {
|
|
|
72
86
|
rules: Map<string, { enabled?: boolean; threshold?: number; severity?: Severity; options: Map<string, number> }>;
|
|
73
87
|
}
|
|
74
88
|
|
|
89
|
+
/**
|
|
90
|
+
* One rule's settings inside a profile. Mirrors the per-rule knobs of the config `rules:` block
|
|
91
|
+
* (`enabled` defaults to true when omitted). `options` is optional here - built-in presets never set
|
|
92
|
+
* options - whereas the loaded `Config.rules` value always carries an (often empty) options map.
|
|
93
|
+
*/
|
|
94
|
+
export interface ProfileRuleSetting {
|
|
95
|
+
enabled?: boolean;
|
|
96
|
+
threshold?: number;
|
|
97
|
+
severity?: Severity;
|
|
98
|
+
options?: Map<string, number>;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
/**
|
|
102
|
+
* What a user writes for `profile:` (or passes to `--profile`): a built-in name / file path string,
|
|
103
|
+
* or an inline object that extends a base profile and layers per-rule and path overrides on top.
|
|
104
|
+
*/
|
|
105
|
+
export type ProfileSpec = string | InlineProfileSpec;
|
|
106
|
+
|
|
107
|
+
/**
|
|
108
|
+
* The inline `profile:` object form. `extends` names the base (a built-in name or a relative file
|
|
109
|
+
* path; defaults to `gruff.recommended` when omitted); `rules` and `ignoredPaths` override the base
|
|
110
|
+
* with child-wins semantics - per-rule fields merge, and the `ignoredPaths` array replaces.
|
|
111
|
+
*/
|
|
112
|
+
export interface InlineProfileSpec {
|
|
113
|
+
extends?: string;
|
|
114
|
+
rules?: Record<string, ProfileRuleSetting>;
|
|
115
|
+
ignoredPaths?: string[];
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/**
|
|
119
|
+
* A fully resolved and flattened profile: the effective rule settings and ignored paths after the
|
|
120
|
+
* whole `extends:` chain has collapsed into one delta from the descriptor defaults. Enabled-at-default
|
|
121
|
+
* rules are omitted from `rules`, so `gruff.recommended` flattens to an empty map (the parity contract).
|
|
122
|
+
*/
|
|
123
|
+
export interface ProfileDefinition {
|
|
124
|
+
name: string;
|
|
125
|
+
rules: Map<string, ProfileRuleSetting>;
|
|
126
|
+
ignoredPaths: string[];
|
|
127
|
+
}
|
|
128
|
+
|
|
75
129
|
/** Stable analysis finding emitted by a rule. */
|
|
76
130
|
export interface Finding {
|
|
77
131
|
ruleId: string;
|
|
@@ -89,6 +143,7 @@ export interface Finding {
|
|
|
89
143
|
remediation?: string;
|
|
90
144
|
metadata: Record<string, unknown>;
|
|
91
145
|
fingerprint: string;
|
|
146
|
+
stableIdentity: string;
|
|
92
147
|
}
|
|
93
148
|
|
|
94
149
|
/** Non-finding runtime diagnostic emitted while preparing or reading inputs. */
|
|
@@ -99,15 +154,37 @@ export interface RunDiagnostic {
|
|
|
99
154
|
line?: number;
|
|
100
155
|
}
|
|
101
156
|
|
|
102
|
-
/**
|
|
157
|
+
/**
|
|
158
|
+
* Source that excluded a path from analysis. `config` (`paths.ignore`) is authoritative in every
|
|
159
|
+
* invocation mode - explicit file operands and diff/changed-region runs included - and is never
|
|
160
|
+
* overridden by `--include-ignored`. `gitignore` and `default` are discovery-walk ignores: they are
|
|
161
|
+
* suppressed by `--include-ignored` and bypassed for an explicitly supplied file operand (ADR-003).
|
|
162
|
+
*/
|
|
163
|
+
export type IgnoreSource = "config" | "gitignore" | "default";
|
|
164
|
+
|
|
165
|
+
/** One path excluded from analysis, with the ignore source and the exact pattern that matched. */
|
|
166
|
+
export interface SkippedPath {
|
|
167
|
+
path: string;
|
|
168
|
+
source: IgnoreSource;
|
|
169
|
+
pattern: string;
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/**
|
|
173
|
+
* Stable gruff.analysis.v2 report schema returned by analyse and JSON report commands.
|
|
174
|
+
*
|
|
175
|
+
* `paths.skipped` (added in 0.3.0, ADR-007) is an additive field: each entry carries the excluded
|
|
176
|
+
* `path`, the ignore `source`, and the matching `pattern`. `paths.ignoredPaths` is retained as the
|
|
177
|
+
* back-compatible `string[]` of the same paths, so existing v2 consumers keep working without change.
|
|
178
|
+
*/
|
|
103
179
|
export interface AnalysisReport {
|
|
104
180
|
schemaVersion: "gruff.analysis.v2";
|
|
105
181
|
tool: { name: "gruff-ts"; version: string };
|
|
106
182
|
run: { projectRoot: string; format: OutputFormat; failOn: FailThreshold; generatedAt: string };
|
|
107
183
|
summary: { advisory: number; warning: number; error: number; total: number };
|
|
108
|
-
paths: { analysedFiles: number; ignoredPaths: string[]; missingPaths: string[] };
|
|
184
|
+
paths: { analysedFiles: number; ignoredPaths: string[]; skipped: SkippedPath[]; missingPaths: string[] };
|
|
109
185
|
diagnostics: RunDiagnostic[];
|
|
110
186
|
findings: Finding[];
|
|
187
|
+
suppressedCount?: number;
|
|
111
188
|
score: {
|
|
112
189
|
composite: number;
|
|
113
190
|
grade: string;
|