@blundergoat/gruff-ts 0.5.0 → 0.6.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 +82 -0
- package/CONTRIBUTING.md +32 -25
- package/README.md +49 -50
- package/SECURITY.md +18 -31
- package/UPGRADING.md +101 -0
- package/bin/gruff-ts +3 -0
- package/docs/README.md +11 -10
- package/docs/agent-hook.md +32 -35
- package/docs/ci-integration.md +38 -24
- package/docs/configuration.md +160 -89
- package/docs/dashboard.md +12 -13
- package/docs/output-formats.md +100 -25
- package/docs/philosophy.md +2 -2
- package/docs/reports-and-ci.md +14 -172
- package/docs/rules.md +126 -98
- package/package.json +10 -8
- package/src/analyser.ts +817 -323
- package/src/baseline-file.ts +867 -0
- package/src/baseline-identity.ts +463 -0
- package/src/baseline-options.ts +139 -34
- package/src/baseline.ts +62 -68
- package/src/blocks.ts +512 -336
- package/src/changed-regions.ts +380 -79
- package/src/check-ignore.ts +28 -13
- package/src/class-rules.ts +445 -436
- package/src/cli-program.ts +915 -172
- package/src/cli.ts +9 -3
- package/src/comment-rules.ts +236 -418
- package/src/comment-scanner.ts +339 -47
- package/src/complexity-metrics.ts +111 -35
- package/src/config-load-error.ts +17 -8
- package/src/config-parse.ts +291 -98
- package/src/config-preservation.ts +81 -26
- package/src/config.ts +751 -223
- package/src/constants.ts +7 -6
- package/src/context-doc-rules.ts +182 -54
- package/src/dashboard.ts +88 -23
- package/src/dead-code-rules.ts +153 -74
- package/src/discovery.ts +493 -140
- package/src/doc-rules.ts +602 -126
- package/src/duplicate-test-group-rules.ts +359 -0
- package/src/findings-helpers.ts +134 -109
- package/src/findings.ts +47 -27
- package/src/fixture-purpose-rules.ts +194 -50
- package/src/github-actions-event-guards.ts +331 -0
- package/src/github-actions-rules.ts +328 -121
- package/src/hook-contract.ts +681 -255
- package/src/init-config.ts +163 -118
- package/src/inline-suppressions.ts +340 -0
- package/src/limit-band.ts +56 -0
- package/src/line-rules.ts +331 -468
- package/src/migrate-config.ts +670 -0
- package/src/naming-pushers.ts +32 -127
- package/src/parsed-script.ts +868 -314
- package/src/pillar-summary.ts +56 -40
- package/src/profiles.ts +86 -74
- package/src/project-config-rules.ts +324 -140
- package/src/project-rules.ts +237 -115
- package/src/public-exports.ts +102 -38
- package/src/report-html.ts +217 -85
- package/src/report-renderers.ts +821 -203
- package/src/rule-list.ts +166 -46
- package/src/rules.ts +100 -104
- package/src/safety-rules.ts +191 -132
- package/src/scoring.ts +249 -55
- package/src/security-flow-rules.ts +791 -115
- package/src/selectors.ts +169 -0
- package/src/sensitive-data-rules.ts +460 -387
- package/src/sensitive-exclusions.ts +435 -0
- package/src/source-text.ts +378 -104
- package/src/static-analysis-redundant-rules.ts +298 -41
- package/src/test-block-rules.ts +343 -253
- package/src/text-scans.ts +62 -11
- package/src/types.ts +220 -71
- package/tsconfig.json +2 -1
- package/src/process-exec-metadata.ts +0 -163
- package/src/test-fixtures.ts +0 -671
|
@@ -1,20 +1,33 @@
|
|
|
1
|
-
// Sensitive-data
|
|
2
|
-
|
|
1
|
+
// Sensitive-data analysis turns reportable secret-like source occurrences into safe findings.
|
|
2
|
+
//
|
|
3
|
+
// It runs each detector in a stable order so repeated scans remain comparable.
|
|
4
|
+
// Users receive fixed category markers, actionable locations, and one report entry per occurrence without matched characters or lengths.
|
|
5
|
+
import { createHash } from "node:crypto";
|
|
3
6
|
import { makeFinding } from "./findings.ts";
|
|
4
7
|
import { byteColumn, byteLine } from "./text-scans.ts";
|
|
5
|
-
import type {
|
|
8
|
+
import type { Finding } from "./types.ts";
|
|
6
9
|
|
|
7
|
-
//
|
|
8
|
-
//
|
|
10
|
+
// Describes the safe file context needed to locate a sensitive finding for the user.
|
|
11
|
+
//
|
|
12
|
+
// The report-facing path is sufficient for navigation, and findings carry nothing else.
|
|
9
13
|
interface SensitiveSourceFile {
|
|
10
14
|
displayPath: string;
|
|
11
15
|
}
|
|
12
16
|
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
17
|
+
/**
|
|
18
|
+
* Runs every sensitive-data detector for one user file in deterministic report order.
|
|
19
|
+
* Keeping pattern order stable prevents baseline churn when no source behavior changed.
|
|
20
|
+
*
|
|
21
|
+
* @param file - Source file metadata supplying the display path for reported findings.
|
|
22
|
+
* @param source - Full source text scanned across pattern and specialized detectors.
|
|
23
|
+
* @param findings - Accumulator array receiving redacted sensitive-data findings.
|
|
24
|
+
* @returns Nothing. Appends matching findings to `findings` in deterministic detector order.
|
|
25
|
+
*/
|
|
26
|
+
function analyseSensitiveData(file: SensitiveSourceFile, source: string, findings: Finding[]): void {
|
|
16
27
|
const patterns: Array<[string, RegExp, string]> = [
|
|
17
|
-
|
|
28
|
+
// ASIA is AWS's prefix for temporary session credentials, over the same fixed body; missing it left a live
|
|
29
|
+
// credential unnamed.
|
|
30
|
+
["sensitive-data.aws-access-key", /(?:AKIA|ASIA)[0-9A-Z]{16}/g, "AWS access key pattern detected."],
|
|
18
31
|
["sensitive-data.private-key", /BEGIN (RSA |OPENSSH |EC |DSA )?PRIVATE KEY/g, "Private key block detected."],
|
|
19
32
|
["sensitive-data.jwt-token", /eyJ[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+/g, "JWT-looking token detected."],
|
|
20
33
|
["sensitive-data.database-url-password", /\b(?:https?|postgres(?:ql)?|mysql|mariadb|mongodb(?:\+srv)?|redis|amqp|amqps|mssql):\/\/[^\/\s:@]+:[^\/\s@]+@/g, "URL appears to include embedded credentials."],
|
|
@@ -27,455 +40,508 @@ function analyseSensitiveData(file: SensitiveSourceFile, source: string, config:
|
|
|
27
40
|
["sensitive-data.phi-pattern", /\b[1-9][ACDEFGHJKMNPQRTUVWXY][ACDEFGHJKMNPQRTUVWXY0-9]\d[ACDEFGHJKMNPQRTUVWXY][ACDEFGHJKMNPQRTUVWXY0-9]\d[ACDEFGHJKMNPQRTUVWXY][ACDEFGHJKMNPQRTUVWXY]\d\d\b/g, "Medicare Beneficiary Identifier (PHI) pattern detected."],
|
|
28
41
|
];
|
|
29
42
|
|
|
43
|
+
// Each detector family contributes findings in this documented order so users do not see unexplained report churn.
|
|
30
44
|
for (const [ruleId, pattern, message] of patterns) {
|
|
45
|
+
// Every matched occurrence remains independently visible, including multiple findings on the same source line.
|
|
31
46
|
for (const match of source.matchAll(pattern)) {
|
|
32
|
-
|
|
33
|
-
|
|
47
|
+
// A missing regex capture is treated as empty source evidence and will be ignored by the explicit-example guard.
|
|
48
|
+
const matchedSensitiveText = match[0] ?? "";
|
|
49
|
+
// Explicit placeholders are teaching material rather than credentials the user needs to rotate. An AWS key
|
|
50
|
+
// is one fixed-shape alphanumeric run, where a marker word can only sit inside the value and never begin a
|
|
51
|
+
// token, so only a mask silences it and AWS's documented example key reports, as it does in every port.
|
|
52
|
+
const isPlaceholder = ruleId === "sensitive-data.aws-access-key" ? isMaskedAwsAccessKey(matchedSensitiveText) : isExplicitExampleCredential(matchedSensitiveText);
|
|
53
|
+
if (isPlaceholder) {
|
|
54
|
+
continue;
|
|
55
|
+
}
|
|
56
|
+
// A URL shape written as a template literal type names no credential at all, and a stock pair on a local host is a
|
|
57
|
+
// documented development default.
|
|
58
|
+
const matchEnd = (match.index ?? 0) + matchedSensitiveText.length;
|
|
59
|
+
if (ruleId === "sensitive-data.database-url-password"
|
|
60
|
+
&& (isTypeLevelUrlCredential(matchedSensitiveText) || isStockDevelopmentUrl(matchedSensitiveText, source.slice(matchEnd, matchEnd + 256)))) {
|
|
34
61
|
continue;
|
|
35
62
|
}
|
|
36
|
-
pushSensitiveFinding({
|
|
63
|
+
pushSensitiveFinding({
|
|
64
|
+
findings,
|
|
65
|
+
file,
|
|
66
|
+
ruleId,
|
|
67
|
+
message,
|
|
68
|
+
line: byteLine(source, match.index ?? 0),
|
|
69
|
+
column: byteColumn(source, match.index ?? 0),
|
|
70
|
+
matchedSensitiveText,
|
|
71
|
+
confidence: "high",
|
|
72
|
+
});
|
|
37
73
|
}
|
|
38
74
|
}
|
|
39
75
|
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
76
|
+
analyseNpmAuthTokens(file, source, findings);
|
|
77
|
+
analysePhiLabelledIdentifiers(file, source, findings);
|
|
78
|
+
analysePaymentCardNumbers(file, source, findings);
|
|
79
|
+
analyseGcpServiceAccountKeys(file, source, findings);
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/**
|
|
83
|
+
* Recognizes a URL credential in type position where the password is wholly `${string}` or `${number}`.
|
|
84
|
+
* Only an interpolated type-keyword password straight after the user qualifies; literal passwords or runtime variables still report.
|
|
85
|
+
* The match stops at `@` because extending it to the host would silence hosts containing "example" (M22 activation bundle, decision 4).
|
|
86
|
+
*
|
|
87
|
+
* @param matchedSensitiveText - Matched scheme-and-userinfo substring ending at `@`.
|
|
88
|
+
* @returns True when `matchedSensitiveText` ends with a type-only `${string}` or `${number}` password interpolation.
|
|
89
|
+
*/
|
|
90
|
+
function isTypeLevelUrlCredential(matchedSensitiveText: string): boolean {
|
|
91
|
+
return /:\/\/[^\/\s:@]+:\$\{\s*(?:string|number)\s*\}@$/.test(matchedSensitiveText);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// Stock development user names and passwords, compared case-insensitively and whole (FAMILY-CONTRACT.md section 5).
|
|
95
|
+
// They are documented defaults such as `postgres:postgres` or `scott:tiger`, not credentials, so they are held as plain text.
|
|
96
|
+
const STOCK_DEVELOPMENT_WORDS = new Set([
|
|
97
|
+
"admin", "bar", "dbpass", "dbuser", "default", "demo", "example", "foo", "guest", "mysql", "pass", "passwd",
|
|
98
|
+
"password", "postgres", "root", "sa", "scott", "secret", "test", "tiger", "user", "username",
|
|
99
|
+
]);
|
|
100
|
+
|
|
101
|
+
// Loopback hosts, on which a stock pair is a development default rather than a live weakness.
|
|
102
|
+
const LOOPBACK_HOSTS = new Set(["localhost", "127.0.0.1", "::1", "0.0.0.0"]);
|
|
103
|
+
|
|
104
|
+
/**
|
|
105
|
+
* Checks whether matched credentials are stock development defaults paired with a qualifying local host.
|
|
106
|
+
* Credentials and hosts compare case-insensitively; other hosts stay reportable under FAMILY-CONTRACT.md section 5.
|
|
107
|
+
* The match stops at `@` to keep hostnames out of example checks.
|
|
108
|
+
*
|
|
109
|
+
* @param matchedSensitiveText - Matched scheme-and-userinfo substring ending at `@`.
|
|
110
|
+
* @param textAfterAt - Authority slice immediately following `@`, used to extract the host.
|
|
111
|
+
* @returns True when user and password are in `STOCK_DEVELOPMENT_WORDS` and the host is loopback or a bare single-label name.
|
|
112
|
+
*/
|
|
113
|
+
function isStockDevelopmentUrl(matchedSensitiveText: string, textAfterAt: string): boolean {
|
|
114
|
+
const userInfo = /:\/\/([^\/\s:@]+):([^\/\s@]+)@$/.exec(matchedSensitiveText);
|
|
115
|
+
const user = userInfo?.[1]?.toLowerCase() ?? "";
|
|
116
|
+
const password = userInfo?.[2]?.toLowerCase() ?? "";
|
|
117
|
+
// Any username or password outside the stock-word set keeps the finding.
|
|
118
|
+
if (!STOCK_DEVELOPMENT_WORDS.has(user) || !STOCK_DEVELOPMENT_WORDS.has(password)) {
|
|
119
|
+
return false;
|
|
120
|
+
}
|
|
121
|
+
const authority = (/^[^\/?#\s"'`]*/.exec(textAfterAt)?.[0] ?? "").toLowerCase();
|
|
122
|
+
// A bracketed IPv6 host such as `[::1]:5432` keeps its colons inside the brackets.
|
|
123
|
+
const bracketed = /^\[([^\]]+)\]/.exec(authority);
|
|
124
|
+
const host = bracketed ? (bracketed[1] ?? "") : (authority.split(":")[0] ?? "");
|
|
125
|
+
return LOOPBACK_HOSTS.has(host) || (host !== "" && !host.includes(".") && !host.includes(":"));
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/**
|
|
129
|
+
* Checks whether the matched credential contains an example marker or matches a supported mask.
|
|
130
|
+
* The detector uses this result to skip placeholder matches before creating findings.
|
|
131
|
+
*
|
|
132
|
+
* @param matchedSensitiveText - Candidate credential text extracted from source.
|
|
133
|
+
* @returns True when `matchedSensitiveText` contains an example/placeholder marker or a masked run.
|
|
134
|
+
*/
|
|
135
|
+
function isExplicitExampleCredential(matchedSensitiveText: string): boolean {
|
|
136
|
+
return /EXAMPLE|REDACTED|PLACEHOLDER|CHANGEME/i.test(matchedSensitiveText) || isMaskedCredential(matchedSensitiveText);
|
|
46
137
|
}
|
|
47
138
|
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
139
|
+
/**
|
|
140
|
+
* Checks whether a matched AWS access key has an all-X body, as required by FAMILY-CONTRACT.md section 5.
|
|
141
|
+
* A real key can contain runs of `X`, so the mask must cover the entire 16-character body.
|
|
142
|
+
*
|
|
143
|
+
* @param matchedSensitiveText - Candidate AWS access key beginning with `AKIA` or `ASIA`.
|
|
144
|
+
* @returns True when all 16 characters after the prefix are uppercase `X`.
|
|
145
|
+
*/
|
|
146
|
+
function isMaskedAwsAccessKey(matchedSensitiveText: string): boolean {
|
|
147
|
+
return /^(?:AKIA|ASIA)X{16}$/.test(matchedSensitiveText);
|
|
54
148
|
}
|
|
55
149
|
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
150
|
+
/**
|
|
151
|
+
* Recognizes a value whose body was masked out with a run of `*` or `X`, which names no credential at all.
|
|
152
|
+
*
|
|
153
|
+
* @param matchedSensitiveText - Candidate credential text extracted from source.
|
|
154
|
+
* @returns True when `matchedSensitiveText` contains four consecutive `*` or `X` characters.
|
|
155
|
+
*/
|
|
156
|
+
function isMaskedCredential(matchedSensitiveText: string): boolean {
|
|
157
|
+
return /\*{4}|X{4}/.test(matchedSensitiveText);
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Scans source lines for labelled medical-record numbers using `file` to anchor each finding.
|
|
162
|
+
* Stable contract: a supported label is required, and only the first matching identifier on each line is reported.
|
|
163
|
+
*
|
|
164
|
+
* @param file - Source file metadata supplying the display path for findings.
|
|
165
|
+
* @param source - Full source text split into lines for MRN label matching.
|
|
166
|
+
* @param findings - Accumulator array receiving fixed-marker PHI findings.
|
|
167
|
+
* @returns Nothing. Appends fixed-marker MRN findings to `findings`.
|
|
168
|
+
*/
|
|
169
|
+
function analysePhiLabelledIdentifiers(file: SensitiveSourceFile, source: string, findings: Finding[]): void {
|
|
59
170
|
const lines = source.split(/\r?\n/);
|
|
171
|
+
// Each source line may represent a separate record the user accidentally embedded in code or a fixture.
|
|
60
172
|
for (const [index, line] of lines.entries()) {
|
|
61
173
|
const match = line.match(/\b(?:MRN|medical[\s_-]?record(?:[\s_-]?number)?)\b\s*[:=#]?\s*([0-9]{6,12})\b/i);
|
|
62
174
|
const medicalRecordNumber = match?.[1];
|
|
175
|
+
// No labelled value means this line cannot produce an MRN finding for the user.
|
|
63
176
|
if (!medicalRecordNumber) {
|
|
64
177
|
continue;
|
|
65
178
|
}
|
|
66
|
-
pushSensitiveFinding({
|
|
179
|
+
pushSensitiveFinding({
|
|
180
|
+
findings,
|
|
181
|
+
file,
|
|
182
|
+
ruleId: "sensitive-data.phi-pattern",
|
|
183
|
+
message: "Medical record number (PHI) detected.",
|
|
184
|
+
line: index + 1,
|
|
185
|
+
column: (match.index ?? 0) + 1,
|
|
186
|
+
matchedSensitiveText: medicalRecordNumber,
|
|
187
|
+
confidence: "high",
|
|
188
|
+
});
|
|
67
189
|
}
|
|
68
190
|
}
|
|
69
191
|
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
192
|
+
/**
|
|
193
|
+
* Scans `source` for a GCP service-account key and reports only when type and private-key evidence coexist.
|
|
194
|
+
* Stable contract: users receive one marker at the type field, while matched identifiers and key material stay hidden.
|
|
195
|
+
*
|
|
196
|
+
* @param file - Source file metadata supplying the display path for the finding.
|
|
197
|
+
* @param source - Full source text checked for `"type": "service_account"` and private-key evidence.
|
|
198
|
+
* @param findings - Accumulator array receiving the service-account finding when both signals match.
|
|
199
|
+
* @returns Nothing. Appends at most one fixed-marker finding to `findings`.
|
|
200
|
+
*/
|
|
201
|
+
function analyseGcpServiceAccountKeys(file: SensitiveSourceFile, source: string, findings: Finding[]): void {
|
|
73
202
|
const typeMatch = source.match(/"type"\s*:\s*"service_account"/);
|
|
203
|
+
// Private-key evidence anywhere in the source can corroborate the type field, regardless of field order.
|
|
74
204
|
if (!typeMatch || !/"private_key"\s*:\s*"|BEGIN (?:RSA |OPENSSH |EC |DSA )?PRIVATE KEY/.test(source)) {
|
|
75
205
|
return;
|
|
76
206
|
}
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
207
|
+
pushSensitiveFinding({
|
|
208
|
+
findings,
|
|
209
|
+
file,
|
|
210
|
+
ruleId: "sensitive-data.gcp-service-account-key",
|
|
211
|
+
message: "GCP service-account key file detected.",
|
|
212
|
+
line: byteLine(source, typeMatch.index ?? 0),
|
|
213
|
+
column: byteColumn(source, typeMatch.index ?? 0),
|
|
214
|
+
matchedSensitiveText: "service_account",
|
|
215
|
+
confidence: "high",
|
|
216
|
+
});
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
/**
|
|
220
|
+
* Scans `source` for payment-card candidates and appends findings only after network, length, checksum, and context checks pass.
|
|
221
|
+
* Stable contract: canonical grouping supplies context; bare digit runs need card vocabulary before users see a finding.
|
|
222
|
+
*
|
|
223
|
+
* @param file - Source file metadata supplying the display path for findings.
|
|
224
|
+
* @param source - Full source text scanned for grouped or bare digit runs.
|
|
225
|
+
* @param findings - Accumulator array receiving credit-card PII findings.
|
|
226
|
+
* @returns Nothing. Appends matching payment-card findings to `findings`.
|
|
88
227
|
*/
|
|
89
|
-
function analysePaymentCardNumbers(file: SensitiveSourceFile, source: string,
|
|
228
|
+
function analysePaymentCardNumbers(file: SensitiveSourceFile, source: string, findings: Finding[]): void {
|
|
90
229
|
const lines = source.split(/\r?\n/);
|
|
230
|
+
// Each digit run is checked independently because a user can paste more than one card-like value into a line or file.
|
|
91
231
|
for (const match of source.matchAll(/\b(?:\d[ -]?){12,18}\d\b/g)) {
|
|
92
|
-
const
|
|
93
|
-
const
|
|
232
|
+
const matchedDigitRun = match[0] ?? "";
|
|
233
|
+
const normalizedCardNumber = normalizedPaymentCardNumber(matchedDigitRun);
|
|
94
234
|
const line = byteLine(source, match.index ?? 0);
|
|
95
|
-
//
|
|
96
|
-
if (!isReportablePaymentCardCandidate(
|
|
235
|
+
// After the card number passes validation, canonical grouping supplies context. A run without that grouping needs card vocabulary on its line.
|
|
236
|
+
if (!isReportablePaymentCardCandidate(matchedDigitRun, normalizedCardNumber, lines[line - 1] ?? "")) {
|
|
97
237
|
continue;
|
|
98
238
|
}
|
|
99
239
|
pushSensitiveFinding({
|
|
100
|
-
config,
|
|
101
240
|
findings,
|
|
102
241
|
file,
|
|
103
242
|
ruleId: "sensitive-data.pii-pattern",
|
|
104
243
|
message: "Credit card number (PII) pattern detected.",
|
|
105
244
|
line,
|
|
106
245
|
column: byteColumn(source, match.index ?? 0),
|
|
107
|
-
|
|
246
|
+
matchedSensitiveText: matchedDigitRun,
|
|
108
247
|
confidence: "high",
|
|
109
|
-
metadata: { piiKind: "credit-card"
|
|
248
|
+
metadata: { piiKind: "credit-card" },
|
|
110
249
|
});
|
|
111
250
|
}
|
|
112
251
|
}
|
|
113
252
|
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
253
|
+
/**
|
|
254
|
+
* Checks whether `matchedDigitRun` is reportable: `normalizedCardNumber` must pass network, length, and checksum checks.
|
|
255
|
+
* The run must also have canonical grouping, or `contextLine` must contain card vocabulary, since ordinary numbers can pass Luhn.
|
|
256
|
+
*
|
|
257
|
+
* @param matchedDigitRun - Raw candidate digit run with any original spaces or hyphens.
|
|
258
|
+
* @param normalizedCardNumber - Digit-only candidate value after stripping separators.
|
|
259
|
+
* @param contextLine - Source line surrounding `matchedDigitRun`, checked for card vocabulary.
|
|
260
|
+
* @returns True when `normalizedCardNumber` is a valid card number with canonical grouping or card context.
|
|
261
|
+
*/
|
|
262
|
+
function isReportablePaymentCardCandidate(matchedDigitRun: string, normalizedCardNumber: string, contextLine: string): boolean {
|
|
263
|
+
if (!isPaymentCardNumber(normalizedCardNumber)) {
|
|
119
264
|
return false;
|
|
120
265
|
}
|
|
121
|
-
return hasCanonicalPaymentCardGrouping(
|
|
266
|
+
return hasCanonicalPaymentCardGrouping(matchedDigitRun, normalizedCardNumber) || hasPaymentCardContext(contextLine);
|
|
122
267
|
}
|
|
123
268
|
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
269
|
+
/**
|
|
270
|
+
* Checks whether `matchedDigitRun` uses one separator and the grouping expected for `normalizedCardNumber`'s network and length.
|
|
271
|
+
* Noncanonical chunks such as `8-8` supply no grouping context; callers can still accept them when the line contains card vocabulary.
|
|
272
|
+
*
|
|
273
|
+
* @param matchedDigitRun - Raw candidate digit run containing spaces or hyphens.
|
|
274
|
+
* @param normalizedCardNumber - Digit-only card value used to select expected group sizes.
|
|
275
|
+
* @returns True when `matchedDigitRun` uses a single separator kind matching the issuer's canonical chunk sizes.
|
|
276
|
+
*/
|
|
277
|
+
function hasCanonicalPaymentCardGrouping(matchedDigitRun: string, normalizedCardNumber: string): boolean {
|
|
278
|
+
// Missing separators mean a bare number needs explicit card vocabulary elsewhere on the line.
|
|
279
|
+
const separators = matchedDigitRun.match(/[ -]/g) ?? [];
|
|
280
|
+
// Mixed or absent separators do not provide the canonical grouping users expect for a card number.
|
|
128
281
|
if (separators.length === 0 || new Set(separators).size !== 1) {
|
|
129
282
|
return false;
|
|
130
283
|
}
|
|
131
|
-
const groupSizes =
|
|
132
|
-
const expectedGroupSizes = isAmericanExpressPaymentCard(
|
|
284
|
+
const groupSizes = matchedDigitRun.split(separators[0] ?? " ").map((group) => group.length);
|
|
285
|
+
const expectedGroupSizes = isAmericanExpressPaymentCard(normalizedCardNumber)
|
|
133
286
|
? [4, 6, 5]
|
|
134
|
-
: isDinersPaymentCard(
|
|
287
|
+
: isDinersPaymentCard(normalizedCardNumber)
|
|
135
288
|
? [4, 6, 4]
|
|
136
|
-
: Array.from({ length: Math.ceil(
|
|
289
|
+
: Array.from({ length: Math.ceil(normalizedCardNumber.length / 4) }, (_, index) => Math.min(4, normalizedCardNumber.length - index * 4));
|
|
137
290
|
return groupSizes.length === expectedGroupSizes.length && groupSizes.every((size, index) => size === expectedGroupSizes[index]);
|
|
138
291
|
}
|
|
139
292
|
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
293
|
+
/**
|
|
294
|
+
* Recognizes card vocabulary around an otherwise ambiguous digit run.
|
|
295
|
+
* Identifier forms such as `cardNumber` count; `PAN` must be a whole word to avoid matching unrelated words such as `panel`.
|
|
296
|
+
*
|
|
297
|
+
* @param lineText - Full source line containing the candidate digit run.
|
|
298
|
+
* @returns True when `lineText` contains card-related terms or a whole-word `PAN` token.
|
|
299
|
+
*/
|
|
143
300
|
function hasPaymentCardContext(lineText: string): boolean {
|
|
144
301
|
return /(?:\bpan\b|card|payment|credit|debit|visa|master|amex|discover|jcb|diners)/i.test(lineText);
|
|
145
302
|
}
|
|
146
303
|
|
|
147
|
-
|
|
148
|
-
|
|
304
|
+
/**
|
|
305
|
+
* Scans `source` for npm `_authToken` values and appends findings for recognized literals, including tokens without `npm_`.
|
|
306
|
+
* Stable contract: scoped and registry `_authToken` lines remain reportable when the general provider pattern cannot classify their prefix.
|
|
307
|
+
*
|
|
308
|
+
* @param file - Source file metadata supplying the display path for findings.
|
|
309
|
+
* @param source - Full source text split into lines to inspect registry auth assignments.
|
|
310
|
+
* @param findings - Accumulator array receiving redacted npm auth token findings.
|
|
311
|
+
* @returns Nothing. Appends matching `_authToken` findings to `findings`.
|
|
312
|
+
*/
|
|
313
|
+
function analyseNpmAuthTokens(file: SensitiveSourceFile, source: string, findings: Finding[]): void {
|
|
149
314
|
const lines = source.split(/\r?\n/);
|
|
315
|
+
// Each config line can contain a separate registry credential the user needs to rotate.
|
|
150
316
|
for (const [index, line] of lines.entries()) {
|
|
151
317
|
const token = npmAuthTokenValue(line);
|
|
318
|
+
// No supported `_authToken` value means this line contributes no npm credential finding.
|
|
152
319
|
if (!token) {
|
|
153
320
|
continue;
|
|
154
321
|
}
|
|
155
322
|
pushSensitiveFinding({
|
|
156
|
-
config,
|
|
157
323
|
findings,
|
|
158
324
|
file,
|
|
159
325
|
ruleId: "sensitive-data.api-key-pattern",
|
|
160
326
|
message: "npm auth token pattern detected.",
|
|
161
327
|
line: index + 1,
|
|
162
|
-
|
|
328
|
+
matchedSensitiveText: token,
|
|
163
329
|
confidence: "high",
|
|
164
330
|
metadata: { keyName: "_authToken" },
|
|
165
331
|
});
|
|
166
332
|
}
|
|
167
333
|
}
|
|
168
334
|
|
|
169
|
-
|
|
335
|
+
/**
|
|
336
|
+
* Extracts the matched literal token from a bare, scoped, or registry-prefixed npm auth line.
|
|
337
|
+
* Missing output means the user's line has no supported literal token for this detector.
|
|
338
|
+
*
|
|
339
|
+
* @param line - Single source or config line checked for a literal `_authToken=` assignment.
|
|
340
|
+
* @returns Matched token literal of at least 20 characters, or `undefined` when no supported token matches.
|
|
341
|
+
*/
|
|
170
342
|
function npmAuthTokenValue(line: string): string | undefined {
|
|
171
343
|
const match = line.match(/(?:^|:)_authToken\s*=\s*([A-Za-z0-9_-]{20,})\b/);
|
|
172
344
|
return match?.[1];
|
|
173
345
|
}
|
|
174
346
|
|
|
175
|
-
//
|
|
176
|
-
//
|
|
177
|
-
//
|
|
178
|
-
|
|
179
|
-
const minLength = threshold(config, "sensitive-data.hardcoded-env-value", 16);
|
|
180
|
-
const requiresQuotedValue = isScriptSourcePath(file.displayPath);
|
|
181
|
-
const lines = source.split(/\r?\n/);
|
|
182
|
-
for (const [index, line] of lines.entries()) {
|
|
183
|
-
const envValue = hardcodedEnvValue(line, minLength, requiresQuotedValue);
|
|
184
|
-
if (!envValue) {
|
|
185
|
-
continue;
|
|
186
|
-
}
|
|
187
|
-
pushSensitiveFinding({
|
|
188
|
-
config,
|
|
189
|
-
findings,
|
|
190
|
-
file,
|
|
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
|
-
});
|
|
199
|
-
}
|
|
200
|
-
}
|
|
201
|
-
|
|
202
|
-
// Shannon-entropy detector with three guardrails (length, case diversity, distinct characters)
|
|
203
|
-
// because plain entropy alone fires on package-lock SRI hashes; the layered checks keep findings
|
|
204
|
-
// stable across runs and prevent noisy regressions in node_modules-heavy projects.
|
|
205
|
-
function analyseHighEntropyStrings(file: SensitiveSourceFile, source: string, config: Config, findings: Finding[]): void {
|
|
206
|
-
const minLength = threshold(config, "sensitive-data.high-entropy-string", 32);
|
|
207
|
-
for (const match of source.matchAll(/(["'`])([A-Za-z0-9_+=./-]{24,})\1/g)) {
|
|
208
|
-
const raw = match[2] ?? "";
|
|
209
|
-
if (!isHighEntropySecretCandidate(raw, minLength)) {
|
|
210
|
-
continue;
|
|
211
|
-
}
|
|
212
|
-
pushSensitiveFinding({
|
|
213
|
-
config,
|
|
214
|
-
findings,
|
|
215
|
-
file,
|
|
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),
|
|
220
|
-
raw,
|
|
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
|
-
});
|
|
225
|
-
}
|
|
226
|
-
}
|
|
227
|
-
|
|
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.
|
|
347
|
+
// Describes one reportable sensitive occurrence before the finding is built.
|
|
348
|
+
//
|
|
349
|
+
// Optional column and metadata enrich the user's report when available.
|
|
350
|
+
// Contract: matched text is used only to choose a fixed public category and never reaches report output or identity.
|
|
232
351
|
interface SensitiveFindingArgs {
|
|
233
|
-
config: Config;
|
|
234
352
|
findings: Finding[];
|
|
235
353
|
file: SensitiveSourceFile;
|
|
236
354
|
ruleId: string;
|
|
237
355
|
message: string;
|
|
238
356
|
line: number;
|
|
239
357
|
column?: number;
|
|
240
|
-
|
|
358
|
+
matchedSensitiveText: string;
|
|
241
359
|
confidence: Finding["confidence"];
|
|
242
360
|
metadata?: Record<string, unknown>;
|
|
243
|
-
severity?: Finding["severity"];
|
|
244
361
|
}
|
|
245
362
|
|
|
246
|
-
//
|
|
247
|
-
//
|
|
248
|
-
//
|
|
249
|
-
//
|
|
250
|
-
|
|
363
|
+
// SHA-256 digests of the 20 values vendors publish as documentation samples, so code that pastes one never reports.
|
|
364
|
+
//
|
|
365
|
+
// They cover AWS and jwt.io examples, fourteen published test cards and Google's reCAPTCHA v2 test site key.
|
|
366
|
+
// Digests keep the literals out of this source (FAMILY-CONTRACT.md section 5).
|
|
367
|
+
const DOCUMENTED_SAMPLE_DIGESTS = new Set([
|
|
368
|
+
"03b970ed8171d73b58bbc9a5c72e3e4eec28503b56b3bb400a0801857dd45614",
|
|
369
|
+
"19ff47cc8024c133d5845d3f8938caca289929031e7d508c3adf7adff177f0c2",
|
|
370
|
+
"1a5d44a2dca19669d72edf4c4f1c27c4c1ca4b4408fbb17f6ce4ad452d78ddb3",
|
|
371
|
+
"1c9d38ed26cd808fa3b02b9b3b988a7caf474e2e42d95789c0fe07e267c80d8f",
|
|
372
|
+
"2f725bbd1f405a1ed0336abaf85ddfeb6902a9984a76fd877c3b5cc3b5085a82",
|
|
373
|
+
"304945e91de3deff52a61d08733141d72dd42ec9d47972f1060534d54c0c7f90",
|
|
374
|
+
"3a134ef77d4e2e4cdad2d2945ff1f76c1a23296c93c851f6244220a8cedea130",
|
|
375
|
+
"477bba133c182267fe5f086924abdc5db71f77bfc27f01f2843f2cdc69d89f05",
|
|
376
|
+
"51a4ae4c6ae999146474a67cbcb3b05fbcf4c17ab683043a066459da95513ea8",
|
|
377
|
+
"53a8fc816e63b7a5ccd17aaff93f28bcf13abbf418209dcd93947722d7c326ba",
|
|
378
|
+
"576c15a8072461c216efb9bd7306a6fc6039b43a6763c4c1a05930a2dd7b788f",
|
|
379
|
+
"78314b11be2e581549ac1c4f616563fad3fdf0c3b71678f6e2299182080e0598",
|
|
380
|
+
"7f75367e7881255134e1375e723d1dea8ad5f6a4fdb79d938df1f1754a830606",
|
|
381
|
+
"9bbef19476623ca56c17da75fd57734dbf82530686043a6e491c6d71befe8f6e",
|
|
382
|
+
"c6ea27c534f993d31f0aef882e3d200e7b87470c379ae79c8f9b19d3bd363dc9",
|
|
383
|
+
"d79449f462cec9af0d857c3e1af888d4fa8bbdaa511b9eaaafcd2805c4ea6471",
|
|
384
|
+
"d8086d483c15c711ebba19f966b97d3c2adcba74025ff8d7e07c3698c9531deb",
|
|
385
|
+
"dd13cdf9af9dd3baf46ce96aecd7163cabf381ccb21e63f15f0fa10b1c663fa9",
|
|
386
|
+
"e21b597ba6b9cafa59d9ebc4d65c0385f5eb3fa56abab2607fa76589ad849a33",
|
|
387
|
+
"f41e7ca4a3d71c4f047581f2ae2d6a8dbb8c58e51a020fa227edc724474aab6e",
|
|
388
|
+
]);
|
|
389
|
+
|
|
390
|
+
/**
|
|
391
|
+
* Checks whether a matched value is, exactly and whole, a vendor-documented sample such as AWS's example key.
|
|
392
|
+
* When `metadata` identifies a credit card, compares digits only; absent or other metadata keeps the original text.
|
|
393
|
+
*
|
|
394
|
+
* @param matchedSensitiveText - Raw matched sensitive value before digest comparison.
|
|
395
|
+
* @param metadata - Optional finding metadata whose `piiKind` selects digit-only normalization for credit cards.
|
|
396
|
+
* @returns True when the SHA-256 digest of the compared value matches `DOCUMENTED_SAMPLE_DIGESTS`.
|
|
397
|
+
*/
|
|
398
|
+
function isDocumentedSample(matchedSensitiveText: string, metadata: Record<string, unknown> | undefined): boolean {
|
|
399
|
+
const comparedText = metadata?.["piiKind"] === "credit-card" ? matchedSensitiveText.replace(/\D/g, "") : matchedSensitiveText;
|
|
400
|
+
return DOCUMENTED_SAMPLE_DIGESTS.has(createHash("sha256").update(comparedText, "utf8").digest("hex"));
|
|
401
|
+
}
|
|
402
|
+
|
|
403
|
+
/**
|
|
404
|
+
* Appends a redacted finding to `args.findings`, unless its matched value is a vendor-documented sample.
|
|
405
|
+
* The redaction contract uses matched text only to choose the public marker and check for a documented sample.
|
|
406
|
+
*
|
|
407
|
+
* @param args - Occurrence details, source location, accumulator array, and matched text used only for redaction.
|
|
408
|
+
* @returns Nothing. Appends one redacted `Finding` to `args.findings` unless skipped as a documented sample.
|
|
409
|
+
*/
|
|
251
410
|
function pushSensitiveFinding(args: SensitiveFindingArgs): void {
|
|
252
|
-
|
|
253
|
-
|
|
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)) {
|
|
411
|
+
// A pasted documentation sample, e.g. AWS's example key id from its docs, is not a credential, so the user sees nothing.
|
|
412
|
+
if (isDocumentedSample(args.matchedSensitiveText, args.metadata)) {
|
|
256
413
|
return;
|
|
257
414
|
}
|
|
415
|
+
const displayMarker = fixedMarkerForSensitiveFinding(args);
|
|
416
|
+
// An unavailable column is omitted. The fixed marker replaces any supplied preview and preserves the other metadata.
|
|
258
417
|
args.findings.push(
|
|
259
418
|
makeFinding({
|
|
260
419
|
ruleId: args.ruleId,
|
|
261
|
-
message: `${args.message} Redacted preview: ${
|
|
420
|
+
message: `${args.message} Redacted preview: ${displayMarker}.`,
|
|
262
421
|
filePath: args.file.displayPath,
|
|
263
422
|
line: args.line,
|
|
264
423
|
...(args.column === undefined ? {} : { column: args.column }),
|
|
265
|
-
severity:
|
|
424
|
+
severity: "warning",
|
|
266
425
|
pillar: "sensitive-data",
|
|
267
426
|
confidence: args.confidence,
|
|
268
427
|
remediation: "Remove the sensitive value and load it from a secure runtime source.",
|
|
269
|
-
metadata: { ...(args.metadata ?? {}), preview },
|
|
428
|
+
metadata: { ...(args.metadata ?? {}), preview: displayMarker },
|
|
270
429
|
}),
|
|
271
430
|
);
|
|
272
431
|
}
|
|
273
432
|
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
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) {
|
|
310
|
-
return undefined;
|
|
433
|
+
/**
|
|
434
|
+
* Selects the fixed category marker users see for one sensitive finding.
|
|
435
|
+
* Uses `args.ruleId`, matched text, and optional metadata to avoid exposing the value; only an approved public URL scheme may be retained.
|
|
436
|
+
* The stable fallback for unknown rules is `[redacted]`. Without metadata, PII uses `[redacted:ssn]` and API keys classify by prefix.
|
|
437
|
+
*
|
|
438
|
+
* @param args - Finding rule id, matched text, and optional metadata controlling marker selection.
|
|
439
|
+
* @returns Fixed public redaction marker string for `args.ruleId`.
|
|
440
|
+
*/
|
|
441
|
+
function fixedMarkerForSensitiveFinding(args: SensitiveFindingArgs): string {
|
|
442
|
+
switch (args.ruleId) {
|
|
443
|
+
case "sensitive-data.aws-access-key":
|
|
444
|
+
return "[redacted:aws-access-key]";
|
|
445
|
+
case "sensitive-data.private-key":
|
|
446
|
+
return "[redacted:private-key]";
|
|
447
|
+
case "sensitive-data.jwt-token":
|
|
448
|
+
return "[redacted:jwt]";
|
|
449
|
+
case "sensitive-data.database-url-password":
|
|
450
|
+
return fixedConnectionStringMarker(args.matchedSensitiveText);
|
|
451
|
+
case "sensitive-data.api-key-pattern":
|
|
452
|
+
return fixedApiKeyMarker(args.matchedSensitiveText, args.metadata);
|
|
453
|
+
case "sensitive-data.pii-pattern":
|
|
454
|
+
return args.metadata?.piiKind === "credit-card" ? "[redacted:payment-card]" : "[redacted:ssn]";
|
|
455
|
+
case "sensitive-data.phi-pattern":
|
|
456
|
+
return /^\d+$/.test(args.matchedSensitiveText) ? "[redacted:mrn]" : "[redacted:medicare]";
|
|
457
|
+
case "sensitive-data.gcp-service-account-key":
|
|
458
|
+
return "[redacted:gcp-service-account]";
|
|
459
|
+
default:
|
|
460
|
+
return "[redacted]";
|
|
311
461
|
}
|
|
312
|
-
return { keyName, value: secretValue, isQuoted: quotedValue !== undefined };
|
|
313
462
|
}
|
|
314
463
|
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
// Cheap shape filter: rejects all-letters words and all-digit numbers before the more expensive
|
|
328
|
-
// entropy work runs. False negatives here are acceptable; false positives waste maintainer time.
|
|
329
|
-
function hasLetterAndDigit(candidateText: string): boolean {
|
|
330
|
-
return /[A-Za-z]/.test(candidateText) && /[0-9]/.test(candidateText);
|
|
331
|
-
}
|
|
332
|
-
|
|
333
|
-
// Layered filter for the entropy detector. Order matters: cheap rejections (length, hex digest,
|
|
334
|
-
// SRI hash) run before character-set checks before the entropy calculation itself, which is the
|
|
335
|
-
// most expensive step. Reordering changes nothing semantically but can regress scan performance.
|
|
336
|
-
function isHighEntropySecretCandidate(candidateText: string, minLength: number): boolean {
|
|
337
|
-
if (isExcludedHighEntropyCandidate(candidateText, minLength)) {
|
|
338
|
-
return false;
|
|
339
|
-
}
|
|
340
|
-
if (!hasLowerUpperAndDigit(candidateText)) {
|
|
341
|
-
return false;
|
|
342
|
-
}
|
|
343
|
-
if (!hasEnoughDistinctCharacters(candidateText)) {
|
|
344
|
-
return false;
|
|
345
|
-
}
|
|
346
|
-
return shannonEntropy(candidateText) >= 4;
|
|
347
|
-
}
|
|
348
|
-
|
|
349
|
-
// Entropy false-positive escape hatches. Hex digests and SRI hashes both look "high entropy" but
|
|
350
|
-
// are well-known non-secrets - without these exclusions, package-lock.json scans become noise.
|
|
351
|
-
// Repo-relative path-shaped strings (slashes plus a known extension and a conventional prefix
|
|
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.
|
|
355
|
-
function isExcludedHighEntropyCandidate(candidateText: string, minLength: number): boolean {
|
|
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
|
-
}
|
|
464
|
+
/**
|
|
465
|
+
* Builds the fixed connection-string marker users see, retaining only the detector-approved public scheme.
|
|
466
|
+
* The matched URL supplies the allowed scheme, which the marker shows in lowercase.
|
|
467
|
+
*
|
|
468
|
+
* @param matchedUrl - Matched credentialed URL whose leading scheme is checked against the allowlist.
|
|
469
|
+
* @returns Scheme-scoped connection-string marker, or `[redacted]` when no approved scheme matches.
|
|
470
|
+
*/
|
|
471
|
+
function fixedConnectionStringMarker(matchedUrl: string): string {
|
|
472
|
+
const acceptedScheme = matchedUrl.match(/^(https?|postgres(?:ql)?|mysql|mariadb|mongodb(?:\+srv)?|redis|amqp|amqps|mssql):\/\//i)?.[1]?.toLowerCase();
|
|
473
|
+
// A missing detector-approved scheme gives users a generic marker rather than echoing any URL text.
|
|
474
|
+
if (!acceptedScheme) {
|
|
475
|
+
return "[redacted]";
|
|
378
476
|
}
|
|
379
|
-
return
|
|
477
|
+
return `[redacted:connection-string:${acceptedScheme}]`;
|
|
380
478
|
}
|
|
381
479
|
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
480
|
+
/**
|
|
481
|
+
* Selects a fixed provider marker for `matchedToken`; optional `metadata` identifies npm auth lines lacking a public prefix.
|
|
482
|
+
* Without npm auth metadata, uses a recognized prefix or `[redacted]` to avoid exposing matched token characters.
|
|
483
|
+
*
|
|
484
|
+
* @param matchedToken - Matched API key or token string classified by prefix or `_authToken` metadata.
|
|
485
|
+
* @param metadata - Optional metadata whose `keyName` identifies unprefixed `_authToken` values.
|
|
486
|
+
* @returns Fixed provider redaction marker, or `[redacted]` for unrecognized tokens.
|
|
487
|
+
*/
|
|
488
|
+
function fixedApiKeyMarker(matchedToken: string, metadata: Record<string, unknown> | undefined): string {
|
|
489
|
+
// An npm auth line may omit the public `npm_` prefix, but its detector-owned key name still identifies the category.
|
|
490
|
+
if (metadata?.keyName === "_authToken" || matchedToken.startsWith("npm_")) {
|
|
491
|
+
return "[redacted:npm-token]";
|
|
390
492
|
}
|
|
391
|
-
if (
|
|
392
|
-
return
|
|
493
|
+
if (/^(?:ghp_|github_pat_|gh[ousr]_)/.test(matchedToken)) {
|
|
494
|
+
return "[redacted:github-token]";
|
|
393
495
|
}
|
|
394
|
-
|
|
395
|
-
if (
|
|
396
|
-
return
|
|
496
|
+
// Slack tokens and webhook URLs share one fixed provider marker in user reports.
|
|
497
|
+
if (/^(?:xox[baprs]-|https:\/\/hooks\.slack\.com\/services\/)/.test(matchedToken)) {
|
|
498
|
+
return "[redacted:slack-token]";
|
|
397
499
|
}
|
|
398
|
-
|
|
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;
|
|
500
|
+
// The public live-key prefix selects the Stripe live-key label. Stripe test-key matches use the generic marker.
|
|
501
|
+
if (matchedToken.startsWith("sk_live_")) {
|
|
502
|
+
return "[redacted:stripe-live-key]";
|
|
408
503
|
}
|
|
409
|
-
|
|
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;
|
|
504
|
+
if (matchedToken.startsWith("AIza")) {
|
|
505
|
+
return "[redacted:google-api-key]";
|
|
418
506
|
}
|
|
419
|
-
|
|
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;
|
|
437
|
-
}
|
|
438
|
-
|
|
439
|
-
// Path-shape guard: a string that contains at least one `/`, has a path-like extension, AND lives
|
|
440
|
-
// under a conventional source/docs/test/workflow prefix is almost always a repo-relative reference
|
|
441
|
-
// rather than a secret. The combined gate keeps the rule firing on real high-entropy material that
|
|
442
|
-
// happens to contain slashes.
|
|
443
|
-
function isRepoPathShape(candidateText: string): boolean {
|
|
444
|
-
const normalized = candidateText.replaceAll("\\", "/");
|
|
445
|
-
const hasKnownExtension = /\.(?:md|mdx|ts|tsx|js|jsx|mjs|cjs|json|yaml|yml|toml|html|css|svg|sh)$/.test(candidateText);
|
|
446
|
-
if (!hasKnownExtension) {
|
|
447
|
-
return false;
|
|
507
|
+
if (matchedToken.startsWith("sk-ant-")) {
|
|
508
|
+
return "[redacted:anthropic-api-key]";
|
|
448
509
|
}
|
|
449
|
-
if (
|
|
450
|
-
return
|
|
510
|
+
if (matchedToken.startsWith("glpat-")) {
|
|
511
|
+
return "[redacted:gitlab-token]";
|
|
451
512
|
}
|
|
452
|
-
return
|
|
453
|
-
}
|
|
454
|
-
|
|
455
|
-
// Basename-only docs and milestone filenames such as `ADR-024-...md` and `M00-...md`
|
|
456
|
-
// appear in fixtures without a directory prefix but are still path references, not secrets.
|
|
457
|
-
function isRepoPathLikeFilename(candidateText: string): boolean {
|
|
458
|
-
return /^(?:ADR-\d{3}|M\d{2,3})-[A-Za-z0-9_.-]+\.(?:md|mdx)$/i.test(candidateText);
|
|
513
|
+
return "[redacted]";
|
|
459
514
|
}
|
|
460
515
|
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
516
|
+
/**
|
|
517
|
+
* Removes spaces and hyphens before validating a payment-card value the user may have pasted.
|
|
518
|
+
* Used for network, checksum, and grouping checks, never for report output.
|
|
519
|
+
*
|
|
520
|
+
* @param candidateText - Raw digit run possibly containing space or hyphen separators.
|
|
521
|
+
* @returns Copy of `candidateText` with all space and hyphen separators removed.
|
|
522
|
+
*/
|
|
468
523
|
function normalizedPaymentCardNumber(candidateText: string): string {
|
|
469
524
|
return candidateText.replace(/[ -]/g, "");
|
|
470
525
|
}
|
|
471
526
|
|
|
472
|
-
|
|
527
|
+
/**
|
|
528
|
+
* Checks issuer shape, supported length, and Luhn checksum before showing a payment-card finding.
|
|
529
|
+
* Ordinary long numbers stay out of the user's report when any gate fails.
|
|
530
|
+
*
|
|
531
|
+
* @param cardNumber - Normalized candidate string checked for digits, length 13-19, known prefix, and Luhn validity.
|
|
532
|
+
* @returns True when `cardNumber` passes all digit, length, issuer-prefix, and Luhn checksum gates.
|
|
533
|
+
*/
|
|
473
534
|
function isPaymentCardNumber(cardNumber: string): boolean {
|
|
474
535
|
return /^[0-9]+$/.test(cardNumber) && cardNumber.length >= 13 && cardNumber.length <= 19 && hasKnownPaymentCardPrefix(cardNumber) && passesLuhnCheck(cardNumber);
|
|
475
536
|
}
|
|
476
537
|
|
|
477
|
-
|
|
478
|
-
|
|
538
|
+
/**
|
|
539
|
+
* Checks whether normalized `cardNumber` has both a supported issuer prefix and a length accepted for that issuer.
|
|
540
|
+
* Network-specific helpers keep user-facing false-positive tuning isolated and readable.
|
|
541
|
+
*
|
|
542
|
+
* @param cardNumber - Digit-only card candidate checked against Visa, Mastercard, Amex, Discover, Diners, and JCB rules.
|
|
543
|
+
* @returns True when `cardNumber` matches any supported payment-card network and its accepted lengths.
|
|
544
|
+
*/
|
|
479
545
|
function hasKnownPaymentCardPrefix(cardNumber: string): boolean {
|
|
480
546
|
return isVisaPaymentCard(cardNumber)
|
|
481
547
|
|| isMastercardPaymentCard(cardNumber)
|
|
@@ -485,59 +551,117 @@ function hasKnownPaymentCardPrefix(cardNumber: string): boolean {
|
|
|
485
551
|
|| isJcbPaymentCard(cardNumber);
|
|
486
552
|
}
|
|
487
553
|
|
|
488
|
-
|
|
554
|
+
/**
|
|
555
|
+
* Checks whether digit-only `cardNumber` starts with `4` and has a supported Visa length of 13, 16, or 19 digits.
|
|
556
|
+
*
|
|
557
|
+
* @param cardNumber - Digit-only card candidate tested against Visa prefix and length rules.
|
|
558
|
+
* @returns True when `cardNumber` begins with `4` and has length 13, 16, or 19.
|
|
559
|
+
*/
|
|
489
560
|
function isVisaPaymentCard(cardNumber: string): boolean {
|
|
490
561
|
return cardNumber.startsWith("4") && isPaymentCardLength(cardNumber, [13, 16, 19]);
|
|
491
562
|
}
|
|
492
563
|
|
|
493
|
-
|
|
564
|
+
/**
|
|
565
|
+
* Checks whether digit-only `cardNumber` has 16 digits and a Mastercard prefix in `51-55` or `2221-2720`.
|
|
566
|
+
*
|
|
567
|
+
* @param cardNumber - Digit-only card candidate tested against Mastercard prefix ranges and length.
|
|
568
|
+
* @returns True when `cardNumber` is 16 digits long and falls in a supported Mastercard prefix range.
|
|
569
|
+
*/
|
|
494
570
|
function isMastercardPaymentCard(cardNumber: string): boolean {
|
|
495
571
|
const firstTwoDigits = Number(cardNumber.slice(0, 2));
|
|
496
572
|
const firstFourDigits = Number(cardNumber.slice(0, 4));
|
|
497
573
|
return (isInRange(firstTwoDigits, 51, 55) || isInRange(firstFourDigits, 2221, 2720)) && isPaymentCardLength(cardNumber, [16]);
|
|
498
574
|
}
|
|
499
575
|
|
|
500
|
-
|
|
576
|
+
/**
|
|
577
|
+
* Checks whether digit-only `cardNumber` has an American Express prefix (`34` or `37`) and 15 digits.
|
|
578
|
+
*
|
|
579
|
+
* @param cardNumber - Digit-only card candidate tested against American Express prefix and length rules.
|
|
580
|
+
* @returns True when `cardNumber` starts with `34` or `37` and has length 15.
|
|
581
|
+
*/
|
|
501
582
|
function isAmericanExpressPaymentCard(cardNumber: string): boolean {
|
|
502
583
|
return (cardNumber.startsWith("34") || cardNumber.startsWith("37")) && isPaymentCardLength(cardNumber, [15]);
|
|
503
584
|
}
|
|
504
585
|
|
|
505
|
-
|
|
586
|
+
/**
|
|
587
|
+
* Checks whether digit-only `cardNumber` has 16 or 19 digits and a supported Discover prefix (`6011`, `65`, or `644-649`).
|
|
588
|
+
*
|
|
589
|
+
* @param cardNumber - Digit-only card candidate tested against Discover prefixes and lengths.
|
|
590
|
+
* @returns True when `cardNumber` matches a supported Discover prefix with length 16 or 19.
|
|
591
|
+
*/
|
|
506
592
|
function isDiscoverPaymentCard(cardNumber: string): boolean {
|
|
507
593
|
const firstThreeDigits = Number(cardNumber.slice(0, 3));
|
|
508
594
|
return (cardNumber.startsWith("6011") || cardNumber.startsWith("65") || isInRange(firstThreeDigits, 644, 649)) && isPaymentCardLength(cardNumber, [16, 19]);
|
|
509
595
|
}
|
|
510
596
|
|
|
511
|
-
|
|
597
|
+
/**
|
|
598
|
+
* Checks whether digit-only `cardNumber` has 14 digits and a Diners Club prefix (`300-305`, `36`, `38`, or `39`).
|
|
599
|
+
*
|
|
600
|
+
* @param cardNumber - Digit-only card candidate tested against Diners Club prefixes and length.
|
|
601
|
+
* @returns True when `cardNumber` matches a supported Diners Club prefix with length 14.
|
|
602
|
+
*/
|
|
512
603
|
function isDinersPaymentCard(cardNumber: string): boolean {
|
|
513
604
|
const firstThreeDigits = Number(cardNumber.slice(0, 3));
|
|
514
605
|
return (isInRange(firstThreeDigits, 300, 305) || cardNumber.startsWith("36") || cardNumber.startsWith("38") || cardNumber.startsWith("39")) && isPaymentCardLength(cardNumber, [14]);
|
|
515
606
|
}
|
|
516
607
|
|
|
517
|
-
|
|
608
|
+
/**
|
|
609
|
+
* Checks whether digit-only `cardNumber` has 16-19 digits and a JCB prefix from `3528` through `3589`.
|
|
610
|
+
*
|
|
611
|
+
* @param cardNumber - Digit-only card candidate tested against JCB prefix range and length rules.
|
|
612
|
+
* @returns True when `cardNumber` has a leading prefix in `3528-3589` and length 16 through 19.
|
|
613
|
+
*/
|
|
518
614
|
function isJcbPaymentCard(cardNumber: string): boolean {
|
|
519
615
|
const firstFourDigits = Number(cardNumber.slice(0, 4));
|
|
520
616
|
return isInRange(firstFourDigits, 3528, 3589) && isPaymentCardLength(cardNumber, [16, 17, 18, 19]);
|
|
521
617
|
}
|
|
522
618
|
|
|
523
|
-
|
|
619
|
+
/**
|
|
620
|
+
* Checks whether a normalized card uses a length supported by its detected network.
|
|
621
|
+
* Keeping the length table explicit makes the user-facing classification easier to audit.
|
|
622
|
+
*
|
|
623
|
+
* @param cardNumber - Digit-only card candidate whose character length is checked.
|
|
624
|
+
* @param allowedLengths - Network-permitted digit counts matched against `cardNumber.length`.
|
|
625
|
+
* @returns True when `allowedLengths` includes `cardNumber.length`.
|
|
626
|
+
*/
|
|
524
627
|
function isPaymentCardLength(cardNumber: string, allowedLengths: number[]): boolean {
|
|
525
628
|
return allowedLengths.includes(cardNumber.length);
|
|
526
629
|
}
|
|
527
630
|
|
|
528
|
-
|
|
631
|
+
/**
|
|
632
|
+
* Checks an issuer identification number against an inclusive network range.
|
|
633
|
+
* Card-prefix helpers use it to decide whether the user should receive a payment-data finding.
|
|
634
|
+
*
|
|
635
|
+
* @param candidateNumber - Parsed leading prefix integer extracted from the card candidate.
|
|
636
|
+
* @param minimum - Inclusive lower bound of the issuer range.
|
|
637
|
+
* @param maximum - Inclusive upper bound of the issuer range.
|
|
638
|
+
* @returns True when `candidateNumber` lies between `minimum` and `maximum` inclusive.
|
|
639
|
+
*/
|
|
529
640
|
function isInRange(candidateNumber: number, minimum: number, maximum: number): boolean {
|
|
530
641
|
return candidateNumber >= minimum && candidateNumber <= maximum;
|
|
531
642
|
}
|
|
532
643
|
|
|
533
|
-
|
|
644
|
+
/**
|
|
645
|
+
* Runs the standard Luhn checksum over normalized digits before a card finding reaches the user.
|
|
646
|
+
* Invalid checksums keep ordinary long numeric identifiers quiet.
|
|
647
|
+
*
|
|
648
|
+
* @param cardNumber - Digit-only card candidate summed from right to left under Luhn weights.
|
|
649
|
+
* @returns True when the weighted digit sum modulo 10 equals zero.
|
|
650
|
+
*/
|
|
534
651
|
function passesLuhnCheck(cardNumber: string): boolean {
|
|
535
652
|
const digits = [...cardNumber].reverse().map((digit) => Number(digit));
|
|
536
653
|
const sum = digits.reduce((total, digit, index) => total + luhnDigitContribution(digit, index), 0);
|
|
537
654
|
return sum % 10 === 0;
|
|
538
655
|
}
|
|
539
656
|
|
|
540
|
-
|
|
657
|
+
/**
|
|
658
|
+
* Calculates one digit's Luhn contribution while validating a possible payment-card value.
|
|
659
|
+
* `indexFromRight` is zero-based, so even positions stay unchanged while odd positions double `digit` and subtract 9 when over 9.
|
|
660
|
+
*
|
|
661
|
+
* @param digit - Single decimal digit (0-9) from the candidate card number.
|
|
662
|
+
* @param indexFromRight - Zero-based position counting from the rightmost digit.
|
|
663
|
+
* @returns Weighted Luhn contribution (`digit` at even indexes, doubled and folded at odd indexes).
|
|
664
|
+
*/
|
|
541
665
|
function luhnDigitContribution(digit: number, indexFromRight: number): number {
|
|
542
666
|
if (indexFromRight % 2 === 0) {
|
|
543
667
|
return digit;
|
|
@@ -546,55 +670,4 @@ function luhnDigitContribution(digit: number, indexFromRight: number): number {
|
|
|
546
670
|
return doubled > 9 ? doubled - 9 : doubled;
|
|
547
671
|
}
|
|
548
672
|
|
|
549
|
-
// All-hex strings - typical for SHA digests, content hashes, and tooling identifiers.
|
|
550
|
-
function isHexDigest(candidateText: string): boolean {
|
|
551
|
-
return /^[0-9a-f]+$/i.test(candidateText);
|
|
552
|
-
}
|
|
553
|
-
|
|
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.
|
|
556
|
-
function isSubresourceIntegrityHash(candidateText: string): boolean {
|
|
557
|
-
return /^sha(?:1|256|384|512)-[A-Za-z0-9+/=]+$/.test(candidateText);
|
|
558
|
-
}
|
|
559
|
-
|
|
560
|
-
// Three-class character requirement that filters out single-case identifiers and pure base64 hashes
|
|
561
|
-
// before the entropy calculation runs. Real API tokens almost always contain all three classes.
|
|
562
|
-
function hasLowerUpperAndDigit(candidateText: string): boolean {
|
|
563
|
-
return /[a-z]/.test(candidateText) && /[A-Z]/.test(candidateText) && /[0-9]/.test(candidateText);
|
|
564
|
-
}
|
|
565
|
-
|
|
566
|
-
// Distinct-character guard. The cap at 12 keeps a long alphabet from inflating the requirement;
|
|
567
|
-
// the `ceil(length/3)` floor scales the threshold with the candidate length.
|
|
568
|
-
function hasEnoughDistinctCharacters(candidateText: string): boolean {
|
|
569
|
-
return new Set(candidateText).size >= Math.min(12, Math.ceil(candidateText.length / 3));
|
|
570
|
-
}
|
|
571
|
-
|
|
572
|
-
// Standard Shannon entropy in bits per symbol. The 4.0-bit threshold in the caller corresponds
|
|
573
|
-
// roughly to a uniform alphabet of 16 distinct characters - the typical floor for real secrets.
|
|
574
|
-
function shannonEntropy(candidateText: string): number {
|
|
575
|
-
const counts = new Map<string, number>();
|
|
576
|
-
for (const character of candidateText) {
|
|
577
|
-
counts.set(character, (counts.get(character) ?? 0) + 1);
|
|
578
|
-
}
|
|
579
|
-
return [...counts.values()].reduce((sum, count) => {
|
|
580
|
-
const probability = count / candidateText.length;
|
|
581
|
-
return sum - probability * Math.log2(probability);
|
|
582
|
-
}, 0);
|
|
583
|
-
}
|
|
584
|
-
|
|
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.
|
|
592
|
-
function redact(rawSecret: string): string {
|
|
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) {
|
|
595
|
-
return `${"*".repeat(rawSecret.length)} (redacted, ${rawSecret.length} chars)`;
|
|
596
|
-
}
|
|
597
|
-
return `${rawSecret.slice(0, VISIBLE_SECRET_EDGE_LENGTH)}...${rawSecret.slice(-VISIBLE_SECRET_EDGE_LENGTH)} (redacted, ${rawSecret.length} chars)`;
|
|
598
|
-
}
|
|
599
|
-
|
|
600
673
|
export { analyseSensitiveData };
|