@blundergoat/gruff-ts 0.3.2 → 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 +54 -1
- package/README.md +16 -6
- package/SECURITY.md +2 -1
- package/docs/README.md +1 -4
- package/docs/agent-hook.md +15 -3
- package/docs/configuration.md +47 -1
- package/docs/dashboard.md +3 -3
- package/docs/reports-and-ci.md +36 -0
- package/docs/rules.md +52 -37
- package/package.json +1 -1
- package/src/analyser.ts +540 -154
- package/src/baseline-options.ts +90 -0
- package/src/baseline.ts +39 -3
- package/src/blocks.ts +116 -77
- package/src/changed-regions.ts +80 -11
- package/src/class-rules.ts +226 -76
- package/src/cli-program.ts +65 -15
- package/src/cli.ts +4 -2
- 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/dead-code-rules.ts +10 -3
- package/src/discovery.ts +66 -22
- 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 +120 -27
- package/src/init-config.ts +15 -5
- package/src/line-rules.ts +175 -19
- package/src/naming-pushers.ts +26 -5
- package/src/parsed-script.ts +652 -0
- package/src/process-exec-metadata.ts +163 -0
- package/src/profiles.ts +14 -0
- package/src/project-config-rules.ts +36 -18
- package/src/project-rules.ts +159 -42
- package/src/public-exports.ts +220 -0
- package/src/report-renderers.ts +58 -4
- package/src/rules.ts +15 -15
- package/src/scoring.ts +13 -4
- package/src/security-flow-rules.ts +169 -24
- package/src/sensitive-data-rules.ts +256 -80
- package/src/source-text.ts +9 -26
- package/src/static-analysis-redundant-rules.ts +46 -2
- 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 +17 -0
|
@@ -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
|
|
@@ -30,7 +30,10 @@ 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
|
-
|
|
33
|
+
if (isExplicitExampleCredential(raw)) {
|
|
34
|
+
continue;
|
|
35
|
+
}
|
|
36
|
+
pushSensitiveFinding({ config, findings, file, ruleId, message, line: byteLine(source, match.index ?? 0), column: byteColumn(source, match.index ?? 0), raw, confidence: "high" });
|
|
34
37
|
}
|
|
35
38
|
}
|
|
36
39
|
|
|
@@ -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 {
|
|
@@ -52,7 +63,7 @@ function analysePhiLabelledIdentifiers(file: SensitiveSourceFile, source: string
|
|
|
52
63
|
if (!medicalRecordNumber) {
|
|
53
64
|
continue;
|
|
54
65
|
}
|
|
55
|
-
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" });
|
|
56
67
|
}
|
|
57
68
|
}
|
|
58
69
|
|
|
@@ -66,30 +77,71 @@ function analyseGcpServiceAccountKeys(file: SensitiveSourceFile, source: string,
|
|
|
66
77
|
const identifier = source.match(/"private_key_id"\s*:\s*"([^"]+)"/)?.[1]
|
|
67
78
|
?? source.match(/"client_email"\s*:\s*"([^"]+)"/)?.[1]
|
|
68
79
|
?? "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");
|
|
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" });
|
|
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 canonically grouped numbers provide formatting evidence on their own.
|
|
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
|
+
const line = byteLine(source, match.index ?? 0);
|
|
95
|
+
// The helper owns the shape/checksum/vocabulary gates; anything failing them is not a card.
|
|
96
|
+
if (!isReportablePaymentCardCandidate(rawCandidate, cardNumber, lines[line - 1] ?? "")) {
|
|
79
97
|
continue;
|
|
80
98
|
}
|
|
81
|
-
pushSensitiveFinding(
|
|
99
|
+
pushSensitiveFinding({
|
|
82
100
|
config,
|
|
83
101
|
findings,
|
|
84
102
|
file,
|
|
85
|
-
"sensitive-data.pii-pattern",
|
|
86
|
-
"Credit card number (PII) pattern detected.",
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
103
|
+
ruleId: "sensitive-data.pii-pattern",
|
|
104
|
+
message: "Credit card number (PII) pattern detected.",
|
|
105
|
+
line,
|
|
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;
|
|
92
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]);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// Card vocabulary gate for bare digit runs. Substring matching is deliberate so identifier forms
|
|
141
|
+
// (`cardNumber`, `creditCard`, `PAYMENT_CARD`) count as context; `pan` stays word-bounded because
|
|
142
|
+
// it is a common substring of unrelated words.
|
|
143
|
+
function hasPaymentCardContext(lineText: string): boolean {
|
|
144
|
+
return /(?:\bpan\b|card|payment|credit|debit|visa|master|amex|discover|jcb|diners)/i.test(lineText);
|
|
93
145
|
}
|
|
94
146
|
|
|
95
147
|
// Stable redaction contract: parses `_authToken=` config lines even when values lack an npm_ prefix.
|
|
@@ -100,17 +152,17 @@ function analyseNpmAuthTokens(file: SensitiveSourceFile, source: string, config:
|
|
|
100
152
|
if (!token) {
|
|
101
153
|
continue;
|
|
102
154
|
}
|
|
103
|
-
pushSensitiveFinding(
|
|
155
|
+
pushSensitiveFinding({
|
|
104
156
|
config,
|
|
105
157
|
findings,
|
|
106
158
|
file,
|
|
107
|
-
"sensitive-data.api-key-pattern",
|
|
108
|
-
"npm auth token pattern detected.",
|
|
109
|
-
index + 1,
|
|
110
|
-
token,
|
|
111
|
-
"high",
|
|
112
|
-
{ keyName: "_authToken" },
|
|
113
|
-
);
|
|
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
|
+
});
|
|
114
166
|
}
|
|
115
167
|
}
|
|
116
168
|
|
|
@@ -125,24 +177,25 @@ function npmAuthTokenValue(line: string): string | undefined {
|
|
|
125
177
|
// from churning the baseline - it is part of the rule's stable, deterministic contract.
|
|
126
178
|
function analyseHardcodedEnvironmentValues(file: SensitiveSourceFile, source: string, config: Config, findings: Finding[]): void {
|
|
127
179
|
const minLength = threshold(config, "sensitive-data.hardcoded-env-value", 16);
|
|
180
|
+
const requiresQuotedValue = isScriptSourcePath(file.displayPath);
|
|
128
181
|
const lines = source.split(/\r?\n/);
|
|
129
182
|
for (const [index, line] of lines.entries()) {
|
|
130
|
-
const envValue = hardcodedEnvValue(line, minLength);
|
|
183
|
+
const envValue = hardcodedEnvValue(line, minLength, requiresQuotedValue);
|
|
131
184
|
if (!envValue) {
|
|
132
185
|
continue;
|
|
133
186
|
}
|
|
134
|
-
pushSensitiveFinding(
|
|
187
|
+
pushSensitiveFinding({
|
|
135
188
|
config,
|
|
136
189
|
findings,
|
|
137
190
|
file,
|
|
138
|
-
"sensitive-data.hardcoded-env-value",
|
|
139
|
-
`Environment-style value \`${envValue.keyName}\` appears to be hardcoded with secret-like content.`,
|
|
140
|
-
index + 1,
|
|
141
|
-
envValue.value,
|
|
142
|
-
"medium",
|
|
143
|
-
{ keyName: envValue.keyName, length: envValue.value.length, threshold: minLength },
|
|
144
|
-
ruleSeverity(config, "sensitive-data.hardcoded-env-value", "error"),
|
|
145
|
-
);
|
|
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
|
+
});
|
|
146
199
|
}
|
|
147
200
|
}
|
|
148
201
|
|
|
@@ -156,72 +209,107 @@ function analyseHighEntropyStrings(file: SensitiveSourceFile, source: string, co
|
|
|
156
209
|
if (!isHighEntropySecretCandidate(raw, minLength)) {
|
|
157
210
|
continue;
|
|
158
211
|
}
|
|
159
|
-
pushSensitiveFinding(
|
|
212
|
+
pushSensitiveFinding({
|
|
160
213
|
config,
|
|
161
214
|
findings,
|
|
162
215
|
file,
|
|
163
|
-
"sensitive-data.high-entropy-string",
|
|
164
|
-
"High-entropy string literal may be an embedded secret.",
|
|
165
|
-
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),
|
|
166
220
|
raw,
|
|
167
|
-
"medium",
|
|
168
|
-
{ length: raw.length, detector: "high-entropy-string", threshold: minLength },
|
|
169
|
-
ruleSeverity(config, "sensitive-data.high-entropy-string", "error"),
|
|
170
|
-
);
|
|
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
|
+
});
|
|
171
225
|
}
|
|
172
226
|
}
|
|
173
227
|
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
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)) {
|
|
188
256
|
return;
|
|
189
257
|
}
|
|
190
|
-
findings.push(
|
|
258
|
+
args.findings.push(
|
|
191
259
|
makeFinding({
|
|
192
|
-
ruleId,
|
|
193
|
-
message: `${message} Redacted preview: ${preview}.`,
|
|
194
|
-
filePath: file.displayPath,
|
|
195
|
-
line,
|
|
196
|
-
|
|
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",
|
|
197
266
|
pillar: "sensitive-data",
|
|
198
|
-
confidence,
|
|
267
|
+
confidence: args.confidence,
|
|
199
268
|
remediation: "Remove the sensitive value and load it from a secure runtime source.",
|
|
200
|
-
metadata: { ...metadata, preview },
|
|
269
|
+
metadata: { ...(args.metadata ?? {}), preview },
|
|
201
270
|
}),
|
|
202
271
|
);
|
|
203
272
|
}
|
|
204
273
|
|
|
205
274
|
// Two-stage filter: parse the line into a (key, value) pair, then apply the secret-shape filters.
|
|
206
275
|
// Splitting them keeps the regex simple - the line shape is shared, only the value test changes.
|
|
207
|
-
|
|
276
|
+
// In script files only quoted values count: an unquoted `TOKEN: expr` line in TS/JS is an
|
|
277
|
+
// expression (schema builder, secret-provider plumbing), not an embedded string literal.
|
|
278
|
+
function hardcodedEnvValue(line: string, minLength: number, requiresQuotedValue: boolean): { keyName: string; value: string } | undefined {
|
|
208
279
|
const candidate = envValueCandidate(line);
|
|
209
280
|
if (!candidate || !isHardcodedEnvCandidate(candidate.value, minLength)) {
|
|
210
281
|
return undefined;
|
|
211
282
|
}
|
|
283
|
+
if (requiresQuotedValue && !candidate.isQuoted) {
|
|
284
|
+
return undefined;
|
|
285
|
+
}
|
|
212
286
|
return candidate;
|
|
213
287
|
}
|
|
214
288
|
|
|
215
|
-
//
|
|
216
|
-
//
|
|
217
|
-
function
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
289
|
+
// Script extensions where unquoted right-hand sides are code expressions rather than literal
|
|
290
|
+
// values. Config formats (.env, .ini, .yaml, .json keys) keep their unquoted-literal semantics.
|
|
291
|
+
function isScriptSourcePath(displayPath: string): boolean {
|
|
292
|
+
return /\.(?:ts|tsx|mts|cts|js|jsx|mjs|cjs)$/i.test(displayPath);
|
|
293
|
+
}
|
|
294
|
+
|
|
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.
|
|
299
|
+
function envValueCandidate(line: string): { keyName: string; value: string; isQuoted: boolean } | undefined {
|
|
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) {
|
|
222
303
|
return undefined;
|
|
223
304
|
}
|
|
224
|
-
|
|
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) {
|
|
310
|
+
return undefined;
|
|
311
|
+
}
|
|
312
|
+
return { keyName, value: secretValue, isQuoted: quotedValue !== undefined };
|
|
225
313
|
}
|
|
226
314
|
|
|
227
315
|
// Three predicates combined: long enough, not a literal placeholder, and shape-like (letters + digits).
|
|
@@ -262,8 +350,90 @@ function isHighEntropySecretCandidate(candidateText: string, minLength: number):
|
|
|
262
350
|
// are well-known non-secrets - without these exclusions, package-lock.json scans become noise.
|
|
263
351
|
// Repo-relative path-shaped strings (slashes plus a known extension and a conventional prefix
|
|
264
352
|
// segment) also clear the entropy bar without being secrets; the path-shape guard suppresses them.
|
|
353
|
+
// Alphabet enumerations and dotted/underscored/slug identifiers that decompose into dictionary-like
|
|
354
|
+
// word segments are the remaining non-secret shapes that pass the entropy bar.
|
|
265
355
|
function isExcludedHighEntropyCandidate(candidateText: string, minLength: number): boolean {
|
|
266
|
-
return candidateText.length < minLength
|
|
356
|
+
return candidateText.length < minLength
|
|
357
|
+
|| isHexDigest(candidateText)
|
|
358
|
+
|| isSubresourceIntegrityHash(candidateText)
|
|
359
|
+
|| isRepoPathShape(candidateText)
|
|
360
|
+
|| isCharacterAlphabetString(candidateText)
|
|
361
|
+
|| isWordSegmentIdentifier(candidateText);
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
// Translation/encoding alphabets ("ABC...xyz0123456789+/" in PlantUML, base64 tables) clear the
|
|
365
|
+
// entropy bar but are enumerations, not secrets. The proof is a run of 10+ consecutive code
|
|
366
|
+
// points, which credential generators essentially never produce.
|
|
367
|
+
function isCharacterAlphabetString(candidateText: string): boolean {
|
|
368
|
+
let runLength = 1;
|
|
369
|
+
for (let index = 1; index < candidateText.length; index += 1) {
|
|
370
|
+
if (candidateText.charCodeAt(index) === candidateText.charCodeAt(index - 1) + 1) {
|
|
371
|
+
runLength += 1;
|
|
372
|
+
if (runLength >= 10) {
|
|
373
|
+
return true;
|
|
374
|
+
}
|
|
375
|
+
} else {
|
|
376
|
+
runLength = 1;
|
|
377
|
+
}
|
|
378
|
+
}
|
|
379
|
+
return false;
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
// Word-segment identifier exemption: a dotted namespace ("Com.Example2.Services.TokenProvider"),
|
|
383
|
+
// an underscored constant ("WC_Admin_Reports_V2"), or a slug-like catalog name
|
|
384
|
+
// ("DeepSeek-R1-Distill-Qwen-32B") decomposes entirely into short dictionary-like segments.
|
|
385
|
+
// Real credentials do not - their segments interleave case and digits or run past word length.
|
|
386
|
+
// The token guard runs FIRST so a JWT or segmented token never earns the exemption.
|
|
387
|
+
function isWordSegmentIdentifier(candidateText: string): boolean {
|
|
388
|
+
if (candidateText.includes("+") || candidateText.includes("=")) {
|
|
389
|
+
return false;
|
|
390
|
+
}
|
|
391
|
+
if (isTokenLikeSegmentedSecret(candidateText)) {
|
|
392
|
+
return false;
|
|
393
|
+
}
|
|
394
|
+
const segments = candidateText.split(/[/._-]+/);
|
|
395
|
+
if (segments.length < 2) {
|
|
396
|
+
return false;
|
|
397
|
+
}
|
|
398
|
+
return segments.every(isWordLikeSegment);
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
// Token guard for the word-segment exemption. JWTs always start with "eyJ" (base64 of `{"`), and
|
|
402
|
+
// any single segment that is a 20+ char mixed-case-with-digit run is credential material even when
|
|
403
|
+
// its separators mimic an identifier. Must stay ahead of the word-segment arms - relaxing it would
|
|
404
|
+
// silently exempt JWT-shaped and long base64url secrets.
|
|
405
|
+
function isTokenLikeSegmentedSecret(candidateText: string): boolean {
|
|
406
|
+
if (candidateText.startsWith("eyJ")) {
|
|
407
|
+
return true;
|
|
408
|
+
}
|
|
409
|
+
return candidateText.split(/[/._-]+/).some((segment) => segment.length >= 20 && hasLowerUpperAndDigit(segment));
|
|
410
|
+
}
|
|
411
|
+
|
|
412
|
+
// One identifier segment: letters with digits at most at one boundary ("Example2", "405B",
|
|
413
|
+
// "20241022"), capped at 16 chars. More than one letter<->digit transition means the segment
|
|
414
|
+
// interleaves like token material and must not earn the exemption.
|
|
415
|
+
function isWordLikeSegment(segment: string): boolean {
|
|
416
|
+
if (segment.length === 0 || segment.length > 16 || !/^[A-Za-z0-9]+$/.test(segment)) {
|
|
417
|
+
return false;
|
|
418
|
+
}
|
|
419
|
+
return letterDigitTransitionCount(segment) <= 1;
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
// Counts boundaries where the segment switches between letter and digit runs; word-like segments
|
|
423
|
+
// have at most one ("Example2"), token material alternates repeatedly ("Xk9pQ2vL").
|
|
424
|
+
function letterDigitTransitionCount(segment: string): number {
|
|
425
|
+
let transitions = 0;
|
|
426
|
+
for (let index = 1; index < segment.length; index += 1) {
|
|
427
|
+
if (isDigitCharCode(segment.charCodeAt(index - 1)) !== isDigitCharCode(segment.charCodeAt(index))) {
|
|
428
|
+
transitions += 1;
|
|
429
|
+
}
|
|
430
|
+
}
|
|
431
|
+
return transitions;
|
|
432
|
+
}
|
|
433
|
+
|
|
434
|
+
// Character-code digit test so the transition counter never needs unchecked string indexing.
|
|
435
|
+
function isDigitCharCode(code: number): boolean {
|
|
436
|
+
return code >= 48 && code <= 57;
|
|
267
437
|
}
|
|
268
438
|
|
|
269
439
|
// Path-shape guard: a string that contains at least one `/`, has a path-like extension, AND lives
|
|
@@ -381,10 +551,10 @@ function isHexDigest(candidateText: string): boolean {
|
|
|
381
551
|
return /^[0-9a-f]+$/i.test(candidateText);
|
|
382
552
|
}
|
|
383
553
|
|
|
384
|
-
//
|
|
385
|
-
// 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.
|
|
386
556
|
function isSubresourceIntegrityHash(candidateText: string): boolean {
|
|
387
|
-
return /^sha(?:256|384|512)-[A-Za-z0-9+/=]+$/.test(candidateText);
|
|
557
|
+
return /^sha(?:1|256|384|512)-[A-Za-z0-9+/=]+$/.test(candidateText);
|
|
388
558
|
}
|
|
389
559
|
|
|
390
560
|
// Three-class character requirement that filters out single-case identifiers and pure base64 hashes
|
|
@@ -412,13 +582,19 @@ function shannonEntropy(candidateText: string): number {
|
|
|
412
582
|
}, 0);
|
|
413
583
|
}
|
|
414
584
|
|
|
415
|
-
//
|
|
416
|
-
|
|
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.
|
|
417
592
|
function redact(rawSecret: string): string {
|
|
418
|
-
|
|
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) {
|
|
419
595
|
return `${"*".repeat(rawSecret.length)} (redacted, ${rawSecret.length} chars)`;
|
|
420
596
|
}
|
|
421
|
-
return `${rawSecret.slice(0,
|
|
597
|
+
return `${rawSecret.slice(0, VISIBLE_SECRET_EDGE_LENGTH)}...${rawSecret.slice(-VISIBLE_SECRET_EDGE_LENGTH)} (redacted, ${rawSecret.length} chars)`;
|
|
422
598
|
}
|
|
423
599
|
|
|
424
600
|
export { analyseSensitiveData };
|
package/src/source-text.ts
CHANGED
|
@@ -2,43 +2,26 @@
|
|
|
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 { parseScript } from "./parsed-script.ts";
|
|
5
6
|
import type { RunDiagnostic } from "./types.ts";
|
|
6
7
|
|
|
7
8
|
// Just enough of `SourceFile` to keep `parseDiagnostics` decoupled from the full project type:
|
|
8
|
-
// `isScript` gates whether
|
|
9
|
+
// `isScript` gates whether parser diagnostics run; `displayPath` is the report-path anchor.
|
|
9
10
|
interface DiagnosticSourceFile {
|
|
10
11
|
displayPath: string;
|
|
11
12
|
isScript: boolean;
|
|
12
13
|
}
|
|
13
14
|
|
|
14
15
|
/**
|
|
15
|
-
*
|
|
16
|
-
*
|
|
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.
|
|
17
19
|
*
|
|
18
20
|
* @param file - Source metadata used to skip non-script inputs and report paths.
|
|
19
|
-
* @param source - Raw file text to
|
|
21
|
+
* @param source - Raw file text to parse for syntax diagnostics.
|
|
20
22
|
*/
|
|
21
23
|
function parseDiagnostics(file: DiagnosticSourceFile, source: string): RunDiagnostic[] {
|
|
22
|
-
|
|
23
|
-
return [];
|
|
24
|
-
}
|
|
25
|
-
const ctx: DelimiterScanContext = {
|
|
26
|
-
scan: defaultDelimiterScanState(),
|
|
27
|
-
counts: { braces: 0, parentheses: 0, brackets: 0 },
|
|
28
|
-
};
|
|
29
|
-
const lines = source.split(/\r?\n/);
|
|
30
|
-
for (const [index, line] of lines.entries()) {
|
|
31
|
-
scanDelimiterLine(line, ctx);
|
|
32
|
-
if (hasNegativeDelimiterCount(ctx.counts)) {
|
|
33
|
-
return [parseErrorDiagnostic(file, index + 1)];
|
|
34
|
-
}
|
|
35
|
-
}
|
|
36
|
-
// Intentional: the EOF imbalance check was removed in M38 false-positive triage. The brace
|
|
37
|
-
// scanner is a regex-vs-division heuristic, not a real parser, and produces drift on valid
|
|
38
|
-
// TypeScript containing nested template literals, regex literals with parens in character
|
|
39
|
-
// classes, and similar constructs. tsc owns syntax validation; gruff's job here is to catch
|
|
40
|
-
// obvious local mismatches (negative counts) rather than rediscover end-of-file parser errors.
|
|
41
|
-
return [];
|
|
24
|
+
return parseScript(file, source)?.diagnostics ?? [];
|
|
42
25
|
}
|
|
43
26
|
|
|
44
27
|
// Running totals for `{}`, `()`, and `[]`. A negative count means a closer appeared with no opener
|
|
@@ -281,10 +264,10 @@ function hasUnbalancedDelimiterCount(counts: DelimiterCounts): boolean {
|
|
|
281
264
|
* whenever diagnostics fire - this builder reports failures so a broken file in the scan tree
|
|
282
265
|
* cannot hide silently rather than throw the error or recover quietly.
|
|
283
266
|
*/
|
|
284
|
-
function parseErrorDiagnostic(file: DiagnosticSourceFile, line: number): RunDiagnostic {
|
|
267
|
+
function parseErrorDiagnostic(file: DiagnosticSourceFile, line: number, message: string): RunDiagnostic {
|
|
285
268
|
return {
|
|
286
269
|
diagnosticType: "parse-error",
|
|
287
|
-
message
|
|
270
|
+
message,
|
|
288
271
|
filePath: file.displayPath,
|
|
289
272
|
line,
|
|
290
273
|
};
|
|
@@ -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;
|