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