@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.
Files changed (77) hide show
  1. package/CHANGELOG.md +123 -1
  2. package/CONTRIBUTING.md +32 -25
  3. package/README.md +55 -46
  4. package/SECURITY.md +18 -30
  5. package/UPGRADING.md +101 -0
  6. package/bin/gruff-ts +3 -0
  7. package/docs/README.md +11 -13
  8. package/docs/agent-hook.md +33 -24
  9. package/docs/ci-integration.md +38 -24
  10. package/docs/configuration.md +173 -71
  11. package/docs/dashboard.md +12 -13
  12. package/docs/output-formats.md +100 -25
  13. package/docs/philosophy.md +2 -2
  14. package/docs/reports-and-ci.md +14 -157
  15. package/docs/rules.md +140 -106
  16. package/package.json +10 -8
  17. package/src/analyser.ts +886 -282
  18. package/src/baseline-file.ts +867 -0
  19. package/src/baseline-identity.ts +463 -0
  20. package/src/baseline-options.ts +139 -34
  21. package/src/baseline.ts +85 -55
  22. package/src/blocks.ts +579 -364
  23. package/src/changed-regions.ts +414 -65
  24. package/src/check-ignore.ts +28 -13
  25. package/src/class-rules.ts +461 -302
  26. package/src/cli-program.ts +956 -166
  27. package/src/cli.ts +9 -2
  28. package/src/comment-rules.ts +277 -414
  29. package/src/comment-scanner.ts +363 -44
  30. package/src/complexity-metrics.ts +320 -0
  31. package/src/config-load-error.ts +17 -8
  32. package/src/config-parse.ts +291 -98
  33. package/src/config-preservation.ts +81 -26
  34. package/src/config.ts +778 -210
  35. package/src/constants.ts +7 -6
  36. package/src/context-doc-rules.ts +188 -61
  37. package/src/dashboard.ts +88 -23
  38. package/src/dead-code-rules.ts +153 -74
  39. package/src/discovery.ts +521 -148
  40. package/src/doc-rules.ts +592 -147
  41. package/src/duplicate-test-group-rules.ts +359 -0
  42. package/src/findings-helpers.ts +240 -89
  43. package/src/findings.ts +48 -24
  44. package/src/fixture-purpose-rules.ts +226 -48
  45. package/src/github-actions-event-guards.ts +331 -0
  46. package/src/github-actions-rules.ts +336 -106
  47. package/src/hook-contract.ts +708 -211
  48. package/src/init-config.ts +169 -114
  49. package/src/inline-suppressions.ts +340 -0
  50. package/src/limit-band.ts +56 -0
  51. package/src/line-rules.ts +331 -419
  52. package/src/migrate-config.ts +670 -0
  53. package/src/naming-pushers.ts +33 -107
  54. package/src/parsed-script.ts +1206 -0
  55. package/src/pillar-summary.ts +56 -40
  56. package/src/profiles.ts +97 -71
  57. package/src/project-config-rules.ts +335 -146
  58. package/src/project-rules.ts +237 -115
  59. package/src/public-exports.ts +284 -0
  60. package/src/report-html.ts +217 -85
  61. package/src/report-renderers.ts +864 -195
  62. package/src/rule-list.ts +166 -46
  63. package/src/rules.ts +100 -104
  64. package/src/safety-rules.ts +191 -132
  65. package/src/scoring.ts +255 -52
  66. package/src/security-flow-rules.ts +930 -109
  67. package/src/selectors.ts +169 -0
  68. package/src/sensitive-data-rules.ts +502 -375
  69. package/src/sensitive-exclusions.ts +435 -0
  70. package/src/source-text.ts +380 -148
  71. package/src/static-analysis-redundant-rules.ts +298 -41
  72. package/src/test-block-rules.ts +422 -228
  73. package/src/text-scans.ts +67 -9
  74. package/src/types.ts +222 -71
  75. package/tsconfig.json +2 -1
  76. package/src/process-exec-metadata.ts +0 -153
  77. package/src/test-fixtures.ts +0 -668
@@ -1,20 +1,33 @@
1
- // Sensitive-data scanners and redaction helpers for secret-like raw text findings.
2
- import { ruleSeverity, threshold } from "./config.ts";
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 { Config, Finding } from "./types.ts";
7
+ import { byteColumn, byteLine } from "./text-scans.ts";
8
+ import type { Finding } from "./types.ts";
6
9
 
7
- // Just the display path - sensitive-data rules anchor findings on file path + line and never need
8
- // the absolute path. Keeping this trimmed keeps the contract narrow for testability.
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
- // Pillar entry point. The pattern array order is the deterministic emission order for findings,
14
- // which the fingerprint contract depends on - reordering would churn baselines without behaviour change.
15
- function analyseSensitiveData(file: SensitiveSourceFile, source: string, config: Config, findings: Finding[]): void {
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
- ["sensitive-data.aws-access-key", /AKIA[0-9A-Z]{16}/g, "AWS access key pattern detected."],
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
- const raw = match[0] ?? "";
33
- if (isExplicitExampleCredential(raw)) {
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(config, findings, file, ruleId, message, byteLine(source, match.index ?? 0), raw, "high");
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
- analyseHardcodedEnvironmentValues(file, source, config, findings);
41
- analyseNpmAuthTokens(file, source, config, findings);
42
- analyseHighEntropyStrings(file, source, config, findings);
43
- analysePhiLabelledIdentifiers(file, source, config, findings);
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
- // Explicit fake-credential evidence inside the MATCHED value itself: the canonical AWS doc keys
49
- // end in EXAMPLE, and redaction fixtures embed REDACTED/PLACEHOLDER/CHANGEME or masked runs.
50
- // A file path or test location alone never suppresses a production-shaped secret - the marker
51
- // must be part of the value the pattern matched.
52
- function isExplicitExampleCredential(raw: string): boolean {
53
- return /EXAMPLE|REDACTED|PLACEHOLDER|CHANGEME/i.test(raw) || /\*{4}|X{4}/.test(raw);
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
- // PHI beyond the MBI shape: medical-record-number assignments. Context-gated on an `MRN` / `medical
57
- // record` label so bare integers stay clean; stable contract is one redacted finding per label.
58
- function analysePhiLabelledIdentifiers(file: SensitiveSourceFile, source: string, config: Config, findings: Finding[]): void {
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(config, findings, file, "sensitive-data.phi-pattern", "Medical record number (PHI) detected.", index + 1, medicalRecordNumber, "high");
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
- // GCP service-account key files carry `"type": "service_account"` next to a private key. Flag the file
71
- // once, anchored on the type line; stable contract keeps raw key bodies covered by private-key.
72
- function analyseGcpServiceAccountKeys(file: SensitiveSourceFile, source: string, config: Config, findings: Finding[]): void {
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
- const identifier = source.match(/"private_key_id"\s*:\s*"([^"]+)"/)?.[1]
78
- ?? source.match(/"client_email"\s*:\s*"([^"]+)"/)?.[1]
79
- ?? "service_account";
80
- pushSensitiveFinding(config, findings, file, "sensitive-data.gcp-service-account-key", "GCP service-account key file detected.", byteLine(source, typeMatch.index ?? 0), identifier, "high");
81
- }
82
-
83
- /*
84
- * Payment-card PII detection contract: candidate shape, known issuer prefix, length, and Luhn
85
- * check must all pass before a stable redacted finding is emitted. A bare unseparated digit run
86
- * additionally needs card vocabulary on its line - large statistics can pass Luhn by coincidence,
87
- * while separator-grouped numbers are card-formatted by construction.
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, config: Config, findings: Finding[]): void {
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 rawCandidate = match[0] ?? "";
93
- const cardNumber = normalizedPaymentCardNumber(rawCandidate);
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
- if (!/[ -]/.test(rawCandidate) && !hasPaymentCardContext(lines[line - 1] ?? "")) {
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
- rawCandidate,
109
- "high",
110
- { piiKind: "credit-card", digits: cardNumber.length },
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
- // Card vocabulary gate for bare digit runs. Substring matching is deliberate so identifier forms
116
- // (`cardNumber`, `creditCard`, `PAYMENT_CARD`) count as context; `pan` stays word-bounded because
117
- // it is a common substring of unrelated words.
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
- // Stable redaction contract: parses `_authToken=` config lines even when values lack an npm_ prefix.
123
- function analyseNpmAuthTokens(file: SensitiveSourceFile, source: string, config: Config, findings: Finding[]): void {
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
- // Extracts the token portion from scoped or registry-prefixed npm auth config lines.
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
- // Targets `KEY=value` and `KEY: value` assignments where the key name signals secrets (API_KEY,
151
- // TOKEN, PASSWORD…). The `minLength` threshold keeps short fixture values like `PLACEHOLDER`
152
- // from churning the baseline - it is part of the rule's stable, deterministic contract.
153
- function analyseHardcodedEnvironmentValues(file: SensitiveSourceFile, source: string, config: Config, findings: Finding[]): void {
154
- const minLength = threshold(config, "sensitive-data.hardcoded-env-value", 16);
155
- const requiresQuotedValue = isScriptSourcePath(file.displayPath);
156
- const lines = source.split(/\r?\n/);
157
- for (const [index, line] of lines.entries()) {
158
- const envValue = hardcodedEnvValue(line, minLength, requiresQuotedValue);
159
- if (!envValue) {
160
- continue;
161
- }
162
- pushSensitiveFinding(
163
- config,
164
- findings,
165
- file,
166
- "sensitive-data.hardcoded-env-value",
167
- `Environment-style value \`${envValue.keyName}\` appears to be hardcoded with secret-like content.`,
168
- index + 1,
169
- envValue.value,
170
- "medium",
171
- { keyName: envValue.keyName, length: envValue.value.length, threshold: minLength },
172
- ruleSeverity(config, "sensitive-data.hardcoded-env-value", "error"),
173
- );
174
- }
175
- }
176
-
177
- // Shannon-entropy detector with three guardrails (length, case diversity, distinct characters)
178
- // because plain entropy alone fires on package-lock SRI hashes; the layered checks keep findings
179
- // stable across runs and prevent noisy regressions in node_modules-heavy projects.
180
- function analyseHighEntropyStrings(file: SensitiveSourceFile, source: string, config: Config, findings: Finding[]): void {
181
- const minLength = threshold(config, "sensitive-data.high-entropy-string", 32);
182
- for (const match of source.matchAll(/(["'`])([A-Za-z0-9_+=./-]{24,})\1/g)) {
183
- const raw = match[2] ?? "";
184
- if (!isHighEntropySecretCandidate(raw, minLength)) {
185
- continue;
186
- }
187
- pushSensitiveFinding(
188
- config,
189
- findings,
190
- file,
191
- "sensitive-data.high-entropy-string",
192
- "High-entropy string literal may be an embedded secret.",
193
- byteLine(source, match.index ?? 0),
194
- raw,
195
- "medium",
196
- { length: raw.length, detector: "high-entropy-string", threshold: minLength },
197
- ruleSeverity(config, "sensitive-data.high-entropy-string", "error"),
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
- function pushSensitiveFinding(
203
- config: Config,
204
- findings: Finding[],
205
- file: SensitiveSourceFile,
206
- ruleId: string,
207
- message: string,
208
- line: number,
209
- raw: string,
210
- confidence: Finding["confidence"],
211
- metadata: Record<string, unknown> = {},
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
- findings.push(
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: ${preview}.`,
222
- filePath: file.displayPath,
223
- line,
224
- severity,
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
- // Two-stage filter: parse the line into a (key, value) pair, then apply the secret-shape filters.
234
- // Splitting them keeps the regex simple - the line shape is shared, only the value test changes.
235
- // In script files only quoted values count: an unquoted `TOKEN: expr` line in TS/JS is an
236
- // expression (schema builder, secret-provider plumbing), not an embedded string literal.
237
- function hardcodedEnvValue(line: string, minLength: number, requiresQuotedValue: boolean): { keyName: string; value: string } | undefined {
238
- const candidate = envValueCandidate(line);
239
- if (!candidate || !isHardcodedEnvCandidate(candidate.value, minLength)) {
240
- return undefined;
241
- }
242
- if (requiresQuotedValue && !candidate.isQuoted) {
243
- return undefined;
244
- }
245
- return candidate;
246
- }
247
-
248
- // Script extensions where unquoted right-hand sides are code expressions rather than literal
249
- // values. Config formats (.env, .ini, .yaml, .json keys) keep their unquoted-literal semantics.
250
- function isScriptSourcePath(displayPath: string): boolean {
251
- return /\.(?:ts|tsx|mts|cts|js|jsx|mjs|cjs)$/i.test(displayPath);
252
- }
253
-
254
- // Matches the documented secret-key vocabulary (API_KEY, TOKEN, SECRET, PASSWORD, DATABASE_URL,
255
- // DSN, CREDENTIAL). Expanding this list will widen sensitive-data coverage - keep it intentional.
256
- function envValueCandidate(line: string): { keyName: string; value: string; isQuoted: boolean } | undefined {
257
- const match = line.match(/^\s*((?:API[_-]?KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|DATABASE_URL|DSN)|[A-Z][A-Z0-9_-]*(?:API[_-]?KEY|TOKEN|SECRET|PASSWORD|CREDENTIAL|DATABASE_URL|DSN)[A-Z0-9_-]*)\s*[:=]\s*(["'`]?)([^"'`\s#]+)["'`]?/i);
258
- const keyName = match?.[1] ?? "";
259
- const openingQuote = match?.[2] ?? "";
260
- const secretValue = match?.[3] ?? "";
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
- // Cheap shape filter: rejects all-letters words and all-digit numbers before the more expensive
280
- // entropy work runs. False negatives here are acceptable; false positives waste maintainer time.
281
- function hasLetterAndDigit(candidateText: string): boolean {
282
- return /[A-Za-z]/.test(candidateText) && /[0-9]/.test(candidateText);
283
- }
284
-
285
- // Layered filter for the entropy detector. Order matters: cheap rejections (length, hex digest,
286
- // SRI hash) run before character-set checks before the entropy calculation itself, which is the
287
- // most expensive step. Reordering changes nothing semantically but can regress scan performance.
288
- function isHighEntropySecretCandidate(candidateText: string, minLength: number): boolean {
289
- if (isExcludedHighEntropyCandidate(candidateText, minLength)) {
290
- return false;
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 false;
477
+ return `[redacted:connection-string:${acceptedScheme}]`;
332
478
  }
333
479
 
334
- // Word-segment identifier exemption: a dotted namespace ("Com.Example2.Services.TokenProvider"),
335
- // an underscored constant ("WC_Admin_Reports_V2"), or a slug-like catalog name
336
- // ("DeepSeek-R1-Distill-Qwen-32B") decomposes entirely into short dictionary-like segments.
337
- // Real credentials do not - their segments interleave case and digits or run past word length.
338
- // The token guard runs FIRST so a JWT or segmented token never earns the exemption.
339
- function isWordSegmentIdentifier(candidateText: string): boolean {
340
- if (candidateText.includes("+") || candidateText.includes("=")) {
341
- return false;
342
- }
343
- if (isTokenLikeSegmentedSecret(candidateText)) {
344
- return false;
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
- const segments = candidateText.split(/[/._-]+/);
347
- if (segments.length < 2) {
348
- return false;
493
+ if (/^(?:ghp_|github_pat_|gh[ousr]_)/.test(matchedToken)) {
494
+ return "[redacted:github-token]";
349
495
  }
350
- return segments.every(isWordLikeSegment);
351
- }
352
-
353
- // Token guard for the word-segment exemption. JWTs always start with "eyJ" (base64 of `{"`), and
354
- // any single segment that is a 20+ char mixed-case-with-digit run is credential material even when
355
- // its separators mimic an identifier. Must stay ahead of the word-segment arms - relaxing it would
356
- // silently exempt JWT-shaped and long base64url secrets.
357
- function isTokenLikeSegmentedSecret(candidateText: string): boolean {
358
- if (candidateText.startsWith("eyJ")) {
359
- return true;
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
- return candidateText.split(/[/._-]+/).some((segment) => segment.length >= 20 && hasLowerUpperAndDigit(segment));
362
- }
363
-
364
- // One identifier segment: letters with digits at most at one boundary ("Example2", "405B",
365
- // "20241022"), capped at 16 chars. More than one letter<->digit transition means the segment
366
- // interleaves like token material and must not earn the exemption.
367
- function isWordLikeSegment(segment: string): boolean {
368
- if (segment.length === 0 || segment.length > 16 || !/^[A-Za-z0-9]+$/.test(segment)) {
369
- return false;
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
- return letterDigitTransitionCount(segment) <= 1;
372
- }
373
-
374
- // Counts boundaries where the segment switches between letter and digit runs; word-like segments
375
- // have at most one ("Example2"), token material alternates repeatedly ("Xk9pQ2vL").
376
- function letterDigitTransitionCount(segment: string): number {
377
- let transitions = 0;
378
- for (let index = 1; index < segment.length; index += 1) {
379
- if (isDigitCharCode(segment.charCodeAt(index - 1)) !== isDigitCharCode(segment.charCodeAt(index))) {
380
- transitions += 1;
381
- }
504
+ if (matchedToken.startsWith("AIza")) {
505
+ return "[redacted:google-api-key]";
382
506
  }
383
- return transitions;
384
- }
385
-
386
- // Character-code digit test so the transition counter never needs unchecked string indexing.
387
- function isDigitCharCode(code: number): boolean {
388
- return code >= 48 && code <= 57;
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 (!normalized.includes("/")) {
402
- return isRepoPathLikeFilename(normalized);
510
+ if (matchedToken.startsWith("glpat-")) {
511
+ return "[redacted:gitlab-token]";
403
512
  }
404
- return hasKnownRepoPathSegment(normalized);
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
- // Removes separators allowed in human-entered payment-card numbers before issuer and checksum checks.
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
- // Stable contract: only card-network-shaped values with a valid Luhn checksum are PII findings.
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
- // Recognises common issuer prefixes by delegating per network because each one has different
430
- // length and IIN-range rules; keeping those branches separate makes false-positive tuning safer.
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
- // Visa cards start with 4 and commonly use 13, 16, or 19 digits.
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
- // Mastercard cards use 51-55 and 2221-2720 IIN ranges with 16 digits.
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
- // American Express cards use 34/37 prefixes with 15 digits.
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
- // Discover cards use 6011, 65, or 644-649 prefixes with 16 or 19 digits.
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
- // Diners Club cards use 300-305, 36, 38, or 39 prefixes with 14 digits.
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
- // JCB cards use 3528-3589 prefixes with 16-19 digits.
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
- // Network-specific length guard kept separate so the prefix table reads as data, not arithmetic.
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
- // Inclusive numeric range helper for issuer identification number ranges.
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
- // Standard Luhn checksum over normalized digits; invalid checksum keeps long numeric identifiers quiet.
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
- // Doubles every second digit from the right and folds two-digit products per the Luhn algorithm.
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 };