@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
|
@@ -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);
|
|
@@ -0,0 +1,411 @@
|
|
|
1
|
+
// Static-analysis-redundant assertion scanner for test blocks. It reports tests that only prove
|
|
2
|
+
// TypeScript-visible code shape, keeping the main per-test-block pass focused on orchestration.
|
|
3
|
+
import { type FunctionBlock } from "./blocks.ts";
|
|
4
|
+
import { type SourceFile } from "./discovery.ts";
|
|
5
|
+
import { makeFinding } from "./findings.ts";
|
|
6
|
+
import { lineOffset } from "./findings-helpers.ts";
|
|
7
|
+
import type { Confidence, Finding } from "./types.ts";
|
|
8
|
+
|
|
9
|
+
// Candidate assertion contract promoted into a real Finding after its test-block line is known.
|
|
10
|
+
interface StaticAnalysisRedundantAssertion {
|
|
11
|
+
assertion: string;
|
|
12
|
+
staticFact: string;
|
|
13
|
+
sourceProof?: string;
|
|
14
|
+
confidence: Confidence;
|
|
15
|
+
recommendation: string;
|
|
16
|
+
index: number;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// Non-nullable declaration evidence captured from a test block before assertion matching runs.
|
|
20
|
+
interface NonNullableReturnDeclaration {
|
|
21
|
+
name: string;
|
|
22
|
+
returnType: string;
|
|
23
|
+
lineOffset: number;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
// Full-file source context used to prove imports and declarations outside the current test body.
|
|
27
|
+
export interface StaticAnalysisSourceContext {
|
|
28
|
+
source: string;
|
|
29
|
+
codeSource: string;
|
|
30
|
+
startLine: number;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
// One TypeScript-visible function fact and the line that proves it to reviewers.
|
|
34
|
+
interface StaticFunctionFact {
|
|
35
|
+
staticFact: string;
|
|
36
|
+
sourceProof: string;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
// Function facts are split by identifier and namespace import so member lookups stay explicit.
|
|
40
|
+
interface StaticFunctionFacts {
|
|
41
|
+
identifiers: Map<string, StaticFunctionFact>;
|
|
42
|
+
namespaceImports: Map<string, StaticFunctionFact>;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
const TYPEOF_FUNCTION_ASSERTION_PATTERNS = [
|
|
46
|
+
/\bassert\.(?:equal|strictEqual)\s*\(\s*typeof\s+([A-Za-z_$][A-Za-z0-9_$]*(?:\.[A-Za-z_$][A-Za-z0-9_$]*)*)\s*,\s*["']function["']\s*(?:,[^)]*)?\)/g,
|
|
47
|
+
/\bassert\.(?:equal|strictEqual)\s*\(\s*["']function["']\s*,\s*typeof\s+([A-Za-z_$][A-Za-z0-9_$]*(?:\.[A-Za-z_$][A-Za-z0-9_$]*)*)\s*(?:,[^)]*)?\)/g,
|
|
48
|
+
/\bexpect\s*\(\s*typeof\s+([A-Za-z_$][A-Za-z0-9_$]*(?:\.[A-Za-z_$][A-Za-z0-9_$]*)*)\s*\)\s*\.\s*to(?:Be|Equal|StrictEqual)\s*\(\s*["']function["']\s*\)/g,
|
|
49
|
+
] as const;
|
|
50
|
+
|
|
51
|
+
const DIRECT_CONSTRUCTION_ASSERTION_PATTERNS = [
|
|
52
|
+
/\bassert\.ok\s*\(\s*new\s+([A-Z][A-Za-z0-9_$]*)\s*\([^)]*\)\s+instanceof\s+\1\s*(?:,[^)]*)?\)/g,
|
|
53
|
+
/\bassert\.(?:equal|strictEqual)\s*\(\s*new\s+([A-Z][A-Za-z0-9_$]*)\s*\([^)]*\)\s+instanceof\s+\1\s*,\s*true\s*(?:,[^)]*)?\)/g,
|
|
54
|
+
/\bexpect\s*\(\s*new\s+([A-Z][A-Za-z0-9_$]*)\s*\([^)]*\)\s*\)\s*\.\s*toBeInstanceOf\s*\(\s*\1\s*\)/g,
|
|
55
|
+
] as const;
|
|
56
|
+
|
|
57
|
+
const NON_NULLABLE_ASSERTION_PATTERNS = [
|
|
58
|
+
/\bassert\.not(?:Equal|StrictEqual)\s*\(\s*([A-Za-z_$][A-Za-z0-9_$]*)\s*\([^)]*\)\s*,\s*(?:null|undefined)\s*(?:,[^)]*)?\)/g,
|
|
59
|
+
/\bexpect\s*\(\s*([A-Za-z_$][A-Za-z0-9_$]*)\s*\([^)]*\)\s*\)\s*\.\s*toBeDefined\s*\(\s*\)/g,
|
|
60
|
+
/\bexpect\s*\(\s*([A-Za-z_$][A-Za-z0-9_$]*)\s*\([^)]*\)\s*\)\s*\.\s*not\s*\.\s*toBeNull\s*\(\s*\)/g,
|
|
61
|
+
] as const;
|
|
62
|
+
|
|
63
|
+
const NON_NULLABLE_DECLARATION_PATTERNS = [
|
|
64
|
+
/\bfunction\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*\([^)]*\)\s*:\s*([A-Za-z_$][A-Za-z0-9_$<>,\s.[\]]*)\s*\{/g,
|
|
65
|
+
/\bconst\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=\s*(?:async\s*)?\([^)]*\)\s*:\s*([A-Za-z_$][A-Za-z0-9_$<>,\s.[\]]*)\s*=>/g,
|
|
66
|
+
] as const;
|
|
67
|
+
|
|
68
|
+
/*
|
|
69
|
+
* Reports stable `test-quality.static-analysis-redundant-test` findings. The contract keeps source
|
|
70
|
+
* proof and recommendation in metadata because reviewers need the assertion and proof side by side.
|
|
71
|
+
*/
|
|
72
|
+
export function pushStaticAnalysisRedundantTestFindings(file: SourceFile, block: FunctionBlock, rawBody: string, codeBody: string, staticContext: StaticAnalysisSourceContext, findings: Finding[]): void {
|
|
73
|
+
for (const candidate of staticAnalysisRedundantAssertions(file, block, rawBody, codeBody, staticContext)) {
|
|
74
|
+
const line = block.startLine + lineOffset(rawBody, candidate.index);
|
|
75
|
+
findings.push(
|
|
76
|
+
makeFinding({
|
|
77
|
+
ruleId: "test-quality.static-analysis-redundant-test",
|
|
78
|
+
message: `Static-analysis-redundant candidate: ${candidate.confidence} confidence. Test \`${block.name}\` asserts code shape rather than behaviour: ${candidate.assertion}.`,
|
|
79
|
+
filePath: file.displayPath,
|
|
80
|
+
line,
|
|
81
|
+
severity: "advisory",
|
|
82
|
+
pillar: "test-quality",
|
|
83
|
+
confidence: candidate.confidence,
|
|
84
|
+
symbol: block.name,
|
|
85
|
+
remediation: candidate.recommendation,
|
|
86
|
+
metadata: {
|
|
87
|
+
testFile: file.displayPath,
|
|
88
|
+
testMethod: block.name,
|
|
89
|
+
assertion: candidate.assertion,
|
|
90
|
+
staticFact: candidate.staticFact,
|
|
91
|
+
sourceProof: candidate.sourceProof ?? `${file.displayPath}:${line}`,
|
|
92
|
+
confidence: candidate.confidence,
|
|
93
|
+
recommendation: candidate.recommendation,
|
|
94
|
+
},
|
|
95
|
+
}),
|
|
96
|
+
);
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
// Runs the three static-shape detectors and preserves deterministic source-order emission.
|
|
101
|
+
function staticAnalysisRedundantAssertions(file: SourceFile, block: FunctionBlock, rawSource: string, codeSource: string, staticContext: StaticAnalysisSourceContext): StaticAnalysisRedundantAssertion[] {
|
|
102
|
+
return [
|
|
103
|
+
...typeofFunctionAssertions(file, rawSource, codeSource, staticContext),
|
|
104
|
+
...directConstructionInstanceAssertions(file, rawSource, codeSource),
|
|
105
|
+
...nonNullableReturnAssertions(file, block, rawSource, codeSource),
|
|
106
|
+
].sort((left, right) => left.index - right.index);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
// Detects `typeof x === "function"`-style assertions when TypeScript already proves the function.
|
|
110
|
+
function typeofFunctionAssertions(file: SourceFile, rawSource: string, codeSource: string, staticContext: StaticAnalysisSourceContext): StaticAnalysisRedundantAssertion[] {
|
|
111
|
+
const functionFacts = staticFunctionFacts(file, staticContext);
|
|
112
|
+
return TYPEOF_FUNCTION_ASSERTION_PATTERNS.flatMap((pattern) => typeofFunctionAssertionsForPattern(file, rawSource, codeSource, functionFacts, pattern));
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
// Evaluates one typeof-function assertion grammar while keeping executable-source checks local.
|
|
116
|
+
function typeofFunctionAssertionsForPattern(file: SourceFile, rawSource: string, codeSource: string, functionFacts: StaticFunctionFacts, pattern: RegExp): StaticAnalysisRedundantAssertion[] {
|
|
117
|
+
return [...rawSource.matchAll(pattern)]
|
|
118
|
+
.map((match) => typeofFunctionCandidateFromMatch(file, rawSource, codeSource, functionFacts, match))
|
|
119
|
+
.filter(isStaticAnalysisRedundantAssertion);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
// Builds one typeof-function candidate only when the expression has static declaration evidence.
|
|
123
|
+
function typeofFunctionCandidateFromMatch(file: SourceFile, rawSource: string, codeSource: string, functionFacts: StaticFunctionFacts, match: RegExpMatchArray): StaticAnalysisRedundantAssertion | undefined {
|
|
124
|
+
const index = match.index ?? 0;
|
|
125
|
+
if (!isExecutableAssertionAt(codeSource, index)) {
|
|
126
|
+
return undefined;
|
|
127
|
+
}
|
|
128
|
+
const expression = match[1] ?? "";
|
|
129
|
+
const fact = staticFunctionFactForExpression(expression, functionFacts);
|
|
130
|
+
if (!fact) {
|
|
131
|
+
return undefined;
|
|
132
|
+
}
|
|
133
|
+
return staticRedundantCandidate({
|
|
134
|
+
file,
|
|
135
|
+
source: rawSource,
|
|
136
|
+
index,
|
|
137
|
+
assertion: normalizedAssertionText(match[0] ?? ""),
|
|
138
|
+
staticFact: fact.staticFact,
|
|
139
|
+
sourceProof: fact.sourceProof,
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
// Gathers declaration and import facts from the full source context once per test-block scan.
|
|
144
|
+
function staticFunctionFacts(file: SourceFile, context: StaticAnalysisSourceContext): StaticFunctionFacts {
|
|
145
|
+
const facts: StaticFunctionFacts = { identifiers: new Map(), namespaceImports: new Map() };
|
|
146
|
+
pushFunctionDeclarationFacts(file, context, facts.identifiers);
|
|
147
|
+
pushConstFunctionFacts(file, context, facts.identifiers);
|
|
148
|
+
pushImportFunctionFacts(file, context, facts);
|
|
149
|
+
return facts;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// Adds facts for `function name()` declarations because comments and strings can mimic syntax.
|
|
153
|
+
function pushFunctionDeclarationFacts(file: SourceFile, context: StaticAnalysisSourceContext, facts: Map<string, StaticFunctionFact>): void {
|
|
154
|
+
for (const match of context.source.matchAll(/\bfunction\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*\(/g)) {
|
|
155
|
+
const index = match.index ?? 0;
|
|
156
|
+
if (!isExecutableFunctionDeclarationAt(context.codeSource, index)) {
|
|
157
|
+
continue;
|
|
158
|
+
}
|
|
159
|
+
const name = match[1] ?? "";
|
|
160
|
+
if (name) {
|
|
161
|
+
facts.set(name, {
|
|
162
|
+
staticFact: `\`${name}\` is declared as a function in this file.`,
|
|
163
|
+
sourceProof: sourceProof(file, context, index),
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
// Adds facts for const-bound functions because these declarations are common test helper shapes.
|
|
170
|
+
function pushConstFunctionFacts(file: SourceFile, context: StaticAnalysisSourceContext, facts: Map<string, StaticFunctionFact>): void {
|
|
171
|
+
const pattern = /\bconst\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=\s*(?:async\s*)?(?:function\b|(?:\([^)]*\)|[A-Za-z_$][A-Za-z0-9_$]*)\s*(?::\s*[^=;]+?)?=>)/g;
|
|
172
|
+
for (const match of context.source.matchAll(pattern)) {
|
|
173
|
+
const index = match.index ?? 0;
|
|
174
|
+
if (!isExecutableFunctionDeclarationAt(context.codeSource, index)) {
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
const name = match[1] ?? "";
|
|
178
|
+
if (name) {
|
|
179
|
+
facts.set(name, {
|
|
180
|
+
staticFact: `\`${name}\` is declared as a function-valued const in this file.`,
|
|
181
|
+
sourceProof: sourceProof(file, context, index),
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
// Dispatches named and namespace import evidence into separate maps for later expression lookup.
|
|
188
|
+
function pushImportFunctionFacts(file: SourceFile, context: StaticAnalysisSourceContext, facts: StaticFunctionFacts): void {
|
|
189
|
+
pushNamedImportFunctionFacts(file, context, facts.identifiers);
|
|
190
|
+
pushNamespaceImportFunctionFacts(file, context, facts.namespaceImports);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
// Adds facts for static named imports, including aliases, when the import is executable code.
|
|
194
|
+
function pushNamedImportFunctionFacts(file: SourceFile, context: StaticAnalysisSourceContext, facts: Map<string, StaticFunctionFact>): void {
|
|
195
|
+
for (const match of context.source.matchAll(/\bimport\s+(?!type\b)\{([^}]+)\}\s*from\b/g)) {
|
|
196
|
+
const index = match.index ?? 0;
|
|
197
|
+
if (!isExecutableImportAt(context.codeSource, index)) {
|
|
198
|
+
continue;
|
|
199
|
+
}
|
|
200
|
+
const proof = sourceProof(file, context, index);
|
|
201
|
+
for (const importedName of namedImportLocals(match[1] ?? "")) {
|
|
202
|
+
facts.set(importedName, namedImportFunctionFact(importedName, proof));
|
|
203
|
+
}
|
|
204
|
+
}
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
// Adds facts for namespace imports because `namespace.member` assertions need import-level proof.
|
|
208
|
+
function pushNamespaceImportFunctionFacts(file: SourceFile, context: StaticAnalysisSourceContext, facts: Map<string, StaticFunctionFact>): void {
|
|
209
|
+
for (const match of context.source.matchAll(/\bimport\s+\*\s+as\s+([A-Za-z_$][A-Za-z0-9_$]*)\s+from\b/g)) {
|
|
210
|
+
const index = match.index ?? 0;
|
|
211
|
+
if (!isExecutableImportAt(context.codeSource, index)) {
|
|
212
|
+
continue;
|
|
213
|
+
}
|
|
214
|
+
const namespaceName = match[1] ?? "";
|
|
215
|
+
if (namespaceName) {
|
|
216
|
+
facts.set(namespaceName, {
|
|
217
|
+
staticFact: `\`${namespaceName}\` is a static ES module namespace import.`,
|
|
218
|
+
sourceProof: sourceProof(file, context, index),
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
// Builds the reviewer-facing fact text for one named import.
|
|
225
|
+
function namedImportFunctionFact(importedName: string, proof: string): StaticFunctionFact {
|
|
226
|
+
return {
|
|
227
|
+
staticFact: `\`${importedName}\` is a static ES module named import, so TypeScript can validate the imported binding's declared function type without executing this test assertion.`,
|
|
228
|
+
sourceProof: proof,
|
|
229
|
+
};
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// Normalises `import { original as local }` clauses to the local binding names used in tests.
|
|
233
|
+
function namedImportLocals(importClause: string): string[] {
|
|
234
|
+
return importClause
|
|
235
|
+
.split(",")
|
|
236
|
+
.map((specifier) => namedImportLocal(specifier))
|
|
237
|
+
.filter((value): value is string => value !== undefined);
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// Returns the local binding name for one named import specifier, ignoring type-only entries.
|
|
241
|
+
function namedImportLocal(specifier: string): string | undefined {
|
|
242
|
+
const trimmed = specifier.trim();
|
|
243
|
+
if (trimmed === "" || /^type\b/.test(trimmed)) {
|
|
244
|
+
return undefined;
|
|
245
|
+
}
|
|
246
|
+
const aliased = trimmed.match(/\bas\s+([A-Za-z_$][A-Za-z0-9_$]*)$/);
|
|
247
|
+
if (aliased) {
|
|
248
|
+
return aliased[1];
|
|
249
|
+
}
|
|
250
|
+
const direct = trimmed.match(/^([A-Za-z_$][A-Za-z0-9_$]*)$/);
|
|
251
|
+
return direct?.[1];
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
// Looks up direct identifiers and namespace-member expressions against static import facts.
|
|
255
|
+
function staticFunctionFactForExpression(expression: string, facts: StaticFunctionFacts): StaticFunctionFact | undefined {
|
|
256
|
+
const direct = facts.identifiers.get(expression);
|
|
257
|
+
if (direct) {
|
|
258
|
+
return direct;
|
|
259
|
+
}
|
|
260
|
+
const namespaceMember = expression.match(/^([A-Za-z_$][A-Za-z0-9_$]*)\.([A-Za-z_$][A-Za-z0-9_$]*)$/);
|
|
261
|
+
if (!namespaceMember) {
|
|
262
|
+
return undefined;
|
|
263
|
+
}
|
|
264
|
+
const namespaceName = namespaceMember[1] ?? "";
|
|
265
|
+
const memberName = namespaceMember[2] ?? "";
|
|
266
|
+
const namespaceFact = facts.namespaceImports.get(namespaceName);
|
|
267
|
+
if (!namespaceFact || !memberName) {
|
|
268
|
+
return undefined;
|
|
269
|
+
}
|
|
270
|
+
return {
|
|
271
|
+
staticFact: `\`${expression}\` is a statically named member of the \`${namespaceName}\` namespace import, so TypeScript can validate that member's declared function type without executing this test assertion.`,
|
|
272
|
+
sourceProof: namespaceFact.sourceProof,
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
// Converts a byte offset in the source context into the display path and 1-based proof line.
|
|
277
|
+
function sourceProof(file: SourceFile, context: StaticAnalysisSourceContext, index: number): string {
|
|
278
|
+
return `${file.displayPath}:${context.startLine + lineOffset(context.source, index)}`;
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
// Detects self-instance assertions where the constructor expression itself proves the relationship.
|
|
282
|
+
function directConstructionInstanceAssertions(file: SourceFile, rawSource: string, codeSource: string): StaticAnalysisRedundantAssertion[] {
|
|
283
|
+
return DIRECT_CONSTRUCTION_ASSERTION_PATTERNS.flatMap((pattern) => directConstructionInstanceAssertionsForPattern(file, rawSource, codeSource, pattern));
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
// Evaluates one direct-construction assertion grammar against executable test code.
|
|
287
|
+
function directConstructionInstanceAssertionsForPattern(file: SourceFile, rawSource: string, codeSource: string, pattern: RegExp): StaticAnalysisRedundantAssertion[] {
|
|
288
|
+
return [...rawSource.matchAll(pattern)]
|
|
289
|
+
.map((match) => directConstructionInstanceCandidate(file, rawSource, codeSource, match))
|
|
290
|
+
.filter(isStaticAnalysisRedundantAssertion);
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
// Builds one direct-construction candidate with a source-order index for stable sorting.
|
|
294
|
+
function directConstructionInstanceCandidate(file: SourceFile, rawSource: string, codeSource: string, match: RegExpMatchArray): StaticAnalysisRedundantAssertion | undefined {
|
|
295
|
+
const index = match.index ?? 0;
|
|
296
|
+
if (!isExecutableAssertionAt(codeSource, index)) {
|
|
297
|
+
return undefined;
|
|
298
|
+
}
|
|
299
|
+
const className = match[1] ?? "";
|
|
300
|
+
return staticRedundantCandidate({
|
|
301
|
+
file,
|
|
302
|
+
source: rawSource,
|
|
303
|
+
index,
|
|
304
|
+
assertion: normalizedAssertionText(match[0] ?? ""),
|
|
305
|
+
staticFact: `\`new ${className}()\` constructs \`${className}\`, so the self-instance relationship is established by the expression shape.`,
|
|
306
|
+
});
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
// Detects assertions that only check non-nullability already guaranteed by a return type.
|
|
310
|
+
function nonNullableReturnAssertions(file: SourceFile, block: FunctionBlock, rawSource: string, codeSource: string): StaticAnalysisRedundantAssertion[] {
|
|
311
|
+
const declarations = nonNullableReturnDeclarations(rawSource, codeSource);
|
|
312
|
+
return NON_NULLABLE_ASSERTION_PATTERNS.flatMap((pattern) => nonNullableReturnAssertionsForPattern(file, block, rawSource, codeSource, declarations, pattern));
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
// Evaluates one non-nullable assertion grammar against collected return-type declarations.
|
|
316
|
+
function nonNullableReturnAssertionsForPattern(file: SourceFile, block: FunctionBlock, rawSource: string, codeSource: string, declarations: Map<string, NonNullableReturnDeclaration>, pattern: RegExp): StaticAnalysisRedundantAssertion[] {
|
|
317
|
+
return [...rawSource.matchAll(pattern)]
|
|
318
|
+
.map((match) => nonNullableReturnCandidate(file, block, rawSource, codeSource, declarations, match))
|
|
319
|
+
.filter(isStaticAnalysisRedundantAssertion);
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
// Builds one non-nullable-return candidate only when declaration evidence exists.
|
|
323
|
+
function nonNullableReturnCandidate(file: SourceFile, block: FunctionBlock, rawSource: string, codeSource: string, declarations: Map<string, NonNullableReturnDeclaration>, match: RegExpMatchArray): StaticAnalysisRedundantAssertion | undefined {
|
|
324
|
+
const index = match.index ?? 0;
|
|
325
|
+
if (!isExecutableAssertionAt(codeSource, index)) {
|
|
326
|
+
return undefined;
|
|
327
|
+
}
|
|
328
|
+
const declaration = declarations.get(match[1] ?? "");
|
|
329
|
+
if (!declaration) {
|
|
330
|
+
return undefined;
|
|
331
|
+
}
|
|
332
|
+
return staticRedundantCandidate({
|
|
333
|
+
file,
|
|
334
|
+
source: rawSource,
|
|
335
|
+
index,
|
|
336
|
+
assertion: normalizedAssertionText(match[0] ?? ""),
|
|
337
|
+
staticFact: `\`${declaration.name}()\` declares a non-nullable \`${declaration.returnType}\` return type.`,
|
|
338
|
+
sourceProof: `${file.displayPath}:${block.startLine + declaration.lineOffset}`,
|
|
339
|
+
});
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
// Collects function and const-arrow declarations whose return type excludes null and undefined.
|
|
343
|
+
function nonNullableReturnDeclarations(source: string, codeSource: string): Map<string, NonNullableReturnDeclaration> {
|
|
344
|
+
const declarations = new Map<string, NonNullableReturnDeclaration>();
|
|
345
|
+
for (const pattern of NON_NULLABLE_DECLARATION_PATTERNS) {
|
|
346
|
+
pushNonNullableReturnDeclarationsForPattern(declarations, source, codeSource, pattern);
|
|
347
|
+
}
|
|
348
|
+
return declarations;
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
// Adds declaration evidence for one grammar while ignoring masked comments and strings.
|
|
352
|
+
function pushNonNullableReturnDeclarationsForPattern(declarations: Map<string, NonNullableReturnDeclaration>, source: string, codeSource: string, pattern: RegExp): void {
|
|
353
|
+
for (const match of source.matchAll(pattern)) {
|
|
354
|
+
if (!isExecutableFunctionDeclarationAt(codeSource, match.index ?? 0)) {
|
|
355
|
+
continue;
|
|
356
|
+
}
|
|
357
|
+
pushNonNullableReturnDeclaration(declarations, source, match.index ?? 0, match[1] ?? "", match[2] ?? "");
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
// Gives each static-shape candidate the shared confidence and remediation contract.
|
|
362
|
+
function staticRedundantCandidate(args: Omit<StaticAnalysisRedundantAssertion, "confidence" | "recommendation"> & { file: SourceFile; source: string }): StaticAnalysisRedundantAssertion {
|
|
363
|
+
const { file: _file, source: _source, ...candidate } = args;
|
|
364
|
+
return {
|
|
365
|
+
...candidate,
|
|
366
|
+
confidence: "high",
|
|
367
|
+
recommendation: "Remove this assertion if it is the only behavior being tested, or replace it with an assertion about the returned value or observable behavior.",
|
|
368
|
+
};
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
// Type guard used after optional candidate builders so callers keep precise arrays.
|
|
372
|
+
function isStaticAnalysisRedundantAssertion(candidate: StaticAnalysisRedundantAssertion | undefined): candidate is StaticAnalysisRedundantAssertion {
|
|
373
|
+
return candidate !== undefined;
|
|
374
|
+
}
|
|
375
|
+
|
|
376
|
+
// Collapses whitespace so finding messages carry readable one-line assertion snippets.
|
|
377
|
+
function normalizedAssertionText(assertion: string): string {
|
|
378
|
+
return assertion.replace(/\s+/g, " ").trim();
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
// Checks masked code at the match offset so comment/string matches cannot create findings.
|
|
382
|
+
function isExecutableAssertionAt(codeSource: string, index: number): boolean {
|
|
383
|
+
return /\b(?:assert|expect)\b/.test(codeSource.slice(index, index + 12));
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
// Checks masked code at the match offset so comment/string declarations are ignored.
|
|
387
|
+
function isExecutableFunctionDeclarationAt(codeSource: string, index: number): boolean {
|
|
388
|
+
return /\b(?:function|const)\b/.test(codeSource.slice(index, index + 12));
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
// Checks masked code at the match offset so commented import examples are ignored.
|
|
392
|
+
function isExecutableImportAt(codeSource: string, index: number): boolean {
|
|
393
|
+
return /\bimport\b/.test(codeSource.slice(index, index + 12));
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
// Stores one declaration only when the name is present and the return type is non-nullable.
|
|
397
|
+
function pushNonNullableReturnDeclaration(declarations: Map<string, NonNullableReturnDeclaration>, source: string, index: number, name: string, returnType: string): void {
|
|
398
|
+
const normalizedReturnType = returnType.replace(/\s+/g, " ").trim();
|
|
399
|
+
if (!name || !isNonNullableReturnType(normalizedReturnType)) {
|
|
400
|
+
return;
|
|
401
|
+
}
|
|
402
|
+
declarations.set(name, { name, returnType: normalizedReturnType, lineOffset: lineOffset(source, index) });
|
|
403
|
+
}
|
|
404
|
+
|
|
405
|
+
// Treats explicit nullable, unknown, and non-returning types as not useful static proof.
|
|
406
|
+
function isNonNullableReturnType(returnType: string): boolean {
|
|
407
|
+
if (returnType === "" || /^(?:any|unknown|void|null|undefined|never)$/.test(returnType)) {
|
|
408
|
+
return false;
|
|
409
|
+
}
|
|
410
|
+
return !/\b(?:null|undefined)\b/.test(returnType);
|
|
411
|
+
}
|