@blundergoat/gruff-ts 0.4.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 +123 -1
- package/CONTRIBUTING.md +32 -25
- package/README.md +55 -46
- package/SECURITY.md +18 -30
- package/UPGRADING.md +101 -0
- package/bin/gruff-ts +3 -0
- package/docs/README.md +11 -13
- package/docs/agent-hook.md +33 -24
- package/docs/ci-integration.md +38 -24
- package/docs/configuration.md +173 -71
- 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 -157
- package/docs/rules.md +140 -106
- package/package.json +10 -8
- package/src/analyser.ts +886 -282
- 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 +85 -55
- package/src/blocks.ts +579 -364
- package/src/changed-regions.ts +414 -65
- package/src/check-ignore.ts +28 -13
- package/src/class-rules.ts +461 -302
- package/src/cli-program.ts +956 -166
- package/src/cli.ts +9 -2
- package/src/comment-rules.ts +277 -414
- package/src/comment-scanner.ts +363 -44
- package/src/complexity-metrics.ts +320 -0
- 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 +778 -210
- package/src/constants.ts +7 -6
- package/src/context-doc-rules.ts +188 -61
- package/src/dashboard.ts +88 -23
- package/src/dead-code-rules.ts +153 -74
- package/src/discovery.ts +521 -148
- package/src/doc-rules.ts +592 -147
- package/src/duplicate-test-group-rules.ts +359 -0
- package/src/findings-helpers.ts +240 -89
- package/src/findings.ts +48 -24
- package/src/fixture-purpose-rules.ts +226 -48
- package/src/github-actions-event-guards.ts +331 -0
- package/src/github-actions-rules.ts +336 -106
- package/src/hook-contract.ts +708 -211
- package/src/init-config.ts +169 -114
- package/src/inline-suppressions.ts +340 -0
- package/src/limit-band.ts +56 -0
- package/src/line-rules.ts +331 -419
- package/src/migrate-config.ts +670 -0
- package/src/naming-pushers.ts +33 -107
- package/src/parsed-script.ts +1206 -0
- package/src/pillar-summary.ts +56 -40
- package/src/profiles.ts +97 -71
- package/src/project-config-rules.ts +335 -146
- package/src/project-rules.ts +237 -115
- package/src/public-exports.ts +284 -0
- package/src/report-html.ts +217 -85
- package/src/report-renderers.ts +864 -195
- package/src/rule-list.ts +166 -46
- package/src/rules.ts +100 -104
- package/src/safety-rules.ts +191 -132
- package/src/scoring.ts +255 -52
- package/src/security-flow-rules.ts +930 -109
- package/src/selectors.ts +169 -0
- package/src/sensitive-data-rules.ts +502 -375
- package/src/sensitive-exclusions.ts +435 -0
- package/src/source-text.ts +380 -148
- package/src/static-analysis-redundant-rules.ts +298 -41
- package/src/test-block-rules.ts +422 -228
- package/src/text-scans.ts +67 -9
- package/src/types.ts +222 -71
- package/tsconfig.json +2 -1
- package/src/process-exec-metadata.ts +0 -153
- package/src/test-fixtures.ts +0 -668
|
@@ -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
|
-
import { byteLine } from "./text-scans.ts";
|
|
5
|
-
import type {
|
|
7
|
+
import { byteColumn, byteLine } from "./text-scans.ts";
|
|
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,407 +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
|
-
analysePaymentCardNumbers(file, source, config, findings);
|
|
45
|
-
analyseGcpServiceAccountKeys(file, source, config, findings);
|
|
76
|
+
analyseNpmAuthTokens(file, source, findings);
|
|
77
|
+
analysePhiLabelledIdentifiers(file, source, findings);
|
|
78
|
+
analysePaymentCardNumbers(file, source, findings);
|
|
79
|
+
analyseGcpServiceAccountKeys(file, source, findings);
|
|
46
80
|
}
|
|
47
81
|
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
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);
|
|
54
137
|
}
|
|
55
138
|
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
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);
|
|
148
|
+
}
|
|
149
|
+
|
|
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
|
|
94
|
-
if (!isPaymentCardNumber(cardNumber)) {
|
|
95
|
-
continue;
|
|
96
|
-
}
|
|
232
|
+
const matchedDigitRun = match[0] ?? "";
|
|
233
|
+
const normalizedCardNumber = normalizedPaymentCardNumber(matchedDigitRun);
|
|
97
234
|
const line = byteLine(source, match.index ?? 0);
|
|
98
|
-
|
|
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] ?? "")) {
|
|
99
237
|
continue;
|
|
100
238
|
}
|
|
101
|
-
pushSensitiveFinding(
|
|
102
|
-
config,
|
|
239
|
+
pushSensitiveFinding({
|
|
103
240
|
findings,
|
|
104
241
|
file,
|
|
105
|
-
"sensitive-data.pii-pattern",
|
|
106
|
-
"Credit card number (PII) pattern detected.",
|
|
242
|
+
ruleId: "sensitive-data.pii-pattern",
|
|
243
|
+
message: "Credit card number (PII) pattern detected.",
|
|
107
244
|
line,
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
245
|
+
column: byteColumn(source, match.index ?? 0),
|
|
246
|
+
matchedSensitiveText: matchedDigitRun,
|
|
247
|
+
confidence: "high",
|
|
248
|
+
metadata: { piiKind: "credit-card" },
|
|
249
|
+
});
|
|
112
250
|
}
|
|
113
251
|
}
|
|
114
252
|
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
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)) {
|
|
264
|
+
return false;
|
|
265
|
+
}
|
|
266
|
+
return hasCanonicalPaymentCardGrouping(matchedDigitRun, normalizedCardNumber) || hasPaymentCardContext(contextLine);
|
|
267
|
+
}
|
|
268
|
+
|
|
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.
|
|
281
|
+
if (separators.length === 0 || new Set(separators).size !== 1) {
|
|
282
|
+
return false;
|
|
283
|
+
}
|
|
284
|
+
const groupSizes = matchedDigitRun.split(separators[0] ?? " ").map((group) => group.length);
|
|
285
|
+
const expectedGroupSizes = isAmericanExpressPaymentCard(normalizedCardNumber)
|
|
286
|
+
? [4, 6, 5]
|
|
287
|
+
: isDinersPaymentCard(normalizedCardNumber)
|
|
288
|
+
? [4, 6, 4]
|
|
289
|
+
: Array.from({ length: Math.ceil(normalizedCardNumber.length / 4) }, (_, index) => Math.min(4, normalizedCardNumber.length - index * 4));
|
|
290
|
+
return groupSizes.length === expectedGroupSizes.length && groupSizes.every((size, index) => size === expectedGroupSizes[index]);
|
|
291
|
+
}
|
|
292
|
+
|
|
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
|
+
*/
|
|
118
300
|
function hasPaymentCardContext(lineText: string): boolean {
|
|
119
301
|
return /(?:\bpan\b|card|payment|credit|debit|visa|master|amex|discover|jcb|diners)/i.test(lineText);
|
|
120
302
|
}
|
|
121
303
|
|
|
122
|
-
|
|
123
|
-
|
|
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 {
|
|
124
314
|
const lines = source.split(/\r?\n/);
|
|
315
|
+
// Each config line can contain a separate registry credential the user needs to rotate.
|
|
125
316
|
for (const [index, line] of lines.entries()) {
|
|
126
317
|
const token = npmAuthTokenValue(line);
|
|
318
|
+
// No supported `_authToken` value means this line contributes no npm credential finding.
|
|
127
319
|
if (!token) {
|
|
128
320
|
continue;
|
|
129
321
|
}
|
|
130
|
-
pushSensitiveFinding(
|
|
131
|
-
config,
|
|
322
|
+
pushSensitiveFinding({
|
|
132
323
|
findings,
|
|
133
324
|
file,
|
|
134
|
-
"sensitive-data.api-key-pattern",
|
|
135
|
-
"npm auth token pattern detected.",
|
|
136
|
-
index + 1,
|
|
137
|
-
token,
|
|
138
|
-
"high",
|
|
139
|
-
{ keyName: "_authToken" },
|
|
140
|
-
);
|
|
325
|
+
ruleId: "sensitive-data.api-key-pattern",
|
|
326
|
+
message: "npm auth token pattern detected.",
|
|
327
|
+
line: index + 1,
|
|
328
|
+
matchedSensitiveText: token,
|
|
329
|
+
confidence: "high",
|
|
330
|
+
metadata: { keyName: "_authToken" },
|
|
331
|
+
});
|
|
141
332
|
}
|
|
142
333
|
}
|
|
143
334
|
|
|
144
|
-
|
|
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
|
+
*/
|
|
145
342
|
function npmAuthTokenValue(line: string): string | undefined {
|
|
146
343
|
const match = line.match(/(?:^|:)_authToken\s*=\s*([A-Za-z0-9_-]{20,})\b/);
|
|
147
344
|
return match?.[1];
|
|
148
345
|
}
|
|
149
346
|
|
|
150
|
-
//
|
|
151
|
-
//
|
|
152
|
-
//
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
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.
|
|
351
|
+
interface SensitiveFindingArgs {
|
|
352
|
+
findings: Finding[];
|
|
353
|
+
file: SensitiveSourceFile;
|
|
354
|
+
ruleId: string;
|
|
355
|
+
message: string;
|
|
356
|
+
line: number;
|
|
357
|
+
column?: number;
|
|
358
|
+
matchedSensitiveText: string;
|
|
359
|
+
confidence: Finding["confidence"];
|
|
360
|
+
metadata?: Record<string, unknown>;
|
|
361
|
+
}
|
|
362
|
+
|
|
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"));
|
|
200
401
|
}
|
|
201
402
|
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
severity: Finding["severity"] = "error",
|
|
213
|
-
): void {
|
|
214
|
-
const preview = redact(raw);
|
|
215
|
-
if (config.secretPreviews.has(preview)) {
|
|
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
|
+
*/
|
|
410
|
+
function pushSensitiveFinding(args: SensitiveFindingArgs): void {
|
|
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)) {
|
|
216
413
|
return;
|
|
217
414
|
}
|
|
218
|
-
|
|
415
|
+
const displayMarker = fixedMarkerForSensitiveFinding(args);
|
|
416
|
+
// An unavailable column is omitted. The fixed marker replaces any supplied preview and preserves the other metadata.
|
|
417
|
+
args.findings.push(
|
|
219
418
|
makeFinding({
|
|
220
|
-
ruleId,
|
|
221
|
-
message: `${message} Redacted preview: ${
|
|
222
|
-
filePath: file.displayPath,
|
|
223
|
-
line,
|
|
224
|
-
|
|
419
|
+
ruleId: args.ruleId,
|
|
420
|
+
message: `${args.message} Redacted preview: ${displayMarker}.`,
|
|
421
|
+
filePath: args.file.displayPath,
|
|
422
|
+
line: args.line,
|
|
423
|
+
...(args.column === undefined ? {} : { column: args.column }),
|
|
424
|
+
severity: "warning",
|
|
225
425
|
pillar: "sensitive-data",
|
|
226
|
-
confidence,
|
|
426
|
+
confidence: args.confidence,
|
|
227
427
|
remediation: "Remove the sensitive value and load it from a secure runtime source.",
|
|
228
|
-
metadata: { ...metadata, preview },
|
|
428
|
+
metadata: { ...(args.metadata ?? {}), preview: displayMarker },
|
|
229
429
|
}),
|
|
230
430
|
);
|
|
231
431
|
}
|
|
232
432
|
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
if (!keyName) {
|
|
262
|
-
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]";
|
|
263
461
|
}
|
|
264
|
-
return { keyName, value: secretValue, isQuoted: openingQuote !== "" };
|
|
265
|
-
}
|
|
266
|
-
|
|
267
|
-
// Three predicates combined: long enough, not a literal placeholder, and shape-like (letters + digits).
|
|
268
|
-
// All three are required - dropping any one regresses to noisy findings on fixture values.
|
|
269
|
-
function isHardcodedEnvCandidate(secretValue: string, minLength: number): boolean {
|
|
270
|
-
return secretValue.length >= minLength && !isPlaceholderSecretValue(secretValue) && hasLetterAndDigit(secretValue);
|
|
271
|
-
}
|
|
272
|
-
|
|
273
|
-
// Allowlist of obvious fixture words. Case-insensitive so `Placeholder`, `PASSWORD` and similar
|
|
274
|
-
// fixture values stay quiet. Extend deliberately - the cost of a missing word is a false positive.
|
|
275
|
-
function isPlaceholderSecretValue(secretValue: string): boolean {
|
|
276
|
-
return /^(?:x-api-key|token|secret|password|example|sample|placeholder)$/i.test(secretValue);
|
|
277
462
|
}
|
|
278
463
|
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
if (
|
|
290
|
-
return
|
|
291
|
-
}
|
|
292
|
-
if (!hasLowerUpperAndDigit(candidateText)) {
|
|
293
|
-
return false;
|
|
294
|
-
}
|
|
295
|
-
if (!hasEnoughDistinctCharacters(candidateText)) {
|
|
296
|
-
return false;
|
|
297
|
-
}
|
|
298
|
-
return shannonEntropy(candidateText) >= 4;
|
|
299
|
-
}
|
|
300
|
-
|
|
301
|
-
// Entropy false-positive escape hatches. Hex digests and SRI hashes both look "high entropy" but
|
|
302
|
-
// are well-known non-secrets - without these exclusions, package-lock.json scans become noise.
|
|
303
|
-
// Repo-relative path-shaped strings (slashes plus a known extension and a conventional prefix
|
|
304
|
-
// segment) also clear the entropy bar without being secrets; the path-shape guard suppresses them.
|
|
305
|
-
// Alphabet enumerations and dotted/underscored/slug identifiers that decompose into dictionary-like
|
|
306
|
-
// word segments are the remaining non-secret shapes that pass the entropy bar.
|
|
307
|
-
function isExcludedHighEntropyCandidate(candidateText: string, minLength: number): boolean {
|
|
308
|
-
return candidateText.length < minLength
|
|
309
|
-
|| isHexDigest(candidateText)
|
|
310
|
-
|| isSubresourceIntegrityHash(candidateText)
|
|
311
|
-
|| isRepoPathShape(candidateText)
|
|
312
|
-
|| isCharacterAlphabetString(candidateText)
|
|
313
|
-
|| isWordSegmentIdentifier(candidateText);
|
|
314
|
-
}
|
|
315
|
-
|
|
316
|
-
// Translation/encoding alphabets ("ABC...xyz0123456789+/" in PlantUML, base64 tables) clear the
|
|
317
|
-
// entropy bar but are enumerations, not secrets. The proof is a run of 10+ consecutive code
|
|
318
|
-
// points, which credential generators essentially never produce.
|
|
319
|
-
function isCharacterAlphabetString(candidateText: string): boolean {
|
|
320
|
-
let runLength = 1;
|
|
321
|
-
for (let index = 1; index < candidateText.length; index += 1) {
|
|
322
|
-
if (candidateText.charCodeAt(index) === candidateText.charCodeAt(index - 1) + 1) {
|
|
323
|
-
runLength += 1;
|
|
324
|
-
if (runLength >= 10) {
|
|
325
|
-
return true;
|
|
326
|
-
}
|
|
327
|
-
} else {
|
|
328
|
-
runLength = 1;
|
|
329
|
-
}
|
|
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]";
|
|
330
476
|
}
|
|
331
|
-
return
|
|
477
|
+
return `[redacted:connection-string:${acceptedScheme}]`;
|
|
332
478
|
}
|
|
333
479
|
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
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]";
|
|
345
492
|
}
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
return false;
|
|
493
|
+
if (/^(?:ghp_|github_pat_|gh[ousr]_)/.test(matchedToken)) {
|
|
494
|
+
return "[redacted:github-token]";
|
|
349
495
|
}
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
// Token guard for the word-segment exemption. JWTs always start with "eyJ" (base64 of `{"`), and
|
|
354
|
-
// any single segment that is a 20+ char mixed-case-with-digit run is credential material even when
|
|
355
|
-
// its separators mimic an identifier. Must stay ahead of the word-segment arms - relaxing it would
|
|
356
|
-
// silently exempt JWT-shaped and long base64url secrets.
|
|
357
|
-
function isTokenLikeSegmentedSecret(candidateText: string): boolean {
|
|
358
|
-
if (candidateText.startsWith("eyJ")) {
|
|
359
|
-
return true;
|
|
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]";
|
|
360
499
|
}
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
// One identifier segment: letters with digits at most at one boundary ("Example2", "405B",
|
|
365
|
-
// "20241022"), capped at 16 chars. More than one letter<->digit transition means the segment
|
|
366
|
-
// interleaves like token material and must not earn the exemption.
|
|
367
|
-
function isWordLikeSegment(segment: string): boolean {
|
|
368
|
-
if (segment.length === 0 || segment.length > 16 || !/^[A-Za-z0-9]+$/.test(segment)) {
|
|
369
|
-
return false;
|
|
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]";
|
|
370
503
|
}
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
// Counts boundaries where the segment switches between letter and digit runs; word-like segments
|
|
375
|
-
// have at most one ("Example2"), token material alternates repeatedly ("Xk9pQ2vL").
|
|
376
|
-
function letterDigitTransitionCount(segment: string): number {
|
|
377
|
-
let transitions = 0;
|
|
378
|
-
for (let index = 1; index < segment.length; index += 1) {
|
|
379
|
-
if (isDigitCharCode(segment.charCodeAt(index - 1)) !== isDigitCharCode(segment.charCodeAt(index))) {
|
|
380
|
-
transitions += 1;
|
|
381
|
-
}
|
|
504
|
+
if (matchedToken.startsWith("AIza")) {
|
|
505
|
+
return "[redacted:google-api-key]";
|
|
382
506
|
}
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
// Character-code digit test so the transition counter never needs unchecked string indexing.
|
|
387
|
-
function isDigitCharCode(code: number): boolean {
|
|
388
|
-
return code >= 48 && code <= 57;
|
|
389
|
-
}
|
|
390
|
-
|
|
391
|
-
// Path-shape guard: a string that contains at least one `/`, has a path-like extension, AND lives
|
|
392
|
-
// under a conventional source/docs/test/workflow prefix is almost always a repo-relative reference
|
|
393
|
-
// rather than a secret. The combined gate keeps the rule firing on real high-entropy material that
|
|
394
|
-
// happens to contain slashes.
|
|
395
|
-
function isRepoPathShape(candidateText: string): boolean {
|
|
396
|
-
const normalized = candidateText.replaceAll("\\", "/");
|
|
397
|
-
const hasKnownExtension = /\.(?:md|mdx|ts|tsx|js|jsx|mjs|cjs|json|yaml|yml|toml|html|css|svg|sh)$/.test(candidateText);
|
|
398
|
-
if (!hasKnownExtension) {
|
|
399
|
-
return false;
|
|
507
|
+
if (matchedToken.startsWith("sk-ant-")) {
|
|
508
|
+
return "[redacted:anthropic-api-key]";
|
|
400
509
|
}
|
|
401
|
-
if (
|
|
402
|
-
return
|
|
510
|
+
if (matchedToken.startsWith("glpat-")) {
|
|
511
|
+
return "[redacted:gitlab-token]";
|
|
403
512
|
}
|
|
404
|
-
return
|
|
405
|
-
}
|
|
406
|
-
|
|
407
|
-
// Basename-only docs and milestone filenames such as `ADR-024-...md` and `M00-...md`
|
|
408
|
-
// appear in fixtures without a directory prefix but are still path references, not secrets.
|
|
409
|
-
function isRepoPathLikeFilename(candidateText: string): boolean {
|
|
410
|
-
return /^(?:ADR-\d{3}|M\d{2,3})-[A-Za-z0-9_.-]+\.(?:md|mdx)$/i.test(candidateText);
|
|
411
|
-
}
|
|
412
|
-
|
|
413
|
-
// Path references may be repo-relative under source directories or fixture-absolute under `/repo`.
|
|
414
|
-
// Requiring a known repository segment keeps slash-containing tokens from being over-suppressed.
|
|
415
|
-
function hasKnownRepoPathSegment(candidateText: string): boolean {
|
|
416
|
-
return /(?:^|\/)(?:\.goat-flow|src|test|tests|fixtures?|docs|scripts|bin|workflow|package(?:-lock)?\.json)(?:\/|$)/.test(candidateText);
|
|
513
|
+
return "[redacted]";
|
|
417
514
|
}
|
|
418
515
|
|
|
419
|
-
|
|
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
|
+
*/
|
|
420
523
|
function normalizedPaymentCardNumber(candidateText: string): string {
|
|
421
524
|
return candidateText.replace(/[ -]/g, "");
|
|
422
525
|
}
|
|
423
526
|
|
|
424
|
-
|
|
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
|
+
*/
|
|
425
534
|
function isPaymentCardNumber(cardNumber: string): boolean {
|
|
426
535
|
return /^[0-9]+$/.test(cardNumber) && cardNumber.length >= 13 && cardNumber.length <= 19 && hasKnownPaymentCardPrefix(cardNumber) && passesLuhnCheck(cardNumber);
|
|
427
536
|
}
|
|
428
537
|
|
|
429
|
-
|
|
430
|
-
|
|
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
|
+
*/
|
|
431
545
|
function hasKnownPaymentCardPrefix(cardNumber: string): boolean {
|
|
432
546
|
return isVisaPaymentCard(cardNumber)
|
|
433
547
|
|| isMastercardPaymentCard(cardNumber)
|
|
@@ -437,59 +551,117 @@ function hasKnownPaymentCardPrefix(cardNumber: string): boolean {
|
|
|
437
551
|
|| isJcbPaymentCard(cardNumber);
|
|
438
552
|
}
|
|
439
553
|
|
|
440
|
-
|
|
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
|
+
*/
|
|
441
560
|
function isVisaPaymentCard(cardNumber: string): boolean {
|
|
442
561
|
return cardNumber.startsWith("4") && isPaymentCardLength(cardNumber, [13, 16, 19]);
|
|
443
562
|
}
|
|
444
563
|
|
|
445
|
-
|
|
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
|
+
*/
|
|
446
570
|
function isMastercardPaymentCard(cardNumber: string): boolean {
|
|
447
571
|
const firstTwoDigits = Number(cardNumber.slice(0, 2));
|
|
448
572
|
const firstFourDigits = Number(cardNumber.slice(0, 4));
|
|
449
573
|
return (isInRange(firstTwoDigits, 51, 55) || isInRange(firstFourDigits, 2221, 2720)) && isPaymentCardLength(cardNumber, [16]);
|
|
450
574
|
}
|
|
451
575
|
|
|
452
|
-
|
|
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
|
+
*/
|
|
453
582
|
function isAmericanExpressPaymentCard(cardNumber: string): boolean {
|
|
454
583
|
return (cardNumber.startsWith("34") || cardNumber.startsWith("37")) && isPaymentCardLength(cardNumber, [15]);
|
|
455
584
|
}
|
|
456
585
|
|
|
457
|
-
|
|
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
|
+
*/
|
|
458
592
|
function isDiscoverPaymentCard(cardNumber: string): boolean {
|
|
459
593
|
const firstThreeDigits = Number(cardNumber.slice(0, 3));
|
|
460
594
|
return (cardNumber.startsWith("6011") || cardNumber.startsWith("65") || isInRange(firstThreeDigits, 644, 649)) && isPaymentCardLength(cardNumber, [16, 19]);
|
|
461
595
|
}
|
|
462
596
|
|
|
463
|
-
|
|
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
|
+
*/
|
|
464
603
|
function isDinersPaymentCard(cardNumber: string): boolean {
|
|
465
604
|
const firstThreeDigits = Number(cardNumber.slice(0, 3));
|
|
466
605
|
return (isInRange(firstThreeDigits, 300, 305) || cardNumber.startsWith("36") || cardNumber.startsWith("38") || cardNumber.startsWith("39")) && isPaymentCardLength(cardNumber, [14]);
|
|
467
606
|
}
|
|
468
607
|
|
|
469
|
-
|
|
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
|
+
*/
|
|
470
614
|
function isJcbPaymentCard(cardNumber: string): boolean {
|
|
471
615
|
const firstFourDigits = Number(cardNumber.slice(0, 4));
|
|
472
616
|
return isInRange(firstFourDigits, 3528, 3589) && isPaymentCardLength(cardNumber, [16, 17, 18, 19]);
|
|
473
617
|
}
|
|
474
618
|
|
|
475
|
-
|
|
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
|
+
*/
|
|
476
627
|
function isPaymentCardLength(cardNumber: string, allowedLengths: number[]): boolean {
|
|
477
628
|
return allowedLengths.includes(cardNumber.length);
|
|
478
629
|
}
|
|
479
630
|
|
|
480
|
-
|
|
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
|
+
*/
|
|
481
640
|
function isInRange(candidateNumber: number, minimum: number, maximum: number): boolean {
|
|
482
641
|
return candidateNumber >= minimum && candidateNumber <= maximum;
|
|
483
642
|
}
|
|
484
643
|
|
|
485
|
-
|
|
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
|
+
*/
|
|
486
651
|
function passesLuhnCheck(cardNumber: string): boolean {
|
|
487
652
|
const digits = [...cardNumber].reverse().map((digit) => Number(digit));
|
|
488
653
|
const sum = digits.reduce((total, digit, index) => total + luhnDigitContribution(digit, index), 0);
|
|
489
654
|
return sum % 10 === 0;
|
|
490
655
|
}
|
|
491
656
|
|
|
492
|
-
|
|
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
|
+
*/
|
|
493
665
|
function luhnDigitContribution(digit: number, indexFromRight: number): number {
|
|
494
666
|
if (indexFromRight % 2 === 0) {
|
|
495
667
|
return digit;
|
|
@@ -498,49 +670,4 @@ function luhnDigitContribution(digit: number, indexFromRight: number): number {
|
|
|
498
670
|
return doubled > 9 ? doubled - 9 : doubled;
|
|
499
671
|
}
|
|
500
672
|
|
|
501
|
-
// All-hex strings - typical for SHA digests, content hashes, and tooling identifiers.
|
|
502
|
-
function isHexDigest(candidateText: string): boolean {
|
|
503
|
-
return /^[0-9a-f]+$/i.test(candidateText);
|
|
504
|
-
}
|
|
505
|
-
|
|
506
|
-
// SRI hashes from `package-lock.json` and `<script integrity=...>` attributes. Excluded so the
|
|
507
|
-
// detector stays quiet on dependency manifests.
|
|
508
|
-
function isSubresourceIntegrityHash(candidateText: string): boolean {
|
|
509
|
-
return /^sha(?:256|384|512)-[A-Za-z0-9+/=]+$/.test(candidateText);
|
|
510
|
-
}
|
|
511
|
-
|
|
512
|
-
// Three-class character requirement that filters out single-case identifiers and pure base64 hashes
|
|
513
|
-
// before the entropy calculation runs. Real API tokens almost always contain all three classes.
|
|
514
|
-
function hasLowerUpperAndDigit(candidateText: string): boolean {
|
|
515
|
-
return /[a-z]/.test(candidateText) && /[A-Z]/.test(candidateText) && /[0-9]/.test(candidateText);
|
|
516
|
-
}
|
|
517
|
-
|
|
518
|
-
// Distinct-character guard. The cap at 12 keeps a long alphabet from inflating the requirement;
|
|
519
|
-
// the `ceil(length/3)` floor scales the threshold with the candidate length.
|
|
520
|
-
function hasEnoughDistinctCharacters(candidateText: string): boolean {
|
|
521
|
-
return new Set(candidateText).size >= Math.min(12, Math.ceil(candidateText.length / 3));
|
|
522
|
-
}
|
|
523
|
-
|
|
524
|
-
// Standard Shannon entropy in bits per symbol. The 4.0-bit threshold in the caller corresponds
|
|
525
|
-
// roughly to a uniform alphabet of 16 distinct characters - the typical floor for real secrets.
|
|
526
|
-
function shannonEntropy(candidateText: string): number {
|
|
527
|
-
const counts = new Map<string, number>();
|
|
528
|
-
for (const character of candidateText) {
|
|
529
|
-
counts.set(character, (counts.get(character) ?? 0) + 1);
|
|
530
|
-
}
|
|
531
|
-
return [...counts.values()].reduce((sum, count) => {
|
|
532
|
-
const probability = count / candidateText.length;
|
|
533
|
-
return sum - probability * Math.log2(probability);
|
|
534
|
-
}, 0);
|
|
535
|
-
}
|
|
536
|
-
|
|
537
|
-
// Preview format used in finding messages. Short values are fully masked; longer values show only
|
|
538
|
-
// the first/last 4 characters so an operator can identify which secret to rotate without leaking it.
|
|
539
|
-
function redact(rawSecret: string): string {
|
|
540
|
-
if (rawSecret.length <= 8) {
|
|
541
|
-
return `${"*".repeat(rawSecret.length)} (redacted, ${rawSecret.length} chars)`;
|
|
542
|
-
}
|
|
543
|
-
return `${rawSecret.slice(0, 4)}...${rawSecret.slice(-4)} (redacted, ${rawSecret.length} chars)`;
|
|
544
|
-
}
|
|
545
|
-
|
|
546
673
|
export { analyseSensitiveData };
|