@blundergoat/gruff-ts 0.1.1 → 0.3.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 +55 -19
- package/README.md +103 -35
- package/docs/README.md +2 -0
- package/docs/agent-hook.md +80 -0
- package/docs/ci-integration.md +16 -0
- package/docs/configuration.md +60 -3
- package/docs/dashboard.md +7 -0
- package/docs/output-formats.md +11 -1
- package/docs/philosophy.md +21 -0
- package/docs/releasing.md +12 -11
- package/docs/reports-and-ci.md +5 -2
- package/docs/rules.md +24 -15
- package/package.json +5 -5
- package/scripts/bump-version.sh +20 -4
- package/scripts/preflight-checks.sh +4 -41
- package/src/analyser.ts +47 -34
- package/src/blocks.ts +82 -75
- 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 +209 -51
- package/src/comment-rules.ts +4 -0
- package/src/config-load-error.ts +18 -0
- package/src/config-parse.ts +458 -0
- package/src/config-preservation.ts +64 -0
- package/src/config.ts +311 -428
- package/src/constants.ts +10 -2
- package/src/context-doc-rules.ts +2 -4
- package/src/dashboard.ts +8 -5
- package/src/dead-code-rules.ts +60 -14
- package/src/discovery.ts +88 -32
- package/src/doc-rules.ts +3 -3
- package/src/findings-helpers.ts +58 -5
- package/src/fixtures/rule-catalogue-security-doctrine.ts +28 -0
- package/src/init-config.ts +94 -31
- package/src/line-rules.ts +58 -4
- package/src/naming-pushers.ts +42 -7
- package/src/pillar-summary.ts +129 -0
- package/src/profiles.ts +232 -0
- package/src/project-config-rules.ts +5 -5
- package/src/project-rules.ts +2 -1
- package/src/report-html.ts +404 -0
- package/src/report-renderers.ts +210 -397
- package/src/rule-list.ts +85 -1
- package/src/rules.ts +28 -27
- package/src/safety-rules.ts +22 -7
- package/src/scoring.ts +78 -8
- package/src/security-flow-rules.ts +533 -0
- package/src/sensitive-data-rules.ts +138 -2
- package/src/test-block-rules.ts +140 -7
- package/src/test-fixtures.ts +59 -13
- package/src/types.ts +108 -5
|
@@ -17,13 +17,14 @@ function analyseSensitiveData(file: SensitiveSourceFile, source: string, config:
|
|
|
17
17
|
["sensitive-data.aws-access-key", /AKIA[0-9A-Z]{16}/g, "AWS access key pattern detected."],
|
|
18
18
|
["sensitive-data.private-key", /BEGIN (RSA |OPENSSH |EC |DSA )?PRIVATE KEY/g, "Private key block detected."],
|
|
19
19
|
["sensitive-data.jwt-token", /eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, "JWT-looking token detected."],
|
|
20
|
-
["sensitive-data.database-url-password", /\b(?:postgres(?:ql)?|mysql|mariadb|mongodb(?:\+srv)?|redis|amqp|amqps|mssql):\/\/[^\/\s:@]+:[^\/\s@]+@/g, "
|
|
20
|
+
["sensitive-data.database-url-password", /\b(?:https?|postgres(?:ql)?|mysql|mariadb|mongodb(?:\+srv)?|redis|amqp|amqps|mssql):\/\/[^\/\s:@]+:[^\/\s@]+@/g, "URL appears to include embedded credentials."],
|
|
21
21
|
[
|
|
22
22
|
"sensitive-data.api-key-pattern",
|
|
23
23
|
/\b(?:sk_live_[A-Za-z0-9_-]{12,}|sk_test_[A-Za-z0-9_-]{12,}|sk-proj-[A-Za-z0-9_-]{16,}|sk-ant-[A-Za-z0-9_-]{16,}|ghp_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,}|gh[ousr]_[A-Za-z0-9_]{20,}|glpat-[A-Za-z0-9_-]{20,}|npm_[A-Za-z0-9]{20,}|AIza[A-Za-z0-9_-]{20,}|xox[baprs]-[A-Za-z0-9-]{10,}|https:\/\/hooks\.slack\.com\/services\/[A-Za-z0-9_-]+\/[A-Za-z0-9_-]+\/[A-Za-z0-9_-]+|https:\/\/discord(?:app)?\.com\/api\/webhooks\/[0-9]+\/[A-Za-z0-9_-]+)\b/g,
|
|
24
24
|
"API key pattern detected.",
|
|
25
25
|
],
|
|
26
26
|
["sensitive-data.pii-pattern", /\b\d{3}-\d{2}-\d{4}\b/g, "PII-like identifier pattern detected."],
|
|
27
|
+
["sensitive-data.phi-pattern", /\b[1-9][ACDEFGHJKMNPQRTUVWXY][ACDEFGHJKMNPQRTUVWXY0-9]\d[ACDEFGHJKMNPQRTUVWXY][ACDEFGHJKMNPQRTUVWXY0-9]\d[ACDEFGHJKMNPQRTUVWXY][ACDEFGHJKMNPQRTUVWXY]\d\d\b/g, "Medicare Beneficiary Identifier (PHI) pattern detected."],
|
|
27
28
|
];
|
|
28
29
|
|
|
29
30
|
for (const [ruleId, pattern, message] of patterns) {
|
|
@@ -36,6 +37,59 @@ function analyseSensitiveData(file: SensitiveSourceFile, source: string, config:
|
|
|
36
37
|
analyseHardcodedEnvironmentValues(file, source, config, findings);
|
|
37
38
|
analyseNpmAuthTokens(file, source, config, findings);
|
|
38
39
|
analyseHighEntropyStrings(file, source, config, findings);
|
|
40
|
+
analysePhiLabelledIdentifiers(file, source, config, findings);
|
|
41
|
+
analysePaymentCardNumbers(file, source, config, findings);
|
|
42
|
+
analyseGcpServiceAccountKeys(file, source, config, findings);
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// PHI beyond the MBI shape: medical-record-number assignments. Context-gated on an `MRN` / `medical
|
|
46
|
+
// record` label so bare integers stay clean; stable contract is one redacted finding per label.
|
|
47
|
+
function analysePhiLabelledIdentifiers(file: SensitiveSourceFile, source: string, config: Config, findings: Finding[]): void {
|
|
48
|
+
const lines = source.split(/\r?\n/);
|
|
49
|
+
for (const [index, line] of lines.entries()) {
|
|
50
|
+
const match = line.match(/\b(?:MRN|medical[\s_-]?record(?:[\s_-]?number)?)\b\s*[:=#]?\s*([0-9]{6,12})\b/i);
|
|
51
|
+
const medicalRecordNumber = match?.[1];
|
|
52
|
+
if (!medicalRecordNumber) {
|
|
53
|
+
continue;
|
|
54
|
+
}
|
|
55
|
+
pushSensitiveFinding(config, findings, file, "sensitive-data.phi-pattern", "Medical record number (PHI) detected.", index + 1, medicalRecordNumber, "high");
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// GCP service-account key files carry `"type": "service_account"` next to a private key. Flag the file
|
|
60
|
+
// once, anchored on the type line; stable contract keeps raw key bodies covered by private-key.
|
|
61
|
+
function analyseGcpServiceAccountKeys(file: SensitiveSourceFile, source: string, config: Config, findings: Finding[]): void {
|
|
62
|
+
const typeMatch = source.match(/"type"\s*:\s*"service_account"/);
|
|
63
|
+
if (!typeMatch || !/"private_key"\s*:\s*"|BEGIN (?:RSA |OPENSSH |EC |DSA )?PRIVATE KEY/.test(source)) {
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
const identifier = source.match(/"private_key_id"\s*:\s*"([^"]+)"/)?.[1]
|
|
67
|
+
?? source.match(/"client_email"\s*:\s*"([^"]+)"/)?.[1]
|
|
68
|
+
?? "service_account";
|
|
69
|
+
pushSensitiveFinding(config, findings, file, "sensitive-data.gcp-service-account-key", "GCP service-account key file detected.", byteLine(source, typeMatch.index ?? 0), identifier, "high");
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Payment-card PII detection is structural: candidate shape, known issuer prefix, length, and Luhn
|
|
73
|
+
// check must all pass before a stable redacted finding is emitted.
|
|
74
|
+
function analysePaymentCardNumbers(file: SensitiveSourceFile, source: string, config: Config, findings: Finding[]): void {
|
|
75
|
+
for (const match of source.matchAll(/\b(?:\d[ -]?){12,18}\d\b/g)) {
|
|
76
|
+
const rawCandidate = match[0] ?? "";
|
|
77
|
+
const cardNumber = normalizedPaymentCardNumber(rawCandidate);
|
|
78
|
+
if (!isPaymentCardNumber(cardNumber)) {
|
|
79
|
+
continue;
|
|
80
|
+
}
|
|
81
|
+
pushSensitiveFinding(
|
|
82
|
+
config,
|
|
83
|
+
findings,
|
|
84
|
+
file,
|
|
85
|
+
"sensitive-data.pii-pattern",
|
|
86
|
+
"Credit card number (PII) pattern detected.",
|
|
87
|
+
byteLine(source, match.index ?? 0),
|
|
88
|
+
rawCandidate,
|
|
89
|
+
"high",
|
|
90
|
+
{ piiKind: "credit-card", digits: cardNumber.length },
|
|
91
|
+
);
|
|
92
|
+
}
|
|
39
93
|
}
|
|
40
94
|
|
|
41
95
|
// Stable redaction contract: parses `_authToken=` config lines even when values lack an npm_ prefix.
|
|
@@ -97,7 +151,7 @@ function analyseHardcodedEnvironmentValues(file: SensitiveSourceFile, source: st
|
|
|
97
151
|
// stable across runs and prevent noisy regressions in node_modules-heavy projects.
|
|
98
152
|
function analyseHighEntropyStrings(file: SensitiveSourceFile, source: string, config: Config, findings: Finding[]): void {
|
|
99
153
|
const minLength = threshold(config, "sensitive-data.high-entropy-string", 32);
|
|
100
|
-
for (const match of source.matchAll(/(["'`])([A-Za-z0-9_+=./-]{
|
|
154
|
+
for (const match of source.matchAll(/(["'`])([A-Za-z0-9_+=./-]{24,})\1/g)) {
|
|
101
155
|
const raw = match[2] ?? "";
|
|
102
156
|
if (!isHighEntropySecretCandidate(raw, minLength)) {
|
|
103
157
|
continue;
|
|
@@ -240,6 +294,88 @@ function hasKnownRepoPathSegment(candidateText: string): boolean {
|
|
|
240
294
|
return /(?:^|\/)(?:\.goat-flow|src|test|tests|fixtures?|docs|scripts|bin|workflow|package(?:-lock)?\.json)(?:\/|$)/.test(candidateText);
|
|
241
295
|
}
|
|
242
296
|
|
|
297
|
+
// Removes separators allowed in human-entered payment-card numbers before issuer and checksum checks.
|
|
298
|
+
function normalizedPaymentCardNumber(candidateText: string): string {
|
|
299
|
+
return candidateText.replace(/[ -]/g, "");
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
// Stable contract: only card-network-shaped values with a valid Luhn checksum are PII findings.
|
|
303
|
+
function isPaymentCardNumber(cardNumber: string): boolean {
|
|
304
|
+
return /^[0-9]+$/.test(cardNumber) && cardNumber.length >= 13 && cardNumber.length <= 19 && hasKnownPaymentCardPrefix(cardNumber) && passesLuhnCheck(cardNumber);
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
// Recognises common issuer prefixes by delegating per network because each one has different
|
|
308
|
+
// length and IIN-range rules; keeping those branches separate makes false-positive tuning safer.
|
|
309
|
+
function hasKnownPaymentCardPrefix(cardNumber: string): boolean {
|
|
310
|
+
return isVisaPaymentCard(cardNumber)
|
|
311
|
+
|| isMastercardPaymentCard(cardNumber)
|
|
312
|
+
|| isAmericanExpressPaymentCard(cardNumber)
|
|
313
|
+
|| isDiscoverPaymentCard(cardNumber)
|
|
314
|
+
|| isDinersPaymentCard(cardNumber)
|
|
315
|
+
|| isJcbPaymentCard(cardNumber);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
// Visa cards start with 4 and commonly use 13, 16, or 19 digits.
|
|
319
|
+
function isVisaPaymentCard(cardNumber: string): boolean {
|
|
320
|
+
return cardNumber.startsWith("4") && isPaymentCardLength(cardNumber, [13, 16, 19]);
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// Mastercard cards use 51-55 and 2221-2720 IIN ranges with 16 digits.
|
|
324
|
+
function isMastercardPaymentCard(cardNumber: string): boolean {
|
|
325
|
+
const firstTwoDigits = Number(cardNumber.slice(0, 2));
|
|
326
|
+
const firstFourDigits = Number(cardNumber.slice(0, 4));
|
|
327
|
+
return (isInRange(firstTwoDigits, 51, 55) || isInRange(firstFourDigits, 2221, 2720)) && isPaymentCardLength(cardNumber, [16]);
|
|
328
|
+
}
|
|
329
|
+
|
|
330
|
+
// American Express cards use 34/37 prefixes with 15 digits.
|
|
331
|
+
function isAmericanExpressPaymentCard(cardNumber: string): boolean {
|
|
332
|
+
return (cardNumber.startsWith("34") || cardNumber.startsWith("37")) && isPaymentCardLength(cardNumber, [15]);
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
// Discover cards use 6011, 65, or 644-649 prefixes with 16 or 19 digits.
|
|
336
|
+
function isDiscoverPaymentCard(cardNumber: string): boolean {
|
|
337
|
+
const firstThreeDigits = Number(cardNumber.slice(0, 3));
|
|
338
|
+
return (cardNumber.startsWith("6011") || cardNumber.startsWith("65") || isInRange(firstThreeDigits, 644, 649)) && isPaymentCardLength(cardNumber, [16, 19]);
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
// Diners Club cards use 300-305, 36, 38, or 39 prefixes with 14 digits.
|
|
342
|
+
function isDinersPaymentCard(cardNumber: string): boolean {
|
|
343
|
+
const firstThreeDigits = Number(cardNumber.slice(0, 3));
|
|
344
|
+
return (isInRange(firstThreeDigits, 300, 305) || cardNumber.startsWith("36") || cardNumber.startsWith("38") || cardNumber.startsWith("39")) && isPaymentCardLength(cardNumber, [14]);
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
// JCB cards use 3528-3589 prefixes with 16-19 digits.
|
|
348
|
+
function isJcbPaymentCard(cardNumber: string): boolean {
|
|
349
|
+
const firstFourDigits = Number(cardNumber.slice(0, 4));
|
|
350
|
+
return isInRange(firstFourDigits, 3528, 3589) && isPaymentCardLength(cardNumber, [16, 17, 18, 19]);
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
// Network-specific length guard kept separate so the prefix table reads as data, not arithmetic.
|
|
354
|
+
function isPaymentCardLength(cardNumber: string, allowedLengths: number[]): boolean {
|
|
355
|
+
return allowedLengths.includes(cardNumber.length);
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
// Inclusive numeric range helper for issuer identification number ranges.
|
|
359
|
+
function isInRange(candidateNumber: number, minimum: number, maximum: number): boolean {
|
|
360
|
+
return candidateNumber >= minimum && candidateNumber <= maximum;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
// Standard Luhn checksum over normalized digits; invalid checksum keeps long numeric identifiers quiet.
|
|
364
|
+
function passesLuhnCheck(cardNumber: string): boolean {
|
|
365
|
+
const digits = [...cardNumber].reverse().map((digit) => Number(digit));
|
|
366
|
+
const sum = digits.reduce((total, digit, index) => total + luhnDigitContribution(digit, index), 0);
|
|
367
|
+
return sum % 10 === 0;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
// Doubles every second digit from the right and folds two-digit products per the Luhn algorithm.
|
|
371
|
+
function luhnDigitContribution(digit: number, indexFromRight: number): number {
|
|
372
|
+
if (indexFromRight % 2 === 0) {
|
|
373
|
+
return digit;
|
|
374
|
+
}
|
|
375
|
+
const doubled = digit * 2;
|
|
376
|
+
return doubled > 9 ? doubled - 9 : doubled;
|
|
377
|
+
}
|
|
378
|
+
|
|
243
379
|
// All-hex strings - typical for SHA digests, content hashes, and tooling identifiers.
|
|
244
380
|
function isHexDigest(candidateText: string): boolean {
|
|
245
381
|
return /^[0-9a-f]+$/i.test(candidateText);
|
package/src/test-block-rules.ts
CHANGED
|
@@ -21,6 +21,7 @@ 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
|
|
|
@@ -64,6 +65,9 @@ function assertionQualityChecks(block: FunctionBlock, body: string): TestBlockCh
|
|
|
64
65
|
* `test-quality.magic-number-assertion` with stable literal metadata for downstream review tools.
|
|
65
66
|
*/
|
|
66
67
|
function pushMagicNumberAssertionFindings(file: SourceFile, block: FunctionBlock, body: string, findings: Finding[]): void {
|
|
68
|
+
if (isConstantContractTestName(block.name)) {
|
|
69
|
+
return;
|
|
70
|
+
}
|
|
67
71
|
for (const assertion of magicNumberAssertions(body)) {
|
|
68
72
|
findings.push(
|
|
69
73
|
blockFindingWithMetadata({
|
|
@@ -132,7 +136,7 @@ function analyseSetupBloat(file: SourceFile, block: FunctionBlock, body: string,
|
|
|
132
136
|
function analyseTestStructureChecks(file: SourceFile, block: FunctionBlock, body: string, findings: Finding[]): void {
|
|
133
137
|
const checks: Array<[string, boolean, string]> = [
|
|
134
138
|
["test-quality.sleep-in-test", /\b(setTimeout|sleep|waitForTimeout)\s*\(/.test(body), "Test sleeps instead of synchronising on behaviour."],
|
|
135
|
-
["test-quality.loop-in-test",
|
|
139
|
+
["test-quality.loop-in-test", controlFlowContainsNonFixtureLoop(body), "Test contains loop logic around assertions."],
|
|
136
140
|
["test-quality.conditional-logic", controlFlowContainsAssertion(body, /\b(?:if|switch)\b/g), "Test contains conditional logic around assertions."],
|
|
137
141
|
["test-quality.only-skip", /\.(only|skip)\s*\(/.test(body), "Focused or skipped test is committed."],
|
|
138
142
|
];
|
|
@@ -143,6 +147,100 @@ function analyseTestStructureChecks(file: SourceFile, block: FunctionBlock, body
|
|
|
143
147
|
}
|
|
144
148
|
}
|
|
145
149
|
|
|
150
|
+
// Loop variant of `controlFlowContainsAssertion` that suppresses fixture loops (table-test pattern):
|
|
151
|
+
// loops over a literal array or `Object.entries|keys|values` of a literal where every code path
|
|
152
|
+
// inside the body reaches an assertion. The existing rule fires on ANY loop wrapping an assertion;
|
|
153
|
+
// this widens the precision so parametric coverage doesn't read as control-flow noise.
|
|
154
|
+
function controlFlowContainsNonFixtureLoop(source: string): boolean {
|
|
155
|
+
for (const match of source.matchAll(/\b(?:for|while)\b/g)) {
|
|
156
|
+
const start = match.index ?? 0;
|
|
157
|
+
const segment = controlFlowSegment(source, start);
|
|
158
|
+
if (!hasAssertion(segment)) {
|
|
159
|
+
continue;
|
|
160
|
+
}
|
|
161
|
+
if (isFixtureLoop(source, start, segment)) {
|
|
162
|
+
continue;
|
|
163
|
+
}
|
|
164
|
+
return true;
|
|
165
|
+
}
|
|
166
|
+
return false;
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// A "fixture loop" is the table-test pattern: iterable is an inline fixture OR a local const-bound
|
|
170
|
+
// fixture table, AND every path through the body terminates in an assertion call. Guard branches
|
|
171
|
+
// without assertions are allowed, but assertion-bearing branches still opt out.
|
|
172
|
+
function isFixtureLoop(source: string, start: number, segment: string): boolean {
|
|
173
|
+
const braceIndex = segment.indexOf("{");
|
|
174
|
+
const header = braceIndex === -1 ? segment : segment.slice(0, braceIndex);
|
|
175
|
+
if (!hasFixtureIterable(source, start, header)) {
|
|
176
|
+
return false;
|
|
177
|
+
}
|
|
178
|
+
if (braceIndex === -1) {
|
|
179
|
+
return false;
|
|
180
|
+
}
|
|
181
|
+
const body = segment.slice(braceIndex + 1, segment.length - 1);
|
|
182
|
+
if (hasUnsafeFixtureLoopBranch(source.slice(0, start + braceIndex + 1), body)) {
|
|
183
|
+
return false;
|
|
184
|
+
}
|
|
185
|
+
const statements = body.split(/[;\n]/).map((statement) => statement.trim()).filter((statement) => statement.length > 0 && statement !== "}" && !/^(?:break|continue)\b/.test(statement));
|
|
186
|
+
const lastStatement = statements[statements.length - 1] ?? "";
|
|
187
|
+
return /^(?:assert\.[a-z]+\s*\(|expect\s*\(|[a-z][A-Za-z0-9_]*\.should(?:Be|Equal)?\s*\()/i.test(lastStatement);
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// Fixture sweeps may carry invariant guards such as `if (expectedIds.has(case.id))`; other branches
|
|
191
|
+
// still opt out because they can hide case-specific expectations inside the loop.
|
|
192
|
+
function hasUnsafeFixtureLoopBranch(sourceBeforeLoopBody: string, body: string): boolean {
|
|
193
|
+
if (/\bswitch\s*\(|\bcase\s|\bdefault\s*:/.test(body)) {
|
|
194
|
+
return true;
|
|
195
|
+
}
|
|
196
|
+
for (const match of body.matchAll(/\bif\b/g)) {
|
|
197
|
+
const start = match.index ?? 0;
|
|
198
|
+
const segment = controlFlowSegment(body, start);
|
|
199
|
+
const sourceBeforeCondition = `${sourceBeforeLoopBody}${body.slice(0, start)}`;
|
|
200
|
+
if (hasAssertion(segment) && !isInvariantAssertionConditional(sourceBeforeCondition, sourceBeforeCondition.length, segment)) {
|
|
201
|
+
return true;
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
return false;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// Inline fixture tables cover `for (... of [...])` and `Object.entries({ ... })`. Const-bound
|
|
208
|
+
// tables cover the common contract-test shape where the named case table is declared immediately
|
|
209
|
+
// before the sweep for readability.
|
|
210
|
+
function hasFixtureIterable(source: string, start: number, header: string): boolean {
|
|
211
|
+
if (/\bof\s*\[/.test(header) || /\bof\s+Object\.(?:entries|keys|values)\s*\(/.test(header)) {
|
|
212
|
+
return true;
|
|
213
|
+
}
|
|
214
|
+
const iterableName = header.match(/\bof\s+([A-Za-z_$][A-Za-z0-9_$]*)\b/)?.[1] ?? "";
|
|
215
|
+
return iterableName !== "" && (isFixtureConstantIterableName(iterableName) || hasConstBoundFixtureIterable(source.slice(0, start), iterableName));
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
// Accepts const-bound fixture loops only when the iterable name and initializer both look like a
|
|
219
|
+
// deterministic case table or discovered fixture set.
|
|
220
|
+
function hasConstBoundFixtureIterable(sourceBeforeLoop: string, iterableName: string): boolean {
|
|
221
|
+
if (!isFixtureIterableName(iterableName)) {
|
|
222
|
+
return false;
|
|
223
|
+
}
|
|
224
|
+
const assignment = sourceBeforeLoop.match(new RegExp(`\\bconst\\s+${escapeRegex(iterableName)}\\s*=\\s*([\\s\\S]*?);\\s*$`));
|
|
225
|
+
const initializer = assignment?.[1]?.trim() ?? "";
|
|
226
|
+
return initializer.startsWith("[") || /^Object\.(?:entries|keys|values)\s*\(/.test(initializer) || isFixtureDiscoveryCall(initializer);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// Limits const-bound loop suppression to table/sweep vocabulary rather than arbitrary arrays.
|
|
230
|
+
function isFixtureIterableName(name: string): boolean {
|
|
231
|
+
return /(?:agents|cases|checks|entries|examples|fixtures|files|ids|paths|records|scenarios|scores|snapshots)$/i.test(name);
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
// UPPER_CASE fixture constants such as HARNESS_CHECKS are named case tables even when imported.
|
|
235
|
+
function isFixtureConstantIterableName(name: string): boolean {
|
|
236
|
+
return /^[A-Z0-9_]+$/.test(name) && isFixtureIterableName(name);
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
// Recognises local fixture discovery calls used by contract sweeps without accepting unknown calls.
|
|
240
|
+
function isFixtureDiscoveryCall(initializer: string): boolean {
|
|
241
|
+
return /\b(?:glob|globSync|readdir|readdirSync|discover[A-Za-z0-9_$]*|find[A-Za-z0-9_$]*|list[A-Za-z0-9_$]*)\s*\(/.test(initializer);
|
|
242
|
+
}
|
|
243
|
+
|
|
146
244
|
// Integration, contract, smoke, and performance tests naturally need more environment setup than
|
|
147
245
|
// focused unit tests; keep the default strict for unit tests and double it for broad-flow suites.
|
|
148
246
|
function setupBloatThreshold(file: SourceFile, config: Config): number {
|
|
@@ -161,13 +259,28 @@ function controlFlowContainsAssertion(source: string, pattern: RegExp): boolean
|
|
|
161
259
|
for (const match of source.matchAll(pattern)) {
|
|
162
260
|
const start = match.index ?? 0;
|
|
163
261
|
const segment = controlFlowSegment(source, start);
|
|
164
|
-
if (hasAssertion(segment)) {
|
|
262
|
+
if (hasAssertion(segment) && !isInvariantAssertionConditional(source, start, segment)) {
|
|
165
263
|
return true;
|
|
166
264
|
}
|
|
167
265
|
}
|
|
168
266
|
return false;
|
|
169
267
|
}
|
|
170
268
|
|
|
269
|
+
// Accepts guard conditionals whose assertion proves a shared invariant rather than branch policy.
|
|
270
|
+
function isInvariantAssertionConditional(source: string, start: number, segment: string): boolean {
|
|
271
|
+
const condition = segment.slice(0, Math.max(0, segment.indexOf("{"))).trim();
|
|
272
|
+
return isFixtureMembershipGuard(source.slice(0, start), condition);
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
// Membership guards over const-bound fixtures keep invariant sweeps readable.
|
|
276
|
+
function isFixtureMembershipGuard(sourceBeforeCondition: string, condition: string): boolean {
|
|
277
|
+
const guardTarget = condition.match(/\b([A-Za-z_$][A-Za-z0-9_$]*)\.(?:has|includes)\s*\(/)?.[1] ?? "";
|
|
278
|
+
if (!guardTarget) {
|
|
279
|
+
return false;
|
|
280
|
+
}
|
|
281
|
+
return new RegExp(`\\bconst\\s+${escapeRegex(guardTarget)}\\s*=\\s*(?:new\\s+Set\\s*\\(|\\[)`).test(sourceBeforeCondition);
|
|
282
|
+
}
|
|
283
|
+
|
|
171
284
|
// Captures the smallest control-flow segment so assertion detection does not scan the whole test.
|
|
172
285
|
function controlFlowSegment(source: string, start: number): string {
|
|
173
286
|
const lineEnd = source.indexOf("\n", start);
|
|
@@ -271,31 +384,51 @@ function isNoThrowOnlyTest(source: string): boolean {
|
|
|
271
384
|
}
|
|
272
385
|
|
|
273
386
|
// Pulls every numeric expected value out of `expect(...).toBe(n)` and `assert.equal(actual, n)`
|
|
274
|
-
// shapes.
|
|
275
|
-
//
|
|
387
|
+
// shapes. Small cardinalities and length/count matchers are excluded because the literal often is
|
|
388
|
+
// the test contract; larger opaque values still surface for naming or rationale.
|
|
276
389
|
function magicNumberAssertions(source: string): Array<{ value: number }> {
|
|
277
390
|
return MAGIC_NUMBER_ASSERTION_PATTERNS.flatMap((candidate) => magicNumberAssertionMatches(source, candidate));
|
|
278
391
|
}
|
|
279
392
|
|
|
280
393
|
const MAGIC_NUMBER_ASSERTION_PATTERNS: MagicNumberAssertionPattern[] = [
|
|
281
|
-
{ pattern: /\bexpect\s*\(\s*([^)]+?)\s*\)\s*\.\s*to(?:Be|Equal|HaveLength|HaveCount)\s*\(\s*(-?\d+(?:\.\d+)?)\s*\)/g, expressionIndex: 1,
|
|
394
|
+
{ pattern: /\bexpect\s*\(\s*([^)]+?)\s*\)\s*\.\s*(to(?:Be|Equal|HaveLength|HaveCount))\s*\(\s*(-?\d+(?:\.\d+)?)\s*\)/g, expressionIndex: 1, matcherIndex: 2, valueIndex: 3 },
|
|
282
395
|
{ pattern: /\bassert\.(?:equal|strictEqual|deepEqual)\s*\(\s*([^,\n]+?)\s*,\s*(-?\d+(?:\.\d+)?)(?:\s*,|\s*\))/g, expressionIndex: 1, valueIndex: 2 },
|
|
283
396
|
];
|
|
284
397
|
|
|
285
398
|
// Extracts reportable numeric literals for one assertion grammar while keeping HTTP statuses quiet.
|
|
286
399
|
function magicNumberAssertionMatches(source: string, candidate: MagicNumberAssertionPattern): Array<{ value: number }> {
|
|
287
|
-
const ignored = new Set([-1, 0, 1]);
|
|
288
400
|
const results: Array<{ value: number }> = [];
|
|
289
401
|
for (const match of source.matchAll(candidate.pattern)) {
|
|
290
402
|
const expression = match[candidate.expressionIndex] ?? "";
|
|
403
|
+
const matcher = candidate.matcherIndex === undefined ? "" : match[candidate.matcherIndex] ?? "";
|
|
291
404
|
const expectedNumber = Number(match[candidate.valueIndex] ?? "0");
|
|
292
|
-
if (!
|
|
405
|
+
if (!isIgnoredMagicNumberAssertion(expression, matcher, expectedNumber)) {
|
|
293
406
|
results.push({ value: expectedNumber });
|
|
294
407
|
}
|
|
295
408
|
}
|
|
296
409
|
return results;
|
|
297
410
|
}
|
|
298
411
|
|
|
412
|
+
// Centralises the rule's non-findings so cardinal, count, and HTTP-status exemptions stay aligned.
|
|
413
|
+
function isIgnoredMagicNumberAssertion(expression: string, matcher: string, expectedNumber: number): boolean {
|
|
414
|
+
return isSmallCardinal(expectedNumber) || isLengthOrCountMatcher(matcher) || isHttpStatusAssertion(expression, expectedNumber);
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
// Small integer cardinals usually express the expected case count directly.
|
|
418
|
+
function isSmallCardinal(cardinal: number): boolean {
|
|
419
|
+
return Number.isInteger(cardinal) && cardinal >= -1 && cardinal <= 3;
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
// Length/count matchers already name the measurement, so the numeric literal is the assertion.
|
|
423
|
+
function isLengthOrCountMatcher(matcher: string): boolean {
|
|
424
|
+
return matcher === "toHaveLength" || matcher === "toHaveCount";
|
|
425
|
+
}
|
|
426
|
+
|
|
427
|
+
// Contract-named tests may assert the documented number directly; the name supplies the rationale.
|
|
428
|
+
function isConstantContractTestName(name: string): boolean {
|
|
429
|
+
return /\b(?:constant|threshold|limit|budget|default|contract)\b/i.test(name);
|
|
430
|
+
}
|
|
431
|
+
|
|
299
432
|
// HTTP response status codes are intentionally numeric at assertion sites; naming every 200/404
|
|
300
433
|
// would add ceremony without making the test clearer.
|
|
301
434
|
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,24 +103,45 @@ 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
|
|
|
108
|
-
//
|
|
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
|
+
|
|
136
|
+
/*
|
|
137
|
+
* Serializes a test YAML config object from the root indentation level. Every fixture YAML is
|
|
138
|
+
* stamped with the required `schemaVersion: gruff-ts.config.v0.1` field at the top (per ADR-004)
|
|
139
|
+
* because the config loader throws when it's missing. The schema invariant is preserved by
|
|
140
|
+
* spreading the input object AFTER schemaVersion so callers can't accidentally override it; tests
|
|
141
|
+
* that need to assert against a missing schemaVersion must write the YAML by hand instead.
|
|
142
|
+
*/
|
|
109
143
|
export function yamlConfigFixture(configObject: Record<string, unknown>): string {
|
|
110
|
-
return yamlConfigObject(configObject, 0);
|
|
144
|
+
return yamlConfigObject({ schemaVersion: "gruff-ts.config.v0.1", ...configObject }, 0);
|
|
111
145
|
}
|
|
112
146
|
|
|
113
147
|
// Serializes nested config objects using the fixture YAML subset.
|
|
@@ -315,8 +349,15 @@ DATABASE_URL=${POSTGRES_URL_FIXTURE_VALUE}
|
|
|
315
349
|
JWT_TOKEN=${JWT_FIXTURE_VALUE}
|
|
316
350
|
OPENAI_API_KEY=${OPENAI_KEY_FIXTURE_VALUE}
|
|
317
351
|
PATIENT_SSN=${SSN_FIXTURE_VALUE}
|
|
352
|
+
PATIENT_MBI=${MBI_FIXTURE_VALUE}
|
|
318
353
|
API_TOKEN=${API_TOKEN_FIXTURE_VALUE}
|
|
319
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
|
+
}),
|
|
320
361
|
"package.json": JSON.stringify({
|
|
321
362
|
scripts: {
|
|
322
363
|
postinstall: "node scripts/setup.js",
|
|
@@ -333,7 +374,6 @@ API_TOKEN=${API_TOKEN_FIXTURE_VALUE}
|
|
|
333
374
|
}),
|
|
334
375
|
".github/workflows/risky.yml": githubActionsCoverageWorkflowSource(),
|
|
335
376
|
"bin/bad.js": "#!/usr/bin/env node\nconsole.log('ok');\n",
|
|
336
|
-
"styles/component.css": ".one { color: red; }\n.two { color: blue; }\n.three { color: green; }\n.four { color: yellow; }\n",
|
|
337
377
|
"tsconfig.json": JSON.stringify({
|
|
338
378
|
compilerOptions: {
|
|
339
379
|
strict: false,
|
|
@@ -377,8 +417,10 @@ const active = true;
|
|
|
377
417
|
const xx = 1;
|
|
378
418
|
const ctx = { request: 1 };
|
|
379
419
|
const disableCache = true;
|
|
380
|
-
const
|
|
381
|
-
const
|
|
420
|
+
const DATABASE_URL = "/health";
|
|
421
|
+
const databaseUrl = "/healthz";
|
|
422
|
+
const project_path = "src";
|
|
423
|
+
const projectPath = "src/index.ts";
|
|
382
424
|
const unsafeAny: any = {};
|
|
383
425
|
const embeddedToken = "${HIGH_ENTROPY_FIXTURE_VALUE}";
|
|
384
426
|
const maxRetryLimit = 12;
|
|
@@ -428,6 +470,10 @@ export function process(flag: boolean, userInput: string, userId: string, userId
|
|
|
428
470
|
fetch(req.body.url);
|
|
429
471
|
res.redirect(req.query.next);
|
|
430
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 });
|
|
431
477
|
Math.random();
|
|
432
478
|
document.write(userInput);
|
|
433
479
|
element.innerHTML = userInput;
|
|
@@ -458,7 +504,7 @@ export function process(flag: boolean, userInput: string, userId: string, userId
|
|
|
458
504
|
try {
|
|
459
505
|
riskyWork();
|
|
460
506
|
} catch (error) {
|
|
461
|
-
//
|
|
507
|
+
// FIXME
|
|
462
508
|
}
|
|
463
509
|
if (flag) {
|
|
464
510
|
if (userId) {
|
|
@@ -588,8 +634,10 @@ ${"test"}("setup bloat and control flow", () => {
|
|
|
588
634
|
const three = buildThree();
|
|
589
635
|
if (one) {
|
|
590
636
|
for (const setupEntry of [one, two, three]) {
|
|
591
|
-
|
|
592
|
-
|
|
637
|
+
if (setupEntry) {
|
|
638
|
+
sleep(setupEntry);
|
|
639
|
+
assert.ok(setupEntry);
|
|
640
|
+
}
|
|
593
641
|
}
|
|
594
642
|
}
|
|
595
643
|
setTimeout(() => undefined, 1);
|
|
@@ -606,12 +654,10 @@ function catalogueCoverageOptions(): AnalyseProjectOptions {
|
|
|
606
654
|
rules: {
|
|
607
655
|
"complexity.cognitive": { threshold: 3, severity: "warning" },
|
|
608
656
|
"complexity.cyclomatic": { threshold: 2, severity: "warning" },
|
|
609
|
-
"complexity.npath": { threshold: 2, severity: "warning" },
|
|
610
657
|
"design.large-module-concentration": { threshold: 35, severity: "advisory", options: { minFiles: 4, minLines: 8 } },
|
|
611
658
|
"size.file-length": { threshold: 8, severity: "warning" },
|
|
612
659
|
"size.function-length": { threshold: 8, severity: "warning" },
|
|
613
660
|
"size.parameter-count": { threshold: 3, severity: "warning" },
|
|
614
|
-
"size.stylesheet-length": { threshold: 3, severity: "warning" },
|
|
615
661
|
"test-quality.setup-bloat": { threshold: 2, severity: "advisory" },
|
|
616
662
|
},
|
|
617
663
|
},
|