@blundergoat/gruff-ts 0.3.1 → 0.4.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 +19 -0
- package/CONTRIBUTING.md +1 -1
- package/README.md +20 -5
- package/SECURITY.md +1 -1
- package/docs/README.md +0 -1
- package/docs/agent-hook.md +14 -2
- package/docs/configuration.md +15 -0
- package/docs/reports-and-ci.md +21 -0
- package/docs/rules.md +22 -12
- package/package.json +17 -2
- package/src/analyser.ts +410 -122
- package/src/baseline-options.ts +90 -0
- package/src/blocks.ts +56 -9
- package/src/changed-regions.ts +46 -17
- package/src/cli-program.ts +103 -4
- package/src/cli.ts +3 -2
- package/src/constants.ts +1 -1
- package/src/dashboard.ts +1 -1
- package/src/dead-code-rules.ts +10 -3
- package/src/discovery.ts +27 -3
- package/src/findings.ts +2 -0
- package/src/hook-contract.ts +457 -0
- package/src/line-rules.ts +126 -19
- package/src/process-exec-metadata.ts +153 -0
- package/src/project-config-rules.ts +21 -8
- package/src/project-rules.ts +159 -42
- package/src/report-renderers.ts +3 -0
- package/src/rule-list.ts +1 -0
- package/src/rules.ts +5 -5
- package/src/sensitive-data-rules.ts +134 -12
- package/src/source-text.ts +47 -22
- package/src/static-analysis-redundant-rules.ts +46 -2
- package/src/types.ts +16 -1
- package/docs/releasing.md +0 -106
- package/fixtures/sample.ts +0 -21
- package/scripts/bump-version.sh +0 -210
- package/scripts/check.sh +0 -4
- package/scripts/dependency-install.sh +0 -96
- package/scripts/dependency-update.sh +0 -177
- package/scripts/npm-publish.sh +0 -258
- package/scripts/preflight-checks.sh +0 -395
- package/scripts/start-dev.sh +0 -8
- package/scripts/test-performance.sh +0 -695
- package/src/fixtures/rule-catalogue-security-doctrine.ts +0 -160
|
@@ -30,6 +30,9 @@ function analyseSensitiveData(file: SensitiveSourceFile, source: string, config:
|
|
|
30
30
|
for (const [ruleId, pattern, message] of patterns) {
|
|
31
31
|
for (const match of source.matchAll(pattern)) {
|
|
32
32
|
const raw = match[0] ?? "";
|
|
33
|
+
if (isExplicitExampleCredential(raw)) {
|
|
34
|
+
continue;
|
|
35
|
+
}
|
|
33
36
|
pushSensitiveFinding(config, findings, file, ruleId, message, byteLine(source, match.index ?? 0), raw, "high");
|
|
34
37
|
}
|
|
35
38
|
}
|
|
@@ -42,6 +45,14 @@ function analyseSensitiveData(file: SensitiveSourceFile, source: string, config:
|
|
|
42
45
|
analyseGcpServiceAccountKeys(file, source, config, findings);
|
|
43
46
|
}
|
|
44
47
|
|
|
48
|
+
// Explicit fake-credential evidence inside the MATCHED value itself: the canonical AWS doc keys
|
|
49
|
+
// end in EXAMPLE, and redaction fixtures embed REDACTED/PLACEHOLDER/CHANGEME or masked runs.
|
|
50
|
+
// A file path or test location alone never suppresses a production-shaped secret - the marker
|
|
51
|
+
// must be part of the value the pattern matched.
|
|
52
|
+
function isExplicitExampleCredential(raw: string): boolean {
|
|
53
|
+
return /EXAMPLE|REDACTED|PLACEHOLDER|CHANGEME/i.test(raw) || /\*{4}|X{4}/.test(raw);
|
|
54
|
+
}
|
|
55
|
+
|
|
45
56
|
// PHI beyond the MBI shape: medical-record-number assignments. Context-gated on an `MRN` / `medical
|
|
46
57
|
// record` label so bare integers stay clean; stable contract is one redacted finding per label.
|
|
47
58
|
function analysePhiLabelledIdentifiers(file: SensitiveSourceFile, source: string, config: Config, findings: Finding[]): void {
|
|
@@ -69,22 +80,31 @@ function analyseGcpServiceAccountKeys(file: SensitiveSourceFile, source: string,
|
|
|
69
80
|
pushSensitiveFinding(config, findings, file, "sensitive-data.gcp-service-account-key", "GCP service-account key file detected.", byteLine(source, typeMatch.index ?? 0), identifier, "high");
|
|
70
81
|
}
|
|
71
82
|
|
|
72
|
-
|
|
73
|
-
|
|
83
|
+
/*
|
|
84
|
+
* Payment-card PII detection contract: candidate shape, known issuer prefix, length, and Luhn
|
|
85
|
+
* check must all pass before a stable redacted finding is emitted. A bare unseparated digit run
|
|
86
|
+
* additionally needs card vocabulary on its line - large statistics can pass Luhn by coincidence,
|
|
87
|
+
* while separator-grouped numbers are card-formatted by construction.
|
|
88
|
+
*/
|
|
74
89
|
function analysePaymentCardNumbers(file: SensitiveSourceFile, source: string, config: Config, findings: Finding[]): void {
|
|
90
|
+
const lines = source.split(/\r?\n/);
|
|
75
91
|
for (const match of source.matchAll(/\b(?:\d[ -]?){12,18}\d\b/g)) {
|
|
76
92
|
const rawCandidate = match[0] ?? "";
|
|
77
93
|
const cardNumber = normalizedPaymentCardNumber(rawCandidate);
|
|
78
94
|
if (!isPaymentCardNumber(cardNumber)) {
|
|
79
95
|
continue;
|
|
80
96
|
}
|
|
97
|
+
const line = byteLine(source, match.index ?? 0);
|
|
98
|
+
if (!/[ -]/.test(rawCandidate) && !hasPaymentCardContext(lines[line - 1] ?? "")) {
|
|
99
|
+
continue;
|
|
100
|
+
}
|
|
81
101
|
pushSensitiveFinding(
|
|
82
102
|
config,
|
|
83
103
|
findings,
|
|
84
104
|
file,
|
|
85
105
|
"sensitive-data.pii-pattern",
|
|
86
106
|
"Credit card number (PII) pattern detected.",
|
|
87
|
-
|
|
107
|
+
line,
|
|
88
108
|
rawCandidate,
|
|
89
109
|
"high",
|
|
90
110
|
{ piiKind: "credit-card", digits: cardNumber.length },
|
|
@@ -92,6 +112,13 @@ function analysePaymentCardNumbers(file: SensitiveSourceFile, source: string, co
|
|
|
92
112
|
}
|
|
93
113
|
}
|
|
94
114
|
|
|
115
|
+
// Card vocabulary gate for bare digit runs. Substring matching is deliberate so identifier forms
|
|
116
|
+
// (`cardNumber`, `creditCard`, `PAYMENT_CARD`) count as context; `pan` stays word-bounded because
|
|
117
|
+
// it is a common substring of unrelated words.
|
|
118
|
+
function hasPaymentCardContext(lineText: string): boolean {
|
|
119
|
+
return /(?:\bpan\b|card|payment|credit|debit|visa|master|amex|discover|jcb|diners)/i.test(lineText);
|
|
120
|
+
}
|
|
121
|
+
|
|
95
122
|
// Stable redaction contract: parses `_authToken=` config lines even when values lack an npm_ prefix.
|
|
96
123
|
function analyseNpmAuthTokens(file: SensitiveSourceFile, source: string, config: Config, findings: Finding[]): void {
|
|
97
124
|
const lines = source.split(/\r?\n/);
|
|
@@ -125,9 +152,10 @@ function npmAuthTokenValue(line: string): string | undefined {
|
|
|
125
152
|
// from churning the baseline - it is part of the rule's stable, deterministic contract.
|
|
126
153
|
function analyseHardcodedEnvironmentValues(file: SensitiveSourceFile, source: string, config: Config, findings: Finding[]): void {
|
|
127
154
|
const minLength = threshold(config, "sensitive-data.hardcoded-env-value", 16);
|
|
155
|
+
const requiresQuotedValue = isScriptSourcePath(file.displayPath);
|
|
128
156
|
const lines = source.split(/\r?\n/);
|
|
129
157
|
for (const [index, line] of lines.entries()) {
|
|
130
|
-
const envValue = hardcodedEnvValue(line, minLength);
|
|
158
|
+
const envValue = hardcodedEnvValue(line, minLength, requiresQuotedValue);
|
|
131
159
|
if (!envValue) {
|
|
132
160
|
continue;
|
|
133
161
|
}
|
|
@@ -140,7 +168,7 @@ function analyseHardcodedEnvironmentValues(file: SensitiveSourceFile, source: st
|
|
|
140
168
|
index + 1,
|
|
141
169
|
envValue.value,
|
|
142
170
|
"medium",
|
|
143
|
-
{ keyName: envValue.keyName, length: envValue.value.length },
|
|
171
|
+
{ keyName: envValue.keyName, length: envValue.value.length, threshold: minLength },
|
|
144
172
|
ruleSeverity(config, "sensitive-data.hardcoded-env-value", "error"),
|
|
145
173
|
);
|
|
146
174
|
}
|
|
@@ -165,7 +193,7 @@ function analyseHighEntropyStrings(file: SensitiveSourceFile, source: string, co
|
|
|
165
193
|
byteLine(source, match.index ?? 0),
|
|
166
194
|
raw,
|
|
167
195
|
"medium",
|
|
168
|
-
{ length: raw.length, detector: "high-entropy-string" },
|
|
196
|
+
{ length: raw.length, detector: "high-entropy-string", threshold: minLength },
|
|
169
197
|
ruleSeverity(config, "sensitive-data.high-entropy-string", "error"),
|
|
170
198
|
);
|
|
171
199
|
}
|
|
@@ -204,24 +232,36 @@ function pushSensitiveFinding(
|
|
|
204
232
|
|
|
205
233
|
// Two-stage filter: parse the line into a (key, value) pair, then apply the secret-shape filters.
|
|
206
234
|
// Splitting them keeps the regex simple - the line shape is shared, only the value test changes.
|
|
207
|
-
|
|
235
|
+
// In script files only quoted values count: an unquoted `TOKEN: expr` line in TS/JS is an
|
|
236
|
+
// expression (schema builder, secret-provider plumbing), not an embedded string literal.
|
|
237
|
+
function hardcodedEnvValue(line: string, minLength: number, requiresQuotedValue: boolean): { keyName: string; value: string } | undefined {
|
|
208
238
|
const candidate = envValueCandidate(line);
|
|
209
239
|
if (!candidate || !isHardcodedEnvCandidate(candidate.value, minLength)) {
|
|
210
240
|
return undefined;
|
|
211
241
|
}
|
|
242
|
+
if (requiresQuotedValue && !candidate.isQuoted) {
|
|
243
|
+
return undefined;
|
|
244
|
+
}
|
|
212
245
|
return candidate;
|
|
213
246
|
}
|
|
214
247
|
|
|
248
|
+
// Script extensions where unquoted right-hand sides are code expressions rather than literal
|
|
249
|
+
// values. Config formats (.env, .ini, .yaml, .json keys) keep their unquoted-literal semantics.
|
|
250
|
+
function isScriptSourcePath(displayPath: string): boolean {
|
|
251
|
+
return /\.(?:ts|tsx|mts|cts|js|jsx|mjs|cjs)$/i.test(displayPath);
|
|
252
|
+
}
|
|
253
|
+
|
|
215
254
|
// Matches the documented secret-key vocabulary (API_KEY, TOKEN, SECRET, PASSWORD, DATABASE_URL,
|
|
216
255
|
// DSN, CREDENTIAL). Expanding this list will widen sensitive-data coverage - keep it intentional.
|
|
217
|
-
function envValueCandidate(line: string): { keyName: string; value: string } | undefined {
|
|
218
|
-
const match = line.match(/^\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*["']?([^"'
|
|
256
|
+
function envValueCandidate(line: string): { keyName: string; value: string; isQuoted: boolean } | undefined {
|
|
257
|
+
const match = line.match(/^\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*(["'`]?)([^"'`\s#]+)["'`]?/i);
|
|
219
258
|
const keyName = match?.[1] ?? "";
|
|
220
|
-
const
|
|
259
|
+
const openingQuote = match?.[2] ?? "";
|
|
260
|
+
const secretValue = match?.[3] ?? "";
|
|
221
261
|
if (!keyName) {
|
|
222
262
|
return undefined;
|
|
223
263
|
}
|
|
224
|
-
return { keyName, value: secretValue };
|
|
264
|
+
return { keyName, value: secretValue, isQuoted: openingQuote !== "" };
|
|
225
265
|
}
|
|
226
266
|
|
|
227
267
|
// Three predicates combined: long enough, not a literal placeholder, and shape-like (letters + digits).
|
|
@@ -262,8 +302,90 @@ function isHighEntropySecretCandidate(candidateText: string, minLength: number):
|
|
|
262
302
|
// are well-known non-secrets - without these exclusions, package-lock.json scans become noise.
|
|
263
303
|
// Repo-relative path-shaped strings (slashes plus a known extension and a conventional prefix
|
|
264
304
|
// segment) also clear the entropy bar without being secrets; the path-shape guard suppresses them.
|
|
305
|
+
// Alphabet enumerations and dotted/underscored/slug identifiers that decompose into dictionary-like
|
|
306
|
+
// word segments are the remaining non-secret shapes that pass the entropy bar.
|
|
265
307
|
function isExcludedHighEntropyCandidate(candidateText: string, minLength: number): boolean {
|
|
266
|
-
return candidateText.length < minLength
|
|
308
|
+
return candidateText.length < minLength
|
|
309
|
+
|| isHexDigest(candidateText)
|
|
310
|
+
|| isSubresourceIntegrityHash(candidateText)
|
|
311
|
+
|| isRepoPathShape(candidateText)
|
|
312
|
+
|| isCharacterAlphabetString(candidateText)
|
|
313
|
+
|| isWordSegmentIdentifier(candidateText);
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
// Translation/encoding alphabets ("ABC...xyz0123456789+/" in PlantUML, base64 tables) clear the
|
|
317
|
+
// entropy bar but are enumerations, not secrets. The proof is a run of 10+ consecutive code
|
|
318
|
+
// points, which credential generators essentially never produce.
|
|
319
|
+
function isCharacterAlphabetString(candidateText: string): boolean {
|
|
320
|
+
let runLength = 1;
|
|
321
|
+
for (let index = 1; index < candidateText.length; index += 1) {
|
|
322
|
+
if (candidateText.charCodeAt(index) === candidateText.charCodeAt(index - 1) + 1) {
|
|
323
|
+
runLength += 1;
|
|
324
|
+
if (runLength >= 10) {
|
|
325
|
+
return true;
|
|
326
|
+
}
|
|
327
|
+
} else {
|
|
328
|
+
runLength = 1;
|
|
329
|
+
}
|
|
330
|
+
}
|
|
331
|
+
return false;
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
// Word-segment identifier exemption: a dotted namespace ("Com.Example2.Services.TokenProvider"),
|
|
335
|
+
// an underscored constant ("WC_Admin_Reports_V2"), or a slug-like catalog name
|
|
336
|
+
// ("DeepSeek-R1-Distill-Qwen-32B") decomposes entirely into short dictionary-like segments.
|
|
337
|
+
// Real credentials do not - their segments interleave case and digits or run past word length.
|
|
338
|
+
// The token guard runs FIRST so a JWT or segmented token never earns the exemption.
|
|
339
|
+
function isWordSegmentIdentifier(candidateText: string): boolean {
|
|
340
|
+
if (candidateText.includes("+") || candidateText.includes("=")) {
|
|
341
|
+
return false;
|
|
342
|
+
}
|
|
343
|
+
if (isTokenLikeSegmentedSecret(candidateText)) {
|
|
344
|
+
return false;
|
|
345
|
+
}
|
|
346
|
+
const segments = candidateText.split(/[/._-]+/);
|
|
347
|
+
if (segments.length < 2) {
|
|
348
|
+
return false;
|
|
349
|
+
}
|
|
350
|
+
return segments.every(isWordLikeSegment);
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
// Token guard for the word-segment exemption. JWTs always start with "eyJ" (base64 of `{"`), and
|
|
354
|
+
// any single segment that is a 20+ char mixed-case-with-digit run is credential material even when
|
|
355
|
+
// its separators mimic an identifier. Must stay ahead of the word-segment arms - relaxing it would
|
|
356
|
+
// silently exempt JWT-shaped and long base64url secrets.
|
|
357
|
+
function isTokenLikeSegmentedSecret(candidateText: string): boolean {
|
|
358
|
+
if (candidateText.startsWith("eyJ")) {
|
|
359
|
+
return true;
|
|
360
|
+
}
|
|
361
|
+
return candidateText.split(/[/._-]+/).some((segment) => segment.length >= 20 && hasLowerUpperAndDigit(segment));
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
// One identifier segment: letters with digits at most at one boundary ("Example2", "405B",
|
|
365
|
+
// "20241022"), capped at 16 chars. More than one letter<->digit transition means the segment
|
|
366
|
+
// interleaves like token material and must not earn the exemption.
|
|
367
|
+
function isWordLikeSegment(segment: string): boolean {
|
|
368
|
+
if (segment.length === 0 || segment.length > 16 || !/^[A-Za-z0-9]+$/.test(segment)) {
|
|
369
|
+
return false;
|
|
370
|
+
}
|
|
371
|
+
return letterDigitTransitionCount(segment) <= 1;
|
|
372
|
+
}
|
|
373
|
+
|
|
374
|
+
// Counts boundaries where the segment switches between letter and digit runs; word-like segments
|
|
375
|
+
// have at most one ("Example2"), token material alternates repeatedly ("Xk9pQ2vL").
|
|
376
|
+
function letterDigitTransitionCount(segment: string): number {
|
|
377
|
+
let transitions = 0;
|
|
378
|
+
for (let index = 1; index < segment.length; index += 1) {
|
|
379
|
+
if (isDigitCharCode(segment.charCodeAt(index - 1)) !== isDigitCharCode(segment.charCodeAt(index))) {
|
|
380
|
+
transitions += 1;
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
return transitions;
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
// Character-code digit test so the transition counter never needs unchecked string indexing.
|
|
387
|
+
function isDigitCharCode(code: number): boolean {
|
|
388
|
+
return code >= 48 && code <= 57;
|
|
267
389
|
}
|
|
268
390
|
|
|
269
391
|
// Path-shape guard: a string that contains at least one `/`, has a path-like extension, AND lives
|
package/src/source-text.ts
CHANGED
|
@@ -2,43 +2,68 @@
|
|
|
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 { createRequire } from "node:module";
|
|
5
6
|
import type { RunDiagnostic } from "./types.ts";
|
|
6
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
|
+
|
|
7
20
|
// Just enough of `SourceFile` to keep `parseDiagnostics` decoupled from the full project type:
|
|
8
|
-
// `isScript` gates whether
|
|
21
|
+
// `isScript` gates whether parser diagnostics run; `displayPath` is the report-path anchor.
|
|
9
22
|
interface DiagnosticSourceFile {
|
|
10
23
|
displayPath: string;
|
|
11
24
|
isScript: boolean;
|
|
12
25
|
}
|
|
13
26
|
|
|
14
27
|
/**
|
|
15
|
-
*
|
|
16
|
-
* reports closers that outrun openers because those are local enough for a heuristic to trust.
|
|
28
|
+
* Syntax-only TypeScript parser diagnostics for script files; non-script inputs stay unparsed.
|
|
17
29
|
*
|
|
18
30
|
* @param file - Source metadata used to skip non-script inputs and report paths.
|
|
19
|
-
* @param source - Raw file text to
|
|
31
|
+
* @param source - Raw file text to parse for syntax diagnostics.
|
|
20
32
|
*/
|
|
21
33
|
function parseDiagnostics(file: DiagnosticSourceFile, source: string): RunDiagnostic[] {
|
|
22
34
|
if (!file.isScript) {
|
|
23
35
|
return [];
|
|
24
36
|
}
|
|
25
|
-
const
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
return [parseErrorDiagnostic(file, index + 1)];
|
|
34
|
-
}
|
|
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;
|
|
35
45
|
}
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
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, " ")}`;
|
|
42
67
|
}
|
|
43
68
|
|
|
44
69
|
// Running totals for `{}`, `()`, and `[]`. A negative count means a closer appeared with no opener
|
|
@@ -281,10 +306,10 @@ function hasUnbalancedDelimiterCount(counts: DelimiterCounts): boolean {
|
|
|
281
306
|
* whenever diagnostics fire - this builder reports failures so a broken file in the scan tree
|
|
282
307
|
* cannot hide silently rather than throw the error or recover quietly.
|
|
283
308
|
*/
|
|
284
|
-
function parseErrorDiagnostic(file: DiagnosticSourceFile, line: number): RunDiagnostic {
|
|
309
|
+
function parseErrorDiagnostic(file: DiagnosticSourceFile, line: number, message: string): RunDiagnostic {
|
|
285
310
|
return {
|
|
286
311
|
diagnosticType: "parse-error",
|
|
287
|
-
message
|
|
312
|
+
message,
|
|
288
313
|
filePath: file.displayPath,
|
|
289
314
|
line,
|
|
290
315
|
};
|
|
@@ -13,6 +13,8 @@ interface StaticAnalysisRedundantAssertion {
|
|
|
13
13
|
sourceProof?: string;
|
|
14
14
|
confidence: Confidence;
|
|
15
15
|
recommendation: string;
|
|
16
|
+
reasonCategory?: string;
|
|
17
|
+
suggestedAction?: string;
|
|
16
18
|
index: number;
|
|
17
19
|
}
|
|
18
20
|
|
|
@@ -75,7 +77,7 @@ export function pushStaticAnalysisRedundantTestFindings(file: SourceFile, block:
|
|
|
75
77
|
findings.push(
|
|
76
78
|
makeFinding({
|
|
77
79
|
ruleId: "test-quality.static-analysis-redundant-test",
|
|
78
|
-
message:
|
|
80
|
+
message: staticAnalysisRedundantMessage(block, candidate),
|
|
79
81
|
filePath: file.displayPath,
|
|
80
82
|
line,
|
|
81
83
|
severity: "advisory",
|
|
@@ -91,6 +93,8 @@ export function pushStaticAnalysisRedundantTestFindings(file: SourceFile, block:
|
|
|
91
93
|
sourceProof: candidate.sourceProof ?? `${file.displayPath}:${line}`,
|
|
92
94
|
confidence: candidate.confidence,
|
|
93
95
|
recommendation: candidate.recommendation,
|
|
96
|
+
...(candidate.reasonCategory ? { reasonCategory: candidate.reasonCategory } : {}),
|
|
97
|
+
...(candidate.suggestedAction ? { suggestedAction: candidate.suggestedAction } : {}),
|
|
94
98
|
},
|
|
95
99
|
}),
|
|
96
100
|
);
|
|
@@ -103,7 +107,9 @@ function staticAnalysisRedundantAssertions(file: SourceFile, block: FunctionBloc
|
|
|
103
107
|
...typeofFunctionAssertions(file, rawSource, codeSource, staticContext),
|
|
104
108
|
...directConstructionInstanceAssertions(file, rawSource, codeSource),
|
|
105
109
|
...nonNullableReturnAssertions(file, block, rawSource, codeSource),
|
|
106
|
-
]
|
|
110
|
+
]
|
|
111
|
+
.map((candidate) => staticAnalysisActionabilityCandidate(block, candidate))
|
|
112
|
+
.sort((left, right) => left.index - right.index);
|
|
107
113
|
}
|
|
108
114
|
|
|
109
115
|
// Detects `typeof x === "function"`-style assertions when TypeScript already proves the function.
|
|
@@ -368,6 +374,44 @@ function staticRedundantCandidate(args: Omit<StaticAnalysisRedundantAssertion, "
|
|
|
368
374
|
};
|
|
369
375
|
}
|
|
370
376
|
|
|
377
|
+
// Downgrades importability sentinel tests to review/document guidance instead of delete guidance.
|
|
378
|
+
function staticAnalysisActionabilityCandidate(block: FunctionBlock, candidate: StaticAnalysisRedundantAssertion): StaticAnalysisRedundantAssertion {
|
|
379
|
+
if (!isImportabilitySentinelCandidate(block, candidate)) {
|
|
380
|
+
return candidate;
|
|
381
|
+
}
|
|
382
|
+
return {
|
|
383
|
+
...candidate,
|
|
384
|
+
confidence: "medium",
|
|
385
|
+
recommendation:
|
|
386
|
+
"Review or document this importability sentinel instead of deleting it mechanically; document why runtime module-load coverage matters if it protects export wiring, or replace it with observable behavior if it only repeats type information.",
|
|
387
|
+
reasonCategory: "importability-sentinel",
|
|
388
|
+
suggestedAction: "review-or-document",
|
|
389
|
+
};
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
// Sentinel candidates need both a module-load style test name and static import evidence.
|
|
393
|
+
function isImportabilitySentinelCandidate(block: FunctionBlock, candidate: StaticAnalysisRedundantAssertion): boolean {
|
|
394
|
+
return hasImportabilitySentinelName(block.name) && hasStaticImportProof(candidate);
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
// Test names that say export/import/module contract imply the assertion may protect wiring.
|
|
398
|
+
function hasImportabilitySentinelName(testName: string): boolean {
|
|
399
|
+
return /\b(?:importability|module[-\s]+load|load[-\s]+graph|exports?|contract)\b/i.test(testName);
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
// Static import proof distinguishes module-load sentinels from ordinary type-shape assertions.
|
|
403
|
+
function hasStaticImportProof(candidate: StaticAnalysisRedundantAssertion): boolean {
|
|
404
|
+
return candidate.sourceProof !== undefined && /\bimport\b/i.test(candidate.staticFact) && /\bstatic(?:ally)?\b/i.test(candidate.staticFact);
|
|
405
|
+
}
|
|
406
|
+
|
|
407
|
+
// Renders the finding message from the final confidence/actionability decision.
|
|
408
|
+
function staticAnalysisRedundantMessage(block: FunctionBlock, candidate: StaticAnalysisRedundantAssertion): string {
|
|
409
|
+
if (candidate.reasonCategory === "importability-sentinel") {
|
|
410
|
+
return `Review importability sentinel: ${candidate.confidence} confidence. Test \`${block.name}\` asserts static import shape rather than behaviour: ${candidate.assertion}.`;
|
|
411
|
+
}
|
|
412
|
+
return `Static-analysis-redundant candidate: ${candidate.confidence} confidence. Test \`${block.name}\` asserts code shape rather than behaviour: ${candidate.assertion}.`;
|
|
413
|
+
}
|
|
414
|
+
|
|
371
415
|
// Type guard used after optional candidate builders so callers keep precise arrays.
|
|
372
416
|
function isStaticAnalysisRedundantAssertion(candidate: StaticAnalysisRedundantAssertion | undefined): candidate is StaticAnalysisRedundantAssertion {
|
|
373
417
|
return candidate !== undefined;
|
package/src/types.ts
CHANGED
|
@@ -25,7 +25,7 @@ export type OutputFormat = "text" | "json" | "html" | "markdown" | "github" | "h
|
|
|
25
25
|
export type FailThreshold = "none" | "advisory" | "warning" | "error";
|
|
26
26
|
|
|
27
27
|
/** Changed-region filter precision for diff-aware analysis. */
|
|
28
|
-
export type ChangedScopeMode = "symbol" | "hunk";
|
|
28
|
+
export type ChangedScopeMode = "symbol" | "hunk" | "file";
|
|
29
29
|
|
|
30
30
|
/** Public options contract consumed by the analyzer core and CLI. */
|
|
31
31
|
export interface AnalysisOptions {
|
|
@@ -169,6 +169,19 @@ export interface SkippedPath {
|
|
|
169
169
|
pattern: string;
|
|
170
170
|
}
|
|
171
171
|
|
|
172
|
+
/**
|
|
173
|
+
* Non-fatal scan-surface note (additive in 0.4.0, owner-approved): explains a scan whose surface
|
|
174
|
+
* differs from what the caller likely expected - a requested input that produced no analysable
|
|
175
|
+
* files (`no-analysable-files`), or a file whose deep script analysis was bounded by the scan
|
|
176
|
+
* budget (`bounded-deep-scan`). Notes never affect exit codes; `diagnostics` stays the surface
|
|
177
|
+
* that drives exit 2.
|
|
178
|
+
*/
|
|
179
|
+
export interface ScanSurfaceNote {
|
|
180
|
+
noteType: "no-analysable-files" | "bounded-deep-scan";
|
|
181
|
+
path: string;
|
|
182
|
+
message: string;
|
|
183
|
+
}
|
|
184
|
+
|
|
172
185
|
/**
|
|
173
186
|
* Stable gruff.analysis.v2 report schema returned by analyse and JSON report commands.
|
|
174
187
|
*
|
|
@@ -183,6 +196,8 @@ export interface AnalysisReport {
|
|
|
183
196
|
summary: { advisory: number; warning: number; error: number; total: number };
|
|
184
197
|
paths: { analysedFiles: number; ignoredPaths: string[]; skipped: SkippedPath[]; missingPaths: string[] };
|
|
185
198
|
diagnostics: RunDiagnostic[];
|
|
199
|
+
/** Additive in 0.4.0: present only when at least one scan-surface note was produced. */
|
|
200
|
+
notes?: ScanSurfaceNote[];
|
|
186
201
|
findings: Finding[];
|
|
187
202
|
suppressedCount?: number;
|
|
188
203
|
score: {
|
package/docs/releasing.md
DELETED
|
@@ -1,106 +0,0 @@
|
|
|
1
|
-
# Releasing
|
|
2
|
-
|
|
3
|
-
This checklist prepares public `@blundergoat/gruff-ts@0.3.x` patch releases.
|
|
4
|
-
Current release line: `0.3.0`.
|
|
5
|
-
|
|
6
|
-
## Bump The Version
|
|
7
|
-
|
|
8
|
-
`scripts/bump-version.sh <semver>` updates `package.json`,
|
|
9
|
-
`package-lock.json`, and `src/constants.ts` together so the CLI `--version`
|
|
10
|
-
output and the published `@blundergoat/gruff-ts` package version cannot drift
|
|
11
|
-
apart. For a no-op release (e.g. fixes folded into the current dated version),
|
|
12
|
-
the version should already match; use `--check` instead of bumping unless the
|
|
13
|
-
release version changes.
|
|
14
|
-
|
|
15
|
-
```bash
|
|
16
|
-
scripts/bump-version.sh --check
|
|
17
|
-
scripts/bump-version.sh 0.3.1
|
|
18
|
-
scripts/bump-version.sh --check
|
|
19
|
-
```
|
|
20
|
-
|
|
21
|
-
The script edits files in place and does not commit or tag. After running it,
|
|
22
|
-
update `CHANGELOG.md` and run `npm run check`.
|
|
23
|
-
|
|
24
|
-
## Before Publishing
|
|
25
|
-
|
|
26
|
-
- [ ] `scripts/bump-version.sh --check` reports the intended version.
|
|
27
|
-
- [ ] `CHANGELOG.md` has an entry for the new version with today's date.
|
|
28
|
-
- [ ] `README.md`, `CONTRIBUTING.md`, `SECURITY.md`, and docs under `docs/`
|
|
29
|
-
reflect any user-visible changes.
|
|
30
|
-
- [ ] `.goat-flow/tasks/0.3.0/` has no unresolved release blockers beyond
|
|
31
|
-
explicitly accepted `human-verification-pending` milestones.
|
|
32
|
-
- [ ] `LICENSE` is present and `package.json` `license` field matches.
|
|
33
|
-
- [ ] `npm run check` passes.
|
|
34
|
-
- [ ] `scripts/preflight-checks.sh` passes (checks version lockstep, runs
|
|
35
|
-
`npm audit --audit-level=moderate`, `npm run check`, a full `gruff-ts`
|
|
36
|
-
self-scan, and `shellcheck` on `scripts/*.sh` when `shellcheck` is
|
|
37
|
-
installed).
|
|
38
|
-
- [ ] `npm pack --dry-run` shows only publishable runtime, docs, scripts, and
|
|
39
|
-
metadata files.
|
|
40
|
-
- [ ] Local smoke scan succeeds:
|
|
41
|
-
|
|
42
|
-
```bash
|
|
43
|
-
./bin/gruff-ts
|
|
44
|
-
./bin/gruff-ts analyse fixtures/sample.ts --fail-on=none
|
|
45
|
-
./bin/gruff-ts summary fixtures/sample.ts --fail-on=none
|
|
46
|
-
./bin/gruff-ts report fixtures/sample.ts --output /tmp/gruff-ts-report.html
|
|
47
|
-
./bin/gruff-ts list-rules
|
|
48
|
-
```
|
|
49
|
-
|
|
50
|
-
## Package Review
|
|
51
|
-
|
|
52
|
-
Preview `@blundergoat/gruff-ts` package contents:
|
|
53
|
-
|
|
54
|
-
```bash
|
|
55
|
-
npm pack --dry-run
|
|
56
|
-
```
|
|
57
|
-
|
|
58
|
-
The package should include:
|
|
59
|
-
|
|
60
|
-
- `bin/gruff-ts`
|
|
61
|
-
- `src/` (all runtime `.ts` files; `src/**/*.test.ts` files are excluded by
|
|
62
|
-
`.npmignore`)
|
|
63
|
-
- `scripts/` (`bump-version.sh`, `check.sh`, `dependency-install.sh`,
|
|
64
|
-
`dependency-update.sh`, `preflight-checks.sh`, `npm-publish.sh`,
|
|
65
|
-
`start-dev.sh`, `test-performance.sh`)
|
|
66
|
-
- `fixtures/sample.ts`
|
|
67
|
-
- `README.md`
|
|
68
|
-
- `CHANGELOG.md`
|
|
69
|
-
- `CONTRIBUTING.md`
|
|
70
|
-
- `SECURITY.md`
|
|
71
|
-
- `LICENSE`
|
|
72
|
-
- `docs/`
|
|
73
|
-
- `package.json`
|
|
74
|
-
- `tsconfig.json`
|
|
75
|
-
|
|
76
|
-
The package must exclude:
|
|
77
|
-
|
|
78
|
-
- `node_modules/`
|
|
79
|
-
- `coverage/`
|
|
80
|
-
- `.agents/`, `.claude/`, `.codex/`, `.github/`, and `.goat-flow/`
|
|
81
|
-
- `AGENTS.md` and `CLAUDE.md`
|
|
82
|
-
- `.gruff-ts.yaml` (this repo's local config)
|
|
83
|
-
- env and secret files (`.env`, `.env.*` except `.env.example`)
|
|
84
|
-
- local scratchpad or log artifacts
|
|
85
|
-
- `src/**/*.test.ts`
|
|
86
|
-
|
|
87
|
-
## Publish
|
|
88
|
-
|
|
89
|
-
```bash
|
|
90
|
-
bash scripts/npm-publish.sh
|
|
91
|
-
```
|
|
92
|
-
|
|
93
|
-
The script verifies npm auth, checks version lockstep, runs
|
|
94
|
-
`scripts/preflight-checks.sh`, prints an `npm publish --dry-run` summary, and
|
|
95
|
-
prompts before publishing.
|
|
96
|
-
|
|
97
|
-
## After Publishing
|
|
98
|
-
|
|
99
|
-
- [ ] Install `@blundergoat/gruff-ts` in a temporary project.
|
|
100
|
-
- [ ] Run `gruff-ts --help`.
|
|
101
|
-
- [ ] Run `gruff-ts analyse . --fail-on=none`.
|
|
102
|
-
- [ ] Run `gruff-ts summary . --fail-on=none`.
|
|
103
|
-
- [ ] Run `gruff-ts list-rules`.
|
|
104
|
-
- [ ] Verify `README.md` install instructions from a clean checkout.
|
|
105
|
-
- [ ] Tag the release in git (`git tag v0.3.0 && git push --tags`) and create
|
|
106
|
-
or update public release notes from `CHANGELOG.md`.
|
package/fixtures/sample.ts
DELETED
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
export class SampleAnalyzer {
|
|
2
|
-
public name = "demo";
|
|
3
|
-
private secretUrl = "mysql://demo:password123@example.test/app";
|
|
4
|
-
|
|
5
|
-
public process(a: boolean, b: string[], c: string, d: string, e: string, f: string): void {
|
|
6
|
-
if (a) {
|
|
7
|
-
for (const item of b) {
|
|
8
|
-
if (item === c) {
|
|
9
|
-
eval(item);
|
|
10
|
-
}
|
|
11
|
-
}
|
|
12
|
-
}
|
|
13
|
-
|
|
14
|
-
const apiKey = "AKIA1111111111111111";
|
|
15
|
-
console.log(apiKey, this.secretUrl, d, e, f);
|
|
16
|
-
}
|
|
17
|
-
}
|
|
18
|
-
|
|
19
|
-
test("sleeps without assertion", async () => {
|
|
20
|
-
await new Promise((resolve) => setTimeout(resolve, 1));
|
|
21
|
-
});
|