@blundergoat/gruff-ts 0.4.0 → 0.5.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 +41 -1
- package/README.md +16 -6
- package/SECURITY.md +2 -1
- package/docs/README.md +1 -4
- package/docs/agent-hook.md +14 -2
- package/docs/configuration.md +32 -1
- package/docs/dashboard.md +3 -3
- package/docs/reports-and-ci.md +15 -0
- package/docs/rules.md +35 -29
- package/package.json +1 -1
- package/src/analyser.ts +163 -53
- package/src/baseline.ts +39 -3
- package/src/blocks.ts +116 -77
- package/src/changed-regions.ts +59 -11
- package/src/class-rules.ts +226 -76
- package/src/cli-program.ts +61 -14
- package/src/cli.ts +1 -0
- package/src/comment-rules.ts +58 -13
- package/src/comment-scanner.ts +27 -0
- package/src/complexity-metrics.ts +244 -0
- package/src/config.ts +56 -16
- package/src/constants.ts +1 -1
- package/src/context-doc-rules.ts +9 -10
- package/src/discovery.ts +39 -19
- package/src/doc-rules.ts +22 -53
- package/src/findings-helpers.ts +127 -1
- package/src/findings.ts +4 -0
- package/src/fixture-purpose-rules.ts +39 -5
- package/src/github-actions-rules.ts +24 -1
- package/src/hook-contract.ts +85 -14
- package/src/init-config.ts +15 -5
- package/src/line-rules.ts +54 -5
- package/src/naming-pushers.ts +26 -5
- package/src/parsed-script.ts +652 -0
- package/src/process-exec-metadata.ts +16 -6
- package/src/profiles.ts +14 -0
- package/src/project-config-rules.ts +15 -10
- package/src/public-exports.ts +220 -0
- package/src/report-renderers.ts +55 -4
- package/src/rules.ts +11 -11
- package/src/scoring.ts +13 -4
- package/src/security-flow-rules.ts +169 -24
- package/src/sensitive-data-rules.ts +132 -78
- package/src/source-text.ts +4 -46
- package/src/test-block-rules.ts +118 -14
- package/src/test-fixtures.ts +4 -1
- package/src/text-scans.ts +8 -1
- package/src/types.ts +5 -3
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// Sensitive-data scanners and redaction helpers for secret-like raw text findings.
|
|
2
2
|
import { ruleSeverity, threshold } from "./config.ts";
|
|
3
3
|
import { makeFinding } from "./findings.ts";
|
|
4
|
-
import { byteLine } from "./text-scans.ts";
|
|
4
|
+
import { byteColumn, byteLine } from "./text-scans.ts";
|
|
5
5
|
import type { Config, Finding } from "./types.ts";
|
|
6
6
|
|
|
7
7
|
// Just the display path - sensitive-data rules anchor findings on file path + line and never need
|
|
@@ -33,7 +33,7 @@ function analyseSensitiveData(file: SensitiveSourceFile, source: string, config:
|
|
|
33
33
|
if (isExplicitExampleCredential(raw)) {
|
|
34
34
|
continue;
|
|
35
35
|
}
|
|
36
|
-
pushSensitiveFinding(config, findings, file, ruleId, message, byteLine(source, match.index ?? 0), raw, "high");
|
|
36
|
+
pushSensitiveFinding({ config, findings, file, ruleId, message, line: byteLine(source, match.index ?? 0), column: byteColumn(source, match.index ?? 0), raw, confidence: "high" });
|
|
37
37
|
}
|
|
38
38
|
}
|
|
39
39
|
|
|
@@ -63,7 +63,7 @@ function analysePhiLabelledIdentifiers(file: SensitiveSourceFile, source: string
|
|
|
63
63
|
if (!medicalRecordNumber) {
|
|
64
64
|
continue;
|
|
65
65
|
}
|
|
66
|
-
pushSensitiveFinding(config, findings, file, "sensitive-data.phi-pattern", "Medical record number (PHI) detected.", index + 1, medicalRecordNumber, "high");
|
|
66
|
+
pushSensitiveFinding({ config, findings, file, ruleId: "sensitive-data.phi-pattern", message: "Medical record number (PHI) detected.", line: index + 1, column: (match.index ?? 0) + 1, raw: medicalRecordNumber, confidence: "high" });
|
|
67
67
|
}
|
|
68
68
|
}
|
|
69
69
|
|
|
@@ -77,39 +77,64 @@ function analyseGcpServiceAccountKeys(file: SensitiveSourceFile, source: string,
|
|
|
77
77
|
const identifier = source.match(/"private_key_id"\s*:\s*"([^"]+)"/)?.[1]
|
|
78
78
|
?? source.match(/"client_email"\s*:\s*"([^"]+)"/)?.[1]
|
|
79
79
|
?? "service_account";
|
|
80
|
-
pushSensitiveFinding(config, findings, file, "sensitive-data.gcp-service-account-key", "GCP service-account key file detected.", byteLine(source, typeMatch.index ?? 0), identifier, "high");
|
|
80
|
+
pushSensitiveFinding({ config, findings, file, ruleId: "sensitive-data.gcp-service-account-key", message: "GCP service-account key file detected.", line: byteLine(source, typeMatch.index ?? 0), column: byteColumn(source, typeMatch.index ?? 0), raw: identifier, confidence: "high" });
|
|
81
81
|
}
|
|
82
82
|
|
|
83
83
|
/*
|
|
84
84
|
* Payment-card PII detection contract: candidate shape, known issuer prefix, length, and Luhn
|
|
85
85
|
* check must all pass before a stable redacted finding is emitted. A bare unseparated digit run
|
|
86
86
|
* additionally needs card vocabulary on its line - large statistics can pass Luhn by coincidence,
|
|
87
|
-
* while
|
|
87
|
+
* while canonically grouped numbers provide formatting evidence on their own.
|
|
88
88
|
*/
|
|
89
89
|
function analysePaymentCardNumbers(file: SensitiveSourceFile, source: string, config: Config, findings: Finding[]): void {
|
|
90
90
|
const lines = source.split(/\r?\n/);
|
|
91
91
|
for (const match of source.matchAll(/\b(?:\d[ -]?){12,18}\d\b/g)) {
|
|
92
92
|
const rawCandidate = match[0] ?? "";
|
|
93
93
|
const cardNumber = normalizedPaymentCardNumber(rawCandidate);
|
|
94
|
-
if (!isPaymentCardNumber(cardNumber)) {
|
|
95
|
-
continue;
|
|
96
|
-
}
|
|
97
94
|
const line = byteLine(source, match.index ?? 0);
|
|
98
|
-
|
|
95
|
+
// The helper owns the shape/checksum/vocabulary gates; anything failing them is not a card.
|
|
96
|
+
if (!isReportablePaymentCardCandidate(rawCandidate, cardNumber, lines[line - 1] ?? "")) {
|
|
99
97
|
continue;
|
|
100
98
|
}
|
|
101
|
-
pushSensitiveFinding(
|
|
99
|
+
pushSensitiveFinding({
|
|
102
100
|
config,
|
|
103
101
|
findings,
|
|
104
102
|
file,
|
|
105
|
-
"sensitive-data.pii-pattern",
|
|
106
|
-
"Credit card number (PII) pattern detected.",
|
|
103
|
+
ruleId: "sensitive-data.pii-pattern",
|
|
104
|
+
message: "Credit card number (PII) pattern detected.",
|
|
107
105
|
line,
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
106
|
+
column: byteColumn(source, match.index ?? 0),
|
|
107
|
+
raw: rawCandidate,
|
|
108
|
+
confidence: "high",
|
|
109
|
+
metadata: { piiKind: "credit-card", digits: cardNumber.length },
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// Full reportability gate for one digit-run candidate: card shape and Luhn first, then the
|
|
115
|
+
// context rule - canonical card grouping provides formatting evidence, while bare or irregularly
|
|
116
|
+
// grouped digit runs need card vocabulary because large statistics can pass Luhn by coincidence.
|
|
117
|
+
function isReportablePaymentCardCandidate(rawCandidate: string, cardNumber: string, contextLine: string): boolean {
|
|
118
|
+
if (!isPaymentCardNumber(cardNumber)) {
|
|
119
|
+
return false;
|
|
120
|
+
}
|
|
121
|
+
return hasCanonicalPaymentCardGrouping(rawCandidate, cardNumber) || hasPaymentCardContext(contextLine);
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
// Accept one consistent separator and the display grouping used by the detected card network.
|
|
125
|
+
// Arbitrary chunks such as 8-8 remain statistics unless their source line supplies card context.
|
|
126
|
+
function hasCanonicalPaymentCardGrouping(rawCandidate: string, cardNumber: string): boolean {
|
|
127
|
+
const separators = rawCandidate.match(/[ -]/g) ?? [];
|
|
128
|
+
if (separators.length === 0 || new Set(separators).size !== 1) {
|
|
129
|
+
return false;
|
|
112
130
|
}
|
|
131
|
+
const groupSizes = rawCandidate.split(separators[0] ?? " ").map((group) => group.length);
|
|
132
|
+
const expectedGroupSizes = isAmericanExpressPaymentCard(cardNumber)
|
|
133
|
+
? [4, 6, 5]
|
|
134
|
+
: isDinersPaymentCard(cardNumber)
|
|
135
|
+
? [4, 6, 4]
|
|
136
|
+
: Array.from({ length: Math.ceil(cardNumber.length / 4) }, (_, index) => Math.min(4, cardNumber.length - index * 4));
|
|
137
|
+
return groupSizes.length === expectedGroupSizes.length && groupSizes.every((size, index) => size === expectedGroupSizes[index]);
|
|
113
138
|
}
|
|
114
139
|
|
|
115
140
|
// Card vocabulary gate for bare digit runs. Substring matching is deliberate so identifier forms
|
|
@@ -127,17 +152,17 @@ function analyseNpmAuthTokens(file: SensitiveSourceFile, source: string, config:
|
|
|
127
152
|
if (!token) {
|
|
128
153
|
continue;
|
|
129
154
|
}
|
|
130
|
-
pushSensitiveFinding(
|
|
155
|
+
pushSensitiveFinding({
|
|
131
156
|
config,
|
|
132
157
|
findings,
|
|
133
158
|
file,
|
|
134
|
-
"sensitive-data.api-key-pattern",
|
|
135
|
-
"npm auth token pattern detected.",
|
|
136
|
-
index + 1,
|
|
137
|
-
token,
|
|
138
|
-
"high",
|
|
139
|
-
{ keyName: "_authToken" },
|
|
140
|
-
);
|
|
159
|
+
ruleId: "sensitive-data.api-key-pattern",
|
|
160
|
+
message: "npm auth token pattern detected.",
|
|
161
|
+
line: index + 1,
|
|
162
|
+
raw: token,
|
|
163
|
+
confidence: "high",
|
|
164
|
+
metadata: { keyName: "_authToken" },
|
|
165
|
+
});
|
|
141
166
|
}
|
|
142
167
|
}
|
|
143
168
|
|
|
@@ -159,18 +184,18 @@ function analyseHardcodedEnvironmentValues(file: SensitiveSourceFile, source: st
|
|
|
159
184
|
if (!envValue) {
|
|
160
185
|
continue;
|
|
161
186
|
}
|
|
162
|
-
pushSensitiveFinding(
|
|
187
|
+
pushSensitiveFinding({
|
|
163
188
|
config,
|
|
164
189
|
findings,
|
|
165
190
|
file,
|
|
166
|
-
"sensitive-data.hardcoded-env-value",
|
|
167
|
-
`Environment-style value \`${envValue.keyName}\` appears to be hardcoded with secret-like content.`,
|
|
168
|
-
index + 1,
|
|
169
|
-
envValue.value,
|
|
170
|
-
"medium",
|
|
171
|
-
{ keyName: envValue.keyName, length: envValue.value.length, threshold: minLength },
|
|
172
|
-
ruleSeverity(config, "sensitive-data.hardcoded-env-value", "error"),
|
|
173
|
-
);
|
|
191
|
+
ruleId: "sensitive-data.hardcoded-env-value",
|
|
192
|
+
message: `Environment-style value \`${envValue.keyName}\` appears to be hardcoded with secret-like content.`,
|
|
193
|
+
line: index + 1,
|
|
194
|
+
raw: envValue.value,
|
|
195
|
+
confidence: "medium",
|
|
196
|
+
metadata: { keyName: envValue.keyName, length: envValue.value.length, threshold: minLength },
|
|
197
|
+
severity: ruleSeverity(config, "sensitive-data.hardcoded-env-value", "error"),
|
|
198
|
+
});
|
|
174
199
|
}
|
|
175
200
|
}
|
|
176
201
|
|
|
@@ -184,48 +209,64 @@ function analyseHighEntropyStrings(file: SensitiveSourceFile, source: string, co
|
|
|
184
209
|
if (!isHighEntropySecretCandidate(raw, minLength)) {
|
|
185
210
|
continue;
|
|
186
211
|
}
|
|
187
|
-
pushSensitiveFinding(
|
|
212
|
+
pushSensitiveFinding({
|
|
188
213
|
config,
|
|
189
214
|
findings,
|
|
190
215
|
file,
|
|
191
|
-
"sensitive-data.high-entropy-string",
|
|
192
|
-
"High-entropy string literal may be an embedded secret.",
|
|
193
|
-
byteLine(source, match.index ?? 0),
|
|
216
|
+
ruleId: "sensitive-data.high-entropy-string",
|
|
217
|
+
message: "High-entropy string literal may be an embedded secret.",
|
|
218
|
+
line: byteLine(source, match.index ?? 0),
|
|
219
|
+
column: byteColumn(source, match.index ?? 0),
|
|
194
220
|
raw,
|
|
195
|
-
"medium",
|
|
196
|
-
{ length: raw.length, detector: "high-entropy-string", threshold: minLength },
|
|
197
|
-
ruleSeverity(config, "sensitive-data.high-entropy-string", "error"),
|
|
198
|
-
);
|
|
221
|
+
confidence: "medium",
|
|
222
|
+
metadata: { length: raw.length, detector: "high-entropy-string", threshold: minLength },
|
|
223
|
+
severity: ruleSeverity(config, "sensitive-data.high-entropy-string", "error"),
|
|
224
|
+
});
|
|
199
225
|
}
|
|
200
226
|
}
|
|
201
227
|
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
228
|
+
// Input bundle for `pushSensitiveFinding`: everything one sensitive occurrence needs to become a
|
|
229
|
+
// redacted finding. `column` is the one-based match offset when the scanner pinpointed one and is
|
|
230
|
+
// absent for line-shaped detectors; `metadata` and `severity` default inside the builder.
|
|
231
|
+
// Stable contract: `raw` never reaches a finding unredacted.
|
|
232
|
+
interface SensitiveFindingArgs {
|
|
233
|
+
config: Config;
|
|
234
|
+
findings: Finding[];
|
|
235
|
+
file: SensitiveSourceFile;
|
|
236
|
+
ruleId: string;
|
|
237
|
+
message: string;
|
|
238
|
+
line: number;
|
|
239
|
+
column?: number;
|
|
240
|
+
raw: string;
|
|
241
|
+
confidence: Finding["confidence"];
|
|
242
|
+
metadata?: Record<string, unknown>;
|
|
243
|
+
severity?: Finding["severity"];
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// Central sensitive-finding emitter: redacts the raw value into the message preview and anchors
|
|
247
|
+
// the finding at line plus, when provided, the match column that keeps two distinct same-line
|
|
248
|
+
// secrets from collapsing into one report entry (ADR-017). Invariant: raw secret values never
|
|
249
|
+
// leave this function unredacted, and the `secretPreviews` allowlist must run before any push.
|
|
250
|
+
// Reports exactly one finding per occurrence and never throws.
|
|
251
|
+
function pushSensitiveFinding(args: SensitiveFindingArgs): void {
|
|
252
|
+
const preview = redact(args.raw);
|
|
253
|
+
// Fully masked short previews identify only a length, so accepting one would suppress every
|
|
254
|
+
// unrelated secret of that length. Only previews with bounded edge context are distinct enough.
|
|
255
|
+
if (args.raw.length >= MINIMUM_SECRET_LENGTH_FOR_CONTEXT && args.config.secretPreviews.has(preview)) {
|
|
216
256
|
return;
|
|
217
257
|
}
|
|
218
|
-
findings.push(
|
|
258
|
+
args.findings.push(
|
|
219
259
|
makeFinding({
|
|
220
|
-
ruleId,
|
|
221
|
-
message: `${message} Redacted preview: ${preview}.`,
|
|
222
|
-
filePath: file.displayPath,
|
|
223
|
-
line,
|
|
224
|
-
|
|
260
|
+
ruleId: args.ruleId,
|
|
261
|
+
message: `${args.message} Redacted preview: ${preview}.`,
|
|
262
|
+
filePath: args.file.displayPath,
|
|
263
|
+
line: args.line,
|
|
264
|
+
...(args.column === undefined ? {} : { column: args.column }),
|
|
265
|
+
severity: args.severity ?? "error",
|
|
225
266
|
pillar: "sensitive-data",
|
|
226
|
-
confidence,
|
|
267
|
+
confidence: args.confidence,
|
|
227
268
|
remediation: "Remove the sensitive value and load it from a secure runtime source.",
|
|
228
|
-
metadata: { ...metadata, preview },
|
|
269
|
+
metadata: { ...(args.metadata ?? {}), preview },
|
|
229
270
|
}),
|
|
230
271
|
);
|
|
231
272
|
}
|
|
@@ -251,17 +292,24 @@ function isScriptSourcePath(displayPath: string): boolean {
|
|
|
251
292
|
return /\.(?:ts|tsx|mts|cts|js|jsx|mjs|cjs)$/i.test(displayPath);
|
|
252
293
|
}
|
|
253
294
|
|
|
254
|
-
|
|
255
|
-
|
|
295
|
+
const SECRET_ASSIGNMENT_PATTERN = /^\s*((?:API[_-]?KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|DATABASE_URL|DSN)|[A-Z][A-Z0-9_-]*(?:API[_-]?KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|DATABASE_URL|DSN)[A-Z0-9_-]*)\s*[:=]\s*(?:"([^"\r\n]+)"|'([^'\r\n]+)'|`([^`\r\n]+)`|([^"'`\s#]+))/i;
|
|
296
|
+
|
|
297
|
+
// Extracts secret-labelled assignment values for scan reporting. Quoted arms preserve hashes,
|
|
298
|
+
// while unquoted values stop at whitespace or hash because comments must not inflate a finding.
|
|
256
299
|
function envValueCandidate(line: string): { keyName: string; value: string; isQuoted: boolean } | undefined {
|
|
257
|
-
const match = line.match(
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
300
|
+
const match = line.match(SECRET_ASSIGNMENT_PATTERN);
|
|
301
|
+
// A user may have supplied an unrelated line or unknown key, which cannot produce this finding.
|
|
302
|
+
if (!match) {
|
|
303
|
+
return undefined;
|
|
304
|
+
}
|
|
305
|
+
const keyName = match[1];
|
|
306
|
+
const quotedValue = match[2] ?? match[3] ?? match[4];
|
|
307
|
+
const secretValue = quotedValue ?? match[5];
|
|
308
|
+
// A user may have supplied an empty or unterminated assignment; neither is a secret candidate.
|
|
309
|
+
if (!keyName || !secretValue) {
|
|
262
310
|
return undefined;
|
|
263
311
|
}
|
|
264
|
-
return { keyName, value: secretValue, isQuoted:
|
|
312
|
+
return { keyName, value: secretValue, isQuoted: quotedValue !== undefined };
|
|
265
313
|
}
|
|
266
314
|
|
|
267
315
|
// Three predicates combined: long enough, not a literal placeholder, and shape-like (letters + digits).
|
|
@@ -503,10 +551,10 @@ function isHexDigest(candidateText: string): boolean {
|
|
|
503
551
|
return /^[0-9a-f]+$/i.test(candidateText);
|
|
504
552
|
}
|
|
505
553
|
|
|
506
|
-
//
|
|
507
|
-
// detector
|
|
554
|
+
// Registry metadata and HTML integrity attributes use public SRI digests, not credentials.
|
|
555
|
+
// Excluding that standard shape keeps the detector focused on values that grant access.
|
|
508
556
|
function isSubresourceIntegrityHash(candidateText: string): boolean {
|
|
509
|
-
return /^sha(?:256|384|512)-[A-Za-z0-9+/=]+$/.test(candidateText);
|
|
557
|
+
return /^sha(?:1|256|384|512)-[A-Za-z0-9+/=]+$/.test(candidateText);
|
|
510
558
|
}
|
|
511
559
|
|
|
512
560
|
// Three-class character requirement that filters out single-case identifiers and pure base64 hashes
|
|
@@ -534,13 +582,19 @@ function shannonEntropy(candidateText: string): number {
|
|
|
534
582
|
}, 0);
|
|
535
583
|
}
|
|
536
584
|
|
|
537
|
-
//
|
|
538
|
-
|
|
585
|
+
// The 24-character threshold prevents edge context from exposing most of a short credential.
|
|
586
|
+
const MINIMUM_SECRET_LENGTH_FOR_CONTEXT = 24;
|
|
587
|
+
// The four-character limit keeps long tokens recognizable without revealing most of their value.
|
|
588
|
+
const VISIBLE_SECRET_EDGE_LENGTH = 4;
|
|
589
|
+
|
|
590
|
+
// Formats the secret evidence shown in findings and every report. Reviewers see only length for
|
|
591
|
+
// short values, while long credentials retain limited edge context to identify what to rotate.
|
|
539
592
|
function redact(rawSecret: string): string {
|
|
540
|
-
|
|
593
|
+
// A reviewer opening any report gets a full mask when edge context would disclose too much.
|
|
594
|
+
if (rawSecret.length < MINIMUM_SECRET_LENGTH_FOR_CONTEXT) {
|
|
541
595
|
return `${"*".repeat(rawSecret.length)} (redacted, ${rawSecret.length} chars)`;
|
|
542
596
|
}
|
|
543
|
-
return `${rawSecret.slice(0,
|
|
597
|
+
return `${rawSecret.slice(0, VISIBLE_SECRET_EDGE_LENGTH)}...${rawSecret.slice(-VISIBLE_SECRET_EDGE_LENGTH)} (redacted, ${rawSecret.length} chars)`;
|
|
544
598
|
}
|
|
545
599
|
|
|
546
600
|
export { analyseSensitiveData };
|
package/src/source-text.ts
CHANGED
|
@@ -2,21 +2,9 @@
|
|
|
2
2
|
* Provides lightweight source text scanners that separate executable TypeScript
|
|
3
3
|
* from comments, strings, and regex bodies before rule matching runs.
|
|
4
4
|
*/
|
|
5
|
-
import {
|
|
5
|
+
import { parseScript } from "./parsed-script.ts";
|
|
6
6
|
import type { RunDiagnostic } from "./types.ts";
|
|
7
7
|
|
|
8
|
-
const require = createRequire(import.meta.url);
|
|
9
|
-
const typescriptSyntax = require("typescript") as typeof import("typescript");
|
|
10
|
-
|
|
11
|
-
type TsDiagnostic = import("typescript").Diagnostic;
|
|
12
|
-
type TsSourceFile = import("typescript").SourceFile;
|
|
13
|
-
|
|
14
|
-
// TypeScript's public SourceFile shape exposes parseDiagnostics at runtime; this interface gives
|
|
15
|
-
// the syntax-only parser result the diagnostic field without requiring a full Program.
|
|
16
|
-
interface ParsedSourceFileWithDiagnostics extends TsSourceFile {
|
|
17
|
-
parseDiagnostics: readonly TsDiagnostic[];
|
|
18
|
-
}
|
|
19
|
-
|
|
20
8
|
// Just enough of `SourceFile` to keep `parseDiagnostics` decoupled from the full project type:
|
|
21
9
|
// `isScript` gates whether parser diagnostics run; `displayPath` is the report-path anchor.
|
|
22
10
|
interface DiagnosticSourceFile {
|
|
@@ -26,44 +14,14 @@ interface DiagnosticSourceFile {
|
|
|
26
14
|
|
|
27
15
|
/**
|
|
28
16
|
* Syntax-only TypeScript parser diagnostics for script files; non-script inputs stay unparsed.
|
|
17
|
+
* Thin wrapper over the shared parse boundary so direct callers keep this signature while the
|
|
18
|
+
* analyser consumes the boundary result once per script.
|
|
29
19
|
*
|
|
30
20
|
* @param file - Source metadata used to skip non-script inputs and report paths.
|
|
31
21
|
* @param source - Raw file text to parse for syntax diagnostics.
|
|
32
22
|
*/
|
|
33
23
|
function parseDiagnostics(file: DiagnosticSourceFile, source: string): RunDiagnostic[] {
|
|
34
|
-
|
|
35
|
-
return [];
|
|
36
|
-
}
|
|
37
|
-
const parsed = typescriptSyntax.createSourceFile(file.displayPath, source, typescriptSyntax.ScriptTarget.Latest, true, scriptKindFor(file.displayPath)) as ParsedSourceFileWithDiagnostics;
|
|
38
|
-
return parsed.parseDiagnostics.map((diagnostic) => parseErrorDiagnostic(file, diagnosticLine(parsed, diagnostic), diagnosticMessage(diagnostic)));
|
|
39
|
-
}
|
|
40
|
-
|
|
41
|
-
// Maps extensions onto the matching TypeScript parser mode so TSX/JSX syntax is parsed as syntax.
|
|
42
|
-
function scriptKindFor(path: string): import("typescript").ScriptKind {
|
|
43
|
-
if (path.endsWith(".tsx")) {
|
|
44
|
-
return typescriptSyntax.ScriptKind.TSX;
|
|
45
|
-
}
|
|
46
|
-
if (path.endsWith(".jsx")) {
|
|
47
|
-
return typescriptSyntax.ScriptKind.JSX;
|
|
48
|
-
}
|
|
49
|
-
if (path.endsWith(".js") || path.endsWith(".mjs") || path.endsWith(".cjs")) {
|
|
50
|
-
return typescriptSyntax.ScriptKind.JS;
|
|
51
|
-
}
|
|
52
|
-
return typescriptSyntax.ScriptKind.TS;
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
// Parser diagnostics may omit a start offset; line 1 is the stable fallback for malformed files.
|
|
56
|
-
function diagnosticLine(sourceFile: TsSourceFile, diagnostic: TsDiagnostic): number {
|
|
57
|
-
if (diagnostic.start === undefined) {
|
|
58
|
-
return 1;
|
|
59
|
-
}
|
|
60
|
-
return sourceFile.getLineAndCharacterOfPosition(diagnostic.start).line + 1;
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
// Prefixes the TypeScript parser message while preserving the existing parse-error diagnostic shape.
|
|
64
|
-
// Chained messages flatten with a space separator so text-format diagnostic rows stay single-line.
|
|
65
|
-
function diagnosticMessage(diagnostic: TsDiagnostic): string {
|
|
66
|
-
return `TypeScript syntax error: ${typescriptSyntax.flattenDiagnosticMessageText(diagnostic.messageText, " ")}`;
|
|
24
|
+
return parseScript(file, source)?.diagnostics ?? [];
|
|
67
25
|
}
|
|
68
26
|
|
|
69
27
|
// Running totals for `{}`, `()`, and `[]`. A negative count means a closer appeared with no opener
|
package/src/test-block-rules.ts
CHANGED
|
@@ -119,14 +119,21 @@ function analyseGlobalStateMutation(file: SourceFile, block: FunctionBlock, body
|
|
|
119
119
|
function analyseTestStructureChecks(file: SourceFile, block: FunctionBlock, body: string, findings: Finding[]): void {
|
|
120
120
|
const checks: Array<[string, boolean, string]> = [
|
|
121
121
|
["test-quality.sleep-in-test", /\b(setTimeout|sleep|waitForTimeout)\s*\(/.test(body), "Test sleeps instead of synchronising on behaviour."],
|
|
122
|
-
["test-quality.loop-in-test", controlFlowContainsNonFixtureLoop(body), "Test contains loop logic
|
|
122
|
+
["test-quality.loop-in-test", controlFlowContainsNonFixtureLoop(body), "Test contains loop logic that hides which iteration failed."],
|
|
123
123
|
["test-quality.conditional-logic", controlFlowContainsAssertion(body, /\b(?:if|switch)\b/g), "Test contains conditional logic around assertions."],
|
|
124
124
|
["test-quality.only-skip", /\.(only|skip)\s*\(/.test(body), "Focused or skipped test is committed."],
|
|
125
125
|
];
|
|
126
126
|
for (const [ruleId, active, message] of checks) {
|
|
127
|
-
if (active) {
|
|
128
|
-
|
|
127
|
+
if (!active) {
|
|
128
|
+
continue;
|
|
129
|
+
}
|
|
130
|
+
// Loop findings report at medium confidence: parametrized tests are a legitimate pattern and
|
|
131
|
+
// the label heuristic cannot see every message shape (multi-line assertion calls, helpers).
|
|
132
|
+
if (ruleId === "test-quality.loop-in-test") {
|
|
133
|
+
findings.push(blockFindingWithMetadata({ ruleId, message, file, block, severity: "advisory", pillar: "test-quality", metadata: {} }));
|
|
134
|
+
continue;
|
|
129
135
|
}
|
|
136
|
+
findings.push(blockFinding({ ruleId, message, file, block, severity: "advisory", pillar: "test-quality" }));
|
|
130
137
|
}
|
|
131
138
|
}
|
|
132
139
|
|
|
@@ -144,32 +151,110 @@ function controlFlowContainsNonFixtureLoop(source: string): boolean {
|
|
|
144
151
|
if (isFixtureLoop(source, start, segment)) {
|
|
145
152
|
continue;
|
|
146
153
|
}
|
|
154
|
+
if (isLabeledCaseLoop(segment)) {
|
|
155
|
+
continue;
|
|
156
|
+
}
|
|
147
157
|
return true;
|
|
148
158
|
}
|
|
149
159
|
return false;
|
|
150
160
|
}
|
|
151
161
|
|
|
162
|
+
/*
|
|
163
|
+
* A data-driven loop whose assertions each carry a per-case template message referencing a
|
|
164
|
+
* loop-bound name keeps a failing row identifiable - the failure mode this rule exists to catch -
|
|
165
|
+
* so it opts out even when the case table is built dynamically. Multi-line assertion calls fall
|
|
166
|
+
* outside the statement split and stay reported; the rule's medium confidence reflects that.
|
|
167
|
+
*/
|
|
168
|
+
function isLabeledCaseLoop(segment: string): boolean {
|
|
169
|
+
const parts = loopSegmentParts(segment);
|
|
170
|
+
if (!parts) {
|
|
171
|
+
return false;
|
|
172
|
+
}
|
|
173
|
+
const boundNames = loopBoundNames(parts.header);
|
|
174
|
+
if (boundNames.length === 0) {
|
|
175
|
+
return false;
|
|
176
|
+
}
|
|
177
|
+
const assertionStatements = parts.body.split(/[;\n]/).map((statement) => statement.trim()).filter((statement) => statement.length > 0 && hasAssertion(statement));
|
|
178
|
+
if (assertionStatements.length === 0) {
|
|
179
|
+
return false;
|
|
180
|
+
}
|
|
181
|
+
return assertionStatements.every((statement) => hasLoopCaseLabel(statement, boundNames));
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
// Identifier names bound by a for..of header - `for (const { name, input } of cases)` binds both.
|
|
185
|
+
// While-loops bind nothing here, so they never take the labeled opt-out.
|
|
186
|
+
function loopBoundNames(header: string): string[] {
|
|
187
|
+
const binding = header.match(/\b(?:const|let|var)\s+([^)]*?)\s+of\b/)?.[1] ?? "";
|
|
188
|
+
return [...binding.matchAll(/[A-Za-z_$][A-Za-z0-9_$]*/g)].map((match) => match[0] ?? "").filter(Boolean);
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
// The per-case label: a template interpolation in the assertion statement naming a bound
|
|
192
|
+
// identifier. Masked source keeps `${...}` expressions intact, so this works on codeBody.
|
|
193
|
+
function hasLoopCaseLabel(statement: string, boundNames: string[]): boolean {
|
|
194
|
+
for (const interpolation of statement.matchAll(/\$\{([^}]*)\}/g)) {
|
|
195
|
+
const expressionText = interpolation[1] ?? "";
|
|
196
|
+
if (boundNames.some((name) => new RegExp(`\\b${escapeRegex(name)}\\b`).test(expressionText))) {
|
|
197
|
+
return true;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
return false;
|
|
201
|
+
}
|
|
202
|
+
|
|
152
203
|
// A "fixture loop" is the table-test pattern: iterable is an inline fixture OR a local const-bound
|
|
153
204
|
// fixture table, AND every path through the body terminates in an assertion call. Guard branches
|
|
154
205
|
// without assertions are allowed, but assertion-bearing branches still opt out.
|
|
155
206
|
function isFixtureLoop(source: string, start: number, segment: string): boolean {
|
|
156
|
-
const
|
|
157
|
-
|
|
158
|
-
if (!hasFixtureIterable(source, start, header)) {
|
|
207
|
+
const parts = loopSegmentParts(segment);
|
|
208
|
+
if (!parts || !hasFixtureIterable(source, start, parts.header)) {
|
|
159
209
|
return false;
|
|
160
210
|
}
|
|
161
|
-
if (
|
|
211
|
+
if (hasUnsafeFixtureLoopBranch(source.slice(0, start + parts.bodyBraceIndex + 1), parts.body)) {
|
|
162
212
|
return false;
|
|
163
213
|
}
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
}
|
|
168
|
-
const statements = body.split(/[;\n]/).map((statement) => statement.trim()).filter((statement) => statement.length > 0 && statement !== "}" && !/^(?:break|continue)\b/.test(statement));
|
|
214
|
+
// Bare `void identifier` lines are lint pacifiers, not work, so they cannot be the loop's
|
|
215
|
+
// terminal action; `void call()` still counts as a real trailing statement.
|
|
216
|
+
const statements = parts.body.split(/[;\n]/).map((statement) => statement.trim()).filter((statement) => statement.length > 0 && statement !== "}" && !/^(?:break|continue)\b/.test(statement) && !/^void\s+[A-Za-z_$][A-Za-z0-9_$]*$/.test(statement));
|
|
169
217
|
const lastStatement = statements[statements.length - 1] ?? "";
|
|
170
218
|
return /^(?:assert\.[a-z]+\s*\(|expect\s*\(|[a-z][A-Za-z0-9_]*\.should(?:Be|Equal)?\s*\()/i.test(lastStatement);
|
|
171
219
|
}
|
|
172
220
|
|
|
221
|
+
// Splits a loop segment into header and body at the body-opening brace, walking past the header's
|
|
222
|
+
// balanced parentheses first so that a destructured binding such as `for (const { name } of rows)`
|
|
223
|
+
// does not end the header at the destructuring brace. Braceless bodies return undefined.
|
|
224
|
+
function loopSegmentParts(segment: string): { header: string; body: string; bodyBraceIndex: number } | undefined {
|
|
225
|
+
const parenIndex = segment.indexOf("(");
|
|
226
|
+
if (parenIndex === -1) {
|
|
227
|
+
return undefined;
|
|
228
|
+
}
|
|
229
|
+
const headerCloseIndex = matchingHeaderCloseParen(segment, parenIndex);
|
|
230
|
+
if (headerCloseIndex === undefined) {
|
|
231
|
+
return undefined;
|
|
232
|
+
}
|
|
233
|
+
const bodyBraceIndex = segment.indexOf("{", headerCloseIndex);
|
|
234
|
+
if (bodyBraceIndex === -1) {
|
|
235
|
+
return undefined;
|
|
236
|
+
}
|
|
237
|
+
return { header: segment.slice(0, bodyBraceIndex), body: segment.slice(bodyBraceIndex + 1, segment.length - 1), bodyBraceIndex };
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
// Walks a header's parentheses to the close of the outermost group, tolerating nested calls such
|
|
241
|
+
// as `of Object.entries({ a: 1 })` inside the loop header.
|
|
242
|
+
function matchingHeaderCloseParen(segment: string, parenIndex: number): number | undefined {
|
|
243
|
+
let depth = 0;
|
|
244
|
+
for (let index = parenIndex; index < segment.length; index += 1) {
|
|
245
|
+
const character = segment[index];
|
|
246
|
+
if (character === "(") {
|
|
247
|
+
depth += 1;
|
|
248
|
+
} else if (character === ")") {
|
|
249
|
+
depth -= 1;
|
|
250
|
+
if (depth === 0) {
|
|
251
|
+
return index;
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
return undefined;
|
|
256
|
+
}
|
|
257
|
+
|
|
173
258
|
// Fixture sweeps may carry invariant guards such as `if (expectedIds.has(case.id))`; other branches
|
|
174
259
|
// still opt out because they can hide case-specific expectations inside the loop.
|
|
175
260
|
function hasUnsafeFixtureLoopBranch(sourceBeforeLoopBody: string, body: string): boolean {
|
|
@@ -255,14 +340,33 @@ function isFixtureMembershipGuard(sourceBeforeCondition: string, condition: stri
|
|
|
255
340
|
// Captures the smallest control-flow segment so assertion detection does not scan the whole test.
|
|
256
341
|
function controlFlowSegment(source: string, start: number): string {
|
|
257
342
|
const lineEnd = source.indexOf("\n", start);
|
|
258
|
-
const openBrace = source
|
|
259
|
-
if (openBrace ===
|
|
343
|
+
const openBrace = controlFlowBodyBraceIndex(source, start, lineEnd);
|
|
344
|
+
if (openBrace === undefined) {
|
|
260
345
|
return source.slice(start, lineEnd === -1 ? source.length : lineEnd);
|
|
261
346
|
}
|
|
262
347
|
const closeBrace = matchingCloseBrace(source, openBrace);
|
|
263
348
|
return source.slice(start, closeBrace === undefined ? openBrace + 1 : closeBrace + 1);
|
|
264
349
|
}
|
|
265
350
|
|
|
351
|
+
// Finds the body-opening brace for a control-flow keyword: the first `{` at parenthesis depth zero
|
|
352
|
+
// on the keyword's line. Braces inside the header parens - destructured bindings such as
|
|
353
|
+
// `for (const { name } of rows)` - belong to the header, not the body.
|
|
354
|
+
function controlFlowBodyBraceIndex(source: string, start: number, lineEnd: number): number | undefined {
|
|
355
|
+
const limit = lineEnd === -1 ? source.length : lineEnd;
|
|
356
|
+
let parenDepth = 0;
|
|
357
|
+
for (let index = start; index < limit; index += 1) {
|
|
358
|
+
const character = source[index];
|
|
359
|
+
if (character === "(") {
|
|
360
|
+
parenDepth += 1;
|
|
361
|
+
} else if (character === ")") {
|
|
362
|
+
parenDepth = Math.max(0, parenDepth - 1);
|
|
363
|
+
} else if (character === "{" && parenDepth === 0) {
|
|
364
|
+
return index;
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
return undefined;
|
|
368
|
+
}
|
|
369
|
+
|
|
266
370
|
// Lightweight brace matcher for already-isolated test block text; enough to bound loop/if bodies.
|
|
267
371
|
function matchingCloseBrace(source: string, openBrace: number): number | undefined {
|
|
268
372
|
let depth = 0;
|
package/src/test-fixtures.ts
CHANGED
|
@@ -312,6 +312,9 @@ function catalogueCoverageFiles(): Record<string, string> {
|
|
|
312
312
|
return {
|
|
313
313
|
"src/catalogue.ts": catalogueRuntimeCoverageSource(),
|
|
314
314
|
"src/dep.ts": `export const usedThing = "used";
|
|
315
|
+
`,
|
|
316
|
+
"src/helpers.ts": `/** Handles payment requests in the catalogue coverage project. */
|
|
317
|
+
export class PaymentController {}
|
|
315
318
|
`,
|
|
316
319
|
"src/catalogue.test.ts": catalogueTestCoverageSource(),
|
|
317
320
|
"src/app/feature/controller.ts": `import { sharedHelper } from "../../../shared/helper";
|
|
@@ -417,7 +420,7 @@ const active = true;
|
|
|
417
420
|
const xx = 1;
|
|
418
421
|
const ctx = { request: 1 };
|
|
419
422
|
const disableCache = true;
|
|
420
|
-
const
|
|
423
|
+
const rawURL = "/health";
|
|
421
424
|
const databaseUrl = "/healthz";
|
|
422
425
|
const project_path = "src";
|
|
423
426
|
const projectPath = "src/index.ts";
|
package/src/text-scans.ts
CHANGED
|
@@ -39,4 +39,11 @@ function byteLine(source: string, index: number): number {
|
|
|
39
39
|
return line;
|
|
40
40
|
}
|
|
41
41
|
|
|
42
|
-
|
|
42
|
+
// One-based column of byte offset `index` on its line. Lets two matches on one line report
|
|
43
|
+
// distinct positions so neither occurrence is lost when their line-keyed identities collide.
|
|
44
|
+
function byteColumn(source: string, index: number): number {
|
|
45
|
+
const end = Math.max(0, index);
|
|
46
|
+
return end - source.lastIndexOf("\n", end - 1);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export { byteColumn, byteLine, countMatches, firstLine };
|
package/src/types.ts
CHANGED
|
@@ -72,6 +72,8 @@ export interface Config {
|
|
|
72
72
|
secretPreviews: Set<string>;
|
|
73
73
|
bannedGenericNames: Set<string>;
|
|
74
74
|
acceptedBooleanNames: Set<string>;
|
|
75
|
+
acceptedClassFilePairs: Set<string>;
|
|
76
|
+
acceptedCasingPairs: Set<string>;
|
|
75
77
|
booleanPrefixes: Set<string>;
|
|
76
78
|
hungarianPrefixes: Set<string>;
|
|
77
79
|
placeholderNames: Set<string>;
|
|
@@ -173,11 +175,11 @@ export interface SkippedPath {
|
|
|
173
175
|
* Non-fatal scan-surface note (additive in 0.4.0, owner-approved): explains a scan whose surface
|
|
174
176
|
* differs from what the caller likely expected - a requested input that produced no analysable
|
|
175
177
|
* files (`no-analysable-files`), or a file whose deep script analysis was bounded by the scan
|
|
176
|
-
* budget (`bounded-deep-scan`)
|
|
177
|
-
* that drives exit 2.
|
|
178
|
+
* budget (`bounded-deep-scan`), or bytes that are not parseable text (`non-text-file`). Notes never
|
|
179
|
+
* affect exit codes; `diagnostics` stays the surface that drives exit 2.
|
|
178
180
|
*/
|
|
179
181
|
export interface ScanSurfaceNote {
|
|
180
|
-
noteType: "no-analysable-files" | "bounded-deep-scan";
|
|
182
|
+
noteType: "no-analysable-files" | "bounded-deep-scan" | "non-text-file";
|
|
181
183
|
path: string;
|
|
182
184
|
message: string;
|
|
183
185
|
}
|