@envseal/detector 0.1.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/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined in Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity exercising
24
+ permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or Object
36
+ form, made available under the License, as indicated by a copyright
37
+ notice that is included in or attached to the work (an example is
38
+ provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original Work and any Derivative Works thereof, that is
50
+ intentionally submitted to, or received by, Licensor for inclusion
51
+ in the Work by the copyright owner or by an individual or Legal
52
+ Entity authorized to submit on behalf of the copyright owner. For
53
+ the purposes of this definition, "submitted" means any form of
54
+ electronic, verbal, or written communication sent to the Licensor
55
+ or its representatives, including but not limited to communication
56
+ on electronic mailing lists, source code control systems, and issue
57
+ tracking systems that are managed by, or on behalf of, the Licensor
58
+ for the purpose of discussing and improving the Work, but excluding
59
+ communication that is conspicuously marked or otherwise designated
60
+ in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any Legal Entity on behalf of
63
+ which a Contribution has been received by Licensor and subsequently
64
+ incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file, then any
107
+ Derivative Works that You distribute must include a readable
108
+ copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE from the Work, provided that
120
+ such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions of this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contribution.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in appropriate
184
+ comment syntax for the file type. We also recommend that you
185
+ include a file or class name and date of last modification in
186
+ the header comment to make it easier to identify the original
187
+ author and when the file was changed.
188
+
189
+ Copyright 2026 The envseal authors
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,3 @@
1
+ export declare function shannonEntropy(s: string): number;
2
+ export declare function charsetClasses(s: string): number;
3
+ //# sourceMappingURL=entropy.d.ts.map
@@ -0,0 +1,33 @@
1
+ export function shannonEntropy(s) {
2
+ if (s.length === 0) {
3
+ return 0;
4
+ }
5
+ const freq = new Map();
6
+ for (const ch of s) {
7
+ freq.set(ch, (freq.get(ch) ?? 0) + 1);
8
+ }
9
+ let entropy = 0;
10
+ const len = s.length;
11
+ for (const count of freq.values()) {
12
+ const p = count / len;
13
+ entropy -= p * Math.log2(p);
14
+ }
15
+ return entropy;
16
+ }
17
+ const LOWERCASE_RE = /[a-z]/;
18
+ const UPPERCASE_RE = /[A-Z]/;
19
+ const DIGIT_RE = /[0-9]/;
20
+ const SYMBOL_RE = /[^a-zA-Z0-9]/;
21
+ export function charsetClasses(s) {
22
+ let classes = 0;
23
+ if (LOWERCASE_RE.test(s))
24
+ classes += 1;
25
+ if (UPPERCASE_RE.test(s))
26
+ classes += 1;
27
+ if (DIGIT_RE.test(s))
28
+ classes += 1;
29
+ if (SYMBOL_RE.test(s))
30
+ classes += 1;
31
+ return classes;
32
+ }
33
+ //# sourceMappingURL=entropy.js.map
@@ -0,0 +1,7 @@
1
+ export interface ExclusionContext {
2
+ before: string;
3
+ after: string;
4
+ }
5
+ export declare function exclusionReason(candidate: string, context: ExclusionContext): string | null;
6
+ export declare function isExcluded(candidate: string, context: ExclusionContext): boolean;
7
+ //# sourceMappingURL=exclusions.d.ts.map
@@ -0,0 +1,196 @@
1
+ import { WORDLIST_LOWER } from './wordlist.js';
2
+ const WORDLIST_SET = new Set(WORDLIST_LOWER.trim().split('\n'));
3
+ export function exclusionReason(candidate, context) {
4
+ if (isNonSecretAssignment(candidate))
5
+ return 'env-assignment-short-value';
6
+ if (isGitSha(candidate))
7
+ return 'git-sha';
8
+ if (isUUID(candidate))
9
+ return 'uuid';
10
+ if (isDigest(candidate, context))
11
+ return 'digest';
12
+ if (isDataUri(candidate, context))
13
+ return 'data-uri';
14
+ if (isFilesystemPath(candidate))
15
+ return 'filesystem-path';
16
+ if (isPlainUrl(candidate))
17
+ return 'plain-url';
18
+ if (isHexColour(candidate))
19
+ return 'hex-colour';
20
+ if (isIsoTimestamp(candidate))
21
+ return 'iso-timestamp';
22
+ if (isSemver(candidate))
23
+ return 'semver';
24
+ if (isRepeatedChar(candidate))
25
+ return 'repeated-char';
26
+ if (isDictionaryText(candidate))
27
+ return 'dictionary-text';
28
+ if (isCodeAdjacent(candidate, context))
29
+ return 'code-adjacent';
30
+ if (isNumeric(candidate))
31
+ return 'numeric';
32
+ if (isPredictableSequence(candidate))
33
+ return 'predictable-sequence';
34
+ if (hasCodeKeyword(candidate))
35
+ return 'code-keyword';
36
+ if (isNonLatinProse(candidate))
37
+ return 'non-latin-prose';
38
+ return null;
39
+ }
40
+ export function isExcluded(candidate, context) {
41
+ return exclusionReason(candidate, context) !== null;
42
+ }
43
+ /**
44
+ * `SCREAMING_SNAKE=value` where the value is too short to be a credential.
45
+ *
46
+ * Text around this product is dense with env-var assignments (`NODE_ENV=production`,
47
+ * `REACT_APP_FEATURE_FLAG_ENABLED=true`), and the whole `KEY=value` token is often
48
+ * long and mixed-case enough to clear the entropy bar on the strength of the key
49
+ * name alone. What matters is the value: anything shorter than the generic-candidate
50
+ * threshold cannot be a credential we would have detected on its own merits, so the
51
+ * assignment as a whole is not evidence of one.
52
+ *
53
+ * This deliberately does NOT suppress `OPENAI_API_KEY=sk-...`: real keys exceed the
54
+ * threshold, and prefixed ones are caught earlier by a high-confidence pattern that
55
+ * never consults the exclusion list.
56
+ */
57
+ const MIN_GENERIC_LENGTH = 24;
58
+ function isNonSecretAssignment(candidate) {
59
+ const match = /^[A-Z][A-Z0-9_]{2,}=(.*)$/.exec(candidate);
60
+ if (match === null)
61
+ return false;
62
+ const value = match[1];
63
+ if (value === undefined)
64
+ return false;
65
+ return value.length < MIN_GENERIC_LENGTH;
66
+ }
67
+ function isGitSha(candidate) {
68
+ const len = candidate.length;
69
+ const isLowerHex = /^[0-9a-f]+$/.test(candidate);
70
+ return isLowerHex && (len === 40 || len === 64 || (len >= 7 && len <= 12));
71
+ }
72
+ function isUUID(candidate) {
73
+ const uuidPattern = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
74
+ return uuidPattern.test(candidate);
75
+ }
76
+ function isDigest(candidate, context) {
77
+ if (candidate.startsWith('sha256:') || candidate.startsWith('sha256-') ||
78
+ candidate.startsWith('sha512-') || candidate.startsWith('sha1-') ||
79
+ candidate.startsWith('md5-')) {
80
+ return true;
81
+ }
82
+ if (context.before.endsWith('integrity=') || context.before.endsWith('integrity="')) {
83
+ return /^[A-Za-z0-9+/=]+$/.test(candidate);
84
+ }
85
+ return false;
86
+ }
87
+ function isDataUri(candidate, context) {
88
+ if (candidate.startsWith('data:'))
89
+ return true;
90
+ return /data:[^/]*\/[^;]*;base64,$/.test(context.before);
91
+ }
92
+ function isFilesystemPath(candidate) {
93
+ const hasPathSep = candidate.includes('/') || candidate.includes(String.fromCharCode(92));
94
+ if (!hasPathSep)
95
+ return false;
96
+ const hasCredential = /[a-z][a-z0-9+.-]*:\/\/[^@]*:.*@/.test(candidate);
97
+ return !hasCredential;
98
+ }
99
+ function isPlainUrl(candidate) {
100
+ try {
101
+ const url = new URL(candidate);
102
+ return (url.protocol === 'http:' || url.protocol === 'https:') &&
103
+ url.username === '' && url.password === '';
104
+ }
105
+ catch {
106
+ return false;
107
+ }
108
+ }
109
+ function isHexColour(candidate) {
110
+ return /^#[0-9a-fA-F]{3}(?:[0-9a-fA-F]{3})?$/.test(candidate) ||
111
+ /^#[0-9a-fA-F]{6}(?:[0-9a-fA-F]{2})?$/.test(candidate);
112
+ }
113
+ function isIsoTimestamp(candidate) {
114
+ const isoPattern = /^\d{4}-\d{2}-\d{2}(?:T\d{2}:\d{2}:\d{2}(?:\.\d{3})?(?:Z|[+-]\d{2}:\d{2})?)?$/;
115
+ return isoPattern.test(candidate);
116
+ }
117
+ function isSemver(candidate) {
118
+ const semverPattern = /^(?:\^|~|>=|<=|>|<)?(?:\d+)(?:\.\d+)?(?:\.\d+)?(?:-[a-zA-Z0-9.-]+)?(?:\+[a-zA-Z0-9.-]+)?$/;
119
+ return semverPattern.test(candidate);
120
+ }
121
+ function isRepeatedChar(candidate) {
122
+ return /^(.)\1+$/.test(candidate);
123
+ }
124
+ function isDictionaryText(candidate) {
125
+ const segments = splitOnBoundaries(candidate);
126
+ const longSegments = segments.map((s) => s.toLowerCase()).filter((s) => s.length >= 3);
127
+ if (longSegments.length < 2)
128
+ return false;
129
+ const inWordlist = longSegments.filter((s) => WORDLIST_SET.has(s)).length;
130
+ return inWordlist / longSegments.length >= 0.3;
131
+ }
132
+ function splitOnBoundaries(candidate) {
133
+ let result = candidate.split(/[^a-zA-Z]/);
134
+ result = result.flatMap((segment) => {
135
+ if (segment.length === 0)
136
+ return [];
137
+ const withBoundaries = segment.replace(/([a-z])([A-Z])/g, '$1|$2');
138
+ return withBoundaries.split('|');
139
+ });
140
+ return result.filter((s) => s.length > 0);
141
+ }
142
+ function isCodeAdjacent(candidate, context) {
143
+ const codeChars = /[{}();,:]/;
144
+ if (context.before.length > 0) {
145
+ const lastChar = context.before.at(-1);
146
+ if (lastChar !== undefined && codeChars.test(lastChar) && !/\s/.test(lastChar))
147
+ return true;
148
+ }
149
+ if (context.after.length > 0) {
150
+ const firstChar = context.after.at(0);
151
+ if (firstChar !== undefined && codeChars.test(firstChar) && !/\s/.test(firstChar))
152
+ return true;
153
+ }
154
+ return false;
155
+ }
156
+ function isNumeric(candidate) {
157
+ return /^\d+$/.test(candidate);
158
+ }
159
+ function isNonLatinProse(candidate) {
160
+ let nonAsciiCount = 0;
161
+ let hasAsciiDigit = false;
162
+ for (let i = 0; i < candidate.length; i++) {
163
+ const charCode = candidate.charCodeAt(i);
164
+ if (charCode > 127)
165
+ nonAsciiCount++;
166
+ if (charCode >= 48 && charCode <= 57)
167
+ hasAsciiDigit = true;
168
+ }
169
+ const nonAsciiRatio = nonAsciiCount / candidate.length;
170
+ return nonAsciiRatio >= 0.5 && !hasAsciiDigit;
171
+ }
172
+ function isPredictableSequence(candidate) {
173
+ if (/^a+b+c+d+e+f+g+h+i+j+k+l+m+n+o+p+q+r+s+t+u+v+w+x+y+z+/.test(candidate)) {
174
+ return true;
175
+ }
176
+ if (/^A+B+C+D+E+F+G+H+I+J+K+L+M+N+O+P+Q+R+S+T+U+V+W+X+Y+Z+/.test(candidate)) {
177
+ return true;
178
+ }
179
+ if (/abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ/.test(candidate)) {
180
+ return true;
181
+ }
182
+ return false;
183
+ }
184
+ function hasCodeKeyword(candidate) {
185
+ const keywords = [
186
+ 'interface', 'type', 'class', 'function', 'const', 'let', 'var',
187
+ 'extends', 'implements', 'readonly', 'record', 'string', 'number',
188
+ 'boolean', 'async', 'await', 'return', 'import', 'export',
189
+ 'docker', 'compose', 'kubernetes', 'kubectl', 'production',
190
+ 'development', 'staging', 'environment', 'authentication', 'provider',
191
+ 'configuration', 'serialized', 'transaction', 'payload', 'metadata',
192
+ ];
193
+ const lower = candidate.toLowerCase();
194
+ return keywords.some(kw => lower.includes(kw));
195
+ }
196
+ //# sourceMappingURL=exclusions.js.map
@@ -0,0 +1,17 @@
1
+ export interface Detection {
2
+ start: number;
3
+ end: number;
4
+ patternId: string;
5
+ providerId?: string;
6
+ confidence: 'high' | 'medium';
7
+ label: string;
8
+ }
9
+ export declare function detect(text: string): Detection[];
10
+ export declare function redactDetections(text: string, detections: Detection[]): string;
11
+ export declare function hasSecret(text: string): boolean;
12
+ export { shannonEntropy, charsetClasses } from './entropy.js';
13
+ export { allPatterns } from './patterns.js';
14
+ export { isExcluded, exclusionReason } from './exclusions.js';
15
+ export type { SecretPattern } from './patterns.js';
16
+ export type { ExclusionContext } from './exclusions.js';
17
+ //# sourceMappingURL=index.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,119 @@
1
+ import { allPatterns } from './patterns.js';
2
+ import { shannonEntropy, charsetClasses } from './entropy.js';
3
+ import { isExcluded } from './exclusions.js';
4
+ /** Minimum token length before the generic entropy heuristic will consider it. */
5
+ const MIN_GENERIC_LENGTH = 24;
6
+ const MIN_ENTROPY = 3.5;
7
+ const MIN_CHARSET_CLASSES = 2;
8
+ /**
9
+ * Characters that terminate a candidate token. Deliberately does not include
10
+ * `-`, `_`, `.`, `+`, `/` or `=` — those appear inside real credentials
11
+ * (base64, JWTs, connection strings) and splitting on them would shred a key
12
+ * into fragments that individually fall under the length threshold.
13
+ */
14
+ const TOKEN_SPLIT_RE = /[\s"'`<>()[\]{},;|\\]+/;
15
+ function scanPatterns(text) {
16
+ const out = [];
17
+ for (const pattern of allPatterns()) {
18
+ // allPatterns() hands back fresh RegExp objects, so lastIndex starts at 0.
19
+ let match;
20
+ while ((match = pattern.regex.exec(text)) !== null) {
21
+ const detection = {
22
+ start: match.index,
23
+ end: match.index + match[0].length,
24
+ patternId: pattern.id,
25
+ confidence: pattern.confidence,
26
+ label: pattern.label,
27
+ };
28
+ if (pattern.providerId !== undefined)
29
+ detection.providerId = pattern.providerId;
30
+ out.push(detection);
31
+ // Zero-length matches would spin forever.
32
+ if (match[0].length === 0)
33
+ pattern.regex.lastIndex += 1;
34
+ }
35
+ }
36
+ return out;
37
+ }
38
+ function scanGeneric(text, covered) {
39
+ const out = [];
40
+ let cursor = 0;
41
+ for (const raw of text.split(TOKEN_SPLIT_RE)) {
42
+ const start = text.indexOf(raw, cursor);
43
+ if (start < 0 || raw.length === 0) {
44
+ cursor += raw.length;
45
+ continue;
46
+ }
47
+ const end = start + raw.length;
48
+ cursor = end;
49
+ if (raw.length < MIN_GENERIC_LENGTH)
50
+ continue;
51
+ // Skip anything a high-confidence pattern already claimed; re-reporting it
52
+ // as a generic hit would only downgrade a precise label.
53
+ if (covered.some((d) => start < d.end && end > d.start))
54
+ continue;
55
+ if (shannonEntropy(raw) < MIN_ENTROPY)
56
+ continue;
57
+ if (charsetClasses(raw) < MIN_CHARSET_CLASSES)
58
+ continue;
59
+ if (isExcluded(raw, { before: text.slice(0, start), after: text.slice(end) }))
60
+ continue;
61
+ out.push({
62
+ start,
63
+ end,
64
+ patternId: 'generic:high-entropy',
65
+ confidence: 'medium',
66
+ label: 'high-entropy string',
67
+ });
68
+ }
69
+ return out;
70
+ }
71
+ /**
72
+ * Merge overlapping detections, preferring high confidence, then the longer
73
+ * span. Returns a sorted, non-overlapping list.
74
+ */
75
+ function merge(detections) {
76
+ const rank = (d) => (d.confidence === 'high' ? 1 : 0);
77
+ const sorted = [...detections].sort((a, b) => {
78
+ if (a.start !== b.start)
79
+ return a.start - b.start;
80
+ if (rank(a) !== rank(b))
81
+ return rank(b) - rank(a);
82
+ return b.end - b.start - (a.end - a.start);
83
+ });
84
+ const out = [];
85
+ for (const d of sorted) {
86
+ const last = out[out.length - 1];
87
+ if (last === undefined || d.start >= last.end) {
88
+ out.push(d);
89
+ continue;
90
+ }
91
+ // Overlap: keep whichever wins on confidence, then on span length.
92
+ const better = rank(d) > rank(last) || (rank(d) === rank(last) && d.end - d.start > last.end - last.start);
93
+ if (better)
94
+ out[out.length - 1] = d;
95
+ }
96
+ return out;
97
+ }
98
+ export function detect(text) {
99
+ const high = scanPatterns(text);
100
+ const generic = scanGeneric(text, high);
101
+ return merge([...high, ...generic]);
102
+ }
103
+ export function redactDetections(text, detections) {
104
+ // Walk backwards so earlier offsets stay valid as we splice.
105
+ const ordered = [...detections].sort((a, b) => b.start - a.start);
106
+ let out = text;
107
+ for (const d of ordered) {
108
+ const token = d.confidence === 'high' ? `«redacted:${d.label}»` : '«redacted-secret»';
109
+ out = out.slice(0, d.start) + token + out.slice(d.end);
110
+ }
111
+ return out;
112
+ }
113
+ export function hasSecret(text) {
114
+ return detect(text).length > 0;
115
+ }
116
+ export { shannonEntropy, charsetClasses } from './entropy.js';
117
+ export { allPatterns } from './patterns.js';
118
+ export { isExcluded, exclusionReason } from './exclusions.js';
119
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,9 @@
1
+ export interface SecretPattern {
2
+ id: string;
3
+ regex: RegExp;
4
+ providerId?: string;
5
+ confidence: 'high' | 'medium';
6
+ label: string;
7
+ }
8
+ export declare function allPatterns(): SecretPattern[];
9
+ //# sourceMappingURL=patterns.d.ts.map
@@ -0,0 +1,72 @@
1
+ import { allPrefixPatterns } from '@envseal/registry';
2
+ function escapeRegExp(s) {
3
+ return s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
4
+ }
5
+ const SW = '[A-Za-z0-9_\\-]';
6
+ const HAND_PATTERNS = [
7
+ { id: 'openai-project-key', label: 'OpenAI project API key', providerId: 'openai', source: `sk-proj-${SW}{20,}` },
8
+ { id: 'anthropic-api03', label: 'Anthropic API key', providerId: 'anthropic', source: `sk-ant-api03-${SW}{20,}` },
9
+ { id: 'github-pat', label: 'GitHub personal access token', providerId: 'github', source: `ghp_${SW}{30,}` },
10
+ { id: 'github-oauth', label: 'GitHub OAuth access token', providerId: 'github', source: `gho_${SW}{30,}` },
11
+ { id: 'github-user', label: 'GitHub user-to-server token', providerId: 'github', source: `ghu_${SW}{30,}` },
12
+ { id: 'github-app', label: 'GitHub server-to-server token', providerId: 'github', source: `ghs_${SW}{30,}` },
13
+ { id: 'github-fine-grained', label: 'GitHub fine-grained token', providerId: 'github', source: `github_pat_[A-Za-z0-9_]{40,}` },
14
+ { id: 'gitlab-pat', label: 'GitLab personal access token', providerId: 'gitlab', source: `glpat-${SW}{16,}` },
15
+ { id: 'aws-access-key', label: 'AWS access key ID', providerId: 'aws', source: `AKIA[0-9A-Z]{16}` },
16
+ { id: 'aws-qualified', label: 'AWS access key', providerId: 'aws', source: `(?:AWS_ACCESS_KEY_ID|AWS_SECRET_ACCESS_KEY)=${SW}{16,}` },
17
+ { id: 'sendgrid', label: 'SendGrid API key', providerId: 'sendgrid', source: `SG\\.[A-Za-z0-9_\\-]{20,}\\.[A-Za-z0-9_\\-]{20,}` },
18
+ { id: 'stripe-secret', label: 'Stripe secret key', providerId: 'stripe', source: `sk_live_${SW}{24,}` },
19
+ { id: 'stripe-publishable', label: 'Stripe publishable key', providerId: 'stripe', source: `pk_live_${SW}{24,}` },
20
+ { id: 'stripe-restricted', label: 'Stripe restricted key', providerId: 'stripe', source: `rk_live_${SW}{24,}` },
21
+ { id: 'google-api-key', label: 'Google API key', providerId: 'gcp', source: `AIza[0-9A-Za-z_\\-]{35}` },
22
+ { id: 'slack-bot', label: 'Slack bot token', providerId: 'slack', source: `xoxb-${SW}{20,}` },
23
+ { id: 'slack-user', label: 'Slack user token', providerId: 'slack', source: `xoxp-${SW}{20,}` },
24
+ { id: 'slack-app', label: 'Slack app-level token', providerId: 'slack', source: `xoxa-${SW}{16,}` },
25
+ { id: 'slack-app-env', label: 'Slack app env token', providerId: 'slack', source: `xapp-${SW}{24,}` },
26
+ { id: 'digitalocean', label: 'DigitalOcean API token', providerId: 'digitalocean', source: `dop_v1_[A-Za-z0-9_]{32,}` },
27
+ { id: 'shopify', label: 'Shopify access token', providerId: 'shopify', source: `shpat_[A-Za-z0-9_]{24,}` },
28
+ { id: 'npm', label: 'npm access token', providerId: 'npm', source: `npm_${SW}{16,}` },
29
+ { id: 'huggingface', label: 'Hugging Face token', providerId: 'huggingface', source: `hf_[A-Za-z0-9_]{16,}` },
30
+ { id: 'groq', label: 'Groq API key', providerId: 'groq', source: `gsk_[A-Za-z0-9_]{24,}` },
31
+ { id: 'openrouter-v1', label: 'OpenRouter v1 key', providerId: 'openrouter', source: `sk-or-v1-${SW}{32,}` },
32
+ { id: 'resend', label: 'Resend API key', providerId: 'resend', source: `re_[A-Za-z0-9]{8}_[A-Za-z0-9]{16,}` },
33
+ { id: 'private-key', label: 'Private key', source: `-----BEGIN (?:RSA |EC |DSA |OPENSSH |PGP )?PRIVATE KEY-----` },
34
+ { id: 'jwt', label: 'JWT token', source: `eyJ[A-Za-z0-9_\\-]+\\.[A-Za-z0-9_\\-]+\\.[A-Za-z0-9_\\-]+` },
35
+ { id: 'conn-string', label: 'database connection string', source: `(?:postgres|postgresql|mysql|mongodb(?:\\+srv)?|redis|amqp)://[^:\\s/]+:[^@\\s]+@` },
36
+ ];
37
+ export function allPatterns() {
38
+ const patterns = [];
39
+ for (const entry of allPrefixPatterns()) {
40
+ if (entry.prefix === undefined) {
41
+ continue;
42
+ }
43
+ // Two guards, both load-bearing for registry-derived patterns, which are
44
+ // synthesised from a bare prefix and so are far weaker than the hand-written
45
+ // ones:
46
+ //
47
+ // 1. A leading boundary. Without it a short prefix matches mid-identifier —
48
+ // Twilio's `AC` matched inside `REACT_APP_FEATURE_FLAG_ENABLED`, turning
49
+ // an ordinary env-var name into a "high confidence" credential hit.
50
+ // 2. An alphanumeric-only body. Real key material is random alphanumerics;
51
+ // SCREAMING_SNAKE identifiers are not. Excluding `_` and `-` from the body
52
+ // stops the pattern from running through word separators.
53
+ patterns.push({
54
+ id: `registry:${entry.providerId}:${entry.envVar}`,
55
+ regex: new RegExp(`(?<![A-Za-z0-9_-])${escapeRegExp(entry.prefix)}[A-Za-z0-9]{16,}`, 'g'),
56
+ providerId: entry.providerId,
57
+ confidence: 'high',
58
+ label: `${entry.providerId} ${entry.envVar}`,
59
+ });
60
+ }
61
+ for (const hp of HAND_PATTERNS) {
62
+ patterns.push({
63
+ id: hp.id,
64
+ regex: new RegExp(hp.source, 'g'),
65
+ providerId: hp.providerId,
66
+ confidence: 'high',
67
+ label: hp.label,
68
+ });
69
+ }
70
+ return patterns;
71
+ }
72
+ //# sourceMappingURL=patterns.js.map