@appystore/secret-shield 0.0.0-stage → 0.1.3

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/dist/index.cjs ADDED
@@ -0,0 +1,2353 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __export = (target, all) => {
9
+ for (var name in all)
10
+ __defProp(target, name, { get: all[name], enumerable: true });
11
+ };
12
+ var __copyProps = (to, from, except, desc) => {
13
+ if (from && typeof from === "object" || typeof from === "function") {
14
+ for (let key of __getOwnPropNames(from))
15
+ if (!__hasOwnProp.call(to, key) && key !== except)
16
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
17
+ }
18
+ return to;
19
+ };
20
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
21
+ // If the importer is in node compatibility mode or this is not an ESM
22
+ // file that has been converted to a CommonJS file using a Babel-
23
+ // compatible transform (i.e. "__esModule" has not been set), then set
24
+ // "default" to the CommonJS "module.exports" for node compatibility.
25
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
26
+ mod
27
+ ));
28
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
29
+
30
+ // src/index.ts
31
+ var index_exports = {};
32
+ __export(index_exports, {
33
+ DEFAULT_IGNORE_PATTERNS: () => DEFAULT_IGNORE_PATTERNS,
34
+ IGNORE_FILE_NAME: () => IGNORE_FILE_NAME,
35
+ SECRET_CATEGORIES: () => SECRET_CATEGORIES,
36
+ SEVERITIES: () => SEVERITIES,
37
+ SecretShield: () => SecretShield,
38
+ SecretShieldError: () => SecretShieldError,
39
+ VERSION: () => VERSION,
40
+ detectLanguage: () => detectLanguage,
41
+ shannonEntropy: () => shannonEntropy
42
+ });
43
+ module.exports = __toCommonJS(index_exports);
44
+
45
+ // src/engine.ts
46
+ var import_node_crypto = require("crypto");
47
+ var import_node_path2 = __toESM(require("path"), 1);
48
+
49
+ // src/analyzer/positions.ts
50
+ var LineIndex = class {
51
+ lineStarts = [0];
52
+ constructor(text) {
53
+ for (let i = 0; i < text.length; i++) {
54
+ if (text.charCodeAt(i) === 10) this.lineStarts.push(i + 1);
55
+ }
56
+ }
57
+ position(offset) {
58
+ let low = 0;
59
+ let high = this.lineStarts.length - 1;
60
+ while (low < high) {
61
+ const mid = low + high + 1 >> 1;
62
+ if ((this.lineStarts[mid] ?? 0) <= offset) low = mid;
63
+ else high = mid - 1;
64
+ }
65
+ return { line: low + 1, column: offset - (this.lineStarts[low] ?? 0) + 1 };
66
+ }
67
+ };
68
+
69
+ // src/detector/detect.ts
70
+ var MIN_PROPAGATION_LENGTH = 8;
71
+ function runRule(rule, input, context) {
72
+ if (rule.scan) return rule.scan(input, context);
73
+ if (!rule.pattern) return [];
74
+ const candidates = [];
75
+ const pattern = new RegExp(rule.pattern.source, rule.pattern.flags);
76
+ let match;
77
+ while ((match = pattern.exec(input)) !== null) {
78
+ if (match[0].length === 0) {
79
+ pattern.lastIndex++;
80
+ continue;
81
+ }
82
+ if (rule.extract) {
83
+ candidates.push(...rule.extract(match, context));
84
+ } else {
85
+ candidates.push({
86
+ start: match.index,
87
+ end: match.index + match[0].length,
88
+ ruleId: rule.id,
89
+ category: rule.category,
90
+ severity: rule.severity,
91
+ confidence: rule.baseConfidence,
92
+ maskPolicy: rule.maskPolicy,
93
+ ...rule.placeholder !== void 0 ? { placeholder: rule.placeholder } : {},
94
+ propagate: true
95
+ });
96
+ }
97
+ }
98
+ return candidates;
99
+ }
100
+ function overlaps(a, b) {
101
+ return a.start < b.end && b.start < a.end;
102
+ }
103
+ var IntervalSet = class {
104
+ items = [];
105
+ get all() {
106
+ return this.items;
107
+ }
108
+ insertionIndex(start) {
109
+ let low = 0;
110
+ let high = this.items.length;
111
+ while (low < high) {
112
+ const mid = low + high >> 1;
113
+ if ((this.items[mid]?.start ?? 0) < start) low = mid + 1;
114
+ else high = mid;
115
+ }
116
+ return low;
117
+ }
118
+ /** Adds the candidate when it overlaps nothing. Returns true when added. */
119
+ tryAdd(candidate) {
120
+ const index = this.insertionIndex(candidate.start);
121
+ const before = this.items[index - 1];
122
+ const after = this.items[index];
123
+ if (before && overlaps(before, candidate) || after && overlaps(after, candidate)) {
124
+ return false;
125
+ }
126
+ this.items.splice(index, 0, candidate);
127
+ return true;
128
+ }
129
+ };
130
+ function detect(input, rules, options) {
131
+ const lowered = input.toLowerCase();
132
+ const raw = [...options.extra ?? []];
133
+ for (const rule of rules) {
134
+ if (rule.keywords && !rule.keywords.some((k) => lowered.includes(k))) continue;
135
+ raw.push(...runRule(rule, input, options));
136
+ }
137
+ const eligible = raw.filter((c) => c.confidence >= options.minConfidence && c.end > c.start).sort(
138
+ (a, b) => b.confidence - a.confidence || b.end - b.start - (a.end - a.start) || a.start - b.start
139
+ );
140
+ const accepted = new IntervalSet();
141
+ for (const candidate of eligible) accepted.tryAdd(candidate);
142
+ const seen = /* @__PURE__ */ new Set();
143
+ for (const candidate of [...accepted.all]) {
144
+ if (!candidate.propagate || candidate.end - candidate.start < MIN_PROPAGATION_LENGTH) continue;
145
+ const value = input.slice(candidate.start, candidate.end);
146
+ if (seen.has(value)) continue;
147
+ seen.add(value);
148
+ let from = 0;
149
+ let index;
150
+ while ((index = input.indexOf(value, from)) !== -1) {
151
+ accepted.tryAdd({ ...candidate, start: index, end: index + value.length });
152
+ from = index + 1;
153
+ }
154
+ }
155
+ const result = [...accepted.all];
156
+ if (options.yamlPlainStarts && options.yamlPlainStarts.size > 0) {
157
+ for (const candidate of result) {
158
+ if (options.yamlPlainStarts.has(candidate.start)) candidate.yamlPlain = true;
159
+ }
160
+ }
161
+ return result;
162
+ }
163
+
164
+ // src/errors.ts
165
+ var MESSAGES = {
166
+ INVALID_INPUT: "The input has an unsupported type or shape.",
167
+ INPUT_TOO_LARGE: "The input exceeds the configured maximum size.",
168
+ INVALID_OPTIONS: "Invalid SecretShield options.",
169
+ INVALID_RULE: "Invalid custom rule definition (check id, category, severity, confidence and RE2 pattern).",
170
+ DUPLICATE_RULE: "A rule with this id already exists.",
171
+ RULE_NOT_FOUND: "No rule with this id exists.",
172
+ TOO_MANY_RULES: "The maximum number of custom rules has been reached.",
173
+ ABORTED: "The operation was cancelled.",
174
+ REDACTION_INCOMPLETE: "Redaction could not be verified; the output was withheld to avoid leaking a secret.",
175
+ INTERNAL_ERROR: "SecretShield encountered an internal error while processing the input."
176
+ };
177
+ var SecretShieldError = class extends Error {
178
+ code;
179
+ constructor(code) {
180
+ super(MESSAGES[code]);
181
+ this.name = "SecretShieldError";
182
+ this.code = code;
183
+ }
184
+ };
185
+ function toSafeError(error) {
186
+ if (error instanceof SecretShieldError) return error;
187
+ return new SecretShieldError("INTERNAL_ERROR");
188
+ }
189
+
190
+ // src/fs/files.ts
191
+ var import_node_fs = require("fs");
192
+ var import_promises = require("fs/promises");
193
+ var import_node_path = __toESM(require("path"), 1);
194
+
195
+ // src/fs/ignore.ts
196
+ var import_re2js = require("re2js");
197
+ var DEFAULT_IGNORE_PATTERNS = [
198
+ ".git/",
199
+ ".hg/",
200
+ ".svn/",
201
+ "node_modules/",
202
+ "dist/",
203
+ "build/",
204
+ "out/",
205
+ "coverage/",
206
+ ".next/",
207
+ ".turbo/",
208
+ ".cache/",
209
+ ".vscode-test/",
210
+ "*.min.js",
211
+ "*.min.css",
212
+ "*.map",
213
+ "package-lock.json",
214
+ "pnpm-lock.yaml",
215
+ "yarn.lock",
216
+ "bun.lockb"
217
+ ];
218
+ var MAX_PATTERNS = 1e3;
219
+ var MAX_PATTERN_LENGTH = 256;
220
+ function translateClass(body) {
221
+ if (!/^[!^]?[A-Za-z0-9._-]+$/.test(body)) return void 0;
222
+ const negated = body.startsWith("!") || body.startsWith("^");
223
+ const content = negated ? body.slice(1) : body;
224
+ return `[${negated ? "^" : ""}${content.replace(/[\\\]]/g, "\\$&")}]`;
225
+ }
226
+ function globToRegex(glob) {
227
+ let out = "";
228
+ let i = 0;
229
+ while (i < glob.length) {
230
+ const char = glob[i];
231
+ if (char === "*") {
232
+ if (glob[i + 1] === "*") {
233
+ const atStart = i === 0;
234
+ const followedBySlash = glob[i + 2] === "/";
235
+ if ((atStart || glob[i - 1] === "/") && followedBySlash) {
236
+ out += "(?:.*/)?";
237
+ i += 3;
238
+ } else {
239
+ out += ".*";
240
+ i += 2;
241
+ }
242
+ } else {
243
+ out += "[^/]*";
244
+ i += 1;
245
+ }
246
+ } else if (char === "?") {
247
+ out += "[^/]";
248
+ i += 1;
249
+ } else if (char === "[") {
250
+ const close = glob.indexOf("]", i + 1);
251
+ const translated = close > i ? translateClass(glob.slice(i + 1, close)) : void 0;
252
+ if (translated !== void 0) {
253
+ out += translated;
254
+ i = close + 1;
255
+ } else {
256
+ out += import_re2js.RE2JS.quote(char);
257
+ i += 1;
258
+ }
259
+ } else if (char === "\\" && i + 1 < glob.length) {
260
+ out += import_re2js.RE2JS.quote(glob[i + 1]);
261
+ i += 2;
262
+ } else {
263
+ out += import_re2js.RE2JS.quote(char);
264
+ i += 1;
265
+ }
266
+ }
267
+ return out;
268
+ }
269
+ function compile(line) {
270
+ let pattern = line.replace(/\r$/, "");
271
+ if (pattern.trim() === "" || pattern.startsWith("#")) return void 0;
272
+ pattern = pattern.replace(/(?<!\\)\s+$/, "");
273
+ if (pattern.length > MAX_PATTERN_LENGTH) return void 0;
274
+ let negated = false;
275
+ if (pattern.startsWith("!")) {
276
+ negated = true;
277
+ pattern = pattern.slice(1);
278
+ }
279
+ let directoryOnly = false;
280
+ if (pattern.endsWith("/")) {
281
+ directoryOnly = true;
282
+ pattern = pattern.slice(0, -1);
283
+ }
284
+ const anchored = pattern.includes("/");
285
+ if (pattern.startsWith("/")) pattern = pattern.slice(1);
286
+ if (pattern === "") return void 0;
287
+ const body = globToRegex(pattern);
288
+ const source = anchored ? `^${body}$` : `^(?:.*/)?${body}$`;
289
+ try {
290
+ return { regex: import_re2js.RE2JS.compile(source), negated, directoryOnly };
291
+ } catch {
292
+ return void 0;
293
+ }
294
+ }
295
+ var IgnoreMatcher = class {
296
+ patterns = [];
297
+ constructor(lines) {
298
+ for (const line of lines.slice(0, MAX_PATTERNS)) {
299
+ const compiled = compile(line);
300
+ if (compiled) this.patterns.push(compiled);
301
+ }
302
+ }
303
+ static fromText(text) {
304
+ return text.split("\n").slice(0, MAX_PATTERNS);
305
+ }
306
+ /** @param relativePath path relative to the root, using `/` separators */
307
+ ignores(relativePath, isDirectory) {
308
+ let ignored = false;
309
+ for (const pattern of this.patterns) {
310
+ if (pattern.directoryOnly && !isDirectory) continue;
311
+ if (pattern.regex.matches(relativePath)) ignored = !pattern.negated;
312
+ }
313
+ return ignored;
314
+ }
315
+ };
316
+
317
+ // src/fs/files.ts
318
+ var DEFAULT_MAX_FILE_SIZE = 2 * 1024 * 1024;
319
+ var HARD_MAX_FILE_SIZE = 50 * 1024 * 1024;
320
+ var BINARY_SNIFF_BYTES = 8e3;
321
+ var MAX_IGNORE_FILE_SIZE = 64 * 1024;
322
+ var IGNORE_FILE_NAME = ".secretshieldignore";
323
+ var BINARY_EXTENSIONS = /* @__PURE__ */ new Set([
324
+ "png",
325
+ "jpg",
326
+ "jpeg",
327
+ "gif",
328
+ "webp",
329
+ "ico",
330
+ "bmp",
331
+ "tiff",
332
+ "psd",
333
+ "pdf",
334
+ "zip",
335
+ "gz",
336
+ "tgz",
337
+ "bz2",
338
+ "xz",
339
+ "7z",
340
+ "rar",
341
+ "jar",
342
+ "war",
343
+ "exe",
344
+ "dll",
345
+ "so",
346
+ "dylib",
347
+ "bin",
348
+ "class",
349
+ "o",
350
+ "a",
351
+ "wasm",
352
+ "woff",
353
+ "woff2",
354
+ "ttf",
355
+ "otf",
356
+ "eot",
357
+ "mp3",
358
+ "mp4",
359
+ "mov",
360
+ "avi",
361
+ "webm",
362
+ "ogg",
363
+ "wav",
364
+ "flac",
365
+ "sqlite",
366
+ "db",
367
+ "lockb",
368
+ "vsix",
369
+ "node",
370
+ "pyc"
371
+ ]);
372
+ var OPEN_FLAGS = import_node_fs.constants.O_RDONLY | (import_node_fs.constants.O_NOFOLLOW ?? 0) | (import_node_fs.constants.O_NONBLOCK ?? 0);
373
+ async function readTextFile(filePath, maxFileSize) {
374
+ const extension = import_node_path.default.extname(filePath).slice(1).toLowerCase();
375
+ if (BINARY_EXTENSIONS.has(extension)) return { ok: false, reason: "binary" };
376
+ let handle;
377
+ try {
378
+ handle = await (0, import_promises.open)(filePath, OPEN_FLAGS);
379
+ } catch (error) {
380
+ const code = error?.code;
381
+ if (code === "ELOOP") return { ok: false, reason: "symlink" };
382
+ if (code === "EISDIR") return { ok: false, reason: "not-a-file" };
383
+ return { ok: false, reason: "unreadable" };
384
+ }
385
+ try {
386
+ const opened = await handle.stat({ bigint: true });
387
+ const linkStats = await (0, import_promises.lstat)(filePath, { bigint: true });
388
+ if (linkStats.isSymbolicLink()) return { ok: false, reason: "symlink" };
389
+ if (linkStats.ino !== opened.ino || linkStats.dev !== opened.dev) {
390
+ return { ok: false, reason: "unreadable" };
391
+ }
392
+ if (!opened.isFile()) return { ok: false, reason: "not-a-file" };
393
+ if (opened.size > BigInt(maxFileSize)) return { ok: false, reason: "too-large" };
394
+ const size = Number(opened.size);
395
+ const buffer = Buffer.alloc(size);
396
+ let read = 0;
397
+ while (read < size) {
398
+ const { bytesRead } = await handle.read(buffer, read, size - read, read);
399
+ if (bytesRead === 0) break;
400
+ read += bytesRead;
401
+ }
402
+ const content = buffer.subarray(0, read);
403
+ if (content.subarray(0, BINARY_SNIFF_BYTES).includes(0)) return { ok: false, reason: "binary" };
404
+ return { ok: true, text: new TextDecoder("utf-8", { fatal: false }).decode(content) };
405
+ } catch {
406
+ return { ok: false, reason: "unreadable" };
407
+ } finally {
408
+ await handle.close().catch(() => void 0);
409
+ }
410
+ }
411
+ function toPosix(relative) {
412
+ return relative.split(import_node_path.default.sep).join("/");
413
+ }
414
+ async function loadIgnoreFile(root) {
415
+ const outcome = await readTextFile(import_node_path.default.join(root, IGNORE_FILE_NAME), MAX_IGNORE_FILE_SIZE);
416
+ return outcome.ok ? IgnoreMatcher.fromText(outcome.text) : [];
417
+ }
418
+ async function walkDirectory(rootInput, options) {
419
+ let root;
420
+ try {
421
+ root = await (0, import_promises.realpath)(import_node_path.default.resolve(rootInput));
422
+ if (!(await (0, import_promises.lstat)(root)).isDirectory()) throw new SecretShieldError("INVALID_INPUT");
423
+ } catch {
424
+ throw new SecretShieldError("INVALID_INPUT");
425
+ }
426
+ const patterns = [
427
+ ...DEFAULT_IGNORE_PATTERNS,
428
+ ...options.useIgnoreFile ? await loadIgnoreFile(root) : [],
429
+ ...options.ignore
430
+ ];
431
+ const matcher = new IgnoreMatcher(patterns);
432
+ const files = [];
433
+ const notScanned = [];
434
+ let truncated = false;
435
+ const stack = [{ dir: root, depth: 0 }];
436
+ while (stack.length > 0) {
437
+ if (options.signal?.aborted) throw new SecretShieldError("ABORTED");
438
+ const { dir, depth } = stack.pop();
439
+ let handle;
440
+ try {
441
+ handle = await (0, import_promises.opendir)(dir);
442
+ } catch {
443
+ notScanned.push({ file: toPosix(import_node_path.default.relative(root, dir)) || ".", reason: "unreadable" });
444
+ continue;
445
+ }
446
+ const entries = [];
447
+ for await (const entry of handle) entries.push(entry);
448
+ entries.sort((a, b) => a.name < b.name ? -1 : a.name > b.name ? 1 : 0);
449
+ for (const entry of entries) {
450
+ const absolute = import_node_path.default.join(dir, entry.name);
451
+ const relative = toPosix(import_node_path.default.relative(root, absolute));
452
+ const isDirectory = entry.isDirectory();
453
+ if (entry.isSymbolicLink()) {
454
+ notScanned.push({ file: relative, reason: "symlink" });
455
+ continue;
456
+ }
457
+ if (matcher.ignores(relative, isDirectory)) {
458
+ notScanned.push({ file: isDirectory ? `${relative}/` : relative, reason: "ignored" });
459
+ continue;
460
+ }
461
+ if (isDirectory) {
462
+ if (depth + 1 > options.maxDepth) {
463
+ notScanned.push({ file: `${relative}/`, reason: "limit-reached" });
464
+ } else {
465
+ stack.push({ dir: absolute, depth: depth + 1 });
466
+ }
467
+ continue;
468
+ }
469
+ if (!entry.isFile()) {
470
+ notScanned.push({ file: relative, reason: "not-a-file" });
471
+ continue;
472
+ }
473
+ if (files.length >= options.maxFiles) {
474
+ truncated = true;
475
+ break;
476
+ }
477
+ files.push(relative);
478
+ }
479
+ if (truncated) {
480
+ notScanned.push({
481
+ file: `${toPosix(import_node_path.default.relative(root, dir)) || "."}/`,
482
+ reason: "limit-reached"
483
+ });
484
+ for (const pending of stack) {
485
+ notScanned.push({
486
+ file: `${toPosix(import_node_path.default.relative(root, pending.dir))}/`,
487
+ reason: "limit-reached"
488
+ });
489
+ }
490
+ break;
491
+ }
492
+ }
493
+ files.sort();
494
+ return { root, files, notScanned, truncated };
495
+ }
496
+
497
+ // src/entropy/shannon.ts
498
+ function shannonEntropy(value) {
499
+ if (value.length === 0) return 0;
500
+ const counts = /* @__PURE__ */ new Map();
501
+ for (const char of value) {
502
+ counts.set(char, (counts.get(char) ?? 0) + 1);
503
+ }
504
+ const length = [...value].length;
505
+ let entropy = 0;
506
+ for (const count of counts.values()) {
507
+ const p = count / length;
508
+ entropy -= p * Math.log2(p);
509
+ }
510
+ return entropy;
511
+ }
512
+
513
+ // src/rules/names.ts
514
+ function tokenizeIdentifier(name) {
515
+ return name.replace(/([a-z0-9])([A-Z])/g, "$1 $2").replace(/([A-Z]+)([A-Z][a-z])/g, "$1 $2").toLowerCase().split(/[^a-z0-9]+/).filter((token) => token.length > 0);
516
+ }
517
+ var BENIGN_LAST_TOKENS = /* @__PURE__ */ new Set([
518
+ "label",
519
+ "field",
520
+ "placeholder",
521
+ "hint",
522
+ "message",
523
+ "msg",
524
+ "text",
525
+ "title",
526
+ "description",
527
+ "desc",
528
+ "prompt",
529
+ "input",
530
+ "type",
531
+ "types",
532
+ "name",
533
+ "names",
534
+ "length",
535
+ "len",
536
+ "min",
537
+ "max",
538
+ "policy",
539
+ "regex",
540
+ "pattern",
541
+ "rule",
542
+ "rules",
543
+ "error",
544
+ "errors",
545
+ "url",
546
+ "uri",
547
+ "endpoint",
548
+ "path",
549
+ "file",
550
+ "route",
551
+ "expires",
552
+ "expiry",
553
+ "expiration",
554
+ "ttl",
555
+ "count",
556
+ "enabled",
557
+ "required",
558
+ "visible",
559
+ "strength",
560
+ "format",
561
+ "version",
562
+ "id",
563
+ "ids",
564
+ "index",
565
+ "end",
566
+ "start",
567
+ "prefix",
568
+ "suffix",
569
+ "separator",
570
+ "delimiter",
571
+ "char",
572
+ "chars",
573
+ "re",
574
+ "regexp",
575
+ "level",
576
+ "severity",
577
+ "mode",
578
+ "kind",
579
+ "param",
580
+ "env",
581
+ "var",
582
+ "location",
583
+ "source"
584
+ ]);
585
+ var PASSWORD_TOKENS = /* @__PURE__ */ new Set(["password", "passwd", "pwd", "pass", "passphrase", "passcode"]);
586
+ function classifySensitiveName(name) {
587
+ if (name.includes("/") || name.startsWith("@")) return void 0;
588
+ const tokens = tokenizeIdentifier(name);
589
+ if (tokens.length === 0) return void 0;
590
+ const last = tokens[tokens.length - 1];
591
+ if (last !== void 0 && BENIGN_LAST_TOKENS.has(last)) return void 0;
592
+ const joined = tokens.join("");
593
+ if (joined.includes("privatekey")) return "private-key";
594
+ if (joined.includes("secretaccesskey") || joined.includes("awssecret")) return "cloud-credential";
595
+ if (joined.includes("clientsecret")) return "client-secret";
596
+ if (joined.includes("accesstoken") || joined.includes("refreshtoken") || joined.includes("authtoken") || joined.includes("bearertoken") || joined.includes("oauthtoken") || joined.includes("idtoken")) {
597
+ return "oauth-token";
598
+ }
599
+ if (tokens.some((t) => PASSWORD_TOKENS.has(t)) || joined.includes("password")) {
600
+ return "password";
601
+ }
602
+ if (joined.includes("apikey") || joined.includes("apisecret") || joined.includes("accesskey") || joined.includes("secretkey") || joined.includes("signingkey") || joined.includes("encryptionkey")) {
603
+ return "api-key";
604
+ }
605
+ if (tokens.includes("authorization") || tokens.includes("bearer")) return "oauth-token";
606
+ if (tokens.includes("secret") || tokens.includes("secrets")) return "client-secret";
607
+ if (tokens.includes("token")) return "oauth-token";
608
+ if (tokens.includes("credential") || tokens.includes("credentials")) return "client-secret";
609
+ return void 0;
610
+ }
611
+ function isAlreadyRedacted(value) {
612
+ return /([*xX•_.-])\1{3}/.test(value) || /\[(?:REDACTED:|[A-Z_]{0,32}REDACTED\])/.test(value);
613
+ }
614
+ function authSchemeCredentialOffset(value) {
615
+ const match = /^(?:Bearer|Basic|Token|Bot)[ \t]{1,4}(?=\S{8,}$)/i.exec(value);
616
+ return match ? match[0].length : void 0;
617
+ }
618
+ var PLACEHOLDER_PATTERNS = [
619
+ /^\$\{[^}]*\}$/,
620
+ // ${ENV_VAR}
621
+ /^\{\{[^}]*\}\}$/,
622
+ // {{ template }}
623
+ /^<[^>]*>$/,
624
+ // <your-key>
625
+ /^%[A-Za-z_]+%$/,
626
+ // %VAR%
627
+ /^\$[A-Z_][A-Z0-9_]*$/,
628
+ // $ENV_VAR
629
+ /^([x*.\-_#…])\1*$/i,
630
+ // xxxx, ****, ...., …
631
+ /^(?:changeme|change_me|password|secret|token|example|sample|dummy|test|null|none|nil|undefined|true|false|todo|redacted|hidden|empty|default)$/i,
632
+ // Type names used as placeholders in schemas and docs (OpenAPI, TypeScript, JSON Schema)
633
+ /^(?:string|number|integer|int|boolean|bool|object|array|any|unknown|str|uuid|date|datetime)$/i,
634
+ /^(?:your|my|insert|enter|replace)[_-]/i
635
+ ];
636
+ function isLikelyNonSecretValue(value) {
637
+ if (/\s/.test(value)) return true;
638
+ if (isAlreadyRedacted(value)) return true;
639
+ if (PLACEHOLDER_PATTERNS.some((p) => p.test(value))) return true;
640
+ if (/^(?:\/|\.\.?\/|~\/)/.test(value)) return true;
641
+ if (/^[a-z][a-z0-9+.-]*:\/\/[^@]*$/i.test(value)) return true;
642
+ if (/^[A-Za-z_$][\w$]*(?:\.[A-Za-z_$][\w$]*)+$/.test(value)) return true;
643
+ if (/^[A-Z_][A-Z0-9_]*$/.test(value) && value.includes("_")) return true;
644
+ if (/^\(\?[:!=<]|^\^.*\$$|\[\^?[A-Za-z0-9]-[A-Za-z0-9]/.test(value)) return true;
645
+ return false;
646
+ }
647
+ function isSequential(value) {
648
+ if (value.length < 6) return false;
649
+ let consecutive = 0;
650
+ for (let i = 1; i < value.length; i++) {
651
+ const delta = value.charCodeAt(i) - value.charCodeAt(i - 1);
652
+ if (delta === 1 || delta === -1) consecutive++;
653
+ }
654
+ return consecutive / (value.length - 1) >= 0.6;
655
+ }
656
+
657
+ // src/rules/prefixes.ts
658
+ var PUBLIC_PREFIXES = [
659
+ /^(?:sk|rk|pk)_(?:live|test)_/,
660
+ // Stripe
661
+ /^github_pat_/,
662
+ // GitHub fine-grained PAT
663
+ /^gh[pousr]_/,
664
+ // GitHub tokens
665
+ /^glpat-/,
666
+ // GitLab PAT
667
+ /^xox[baprs]-/,
668
+ // Slack
669
+ /^(?:AKIA|ASIA|ABIA|ACCA)/,
670
+ // AWS access key IDs
671
+ /^AIza/,
672
+ // Google API keys
673
+ /^npm_/,
674
+ // npm tokens
675
+ /^SG\./,
676
+ // SendGrid
677
+ /^sk-ant-/,
678
+ // Anthropic
679
+ /^sk-proj-/,
680
+ // OpenAI project keys
681
+ /^eyJ/
682
+ // JWT header ("{")
683
+ ];
684
+ var MIN_HIDDEN_AFTER_PREFIX = 4;
685
+ function publicPrefixOf(value) {
686
+ for (const pattern of PUBLIC_PREFIXES) {
687
+ const match = pattern.exec(value);
688
+ if (match && value.length - match[0].length >= MIN_HIDDEN_AFTER_PREFIX) {
689
+ return match[0];
690
+ }
691
+ }
692
+ return void 0;
693
+ }
694
+
695
+ // src/scoring/assigned.ts
696
+ var SEVERITY_BY_CATEGORY = {
697
+ "api-key": "high",
698
+ "client-secret": "high",
699
+ password: "high",
700
+ jwt: "high",
701
+ "oauth-token": "high",
702
+ "private-key": "critical",
703
+ "database-credential": "critical",
704
+ "cloud-credential": "critical",
705
+ "generic-secret": "medium",
706
+ custom: "medium"
707
+ };
708
+ var BASE_CONFIDENCE = {
709
+ regexUnquoted: 55,
710
+ regexQuoted: 60,
711
+ ast: 70
712
+ };
713
+ function scoreAssignedValue(value, category, base, context) {
714
+ const minLength = category === "password" ? 4 : 8;
715
+ if (value.length < minLength) return void 0;
716
+ if (isLikelyNonSecretValue(value)) return void 0;
717
+ if (value.length < 8 && /^[a-z]+$/.test(value)) return void 0;
718
+ const hasDigit = /\d/.test(value);
719
+ const hasLetter = /[A-Za-z]/.test(value);
720
+ let score = base;
721
+ if (category === "password") score += 10;
722
+ if (publicPrefixOf(value) !== void 0) score += 15;
723
+ if (hasDigit && hasLetter) score += 5;
724
+ if (context.entropy) {
725
+ const entropy = shannonEntropy(value);
726
+ if (entropy >= 3.5) score += 15;
727
+ else if (entropy >= 3) score += 10;
728
+ else if (entropy < 2) score -= 15;
729
+ if (category !== "password" && entropy < 3 && !hasDigit) return void 0;
730
+ }
731
+ return Math.max(0, Math.min(95, score));
732
+ }
733
+ function assignedValueCandidate(name, value, valueStart, base, ruleId, context, rawLength = value.length) {
734
+ if (!context.contextual) return void 0;
735
+ const category = classifySensitiveName(name);
736
+ if (category === void 0) return void 0;
737
+ let secret = value;
738
+ let start = valueStart;
739
+ let end = valueStart + rawLength;
740
+ const credentialOffset = authSchemeCredentialOffset(value);
741
+ if (credentialOffset !== void 0 && rawLength === value.length) {
742
+ secret = value.slice(credentialOffset);
743
+ start = valueStart + credentialOffset;
744
+ }
745
+ const confidence = scoreAssignedValue(secret, category, base, context);
746
+ if (confidence === void 0) return void 0;
747
+ end = Math.max(end, start + 1);
748
+ return {
749
+ start,
750
+ end,
751
+ ruleId,
752
+ category,
753
+ severity: SEVERITY_BY_CATEGORY[category],
754
+ confidence,
755
+ maskPolicy: "public-prefix",
756
+ propagate: true
757
+ };
758
+ }
759
+
760
+ // src/parsers/json.ts
761
+ var import_jsonc_parser = require("jsonc-parser");
762
+ function nearestName(path3) {
763
+ for (let i = path3.length - 1; i >= 0; i--) {
764
+ const segment = path3[i];
765
+ if (typeof segment === "string") return segment;
766
+ }
767
+ return void 0;
768
+ }
769
+ function analyzeJson(text, offset) {
770
+ const results = [];
771
+ (0, import_jsonc_parser.visit)(
772
+ text,
773
+ {
774
+ onLiteralValue(value, valueOffset, length, _line, _column, pathSupplier) {
775
+ if (typeof value !== "string" || length < 3) return;
776
+ const name = nearestName(pathSupplier());
777
+ if (name === void 0) return;
778
+ results.push({
779
+ name,
780
+ value,
781
+ start: offset + valueOffset + 1,
782
+ end: offset + valueOffset + length - 1
783
+ });
784
+ }
785
+ },
786
+ { allowTrailingComma: true, disallowComments: false }
787
+ );
788
+ return results;
789
+ }
790
+
791
+ // src/parsers/language.ts
792
+ var BY_EXTENSION = {
793
+ js: "javascript",
794
+ mjs: "javascript",
795
+ cjs: "javascript",
796
+ jsx: "javascript",
797
+ ts: "typescript",
798
+ mts: "typescript",
799
+ cts: "typescript",
800
+ tsx: "typescript",
801
+ json: "json",
802
+ jsonc: "json",
803
+ yaml: "yaml",
804
+ yml: "yaml",
805
+ env: "dotenv",
806
+ properties: "dotenv",
807
+ ini: "dotenv"
808
+ };
809
+ function detectLanguage(file) {
810
+ if (!file) return "text";
811
+ const base = file.replace(/\\/g, "/").split("/").pop() ?? "";
812
+ const lower = base.toLowerCase();
813
+ if (lower === ".env" || lower.startsWith(".env.") || lower.endsWith(".env")) return "dotenv";
814
+ const dot = lower.lastIndexOf(".");
815
+ if (dot <= 0 && !lower.startsWith(".")) return "text";
816
+ return BY_EXTENSION[lower.slice(dot + 1)] ?? "text";
817
+ }
818
+ var FENCE_LANGUAGES = {
819
+ js: "javascript",
820
+ javascript: "javascript",
821
+ jsx: "javascript",
822
+ mjs: "javascript",
823
+ node: "javascript",
824
+ ts: "typescript",
825
+ typescript: "typescript",
826
+ tsx: "typescript",
827
+ json: "json",
828
+ jsonc: "json",
829
+ yaml: "yaml",
830
+ yml: "yaml",
831
+ env: "dotenv",
832
+ dotenv: "dotenv",
833
+ sh: "dotenv",
834
+ bash: "dotenv"
835
+ };
836
+ function fenceLanguage(info) {
837
+ const id = info.trim().split(/[\s{]/)[0]?.toLowerCase() ?? "";
838
+ return FENCE_LANGUAGES[id];
839
+ }
840
+
841
+ // src/parsers/typescript.ts
842
+ var import_typescript = __toESM(require("typescript"), 1);
843
+ function propertyNameText(name) {
844
+ if (!name) return void 0;
845
+ if (import_typescript.default.isIdentifier(name) || import_typescript.default.isPrivateIdentifier(name)) return name.text;
846
+ if (import_typescript.default.isStringLiteralLike(name) || import_typescript.default.isNumericLiteral(name)) return name.text;
847
+ if (import_typescript.default.isComputedPropertyName(name) && import_typescript.default.isStringLiteralLike(name.expression)) {
848
+ return name.expression.text;
849
+ }
850
+ return void 0;
851
+ }
852
+ function targetName(node) {
853
+ if (import_typescript.default.isIdentifier(node)) return node.text;
854
+ if (import_typescript.default.isPropertyAccessExpression(node)) return node.name.text;
855
+ if (import_typescript.default.isElementAccessExpression(node) && import_typescript.default.isStringLiteralLike(node.argumentExpression)) {
856
+ return node.argumentExpression.text;
857
+ }
858
+ return void 0;
859
+ }
860
+ var ASSIGNMENT_OPERATORS = /* @__PURE__ */ new Set([
861
+ import_typescript.default.SyntaxKind.EqualsToken,
862
+ import_typescript.default.SyntaxKind.EqualsEqualsToken,
863
+ import_typescript.default.SyntaxKind.EqualsEqualsEqualsToken,
864
+ import_typescript.default.SyntaxKind.ExclamationEqualsToken,
865
+ import_typescript.default.SyntaxKind.ExclamationEqualsEqualsToken,
866
+ import_typescript.default.SyntaxKind.QuestionQuestionEqualsToken,
867
+ import_typescript.default.SyntaxKind.BarBarEqualsToken
868
+ ]);
869
+ function effectiveChild(node) {
870
+ let current = node;
871
+ for (; ; ) {
872
+ const parent = current.parent;
873
+ if (!parent) return current;
874
+ const transparent = import_typescript.default.isParenthesizedExpression(parent) || import_typescript.default.isAsExpression(parent) || import_typescript.default.isSatisfiesExpression(parent) || import_typescript.default.isTypeAssertionExpression(parent) || import_typescript.default.isNonNullExpression(parent) || import_typescript.default.isBinaryExpression(parent) && parent.right === current && (parent.operatorToken.kind === import_typescript.default.SyntaxKind.QuestionQuestionToken || parent.operatorToken.kind === import_typescript.default.SyntaxKind.BarBarToken) || import_typescript.default.isConditionalExpression(parent) && parent.condition !== current;
875
+ if (!transparent) return current;
876
+ current = parent;
877
+ }
878
+ }
879
+ function nameForLiteral(literal) {
880
+ const child = effectiveChild(literal);
881
+ const parent = child.parent;
882
+ if (!parent) return void 0;
883
+ if (import_typescript.default.isVariableDeclaration(parent) && parent.initializer === child) {
884
+ return import_typescript.default.isIdentifier(parent.name) ? parent.name.text : void 0;
885
+ }
886
+ if ((import_typescript.default.isPropertyAssignment(parent) || import_typescript.default.isPropertyDeclaration(parent) || import_typescript.default.isEnumMember(parent) || import_typescript.default.isParameter(parent) || import_typescript.default.isBindingElement(parent)) && parent.initializer === child) {
887
+ return propertyNameText(parent.name);
888
+ }
889
+ if (import_typescript.default.isBinaryExpression(parent) && ASSIGNMENT_OPERATORS.has(parent.operatorToken.kind)) {
890
+ const other = parent.right === child ? parent.left : parent.right;
891
+ return targetName(other);
892
+ }
893
+ if (import_typescript.default.isJsxAttribute(parent) && parent.initializer === child) {
894
+ return propertyNameText(parent.name);
895
+ }
896
+ if (import_typescript.default.isCallExpression(parent) || import_typescript.default.isNewExpression(parent)) {
897
+ const args = parent.arguments ?? import_typescript.default.factory.createNodeArray();
898
+ const index = args.findIndex((arg) => arg === child);
899
+ const previous = index > 0 ? args[index - 1] : void 0;
900
+ if (previous && import_typescript.default.isStringLiteralLike(previous)) return previous.text;
901
+ }
902
+ if (import_typescript.default.isArrayLiteralExpression(parent) && parent.elements.length === 2) {
903
+ const [key, value] = parent.elements;
904
+ if (value === child && key && import_typescript.default.isStringLiteralLike(key)) return key.text;
905
+ }
906
+ return void 0;
907
+ }
908
+ function analyzeTypeScript(text, offset, kind, fileName = kind === "typescript" ? "input.tsx" : "input.jsx") {
909
+ const scriptKind = kind === "typescript" ? import_typescript.default.ScriptKind.TSX : import_typescript.default.ScriptKind.JSX;
910
+ const sourceFile = import_typescript.default.createSourceFile(
911
+ fileName,
912
+ text,
913
+ import_typescript.default.ScriptTarget.Latest,
914
+ /* setParentNodes */
915
+ true,
916
+ scriptKind
917
+ );
918
+ const results = [];
919
+ const visit3 = (node) => {
920
+ if (import_typescript.default.isStringLiteral(node) || import_typescript.default.isNoSubstitutionTemplateLiteral(node)) {
921
+ const name = nameForLiteral(node);
922
+ if (name !== void 0) {
923
+ const start = node.getStart(sourceFile) + 1;
924
+ const end = node.getEnd() - 1;
925
+ if (end > start) {
926
+ results.push({ name, value: node.text, start: offset + start, end: offset + end });
927
+ }
928
+ }
929
+ return;
930
+ }
931
+ import_typescript.default.forEachChild(node, visit3);
932
+ };
933
+ visit3(sourceFile);
934
+ return results;
935
+ }
936
+
937
+ // src/parsers/yaml.ts
938
+ var import_yaml = require("yaml");
939
+ var YAML_OPTIONS = {
940
+ schema: "core",
941
+ customTags: [],
942
+ merge: false,
943
+ uniqueKeys: false,
944
+ strict: false,
945
+ prettyErrors: false,
946
+ keepSourceTokens: false
947
+ };
948
+ function analyzeYaml(text, offset) {
949
+ const results = [];
950
+ const documents = (0, import_yaml.parseAllDocuments)(text, YAML_OPTIONS);
951
+ const list = Array.isArray(documents) ? documents : [documents];
952
+ for (const document of list) {
953
+ if (document.errors.length > 0) continue;
954
+ (0, import_yaml.visit)(document, {
955
+ Scalar(key, node, path3) {
956
+ if (key === "key") return;
957
+ if (typeof node.value !== "string" || !node.range) return;
958
+ let name;
959
+ for (let i = path3.length - 1; i >= 0; i--) {
960
+ const ancestor = path3[i];
961
+ if ((0, import_yaml.isPair)(ancestor) && (0, import_yaml.isScalar)(ancestor.key)) {
962
+ name = String(ancestor.key.value);
963
+ break;
964
+ }
965
+ }
966
+ if (name === void 0) return;
967
+ const [rangeStart, valueEnd] = node.range;
968
+ let start = rangeStart;
969
+ let end = valueEnd;
970
+ const type = node.type;
971
+ if (type === "QUOTE_DOUBLE" || type === "QUOTE_SINGLE") {
972
+ start += 1;
973
+ end -= 1;
974
+ } else if (type !== "PLAIN") {
975
+ return;
976
+ }
977
+ if (end <= start) return;
978
+ results.push({
979
+ name,
980
+ value: node.value,
981
+ start: offset + start,
982
+ end: offset + end,
983
+ ...type === "PLAIN" ? { yamlPlain: true } : {}
984
+ });
985
+ }
986
+ });
987
+ }
988
+ return results;
989
+ }
990
+
991
+ // src/parsers/index.ts
992
+ function findFencedBlocks(text) {
993
+ const segments = [];
994
+ const fence = /^ {0,3}(`{3,}|~{3,})(.*)$/;
995
+ let open2;
996
+ let lineStart = 0;
997
+ while (lineStart <= text.length) {
998
+ let lineEnd = text.indexOf("\n", lineStart);
999
+ if (lineEnd === -1) lineEnd = text.length;
1000
+ const line = text.slice(lineStart, lineEnd).replace(/\r$/, "");
1001
+ const match = fence.exec(line);
1002
+ if (open2 === void 0) {
1003
+ if (match && !(match[1]?.startsWith("`") && match[2]?.includes("`"))) {
1004
+ open2 = {
1005
+ marker: match[1] ?? "```",
1006
+ language: fenceLanguage(match[2] ?? ""),
1007
+ contentStart: lineEnd + 1
1008
+ };
1009
+ }
1010
+ } else if (match && match[1]?.[0] === open2.marker[0] && (match[1]?.length ?? 0) >= open2.marker.length && (match[2] ?? "").trim() === "") {
1011
+ if (open2.language !== void 0 && lineStart > open2.contentStart) {
1012
+ segments.push({ language: open2.language, start: open2.contentStart, end: lineStart });
1013
+ }
1014
+ open2 = void 0;
1015
+ }
1016
+ if (lineEnd === text.length) break;
1017
+ lineStart = lineEnd + 1;
1018
+ }
1019
+ return segments;
1020
+ }
1021
+ function literalsFor(text, offset, language) {
1022
+ switch (language) {
1023
+ case "javascript":
1024
+ case "typescript":
1025
+ return analyzeTypeScript(text, offset, language);
1026
+ case "json":
1027
+ return analyzeJson(text, offset);
1028
+ case "yaml":
1029
+ return analyzeYaml(text, offset);
1030
+ default:
1031
+ return [];
1032
+ }
1033
+ }
1034
+ function astCandidates(input, language, context) {
1035
+ const segments = language === "text" ? findFencedBlocks(input) : [{ language, start: 0, end: input.length }];
1036
+ const candidates = [];
1037
+ const yamlPlainStarts = /* @__PURE__ */ new Set();
1038
+ for (const segment of segments) {
1039
+ let literals;
1040
+ try {
1041
+ literals = literalsFor(
1042
+ input.slice(segment.start, segment.end),
1043
+ segment.start,
1044
+ segment.language
1045
+ );
1046
+ } catch {
1047
+ continue;
1048
+ }
1049
+ for (const literal of literals) {
1050
+ const raw = input.slice(literal.start, literal.end);
1051
+ if (raw.includes("\n")) continue;
1052
+ if (literal.yamlPlain) yamlPlainStarts.add(literal.start);
1053
+ const candidate = assignedValueCandidate(
1054
+ literal.name,
1055
+ literal.value,
1056
+ literal.start,
1057
+ BASE_CONFIDENCE.ast,
1058
+ "ast-sensitive-assignment",
1059
+ context,
1060
+ raw.length
1061
+ );
1062
+ if (!candidate) continue;
1063
+ if (raw !== literal.value) {
1064
+ candidate.start = literal.start;
1065
+ candidate.end = literal.end;
1066
+ }
1067
+ candidates.push(candidate);
1068
+ }
1069
+ }
1070
+ return { candidates, yamlPlainStarts };
1071
+ }
1072
+
1073
+ // src/redaction/mask.ts
1074
+ var Masker = class {
1075
+ constructor(options) {
1076
+ this.options = options;
1077
+ this.mask = options.maskChar.repeat(options.maskLength);
1078
+ }
1079
+ options;
1080
+ tokens = /* @__PURE__ */ new Map();
1081
+ counters = /* @__PURE__ */ new Map();
1082
+ mask;
1083
+ maskValue(value, candidate) {
1084
+ const masked = this.rawMask(value, candidate);
1085
+ if (candidate.yamlPlain && /^[*&!%@`|>?:,[\]{}#'"-]/.test(masked)) return `"${masked}"`;
1086
+ return masked;
1087
+ }
1088
+ rawMask(value, candidate) {
1089
+ if (this.options.strategy === "token") {
1090
+ const existing = this.tokens.get(value);
1091
+ if (existing !== void 0) return existing;
1092
+ const next = (this.counters.get(candidate.category) ?? 0) + 1;
1093
+ this.counters.set(candidate.category, next);
1094
+ const token = `[REDACTED:${candidate.category}#${next}]`;
1095
+ this.tokens.set(value, token);
1096
+ return token;
1097
+ }
1098
+ if (candidate.maskPolicy === "placeholder" && candidate.placeholder !== void 0) {
1099
+ return candidate.placeholder;
1100
+ }
1101
+ if (this.options.strategy === "partial" && candidate.maskPolicy === "public-prefix") {
1102
+ const prefix = publicPrefixOf(value);
1103
+ if (prefix !== void 0) return prefix + this.mask;
1104
+ }
1105
+ return this.mask;
1106
+ }
1107
+ /** Releases every value held for correlation. */
1108
+ dispose() {
1109
+ this.tokens.clear();
1110
+ this.counters.clear();
1111
+ }
1112
+ };
1113
+
1114
+ // src/redaction/object.ts
1115
+ var MAX_OBJECT_DEPTH = 64;
1116
+ var MAX_OBJECT_NODES = 1e5;
1117
+ var FORBIDDEN_KEYS = /* @__PURE__ */ new Set(["__proto__", "constructor", "prototype"]);
1118
+ function formatPath(parent, key) {
1119
+ if (typeof key === "number") return `${parent}[${key}]`;
1120
+ if (/^[A-Za-z_$][\w$]*$/.test(key)) return `${parent}.${key}`;
1121
+ return `${parent}[${JSON.stringify(key.length > 128 ? `${key.slice(0, 128)}\u2026` : key)}]`;
1122
+ }
1123
+ function isPlainLike(value) {
1124
+ const proto = Object.getPrototypeOf(value);
1125
+ return proto === Object.prototype || proto === null;
1126
+ }
1127
+ function redactObjectValue(input, hooks) {
1128
+ const ancestors = /* @__PURE__ */ new WeakSet();
1129
+ let nodes = 0;
1130
+ const visit3 = (value, name, path3, depth) => {
1131
+ if (++nodes > MAX_OBJECT_NODES) throw new SecretShieldError("INPUT_TOO_LARGE");
1132
+ if (typeof value === "string") {
1133
+ if (name !== void 0) {
1134
+ const candidate = hooks.namedCandidate(name, value);
1135
+ if (candidate) {
1136
+ const secret = value.slice(candidate.start, candidate.end);
1137
+ const masked = hooks.mask(secret, candidate);
1138
+ hooks.onFinding(candidate, path3, masked);
1139
+ return value.slice(0, candidate.start) + masked + value.slice(candidate.end);
1140
+ }
1141
+ }
1142
+ const { text, findings } = hooks.redactText(value);
1143
+ for (const finding of findings) hooks.onFinding(finding, path3, finding.maskedValue);
1144
+ return text;
1145
+ }
1146
+ if (value === null || typeof value !== "object") return value;
1147
+ if (depth >= MAX_OBJECT_DEPTH) return "[MaxDepth]";
1148
+ if (ancestors.has(value)) return "[Circular]";
1149
+ ancestors.add(value);
1150
+ try {
1151
+ if (Array.isArray(value)) {
1152
+ return value.map((item, index) => visit3(item, name, formatPath(path3, index), depth + 1));
1153
+ }
1154
+ if (value instanceof Date) return new Date(value.getTime());
1155
+ if (value instanceof RegExp) return new RegExp(value.source, value.flags);
1156
+ if (value instanceof ArrayBuffer) return value.slice(0);
1157
+ if (ArrayBuffer.isView(value)) {
1158
+ return new Uint8Array(value.buffer, value.byteOffset, value.byteLength).slice();
1159
+ }
1160
+ if (value instanceof Map) {
1161
+ const out2 = /* @__PURE__ */ new Map();
1162
+ for (const [key, item] of value) {
1163
+ const keyName = typeof key === "string" ? key : void 0;
1164
+ out2.set(key, visit3(item, keyName, formatPath(path3, String(key)), depth + 1));
1165
+ }
1166
+ return out2;
1167
+ }
1168
+ if (value instanceof Set) {
1169
+ const out2 = /* @__PURE__ */ new Set();
1170
+ let index = 0;
1171
+ for (const item of value) out2.add(visit3(item, name, formatPath(path3, index++), depth + 1));
1172
+ return out2;
1173
+ }
1174
+ const out = isPlainLike(value) && Object.getPrototypeOf(value) === null ? /* @__PURE__ */ Object.create(null) : {};
1175
+ for (const key of Object.keys(value)) {
1176
+ if (FORBIDDEN_KEYS.has(key)) continue;
1177
+ let item;
1178
+ try {
1179
+ item = value[key];
1180
+ } catch {
1181
+ continue;
1182
+ }
1183
+ Object.defineProperty(out, key, {
1184
+ value: visit3(item, key, formatPath(path3, key), depth + 1),
1185
+ enumerable: true,
1186
+ writable: true,
1187
+ configurable: true
1188
+ });
1189
+ }
1190
+ return out;
1191
+ } finally {
1192
+ ancestors.delete(value);
1193
+ }
1194
+ };
1195
+ return visit3(input, void 0, "$", 0);
1196
+ }
1197
+
1198
+ // src/version.ts
1199
+ var VERSION = "0.1.3";
1200
+
1201
+ // src/reporting/report.ts
1202
+ var DISCLAIMER = "SecretShield reduces the risk of accidental disclosure but cannot guarantee that every secret was detected. Files listed as not scanned were not analysed and must not be considered safe.";
1203
+ function isObject(value) {
1204
+ return typeof value === "object" && value !== null;
1205
+ }
1206
+ function entriesFromFindings(findings, file) {
1207
+ if (!Array.isArray(findings)) throw new SecretShieldError("INVALID_INPUT");
1208
+ return findings.map((raw) => {
1209
+ if (!isObject(raw)) throw new SecretShieldError("INVALID_INPUT");
1210
+ const entry = {
1211
+ ruleId: String(raw["ruleId"]),
1212
+ category: raw["category"],
1213
+ severity: raw["severity"],
1214
+ confidence: Number(raw["confidence"])
1215
+ };
1216
+ const fileName = typeof raw["file"] === "string" ? raw["file"] : file;
1217
+ if (fileName !== void 0) entry.file = fileName;
1218
+ if (typeof raw["path"] === "string") entry.path = raw["path"];
1219
+ if (typeof raw["line"] === "number") entry.line = raw["line"];
1220
+ if (typeof raw["column"] === "number") entry.column = raw["column"];
1221
+ return entry;
1222
+ });
1223
+ }
1224
+ function normalize(input) {
1225
+ if (Array.isArray(input)) {
1226
+ const entries = [];
1227
+ const notScanned = [];
1228
+ for (const file2 of input) {
1229
+ if (!isObject(file2)) throw new SecretShieldError("INVALID_INPUT");
1230
+ const name = String(file2["file"]);
1231
+ if (file2["status"] === "not-scanned") {
1232
+ notScanned.push({ file: name, reason: file2["reason"] });
1233
+ } else {
1234
+ entries.push(...entriesFromFindings(file2["findings"], name));
1235
+ }
1236
+ }
1237
+ return { entries, notScanned };
1238
+ }
1239
+ if (!isObject(input)) throw new SecretShieldError("INVALID_INPUT");
1240
+ if (Array.isArray(input["files"]) && Array.isArray(input["notScanned"])) {
1241
+ const nested = normalize(input["files"]);
1242
+ const notScanned = input["notScanned"].map((raw) => {
1243
+ if (!isObject(raw)) throw new SecretShieldError("INVALID_INPUT");
1244
+ return { file: String(raw["file"]), reason: raw["reason"] };
1245
+ });
1246
+ return { entries: nested.entries, notScanned: [...nested.notScanned, ...notScanned] };
1247
+ }
1248
+ if (input["status"] === "not-scanned") {
1249
+ return {
1250
+ entries: [],
1251
+ notScanned: [
1252
+ { file: String(input["file"]), reason: input["reason"] }
1253
+ ]
1254
+ };
1255
+ }
1256
+ const file = typeof input["file"] === "string" ? input["file"] : void 0;
1257
+ return { entries: entriesFromFindings(input["findings"], file), notScanned: [] };
1258
+ }
1259
+ function summarizeEntries(entries) {
1260
+ const summary = {
1261
+ total: entries.length,
1262
+ critical: 0,
1263
+ high: 0,
1264
+ medium: 0,
1265
+ low: 0
1266
+ };
1267
+ for (const entry of entries) {
1268
+ if (entry.severity in summary) summary[entry.severity]++;
1269
+ }
1270
+ return summary;
1271
+ }
1272
+ function buildJsonReport(input, now = /* @__PURE__ */ new Date()) {
1273
+ const { entries, notScanned } = normalize(input);
1274
+ const byCategory = {};
1275
+ for (const entry of entries) byCategory[entry.category] = (byCategory[entry.category] ?? 0) + 1;
1276
+ return {
1277
+ tool: { name: "SecretShield", version: VERSION },
1278
+ generatedAt: now.toISOString(),
1279
+ summary: summarizeEntries(entries),
1280
+ byCategory,
1281
+ results: entries,
1282
+ notScanned,
1283
+ disclaimer: DISCLAIMER
1284
+ };
1285
+ }
1286
+ function md(text) {
1287
+ return text.replace(/[\r\n]+/g, " ").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/[\\`*_[\]{}()#+!|~-]/g, (char) => `\\${char}`);
1288
+ }
1289
+ function toMarkdown(report) {
1290
+ const lines = [
1291
+ "# SecretShield Security Report",
1292
+ "",
1293
+ `Generated: ${report.generatedAt} \xB7 SecretShield ${md(report.tool.version)}`,
1294
+ "",
1295
+ "## Summary",
1296
+ "",
1297
+ "| Total | Critical | High | Medium | Low |",
1298
+ "| ----: | -------: | ---: | -----: | --: |",
1299
+ `| ${report.summary.total} | ${report.summary.critical} | ${report.summary.high} | ${report.summary.medium} | ${report.summary.low} |`,
1300
+ ""
1301
+ ];
1302
+ if (report.results.length > 0) {
1303
+ lines.push("## Findings", "", "| Location | Line | Category | Severity | Confidence | Rule |");
1304
+ lines.push("| -------- | ---: | -------- | -------- | ---------: | ---- |");
1305
+ for (const entry of report.results) {
1306
+ const location = entry.file ?? entry.path ?? "(input)";
1307
+ lines.push(
1308
+ `| ${md(location)} | ${entry.line ?? ""} | ${md(entry.category)} | ${md(entry.severity)} | ${entry.confidence}% | ${md(entry.ruleId)} |`
1309
+ );
1310
+ }
1311
+ lines.push("");
1312
+ } else {
1313
+ lines.push("No secrets detected in the scanned content.", "");
1314
+ }
1315
+ if (report.notScanned.length > 0) {
1316
+ lines.push(
1317
+ "## Not scanned",
1318
+ "",
1319
+ "These paths were **not analysed** and must not be considered safe.",
1320
+ ""
1321
+ );
1322
+ lines.push("| Path | Reason |", "| ---- | ------ |");
1323
+ for (const entry of report.notScanned)
1324
+ lines.push(`| ${md(entry.file)} | ${md(entry.reason)} |`);
1325
+ lines.push("");
1326
+ }
1327
+ lines.push("---", "", `_${DISCLAIMER}_`, "");
1328
+ return lines.join("\n");
1329
+ }
1330
+ var SARIF_LEVEL = {
1331
+ critical: "error",
1332
+ high: "error",
1333
+ medium: "warning",
1334
+ low: "note"
1335
+ };
1336
+ function toSarif(report) {
1337
+ const ruleIds = [...new Set(report.results.map((r) => r.ruleId))].sort();
1338
+ const sarif = {
1339
+ $schema: "https://json.schemastore.org/sarif-2.1.0.json",
1340
+ version: "2.1.0",
1341
+ runs: [
1342
+ {
1343
+ tool: {
1344
+ driver: {
1345
+ name: "SecretShield",
1346
+ version: report.tool.version,
1347
+ informationUri: "https://www.npmjs.com/package/@appystore/secret-shield",
1348
+ rules: ruleIds.map((id) => ({
1349
+ id,
1350
+ name: id,
1351
+ shortDescription: { text: `Possible secret detected by rule ${id}.` }
1352
+ }))
1353
+ }
1354
+ },
1355
+ invocations: [
1356
+ {
1357
+ executionSuccessful: true,
1358
+ toolExecutionNotifications: report.notScanned.map((entry) => ({
1359
+ level: "warning",
1360
+ message: {
1361
+ text: `Not scanned (${entry.reason}). This path was not analysed and must not be considered safe.`
1362
+ },
1363
+ locations: [{ physicalLocation: { artifactLocation: { uri: entry.file } } }]
1364
+ }))
1365
+ }
1366
+ ],
1367
+ results: report.results.map((entry) => ({
1368
+ ruleId: entry.ruleId,
1369
+ level: SARIF_LEVEL[entry.severity] ?? "warning",
1370
+ message: {
1371
+ text: `Possible ${entry.category} detected (confidence ${entry.confidence}%). The value is not included in this report.`
1372
+ },
1373
+ locations: [
1374
+ {
1375
+ physicalLocation: {
1376
+ artifactLocation: { uri: entry.file ?? "input" },
1377
+ region: { startLine: entry.line ?? 1, startColumn: entry.column ?? 1 }
1378
+ }
1379
+ }
1380
+ ],
1381
+ properties: {
1382
+ category: entry.category,
1383
+ severity: entry.severity,
1384
+ confidence: entry.confidence
1385
+ }
1386
+ }))
1387
+ }
1388
+ ]
1389
+ };
1390
+ return JSON.stringify(sarif, null, 2);
1391
+ }
1392
+ function generateReport(input, format = "json") {
1393
+ const report = buildJsonReport(input);
1394
+ switch (format) {
1395
+ case "json":
1396
+ return JSON.stringify(report, null, 2);
1397
+ case "markdown":
1398
+ return toMarkdown(report);
1399
+ case "sarif":
1400
+ return toSarif(report);
1401
+ default:
1402
+ throw new SecretShieldError("INVALID_OPTIONS");
1403
+ }
1404
+ }
1405
+
1406
+ // src/rules/builtin.ts
1407
+ var TOKEN_END = "(?![A-Za-z0-9_-])";
1408
+ var DATABASE_SCHEMES = /* @__PURE__ */ new Set([
1409
+ "postgres",
1410
+ "postgresql",
1411
+ "mysql",
1412
+ "mariadb",
1413
+ "mongodb",
1414
+ "mongodb+srv",
1415
+ "redis",
1416
+ "rediss",
1417
+ "amqp",
1418
+ "amqps",
1419
+ "mssql",
1420
+ "sqlserver",
1421
+ "cockroachdb"
1422
+ ]);
1423
+ function groupSpan(match, group) {
1424
+ const span = match.indices?.[group];
1425
+ return span ? [span[0], span[1]] : void 0;
1426
+ }
1427
+ function assignmentExtractor(ruleId, base, nameGroup, valueGroups) {
1428
+ return (match, context) => {
1429
+ const name = match[nameGroup];
1430
+ if (name === void 0) return [];
1431
+ const valueGroup = valueGroups.find((g) => match[g] !== void 0);
1432
+ if (valueGroup === void 0) return [];
1433
+ const value = match[valueGroup] ?? "";
1434
+ const span = groupSpan(match, valueGroup);
1435
+ if (!span) return [];
1436
+ const candidate = assignedValueCandidate(name, value, span[0], base, ruleId, context);
1437
+ return candidate ? [candidate] : [];
1438
+ };
1439
+ }
1440
+ var HIGH_ENTROPY_EXCLUSIONS = [
1441
+ /^(?:sha1|sha256|sha384|sha512|md5)[-:]/i,
1442
+ /^[0-9a-f]+$/i,
1443
+ // hex digests, commit SHAs (named hex secrets are caught by assignment rules)
1444
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i,
1445
+ // UUID
1446
+ /^[a-z]+(?:[_.-][a-z0-9]+)+$/
1447
+ // snake_case / dotted.names / kebab-case
1448
+ ];
1449
+ function looksLikeWords(value) {
1450
+ if (!/^[A-Za-z][A-Za-z]*\d{0,4}$/.test(value)) return false;
1451
+ const segments = value.replace(/\d+$/, "").split(/(?=[A-Z][a-z])|(?<=[a-z])(?=[A-Z])/);
1452
+ const wordLike = segments.filter((s) => /^[A-Z]?[a-z]{2,}$/.test(s) || /^[A-Z]{1,5}$/.test(s));
1453
+ return wordLike.length / segments.length >= 0.8;
1454
+ }
1455
+ function highEntropyExtractor(match, context) {
1456
+ if (!context.entropy) return [];
1457
+ const value = match[2] ?? "";
1458
+ const span = groupSpan(match, 2);
1459
+ if (!span) return [];
1460
+ if (!/[a-z]/.test(value) || !/[A-Z]/.test(value) || !/\d/.test(value)) return [];
1461
+ if (isLikelyNonSecretValue(value)) return [];
1462
+ if (HIGH_ENTROPY_EXCLUSIONS.some((p) => p.test(value)) || looksLikeWords(value) || isSequential(value)) {
1463
+ return [];
1464
+ }
1465
+ const entropy = shannonEntropy(value);
1466
+ const threshold = Math.min(4.2, Math.log2(value.length) * 0.85);
1467
+ if (entropy < threshold) return [];
1468
+ return [
1469
+ {
1470
+ start: span[0],
1471
+ end: span[1],
1472
+ ruleId: "high-entropy-string",
1473
+ category: "generic-secret",
1474
+ severity: "medium",
1475
+ confidence: entropy >= 4.5 ? 55 : 45,
1476
+ maskPolicy: "full",
1477
+ propagate: true
1478
+ }
1479
+ ];
1480
+ }
1481
+ var PEM_BEGIN = /-----BEGIN (?:[A-Z0-9]{1,16} ){0,4}PRIVATE KEY(?: BLOCK)?-----/g;
1482
+ var PEM_END = /-----END (?:[A-Z0-9]{1,16} ){0,4}PRIVATE KEY(?: BLOCK)?-----/g;
1483
+ var PEM_MAX_BLOCK_LENGTH = 32768;
1484
+ function scanPemPrivateKeys(input) {
1485
+ const candidates = [];
1486
+ const begin = new RegExp(PEM_BEGIN.source, "g");
1487
+ const end = new RegExp(PEM_END.source, "g");
1488
+ let nextEnd;
1489
+ let match;
1490
+ while ((match = begin.exec(input)) !== null) {
1491
+ const headerEnd = match.index + match[0].length;
1492
+ if (nextEnd === void 0 || nextEnd !== null && nextEnd.index < headerEnd) {
1493
+ end.lastIndex = headerEnd;
1494
+ nextEnd = end.exec(input);
1495
+ }
1496
+ if (nextEnd === null) break;
1497
+ const blockEnd = nextEnd.index + nextEnd[0].length;
1498
+ if (blockEnd - match.index > PEM_MAX_BLOCK_LENGTH) continue;
1499
+ candidates.push({
1500
+ start: match.index,
1501
+ end: blockEnd,
1502
+ ruleId: "private-key-pem",
1503
+ category: "private-key",
1504
+ severity: "critical",
1505
+ confidence: 99,
1506
+ maskPolicy: "placeholder",
1507
+ placeholder: "[PRIVATE_KEY_REDACTED]",
1508
+ propagate: true
1509
+ });
1510
+ begin.lastIndex = blockEnd;
1511
+ }
1512
+ return candidates;
1513
+ }
1514
+ var BUILTIN_RULES = [
1515
+ {
1516
+ id: "private-key-pem",
1517
+ name: "PEM private key",
1518
+ category: "private-key",
1519
+ severity: "critical",
1520
+ baseConfidence: 99,
1521
+ maskPolicy: "placeholder",
1522
+ placeholder: "[PRIVATE_KEY_REDACTED]",
1523
+ keywords: ["private key"],
1524
+ scan: scanPemPrivateKeys
1525
+ },
1526
+ {
1527
+ id: "aws-access-key-id",
1528
+ name: "AWS access key ID",
1529
+ category: "cloud-credential",
1530
+ severity: "critical",
1531
+ baseConfidence: 95,
1532
+ maskPolicy: "public-prefix",
1533
+ keywords: ["akia", "asia", "abia", "acca"],
1534
+ pattern: new RegExp(`\\b(?:AKIA|ASIA|ABIA|ACCA)[A-Z2-7]{16}${TOKEN_END}`, "dg")
1535
+ },
1536
+ {
1537
+ id: "github-token",
1538
+ name: "GitHub token",
1539
+ category: "api-key",
1540
+ severity: "critical",
1541
+ baseConfidence: 95,
1542
+ maskPolicy: "public-prefix",
1543
+ keywords: ["ghp_", "gho_", "ghu_", "ghs_", "ghr_", "github_pat_"],
1544
+ pattern: new RegExp(
1545
+ `\\b(?:gh[pousr]_[A-Za-z0-9]{36,251}|github_pat_[A-Za-z0-9_]{22,255})${TOKEN_END}`,
1546
+ "dg"
1547
+ )
1548
+ },
1549
+ {
1550
+ id: "gitlab-token",
1551
+ name: "GitLab personal access token",
1552
+ category: "api-key",
1553
+ severity: "critical",
1554
+ baseConfidence: 95,
1555
+ maskPolicy: "public-prefix",
1556
+ keywords: ["glpat-"],
1557
+ pattern: new RegExp(`\\bglpat-[A-Za-z0-9_-]{20,64}${TOKEN_END}`, "dg")
1558
+ },
1559
+ {
1560
+ id: "stripe-key",
1561
+ name: "Stripe secret or restricted key",
1562
+ category: "api-key",
1563
+ severity: "critical",
1564
+ baseConfidence: 95,
1565
+ maskPolicy: "public-prefix",
1566
+ keywords: ["sk_live_", "sk_test_", "rk_live_", "rk_test_"],
1567
+ pattern: new RegExp(`\\b(?:sk|rk)_(?:live|test)_[A-Za-z0-9]{10,247}${TOKEN_END}`, "dg")
1568
+ },
1569
+ {
1570
+ id: "slack-token",
1571
+ name: "Slack token",
1572
+ category: "oauth-token",
1573
+ severity: "high",
1574
+ baseConfidence: 90,
1575
+ maskPolicy: "public-prefix",
1576
+ keywords: ["xox"],
1577
+ pattern: new RegExp(`\\bxox[baprs]-[A-Za-z0-9-]{10,250}${TOKEN_END}`, "dg")
1578
+ },
1579
+ {
1580
+ id: "google-api-key",
1581
+ name: "Google API key",
1582
+ category: "api-key",
1583
+ severity: "high",
1584
+ baseConfidence: 90,
1585
+ maskPolicy: "public-prefix",
1586
+ keywords: ["aiza"],
1587
+ pattern: new RegExp(`\\bAIza[0-9A-Za-z_-]{35}${TOKEN_END}`, "dg")
1588
+ },
1589
+ {
1590
+ id: "npm-token",
1591
+ name: "npm access token",
1592
+ category: "api-key",
1593
+ severity: "critical",
1594
+ baseConfidence: 95,
1595
+ maskPolicy: "public-prefix",
1596
+ keywords: ["npm_"],
1597
+ pattern: new RegExp(`\\bnpm_[A-Za-z0-9]{36}${TOKEN_END}`, "dg")
1598
+ },
1599
+ {
1600
+ id: "anthropic-api-key",
1601
+ name: "Anthropic API key",
1602
+ category: "api-key",
1603
+ severity: "critical",
1604
+ baseConfidence: 95,
1605
+ maskPolicy: "public-prefix",
1606
+ keywords: ["sk-ant-"],
1607
+ pattern: new RegExp(`\\bsk-ant-[A-Za-z0-9_-]{32,200}${TOKEN_END}`, "dg")
1608
+ },
1609
+ {
1610
+ id: "openai-project-key",
1611
+ name: "OpenAI project API key",
1612
+ category: "api-key",
1613
+ severity: "critical",
1614
+ baseConfidence: 95,
1615
+ maskPolicy: "public-prefix",
1616
+ keywords: ["sk-proj-"],
1617
+ pattern: new RegExp(`\\bsk-proj-[A-Za-z0-9_-]{32,200}${TOKEN_END}`, "dg")
1618
+ },
1619
+ {
1620
+ id: "jwt",
1621
+ name: "JSON Web Token",
1622
+ category: "jwt",
1623
+ severity: "high",
1624
+ baseConfidence: 90,
1625
+ maskPolicy: "public-prefix",
1626
+ keywords: ["eyj"],
1627
+ pattern: new RegExp(
1628
+ `\\beyJ[A-Za-z0-9_-]{8,4096}\\.eyJ[A-Za-z0-9_-]{8,8192}\\.[A-Za-z0-9_-]{0,4096}${TOKEN_END}`,
1629
+ "dg"
1630
+ )
1631
+ },
1632
+ {
1633
+ id: "uri-credentials",
1634
+ name: "Credentials embedded in a connection URI",
1635
+ category: "database-credential",
1636
+ severity: "critical",
1637
+ baseConfidence: 95,
1638
+ maskPolicy: "full",
1639
+ keywords: ["://"],
1640
+ // scheme://user:password@host — user and password are masked, host and database are kept.
1641
+ pattern: /\b([A-Za-z][A-Za-z0-9+.-]{1,30}):\/\/([^\s:@/'"`<>]{0,256}):([^\s@/'"`<>]{1,256})@/dg,
1642
+ extract(match) {
1643
+ const scheme = (match[1] ?? "").toLowerCase();
1644
+ const password = match[3] ?? "";
1645
+ if (isLikelyNonSecretValue(password)) return [];
1646
+ const category = DATABASE_SCHEMES.has(scheme) ? "database-credential" : "password";
1647
+ const candidates = [];
1648
+ const userSpan = groupSpan(match, 2);
1649
+ if (userSpan && userSpan[1] > userSpan[0]) {
1650
+ candidates.push({
1651
+ start: userSpan[0],
1652
+ end: userSpan[1],
1653
+ ruleId: "uri-credentials",
1654
+ category,
1655
+ severity: "high",
1656
+ confidence: 90,
1657
+ maskPolicy: "full",
1658
+ propagate: false
1659
+ });
1660
+ }
1661
+ const passwordSpan = groupSpan(match, 3);
1662
+ if (passwordSpan) {
1663
+ candidates.push({
1664
+ start: passwordSpan[0],
1665
+ end: passwordSpan[1],
1666
+ ruleId: "uri-credentials",
1667
+ category,
1668
+ severity: "critical",
1669
+ confidence: 95,
1670
+ maskPolicy: "full",
1671
+ propagate: true
1672
+ });
1673
+ }
1674
+ return candidates;
1675
+ }
1676
+ },
1677
+ {
1678
+ id: "sensitive-assignment-quoted",
1679
+ name: "Quoted value assigned to a sensitive name",
1680
+ category: "custom",
1681
+ severity: "high",
1682
+ baseConfidence: 60,
1683
+ maskPolicy: "public-prefix",
1684
+ // name ["']? (= | == | : | := | =>) "value" | 'value' | `value`
1685
+ pattern: /(?<![\w$.@/-])([A-Za-z_$][\w$.-]{0,127})["']?[ \t]{0,16}(?::=|=>|==?|:)[ \t]{0,16}(?:"([^"\r\n]{1,1024})"|'([^'\r\n]{1,1024})'|`([^`$\r\n]{1,1024})`)/dg,
1686
+ extract: assignmentExtractor(
1687
+ "sensitive-assignment-quoted",
1688
+ BASE_CONFIDENCE.regexQuoted,
1689
+ 1,
1690
+ [2, 3, 4]
1691
+ )
1692
+ },
1693
+ {
1694
+ id: "authorization-header",
1695
+ name: "HTTP Authorization header credential",
1696
+ category: "oauth-token",
1697
+ severity: "high",
1698
+ baseConfidence: 85,
1699
+ maskPolicy: "full",
1700
+ keywords: ["authorization"],
1701
+ pattern: /\b(?:Proxy-)?Authorization["']?[ \t]{0,4}[:=][ \t]{0,4}["']?(?:Bearer|Basic|Token|Bot)[ \t]{1,4}([A-Za-z0-9._~+/=-]{8,8192})/dgi,
1702
+ extract(match) {
1703
+ const span = groupSpan(match, 1);
1704
+ const value = match[1] ?? "";
1705
+ if (!span || isLikelyNonSecretValue(value)) return [];
1706
+ return [
1707
+ {
1708
+ start: span[0],
1709
+ end: span[1],
1710
+ ruleId: "authorization-header",
1711
+ category: "oauth-token",
1712
+ severity: "high",
1713
+ confidence: 85,
1714
+ maskPolicy: "public-prefix",
1715
+ propagate: true
1716
+ }
1717
+ ];
1718
+ }
1719
+ },
1720
+ {
1721
+ id: "high-entropy-string",
1722
+ name: "High-entropy quoted string",
1723
+ category: "generic-secret",
1724
+ severity: "medium",
1725
+ baseConfidence: 45,
1726
+ maskPolicy: "full",
1727
+ pattern: /(["'`])([A-Za-z0-9+/=_.~-]{20,1024})\1/dg,
1728
+ extract: highEntropyExtractor
1729
+ },
1730
+ {
1731
+ id: "sensitive-assignment-unquoted",
1732
+ name: "Unquoted value assigned to a sensitive name (.env, YAML, properties)",
1733
+ category: "custom",
1734
+ severity: "high",
1735
+ baseConfidence: 55,
1736
+ maskPolicy: "public-prefix",
1737
+ pattern: /^[ \t]{0,64}(?:export[ \t]{1,8})?(?:-[ \t]{1,8})?([A-Za-z_][\w.-]{0,127})[ \t]{0,16}[:=][ \t]{0,16}([^\s"'`#,;{}()[\]<>=][^\s"'`#,;{}()[\]<>]{0,1023})[ \t]{0,64}\r?$/dgm,
1738
+ extract: assignmentExtractor(
1739
+ "sensitive-assignment-unquoted",
1740
+ BASE_CONFIDENCE.regexUnquoted,
1741
+ 1,
1742
+ [2]
1743
+ )
1744
+ }
1745
+ ];
1746
+
1747
+ // src/rules/custom.ts
1748
+ var import_re2js2 = require("re2js");
1749
+
1750
+ // src/types.ts
1751
+ var SECRET_CATEGORIES = [
1752
+ "api-key",
1753
+ "client-secret",
1754
+ "password",
1755
+ "jwt",
1756
+ "oauth-token",
1757
+ "private-key",
1758
+ "database-credential",
1759
+ "cloud-credential",
1760
+ "generic-secret",
1761
+ "custom"
1762
+ ];
1763
+ var SEVERITIES = ["low", "medium", "high", "critical"];
1764
+
1765
+ // src/rules/custom.ts
1766
+ var MAX_CUSTOM_RULES = 256;
1767
+ var MAX_PATTERN_LENGTH2 = 1024;
1768
+ var MAX_MATCHES_PER_RULE = 1e4;
1769
+ var ID_PATTERN = /^[a-z0-9][a-z0-9._-]{0,63}$/;
1770
+ var PLACEHOLDER_PATTERN = /^\[[A-Z0-9_:#-]{1,48}\]$/;
1771
+ var MASK_POLICIES = ["public-prefix", "full", "placeholder"];
1772
+ function invalid() {
1773
+ throw new SecretShieldError("INVALID_RULE");
1774
+ }
1775
+ function compileFlags(flags) {
1776
+ let compiled = 0;
1777
+ for (const flag of flags) {
1778
+ switch (flag) {
1779
+ case "i":
1780
+ compiled |= import_re2js2.RE2JS.CASE_INSENSITIVE;
1781
+ break;
1782
+ case "m":
1783
+ compiled |= import_re2js2.RE2JS.MULTILINE;
1784
+ break;
1785
+ case "s":
1786
+ compiled |= import_re2js2.RE2JS.DOTALL;
1787
+ break;
1788
+ case "g":
1789
+ case "d":
1790
+ case "u":
1791
+ break;
1792
+ // irrelevant for RE2JS
1793
+ default:
1794
+ invalid();
1795
+ }
1796
+ }
1797
+ return compiled;
1798
+ }
1799
+ function normalizeCustomRule(definition) {
1800
+ if (typeof definition !== "object" || definition === null) invalid();
1801
+ const { id, name, category, severity, confidence } = definition;
1802
+ if (typeof id !== "string" || !ID_PATTERN.test(id)) invalid();
1803
+ if (typeof name !== "string" || name.length === 0 || name.length > 100) invalid();
1804
+ if (definition.description !== void 0) {
1805
+ if (typeof definition.description !== "string" || definition.description.length > 500)
1806
+ invalid();
1807
+ }
1808
+ if (!SECRET_CATEGORIES.includes(category)) invalid();
1809
+ if (!SEVERITIES.includes(severity)) invalid();
1810
+ if (!Number.isInteger(confidence) || confidence < 0 || confidence > 100) invalid();
1811
+ const maskPolicy = definition.maskPolicy ?? "full";
1812
+ if (!MASK_POLICIES.includes(maskPolicy)) invalid();
1813
+ if (maskPolicy === "placeholder") {
1814
+ if (typeof definition.placeholder !== "string" || !PLACEHOLDER_PATTERN.test(definition.placeholder)) {
1815
+ invalid();
1816
+ }
1817
+ }
1818
+ if (definition.secretGroup !== void 0) {
1819
+ if (!Number.isInteger(definition.secretGroup) || definition.secretGroup < 0 || definition.secretGroup > 20) {
1820
+ invalid();
1821
+ }
1822
+ }
1823
+ if (definition.keywords !== void 0) {
1824
+ if (!Array.isArray(definition.keywords) || definition.keywords.length > 32 || !definition.keywords.every((k) => typeof k === "string" && k.length > 0 && k.length <= 64)) {
1825
+ invalid();
1826
+ }
1827
+ }
1828
+ let source;
1829
+ let flags;
1830
+ if (definition.pattern instanceof RegExp) {
1831
+ source = definition.pattern.source;
1832
+ flags = definition.pattern.flags;
1833
+ } else if (typeof definition.pattern === "string") {
1834
+ source = definition.pattern;
1835
+ flags = definition.flags ?? "";
1836
+ if (typeof flags !== "string") invalid();
1837
+ } else {
1838
+ invalid();
1839
+ }
1840
+ if (source.length === 0 || source.length > MAX_PATTERN_LENGTH2) invalid();
1841
+ compileFlags(flags);
1842
+ return Object.freeze({
1843
+ id,
1844
+ name,
1845
+ ...definition.description !== void 0 ? { description: definition.description } : {},
1846
+ category,
1847
+ severity,
1848
+ pattern: source,
1849
+ flags: flags.replace(/[gdu]/g, ""),
1850
+ confidence,
1851
+ enabled: definition.enabled ?? true,
1852
+ ...definition.secretGroup !== void 0 ? { secretGroup: definition.secretGroup } : {},
1853
+ maskPolicy,
1854
+ ...definition.placeholder !== void 0 ? { placeholder: definition.placeholder } : {},
1855
+ ...definition.keywords !== void 0 ? { keywords: definition.keywords.map((k) => k.toLowerCase()) } : {}
1856
+ });
1857
+ }
1858
+ function compileCustomRule(definition) {
1859
+ let compiled;
1860
+ try {
1861
+ compiled = import_re2js2.RE2JS.compile(definition.pattern, compileFlags(definition.flags ?? ""));
1862
+ } catch {
1863
+ invalid();
1864
+ }
1865
+ const group = definition.secretGroup ?? 0;
1866
+ if (group > compiled.groupCount()) invalid();
1867
+ const base = {
1868
+ ruleId: definition.id,
1869
+ category: definition.category,
1870
+ severity: definition.severity,
1871
+ confidence: definition.confidence,
1872
+ maskPolicy: definition.maskPolicy ?? "full",
1873
+ ...definition.placeholder !== void 0 ? { placeholder: definition.placeholder } : {},
1874
+ propagate: true
1875
+ };
1876
+ return {
1877
+ id: definition.id,
1878
+ name: definition.name,
1879
+ category: definition.category,
1880
+ severity: definition.severity,
1881
+ baseConfidence: definition.confidence,
1882
+ maskPolicy: base.maskPolicy,
1883
+ ...definition.placeholder !== void 0 ? { placeholder: definition.placeholder } : {},
1884
+ ...definition.keywords !== void 0 ? { keywords: definition.keywords } : {},
1885
+ scan(input) {
1886
+ const candidates = [];
1887
+ const matcher = compiled.matcher(input);
1888
+ let count = 0;
1889
+ while (matcher.find() && count < MAX_MATCHES_PER_RULE) {
1890
+ count++;
1891
+ const start = matcher.start(group);
1892
+ const end = matcher.end(group);
1893
+ if (start < 0 || end <= start) continue;
1894
+ candidates.push({ ...base, start, end });
1895
+ }
1896
+ return candidates;
1897
+ }
1898
+ };
1899
+ }
1900
+
1901
+ // src/engine.ts
1902
+ var DEFAULT_MAX_INPUT_LENGTH = 5e6;
1903
+ var HARD_MAX_INPUT_LENGTH = 5e7;
1904
+ var ALLOWED_MASK_CHARS = /* @__PURE__ */ new Set(["*", "x", "X", "\u2022", "_", "-", "."]);
1905
+ var FINDING_KEYS = /* @__PURE__ */ new Set([
1906
+ "id",
1907
+ "ruleId",
1908
+ "category",
1909
+ "severity",
1910
+ "confidence",
1911
+ "confidenceLevel",
1912
+ "file",
1913
+ "line",
1914
+ "column",
1915
+ "endLine",
1916
+ "endColumn",
1917
+ "maskedValue"
1918
+ ]);
1919
+ function isBoolean(value) {
1920
+ return value === void 0 || typeof value === "boolean";
1921
+ }
1922
+ function resolveOptions(options = {}) {
1923
+ if (typeof options !== "object" || options === null) {
1924
+ throw new SecretShieldError("INVALID_OPTIONS");
1925
+ }
1926
+ const detection = options.detection ?? {};
1927
+ const minConfidence = detection.minConfidence ?? 40;
1928
+ const maskChar = options.masking?.maskChar ?? "*";
1929
+ const maskLength = options.masking?.maskLength ?? 8;
1930
+ const strategy = options.masking?.strategy ?? "partial";
1931
+ const maxInputLength = options.limits?.maxInputLength ?? DEFAULT_MAX_INPUT_LENGTH;
1932
+ const valid = isBoolean(detection.regex) && isBoolean(detection.ast) && isBoolean(detection.entropy) && isBoolean(detection.contextual) && Number.isFinite(minConfidence) && minConfidence >= 0 && minConfidence <= 100 && typeof maskChar === "string" && ALLOWED_MASK_CHARS.has(maskChar) && Number.isInteger(maskLength) && maskLength >= 4 && maskLength <= 64 && (strategy === "partial" || strategy === "full" || strategy === "token") && Number.isInteger(maxInputLength) && maxInputLength > 0 && maxInputLength <= HARD_MAX_INPUT_LENGTH;
1933
+ if (!valid) throw new SecretShieldError("INVALID_OPTIONS");
1934
+ return {
1935
+ regex: detection.regex ?? true,
1936
+ ast: detection.ast ?? true,
1937
+ entropy: detection.entropy ?? true,
1938
+ contextual: detection.contextual ?? true,
1939
+ minConfidence,
1940
+ masking: { strategy, maskChar, maskLength },
1941
+ maxInputLength
1942
+ };
1943
+ }
1944
+ function confidenceLevel(confidence) {
1945
+ if (confidence >= 90) return "very-high";
1946
+ if (confidence >= 70) return "high";
1947
+ if (confidence >= 40) return "suspicious";
1948
+ return "weak";
1949
+ }
1950
+ function summarize(items) {
1951
+ const summary = { total: items.length, critical: 0, high: 0, medium: 0, low: 0 };
1952
+ for (const item of items) summary[item.severity]++;
1953
+ return summary;
1954
+ }
1955
+ function addSummaries(target, source) {
1956
+ target.total += source.total;
1957
+ target.critical += source.critical;
1958
+ target.high += source.high;
1959
+ target.medium += source.medium;
1960
+ target.low += source.low;
1961
+ }
1962
+ function emptyResult(file, reason) {
1963
+ return {
1964
+ file,
1965
+ status: "not-scanned",
1966
+ ...reason !== void 0 ? { reason } : {},
1967
+ findings: [],
1968
+ summary: summarize([])
1969
+ };
1970
+ }
1971
+ function resolveMaxFileSize(options) {
1972
+ const size = options.maxFileSize ?? DEFAULT_MAX_FILE_SIZE;
1973
+ if (!Number.isInteger(size) || size <= 0 || size > HARD_MAX_FILE_SIZE) {
1974
+ throw new SecretShieldError("INVALID_OPTIONS");
1975
+ }
1976
+ return size;
1977
+ }
1978
+ var SecretShield = class {
1979
+ options;
1980
+ customRules = /* @__PURE__ */ new Map();
1981
+ disabledRules = /* @__PURE__ */ new Set();
1982
+ constructor(options) {
1983
+ this.options = resolveOptions(options);
1984
+ const ruleOptions = options?.rules;
1985
+ if (ruleOptions !== void 0) {
1986
+ if (typeof ruleOptions !== "object" || ruleOptions === null) {
1987
+ throw new SecretShieldError("INVALID_OPTIONS");
1988
+ }
1989
+ for (const definition of ruleOptions.custom ?? []) this.registerRule(definition);
1990
+ for (const id of ruleOptions.disabled ?? []) {
1991
+ if (typeof id !== "string") throw new SecretShieldError("INVALID_OPTIONS");
1992
+ this.disabledRules.add(id);
1993
+ }
1994
+ }
1995
+ }
1996
+ // -------------------------------------------------------------------------
1997
+ // Text
1998
+ // -------------------------------------------------------------------------
1999
+ /** Detects secrets without modifying the input. */
2000
+ scan(input, options = {}) {
2001
+ return this.guard(() => {
2002
+ const { findings } = this.process(input, options);
2003
+ return { findings, summary: summarize(findings) };
2004
+ });
2005
+ }
2006
+ /**
2007
+ * Detects and masks secrets. Formatting, quotes and non-sensitive values are
2008
+ * preserved. Fails closed: if the result cannot be verified, an error is
2009
+ * thrown and no text is returned.
2010
+ */
2011
+ redact(input, options = {}) {
2012
+ return this.guard(() => {
2013
+ const { findings, text } = this.process(input, options);
2014
+ return { text, findings, summary: summarize(findings) };
2015
+ });
2016
+ }
2017
+ /**
2018
+ * Protects a prompt intended for an LLM. Fenced code blocks (```ts, ```json,
2019
+ * ```yaml…) are analysed with the matching parser.
2020
+ */
2021
+ redactPrompt(prompt) {
2022
+ return this.redact(prompt, { language: "text" });
2023
+ }
2024
+ // -------------------------------------------------------------------------
2025
+ // Files and directories (read-only)
2026
+ // -------------------------------------------------------------------------
2027
+ async scanFile(filePath, options = {}) {
2028
+ const result = await this.redactFile(filePath, options);
2029
+ delete result.text;
2030
+ return result;
2031
+ }
2032
+ /** Returns a redacted version of a file. The file on disk is never modified. */
2033
+ async redactFile(filePath, options = {}) {
2034
+ if (typeof filePath !== "string" || filePath.length === 0) {
2035
+ throw new SecretShieldError("INVALID_INPUT");
2036
+ }
2037
+ const maxFileSize = resolveMaxFileSize(options);
2038
+ const outcome = await readTextFile(filePath, maxFileSize);
2039
+ if (!outcome.ok) return emptyResult(filePath, outcome.reason);
2040
+ return this.guard(() => {
2041
+ const language = options.language ?? detectLanguage(filePath);
2042
+ const { findings, text } = this.process(outcome.text, { file: filePath, language });
2043
+ return { file: filePath, status: "scanned", findings, summary: summarize(findings), text };
2044
+ });
2045
+ }
2046
+ /**
2047
+ * Scans a directory tree. Symbolic links are never followed, ignored and
2048
+ * unreadable paths are reported in `notScanned`.
2049
+ */
2050
+ async scanDirectory(root, options = {}) {
2051
+ if (typeof root !== "string" || root.length === 0) throw new SecretShieldError("INVALID_INPUT");
2052
+ const maxFileSize = resolveMaxFileSize(options);
2053
+ const maxFiles = options.maxFiles ?? 2e4;
2054
+ const maxDepth = options.maxDepth ?? 32;
2055
+ const concurrency = options.concurrency ?? 8;
2056
+ const ignore = options.ignore ?? [];
2057
+ if (!Number.isInteger(maxFiles) || maxFiles <= 0 || maxFiles > 1e6 || !Number.isInteger(maxDepth) || maxDepth < 0 || maxDepth > 256 || !Number.isInteger(concurrency) || concurrency < 1 || concurrency > 64 || !Array.isArray(ignore) || !ignore.every((p) => typeof p === "string")) {
2058
+ throw new SecretShieldError("INVALID_OPTIONS");
2059
+ }
2060
+ const walk = await walkDirectory(root, {
2061
+ useIgnoreFile: options.useIgnoreFile ?? true,
2062
+ ignore,
2063
+ maxFiles,
2064
+ maxDepth,
2065
+ signal: options.signal
2066
+ });
2067
+ const files = [];
2068
+ const notScanned = [...walk.notScanned];
2069
+ const summary = summarize([]);
2070
+ let scanned = 0;
2071
+ let next = 0;
2072
+ const worker = async () => {
2073
+ while (next < walk.files.length) {
2074
+ if (options.signal?.aborted) throw new SecretShieldError("ABORTED");
2075
+ const relative = walk.files[next++];
2076
+ const absolute = import_node_path2.default.join(walk.root, ...relative.split("/"));
2077
+ const outcome = await readTextFile(absolute, maxFileSize);
2078
+ if (!outcome.ok) {
2079
+ notScanned.push({ file: relative, reason: outcome.reason });
2080
+ } else {
2081
+ const language = options.language ?? detectLanguage(relative);
2082
+ let result;
2083
+ try {
2084
+ const { findings } = this.process(outcome.text, { file: relative, language });
2085
+ result = { file: relative, status: "scanned", findings, summary: summarize(findings) };
2086
+ } catch (error) {
2087
+ const safe = toSafeError(error);
2088
+ if (safe.code === "INPUT_TOO_LARGE") {
2089
+ notScanned.push({ file: relative, reason: "too-large" });
2090
+ continue;
2091
+ }
2092
+ throw safe;
2093
+ }
2094
+ scanned++;
2095
+ if (result.findings.length > 0) {
2096
+ files.push(result);
2097
+ addSummaries(summary, result.summary);
2098
+ }
2099
+ }
2100
+ options.onProgress?.({ scanned, notScanned: notScanned.length });
2101
+ }
2102
+ };
2103
+ try {
2104
+ await Promise.all(
2105
+ Array.from({ length: Math.min(concurrency, walk.files.length || 1) }, worker)
2106
+ );
2107
+ } catch (error) {
2108
+ throw toSafeError(error);
2109
+ }
2110
+ files.sort((a, b) => a.file < b.file ? -1 : a.file > b.file ? 1 : 0);
2111
+ notScanned.sort((a, b) => a.file < b.file ? -1 : a.file > b.file ? 1 : 0);
2112
+ return {
2113
+ root: walk.root,
2114
+ files,
2115
+ notScanned,
2116
+ scannedFiles: scanned,
2117
+ truncated: walk.truncated,
2118
+ summary
2119
+ };
2120
+ }
2121
+ // -------------------------------------------------------------------------
2122
+ // Objects
2123
+ // -------------------------------------------------------------------------
2124
+ /**
2125
+ * Returns a deep copy of `input` with sensitive values masked: values of
2126
+ * sensitive properties (`password`, `apiKey`…) and known secret formats in
2127
+ * any string. The input is never mutated.
2128
+ */
2129
+ redactObject(input) {
2130
+ return this.guard(() => {
2131
+ const masker = new Masker(this.options.masking);
2132
+ const findings = [];
2133
+ const context = this.extractContext();
2134
+ try {
2135
+ const value = redactObjectValue(input, {
2136
+ namedCandidate: (name, value2) => {
2137
+ if (value2.length > this.options.maxInputLength)
2138
+ throw new SecretShieldError("INPUT_TOO_LARGE");
2139
+ const candidate = assignedValueCandidate(
2140
+ name,
2141
+ value2,
2142
+ 0,
2143
+ BASE_CONFIDENCE.ast,
2144
+ "object-sensitive-property",
2145
+ context
2146
+ );
2147
+ return candidate && candidate.confidence >= this.options.minConfidence ? candidate : void 0;
2148
+ },
2149
+ mask: (value2, candidate) => masker.maskValue(value2, candidate),
2150
+ redactText: (value2) => this.process(value2, { language: "text" }, masker),
2151
+ onFinding: (candidate, findingPath, masked) => {
2152
+ findings.push({
2153
+ id: (0, import_node_crypto.randomUUID)(),
2154
+ ruleId: candidate.ruleId,
2155
+ category: candidate.category,
2156
+ severity: candidate.severity,
2157
+ confidence: candidate.confidence,
2158
+ confidenceLevel: confidenceLevel(candidate.confidence),
2159
+ path: findingPath,
2160
+ maskedValue: masked
2161
+ });
2162
+ }
2163
+ });
2164
+ return { value, findings, summary: summarize(findings) };
2165
+ } finally {
2166
+ masker.dispose();
2167
+ }
2168
+ });
2169
+ }
2170
+ // -------------------------------------------------------------------------
2171
+ // Rules
2172
+ // -------------------------------------------------------------------------
2173
+ /** Registers a custom rule (compiled with RE2: linear time, no ReDoS). */
2174
+ registerRule(definition) {
2175
+ const normalized = normalizeCustomRule(definition);
2176
+ if (this.customRules.has(normalized.id) || BUILTIN_RULES.some((r) => r.id === normalized.id)) {
2177
+ throw new SecretShieldError("DUPLICATE_RULE");
2178
+ }
2179
+ if (this.customRules.size >= MAX_CUSTOM_RULES) throw new SecretShieldError("TOO_MANY_RULES");
2180
+ const rule = compileCustomRule(normalized);
2181
+ this.customRules.set(normalized.id, { definition: normalized, rule });
2182
+ if (normalized.enabled === false) this.disabledRules.add(normalized.id);
2183
+ else this.disabledRules.delete(normalized.id);
2184
+ return this.ruleInfo(rule, "custom");
2185
+ }
2186
+ /** Removes a custom rule. Built-in rules cannot be removed, only disabled. */
2187
+ removeRule(id) {
2188
+ if (!this.customRules.delete(id)) throw new SecretShieldError("RULE_NOT_FOUND");
2189
+ this.disabledRules.delete(id);
2190
+ }
2191
+ /** Enables or disables a built-in or custom rule. */
2192
+ setRuleEnabled(id, enabled) {
2193
+ const exists = this.customRules.has(id) || BUILTIN_RULES.some((r) => r.id === id);
2194
+ if (!exists) throw new SecretShieldError("RULE_NOT_FOUND");
2195
+ if (enabled) this.disabledRules.delete(id);
2196
+ else this.disabledRules.add(id);
2197
+ }
2198
+ listRules() {
2199
+ return [
2200
+ ...BUILTIN_RULES.map((rule) => this.ruleInfo(rule, "builtin")),
2201
+ ...[...this.customRules.values()].map(({ rule }) => this.ruleInfo(rule, "custom"))
2202
+ ];
2203
+ }
2204
+ /**
2205
+ * Tests a rule definition against a sample without registering it. Only that
2206
+ * rule runs, so the result shows exactly what it would detect.
2207
+ */
2208
+ testRule(definition, sample) {
2209
+ return this.guard(() => {
2210
+ const rule = compileCustomRule(normalizeCustomRule({ ...definition, enabled: true }));
2211
+ const { findings, text } = this.process(sample, { language: "text" }, void 0, [rule]);
2212
+ return { text, findings, summary: summarize(findings) };
2213
+ });
2214
+ }
2215
+ // -------------------------------------------------------------------------
2216
+ // Reports and validation
2217
+ // -------------------------------------------------------------------------
2218
+ /** Generates a shareable report: no secret values, no masked values, no lengths. */
2219
+ generateReport(input, format = "json") {
2220
+ return this.guard(() => generateReport(input, format));
2221
+ }
2222
+ /**
2223
+ * Verifies a redaction result: re-scans the redacted text for residual
2224
+ * secrets and checks that findings carry only allowed fields.
2225
+ */
2226
+ validate(result) {
2227
+ return this.guard(() => {
2228
+ if (typeof result !== "object" || result === null || typeof result.text !== "string") {
2229
+ throw new SecretShieldError("INVALID_INPUT");
2230
+ }
2231
+ const issues = [];
2232
+ for (const finding of result.findings ?? []) {
2233
+ if (typeof finding !== "object" || finding === null) {
2234
+ issues.push({ code: "INVALID_FINDING" });
2235
+ continue;
2236
+ }
2237
+ if (Object.keys(finding).some((key) => !FINDING_KEYS.has(key))) {
2238
+ issues.push({ code: "UNEXPECTED_FINDING_FIELD", line: finding.line });
2239
+ }
2240
+ if (typeof finding.maskedValue !== "string" || !this.looksMasked(finding.maskedValue)) {
2241
+ issues.push({ code: "INVALID_FINDING", line: finding.line });
2242
+ }
2243
+ }
2244
+ const expected = summarize(result.findings ?? []);
2245
+ const actual = result.summary;
2246
+ if (!actual || actual.total !== expected.total || actual.critical !== expected.critical || actual.high !== expected.high || actual.medium !== expected.medium || actual.low !== expected.low) {
2247
+ issues.push({ code: "SUMMARY_MISMATCH" });
2248
+ }
2249
+ for (const residual of this.process(result.text, { language: "text" }).findings) {
2250
+ issues.push({ code: "RESIDUAL_SECRET", line: residual.line });
2251
+ }
2252
+ return { valid: issues.length === 0, issues };
2253
+ });
2254
+ }
2255
+ // -------------------------------------------------------------------------
2256
+ // Internals
2257
+ // -------------------------------------------------------------------------
2258
+ guard(operation) {
2259
+ try {
2260
+ return operation();
2261
+ } catch (error) {
2262
+ throw toSafeError(error);
2263
+ }
2264
+ }
2265
+ ruleInfo(rule, source) {
2266
+ return {
2267
+ id: rule.id,
2268
+ name: rule.name,
2269
+ category: rule.category,
2270
+ severity: rule.severity,
2271
+ source,
2272
+ enabled: !this.disabledRules.has(rule.id)
2273
+ };
2274
+ }
2275
+ extractContext() {
2276
+ return { entropy: this.options.entropy, contextual: this.options.contextual };
2277
+ }
2278
+ looksMasked(masked) {
2279
+ return isAlreadyRedacted(masked) || /^\[[A-Z0-9_:#-]{1,48}\]$/.test(masked) || /^"/.test(masked);
2280
+ }
2281
+ activeRules() {
2282
+ if (!this.options.regex) return [];
2283
+ const rules = [...BUILTIN_RULES, ...[...this.customRules.values()].map(({ rule }) => rule)];
2284
+ return rules.filter((rule) => !this.disabledRules.has(rule.id));
2285
+ }
2286
+ process(input, scanOptions, sharedMasker, rulesOverride) {
2287
+ if (typeof input !== "string") throw new SecretShieldError("INVALID_INPUT");
2288
+ if (input.length > this.options.maxInputLength) throw new SecretShieldError("INPUT_TOO_LARGE");
2289
+ if (typeof scanOptions !== "object" || scanOptions === null) {
2290
+ throw new SecretShieldError("INVALID_OPTIONS");
2291
+ }
2292
+ const context = this.extractContext();
2293
+ const language = scanOptions.language ?? detectLanguage(scanOptions.file);
2294
+ const ast = rulesOverride === void 0 && this.options.ast && this.options.contextual ? astCandidates(input, language, context) : void 0;
2295
+ const candidates = detect(input, rulesOverride ?? this.activeRules(), {
2296
+ ...context,
2297
+ minConfidence: this.options.minConfidence,
2298
+ ...ast ? { extra: ast.candidates, yamlPlainStarts: ast.yamlPlainStarts } : {}
2299
+ });
2300
+ const masker = sharedMasker ?? new Masker(this.options.masking);
2301
+ const lines = new LineIndex(input);
2302
+ const parts = [];
2303
+ const findings = [];
2304
+ const verify = /* @__PURE__ */ new Set();
2305
+ let cursor = 0;
2306
+ try {
2307
+ for (const candidate of candidates) {
2308
+ const value = input.slice(candidate.start, candidate.end);
2309
+ const masked = masker.maskValue(value, candidate);
2310
+ if (candidate.propagate && value.length >= MIN_PROPAGATION_LENGTH) verify.add(value);
2311
+ parts.push(input.slice(cursor, candidate.start), masked);
2312
+ cursor = candidate.end;
2313
+ const start = lines.position(candidate.start);
2314
+ const end = lines.position(candidate.end);
2315
+ findings.push({
2316
+ id: (0, import_node_crypto.randomUUID)(),
2317
+ ruleId: candidate.ruleId,
2318
+ category: candidate.category,
2319
+ severity: candidate.severity,
2320
+ confidence: candidate.confidence,
2321
+ confidenceLevel: confidenceLevel(candidate.confidence),
2322
+ ...scanOptions.file !== void 0 ? { file: scanOptions.file } : {},
2323
+ line: start.line,
2324
+ column: start.column,
2325
+ endLine: end.line,
2326
+ endColumn: end.column,
2327
+ maskedValue: masked
2328
+ });
2329
+ }
2330
+ parts.push(input.slice(cursor));
2331
+ const text = parts.join("");
2332
+ for (const value of verify) {
2333
+ if (text.includes(value)) throw new SecretShieldError("REDACTION_INCOMPLETE");
2334
+ }
2335
+ return { findings, text };
2336
+ } finally {
2337
+ if (!sharedMasker) masker.dispose();
2338
+ verify.clear();
2339
+ }
2340
+ }
2341
+ };
2342
+ // Annotate the CommonJS export names for ESM import in node:
2343
+ 0 && (module.exports = {
2344
+ DEFAULT_IGNORE_PATTERNS,
2345
+ IGNORE_FILE_NAME,
2346
+ SECRET_CATEGORIES,
2347
+ SEVERITIES,
2348
+ SecretShield,
2349
+ SecretShieldError,
2350
+ VERSION,
2351
+ detectLanguage,
2352
+ shannonEntropy
2353
+ });