prepublic 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +14 -0
- package/LICENSE +21 -0
- package/README.md +164 -2
- package/SECURITY.md +18 -0
- package/bin/prepublic.js +12 -0
- package/package.json +50 -4
- package/scripts/make-examples.mjs +200 -0
- package/src/checks/history.js +210 -0
- package/src/checks/project.js +351 -0
- package/src/checks/worktree.js +268 -0
- package/src/cli.js +203 -0
- package/src/config.js +59 -0
- package/src/findings.js +53 -0
- package/src/git.js +164 -0
- package/src/gitleaks.js +118 -0
- package/src/index.js +5 -0
- package/src/report/fonts/OFL.txt +192 -0
- package/src/report/fonts/ibm-plex-mono-latin-400.woff2 +0 -0
- package/src/report/fonts/ibm-plex-mono-latin-500.woff2 +0 -0
- package/src/report/fonts/ibm-plex-sans-latin-wght.woff2 +0 -0
- package/src/report/html.js +58 -0
- package/src/report/markdown.js +63 -0
- package/src/report/ui/app.js +590 -0
- package/src/report/ui/styles.css +356 -0
- package/src/report/ui/template.html +87 -0
- package/src/rules/files.js +78 -0
- package/src/rules/personal.js +76 -0
- package/src/rules/secrets.js +241 -0
- package/src/scan.js +221 -0
- package/src/version.js +2 -0
|
@@ -0,0 +1,241 @@
|
|
|
1
|
+
// Built-in secret detectors.
|
|
2
|
+
//
|
|
3
|
+
// These are deliberately conservative, high-signal formats. Prepublic is not a
|
|
4
|
+
// replacement for a dedicated secret scanner: when Gitleaks is installed it is
|
|
5
|
+
// used as a second, deeper engine. Raw values found here never leave memory;
|
|
6
|
+
// callers only receive a masked preview and the value's length.
|
|
7
|
+
|
|
8
|
+
const PLACEHOLDER_HINTS = [
|
|
9
|
+
'example', 'sample', 'placeholder', 'your_', 'your-', 'yourkey', 'xxxx', 'changeme', 'change_me',
|
|
10
|
+
'dummy', 'redacted', 'insert', 'replace', '<', '>', '${', '{{', '%(', '***', '…', '...', 'fake', 'notreal', 'not_real',
|
|
11
|
+
];
|
|
12
|
+
|
|
13
|
+
const WEAK_PASSWORD_WORDS = new Set([
|
|
14
|
+
'password', 'pass', 'passwd', 'secret', 'changeme', 'admin', 'root', 'postgres', 'mysql', 'user', 'username',
|
|
15
|
+
'test', 'guest', 'example', 'pwd', 'redis', 'rabbit', 'mongo', 'xxx', 'token',
|
|
16
|
+
]);
|
|
17
|
+
|
|
18
|
+
/** Shannon entropy in bits per character. */
|
|
19
|
+
export function entropy(value) {
|
|
20
|
+
if (!value) return 0;
|
|
21
|
+
const counts = new Map();
|
|
22
|
+
for (const ch of value) counts.set(ch, (counts.get(ch) || 0) + 1);
|
|
23
|
+
let h = 0;
|
|
24
|
+
for (const n of counts.values()) {
|
|
25
|
+
const p = n / value.length;
|
|
26
|
+
h -= p * Math.log2(p);
|
|
27
|
+
}
|
|
28
|
+
return h;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
export function looksLikePlaceholder(value) {
|
|
32
|
+
const v = value.toLowerCase();
|
|
33
|
+
if (PLACEHOLDER_HINTS.some((hint) => v.includes(hint))) return true;
|
|
34
|
+
if (/^(.)\1+$/.test(v)) return true; // aaaaaaa, 0000000
|
|
35
|
+
if (/^[x*•.\-_0]+$/i.test(v)) return true;
|
|
36
|
+
if (/^(abc|123|abcd|1234|qwerty)/.test(v) && entropy(v) < 3.2) return true;
|
|
37
|
+
return false;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
const LOCAL_HOST = /@(localhost|127\.0\.0\.1|0\.0\.0\.0|\[::1\]|db|database|postgres|mysql|redis|mongo|rabbitmq|host\.docker\.internal)(?=[:/]|$)/i;
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Each rule: id, title, severity, confidence, regex (global), group (capture
|
|
44
|
+
* index holding the secret), keywords (lowercase prefilter), prefix (number of
|
|
45
|
+
* leading characters that are a public format marker and may be shown).
|
|
46
|
+
*/
|
|
47
|
+
export const SECRET_RULES = [
|
|
48
|
+
{
|
|
49
|
+
id: 'private-key', title: 'Private key block', severity: 'critical', confidence: 'high',
|
|
50
|
+
re: /-----BEGIN ((?:RSA |DSA |EC |OPENSSH |PGP |ENCRYPTED )?PRIVATE KEY(?: BLOCK)?)-----/g,
|
|
51
|
+
group: 0, keywords: ['private key'], prefix: 0, describeValue: () => 'private key header',
|
|
52
|
+
},
|
|
53
|
+
{
|
|
54
|
+
id: 'aws-access-key-id', title: 'AWS access key ID', severity: 'critical', confidence: 'high',
|
|
55
|
+
re: /\b((?:AKIA|ASIA|ABIA|ACCA)[A-Z0-9]{16})\b/g, group: 1, keywords: ['akia', 'asia', 'abia', 'acca'], prefix: 4,
|
|
56
|
+
},
|
|
57
|
+
{
|
|
58
|
+
id: 'aws-secret-access-key', title: 'AWS secret access key', severity: 'critical', confidence: 'medium',
|
|
59
|
+
re: /aws.{0,64}?(?:secret|sk)[a-z_\-]{0,24}["']?\s*[:=]\s*["']?([A-Za-z0-9/+=]{40})(?![A-Za-z0-9/+=])/gi,
|
|
60
|
+
group: 1, keywords: ['aws'], prefix: 0, minEntropy: 3.5,
|
|
61
|
+
},
|
|
62
|
+
{
|
|
63
|
+
id: 'github-token', title: 'GitHub token', severity: 'critical', confidence: 'high',
|
|
64
|
+
re: /\b((?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{36,255})\b/g, group: 1, keywords: ['ghp_', 'gho_', 'ghu_', 'ghs_', 'ghr_'], prefix: 4,
|
|
65
|
+
},
|
|
66
|
+
{
|
|
67
|
+
id: 'github-fine-grained-token', title: 'GitHub fine-grained token', severity: 'critical', confidence: 'high',
|
|
68
|
+
re: /\b(github_pat_[A-Za-z0-9_]{60,255})\b/g, group: 1, keywords: ['github_pat_'], prefix: 11,
|
|
69
|
+
},
|
|
70
|
+
{
|
|
71
|
+
id: 'gitlab-token', title: 'GitLab personal access token', severity: 'critical', confidence: 'high',
|
|
72
|
+
re: /\b(glpat-[A-Za-z0-9_-]{20,})\b/g, group: 1, keywords: ['glpat-'], prefix: 6,
|
|
73
|
+
},
|
|
74
|
+
{
|
|
75
|
+
id: 'slack-token', title: 'Slack token', severity: 'critical', confidence: 'high',
|
|
76
|
+
re: /\b(xox[abprs]-[A-Za-z0-9-]{10,})\b/g, group: 1, keywords: ['xox'], prefix: 5,
|
|
77
|
+
},
|
|
78
|
+
{
|
|
79
|
+
id: 'slack-webhook', title: 'Slack incoming webhook URL', severity: 'high', confidence: 'high',
|
|
80
|
+
re: /(https:\/\/hooks\.slack\.com\/services\/T[A-Z0-9]+\/B[A-Z0-9]+\/[A-Za-z0-9]{16,})/g, group: 1, keywords: ['hooks.slack.com'], prefix: 32,
|
|
81
|
+
},
|
|
82
|
+
{
|
|
83
|
+
id: 'discord-webhook', title: 'Discord webhook URL', severity: 'high', confidence: 'high',
|
|
84
|
+
re: /(https:\/\/(?:ptb\.|canary\.)?discord(?:app)?\.com\/api\/webhooks\/\d+\/[A-Za-z0-9_-]{20,})/g, group: 1, keywords: ['/api/webhooks/'], prefix: 0,
|
|
85
|
+
},
|
|
86
|
+
{
|
|
87
|
+
id: 'stripe-secret-key', title: 'Stripe live secret key', severity: 'critical', confidence: 'high',
|
|
88
|
+
re: /\b((?:sk|rk)_live_[A-Za-z0-9]{20,})\b/g, group: 1, keywords: ['_live_'], prefix: 8,
|
|
89
|
+
},
|
|
90
|
+
{
|
|
91
|
+
id: 'google-api-key', title: 'Google API key', severity: 'high', confidence: 'high',
|
|
92
|
+
re: /\b(AIza[0-9A-Za-z_-]{35})(?![0-9A-Za-z_-])/g, group: 1, keywords: ['aiza'], prefix: 4,
|
|
93
|
+
},
|
|
94
|
+
{
|
|
95
|
+
id: 'openai-api-key', title: 'OpenAI API key', severity: 'critical', confidence: 'high',
|
|
96
|
+
re: /\b(sk-(?:(?:proj|svcacct|admin)-[A-Za-z0-9_-]{40,}|[A-Za-z0-9]{20}T3BlbkFJ[A-Za-z0-9]{20}))(?![A-Za-z0-9_-])/g,
|
|
97
|
+
group: 1, keywords: ['sk-'], prefix: 3,
|
|
98
|
+
},
|
|
99
|
+
{
|
|
100
|
+
id: 'anthropic-api-key', title: 'Anthropic API key', severity: 'critical', confidence: 'high',
|
|
101
|
+
re: /\b(sk-ant-(?:api|admin)\d{2}-[A-Za-z0-9_-]{80,})(?![A-Za-z0-9_-])/g, group: 1, keywords: ['sk-ant-'], prefix: 7,
|
|
102
|
+
},
|
|
103
|
+
{
|
|
104
|
+
id: 'npm-token', title: 'npm access token', severity: 'critical', confidence: 'high',
|
|
105
|
+
re: /\b(npm_[A-Za-z0-9]{36})\b/g, group: 1, keywords: ['npm_'], prefix: 4,
|
|
106
|
+
},
|
|
107
|
+
{
|
|
108
|
+
id: 'pypi-token', title: 'PyPI upload token', severity: 'critical', confidence: 'high',
|
|
109
|
+
re: /\b(pypi-AgEIcHlwaS5vcmc[A-Za-z0-9_-]{50,})/g, group: 1, keywords: ['pypi-'], prefix: 5,
|
|
110
|
+
},
|
|
111
|
+
{
|
|
112
|
+
id: 'sendgrid-api-key', title: 'SendGrid API key', severity: 'high', confidence: 'high',
|
|
113
|
+
re: /\b(SG\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43})(?![A-Za-z0-9_-])/g, group: 1, keywords: ['sg.'], prefix: 3,
|
|
114
|
+
},
|
|
115
|
+
{
|
|
116
|
+
id: 'telegram-bot-token', title: 'Telegram bot token', severity: 'high', confidence: 'medium',
|
|
117
|
+
re: /\b(\d{8,10}:AA[A-Za-z0-9_-]{33})(?![A-Za-z0-9_-])/g, group: 1, keywords: [':aa'], prefix: 0,
|
|
118
|
+
},
|
|
119
|
+
{
|
|
120
|
+
id: 'azure-storage-key', title: 'Azure storage account key', severity: 'critical', confidence: 'high',
|
|
121
|
+
re: /AccountKey=([A-Za-z0-9+/]{86}==)/g, group: 1, keywords: ['accountkey='], prefix: 0,
|
|
122
|
+
},
|
|
123
|
+
{
|
|
124
|
+
id: 'jwt', title: 'JSON Web Token', severity: 'medium', confidence: 'medium',
|
|
125
|
+
re: /\b(eyJ[A-Za-z0-9_-]{10,}\.eyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{16,})(?![A-Za-z0-9_-])/g, group: 1, keywords: ['eyj'], prefix: 3,
|
|
126
|
+
},
|
|
127
|
+
{
|
|
128
|
+
id: 'connection-string-password', title: 'Database or broker URL with password', severity: 'high', confidence: 'medium',
|
|
129
|
+
re: /\b((?:postgres(?:ql)?|mysql|mariadb|mongodb(?:\+srv)?|redis|rediss|amqps?|mssql|sqlserver):\/\/[^\s:@/'"`]+:([^\s@/'"`]{3,})@[^\s'"`]+)/gi,
|
|
130
|
+
group: 2, keywords: ['://'], prefix: 0, contextual: true,
|
|
131
|
+
},
|
|
132
|
+
{
|
|
133
|
+
id: 'url-basic-auth', title: 'URL with embedded credentials', severity: 'high', confidence: 'medium',
|
|
134
|
+
re: /\b(https?:\/\/[^\s:@/'"`]+:([^\s@/'"`]{6,})@[^\s'"`]+)/gi, group: 2, keywords: ['://'], prefix: 0, contextual: true,
|
|
135
|
+
},
|
|
136
|
+
{
|
|
137
|
+
id: 'generic-secret', title: 'Hard-coded secret assignment', severity: 'medium', confidence: 'medium',
|
|
138
|
+
re: /\b([A-Za-z0-9_.-]*(?:password|passwd|secret|api[_-]?key|apikey|access[_-]?token|auth[_-]?token|client[_-]?secret|private[_-]?key|token)[A-Za-z0-9_.-]*)["']?\s*(?:[:=]|=>|:=)\s*["'`]([^"'`\s]{8,200})["'`]/gi,
|
|
139
|
+
group: 2, keywords: ['pass', 'secret', 'key', 'token'], prefix: 0, minEntropy: 3.0, generic: true,
|
|
140
|
+
},
|
|
141
|
+
];
|
|
142
|
+
|
|
143
|
+
const RULE_BY_ID = new Map(SECRET_RULES.map((r) => [r.id, r]));
|
|
144
|
+
export const getSecretRule = (id) => RULE_BY_ID.get(id);
|
|
145
|
+
|
|
146
|
+
/** Mask a secret value: public format prefix + bullets + length. */
|
|
147
|
+
export function maskValue(rule, value) {
|
|
148
|
+
if (rule.describeValue) return rule.describeValue(value);
|
|
149
|
+
const keep = Math.min(rule.prefix || 0, Math.max(0, value.length - 8));
|
|
150
|
+
return `${value.slice(0, keep)}${'•'.repeat(8)} (${value.length} chars)`;
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/**
|
|
154
|
+
* Find secrets in a single line of text.
|
|
155
|
+
* @returns {{rule: object, value: string, index: number, severity: string}[]}
|
|
156
|
+
*/
|
|
157
|
+
export function findSecretsInLine(line, { path = '' } = {}) {
|
|
158
|
+
if (line.length > 20000) return [];
|
|
159
|
+
const lower = line.toLowerCase();
|
|
160
|
+
if (lower.includes('prepublic:allow') || lower.includes('gitleaks:allow')) return [];
|
|
161
|
+
const hits = [];
|
|
162
|
+
const taken = [];
|
|
163
|
+
for (const rule of SECRET_RULES) {
|
|
164
|
+
if (!rule.keywords.some((k) => lower.includes(k))) continue;
|
|
165
|
+
rule.re.lastIndex = 0;
|
|
166
|
+
let m;
|
|
167
|
+
while ((m = rule.re.exec(line)) !== null) {
|
|
168
|
+
if (m[0].length === 0) { rule.re.lastIndex++; continue; }
|
|
169
|
+
const value = m[rule.group] ?? m[0];
|
|
170
|
+
const index = m.index + m[0].indexOf(value);
|
|
171
|
+
// Skip overlaps with an earlier, more specific rule.
|
|
172
|
+
if (taken.some(([s, e]) => index < e && index + value.length > s)) continue;
|
|
173
|
+
const verdict = evaluate(rule, value, m, line, path);
|
|
174
|
+
if (!verdict) continue;
|
|
175
|
+
taken.push([index, index + value.length]);
|
|
176
|
+
hits.push({ rule, value, index, severity: verdict.severity, confidence: verdict.confidence });
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
return hits;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function evaluate(rule, value, match, line, path) {
|
|
183
|
+
let severity = rule.severity;
|
|
184
|
+
let confidence = rule.confidence;
|
|
185
|
+
if (rule.id !== 'private-key' && looksLikePlaceholder(value)) return null;
|
|
186
|
+
if (rule.minEntropy && entropy(value) < rule.minEntropy) return null;
|
|
187
|
+
if (rule.contextual) {
|
|
188
|
+
const word = value.toLowerCase();
|
|
189
|
+
if (WEAK_PASSWORD_WORDS.has(word) || looksLikePlaceholder(word)) return null;
|
|
190
|
+
if (LOCAL_HOST.test(match[1])) {
|
|
191
|
+
severity = 'low';
|
|
192
|
+
confidence = 'low';
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
if (rule.generic) {
|
|
196
|
+
const name = match[1].toLowerCase();
|
|
197
|
+
if (/^(true|false|null|none|undefined)$/i.test(value)) return null;
|
|
198
|
+
// Values that are code references, not literals.
|
|
199
|
+
if (/^(process\.env|os\.environ|env\(|getenv|config\.|settings\.)/i.test(value)) return null;
|
|
200
|
+
if (/(_file|_path|_url|_name|_header|_field|_length|_type|_env|_var)$/.test(name)) return null;
|
|
201
|
+
if (/^[a-z]+([A-Z][a-z]+)+$/.test(value)) return null; // camelCase identifiers
|
|
202
|
+
if (/^[\w.-]+\.(json|ya?ml|txt|pem|key|env)$/i.test(value)) return null;
|
|
203
|
+
if (name.includes('token') && !/(access|auth|api|secret|bearer|refresh|bot)/.test(name) && entropy(value) < 3.8) return null;
|
|
204
|
+
}
|
|
205
|
+
if (isLikelyFixturePath(path) && severity !== 'low') {
|
|
206
|
+
confidence = confidence === 'high' ? 'medium' : 'low';
|
|
207
|
+
}
|
|
208
|
+
return { severity, confidence };
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
export function isLikelyFixturePath(path) {
|
|
212
|
+
return /(^|\/)(tests?|__tests__|spec|fixtures?|testdata|examples?|samples?|mocks?|docs?)\//i.test(path)
|
|
213
|
+
|| /\.(test|spec)\.[a-z]+$/i.test(path);
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Replace every detected secret on a line with a marker and clip it so that
|
|
218
|
+
* evidence can be shown safely.
|
|
219
|
+
*/
|
|
220
|
+
export function redactLine(line, hits, maxLength = 160) {
|
|
221
|
+
let out = line;
|
|
222
|
+
// Replace from the right so indexes stay valid.
|
|
223
|
+
const sorted = [...hits].sort((a, b) => b.index - a.index);
|
|
224
|
+
for (const h of sorted) {
|
|
225
|
+
if (h.rule.id === 'private-key') continue; // header line is not secret
|
|
226
|
+
out = out.slice(0, h.index) + `‹redacted:${h.rule.id}›` + out.slice(h.index + h.value.length);
|
|
227
|
+
}
|
|
228
|
+
// Second pass: anything that still looks like a secret is removed too.
|
|
229
|
+
const again = findSecretsInLine(out);
|
|
230
|
+
for (const h of again.sort((a, b) => b.index - a.index)) {
|
|
231
|
+
if (h.rule.id === 'private-key') continue;
|
|
232
|
+
out = out.slice(0, h.index) + `‹redacted:${h.rule.id}›` + out.slice(h.index + h.value.length);
|
|
233
|
+
}
|
|
234
|
+
out = out.trim();
|
|
235
|
+
if (out.length > maxLength) {
|
|
236
|
+
const first = out.indexOf('‹redacted');
|
|
237
|
+
const start = Math.max(0, Math.min(first === -1 ? 0 : first - 40, out.length - maxLength));
|
|
238
|
+
out = (start > 0 ? '…' : '') + out.slice(start, start + maxLength) + (start + maxLength < out.length ? '…' : '');
|
|
239
|
+
}
|
|
240
|
+
return out;
|
|
241
|
+
}
|
package/src/scan.js
ADDED
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
// Orchestrates a read-only scan and builds the report model.
|
|
2
|
+
|
|
3
|
+
import { basename } from 'node:path';
|
|
4
|
+
import { gitText, gitNulList, resolveRepo } from './git.js';
|
|
5
|
+
import { loadConfig, makePathFilter, CONFIG_FILE } from './config.js';
|
|
6
|
+
import { scanWorktree } from './checks/worktree.js';
|
|
7
|
+
import { scanHistory } from './checks/history.js';
|
|
8
|
+
import { scanProject } from './checks/project.js';
|
|
9
|
+
import { runGitleaks, gitleaksFindings } from './gitleaks.js';
|
|
10
|
+
import { SEVERITIES, SEVERITY_RANK, CATEGORIES, sortFindings } from './findings.js';
|
|
11
|
+
import { findSecretsInLine, redactLine } from './rules/secrets.js';
|
|
12
|
+
import { maskPersonalPaths } from './rules/personal.js';
|
|
13
|
+
import { VERSION } from './version.js';
|
|
14
|
+
|
|
15
|
+
export const DEFAULTS = {
|
|
16
|
+
history: true,
|
|
17
|
+
gitleaks: 'auto',
|
|
18
|
+
gitleaksCommand: null,
|
|
19
|
+
maxFileBytes: 2 * 1024 * 1024,
|
|
20
|
+
maxHistoryBytes: 512 * 1024 * 1024,
|
|
21
|
+
snippets: true,
|
|
22
|
+
};
|
|
23
|
+
|
|
24
|
+
const PENALTY = { critical: 30, high: 15, medium: 6, low: 2, info: 0 };
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Scan a repository. Never writes to the repository.
|
|
28
|
+
* @param {string} dir any directory inside the repository
|
|
29
|
+
* @param {Partial<typeof DEFAULTS>} options
|
|
30
|
+
*/
|
|
31
|
+
export async function scanRepository(dir, options = {}) {
|
|
32
|
+
const opts = { ...DEFAULTS, ...options };
|
|
33
|
+
const started = Date.now();
|
|
34
|
+
const root = await resolveRepo(dir);
|
|
35
|
+
const config = await loadConfig(root);
|
|
36
|
+
const isIgnoredPath = makePathFilter(config.ignorePaths);
|
|
37
|
+
|
|
38
|
+
const tracked = await gitNulList(['ls-files', '-z', '--cached'], { cwd: root });
|
|
39
|
+
const untracked = await gitNulList(['ls-files', '-z', '--others', '--exclude-standard'], { cwd: root });
|
|
40
|
+
const modified = await gitNulList(['ls-files', '-z', '--modified'], { cwd: root });
|
|
41
|
+
const headShort = (await gitText(['rev-parse', '--short', '--verify', '-q', 'HEAD'], { cwd: root, allowFailure: true })).trim() || null;
|
|
42
|
+
const branch = (await gitText(['symbolic-ref', '--short', '-q', 'HEAD'], { cwd: root, allowFailure: true })).trim() || (headShort ? 'detached HEAD' : null);
|
|
43
|
+
|
|
44
|
+
const findings = [];
|
|
45
|
+
const suppressed = { paths: 0, rules: 0, lines: 0 };
|
|
46
|
+
const ctx = {
|
|
47
|
+
root, opts, config, tracked, trackedSet: new Set(tracked), untracked, modified, isIgnoredPath, suppressed,
|
|
48
|
+
worktreeSecrets: new Map(), historyPaths: new Set(), facts: {},
|
|
49
|
+
coverage: {
|
|
50
|
+
worktree: { tracked: tracked.length, files: 0, textFiles: 0, bytes: 0, binary: 0, skippedLarge: 0, symlinks: 0, missing: 0, untracked: 0, maxFileBytes: opts.maxFileBytes },
|
|
51
|
+
history: { enabled: false, commits: 0, commitsScanned: 0, refs: 0, patchBytes: 0, truncated: false, authorEmails: 0, maxBytes: opts.maxHistoryBytes },
|
|
52
|
+
gitleaks: null,
|
|
53
|
+
},
|
|
54
|
+
add(f) {
|
|
55
|
+
if (config.ignoreRules.some((r) => r === f.ruleId || (r.endsWith('*') && f.ruleId.startsWith(r.slice(0, -1))))) {
|
|
56
|
+
suppressed.rules++;
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
findings.push(f);
|
|
60
|
+
return f;
|
|
61
|
+
},
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
await scanWorktree(ctx);
|
|
65
|
+
if (opts.history && headShort) await scanHistory(ctx);
|
|
66
|
+
await scanProject(ctx);
|
|
67
|
+
|
|
68
|
+
const gl = await runGitleaks(root, { mode: opts.gitleaks, command: opts.gitleaksCommand || undefined });
|
|
69
|
+
ctx.coverage.gitleaks = gl.status;
|
|
70
|
+
if (gl.results.length) {
|
|
71
|
+
const glFindings = gitleaksFindings(gl.results.filter((r) => !isIgnoredPath(r.file)), { trackedSet: ctx.trackedSet, root });
|
|
72
|
+
// Note overlap with built-in detections instead of duplicating noise.
|
|
73
|
+
for (const f of glFindings) {
|
|
74
|
+
const overlap = findings.find((b) => b.source === 'builtin' && (b.category === 'secrets' || b.category === 'history')
|
|
75
|
+
&& b.locations.some((l) => f.locations.some((g) => g.path === l.path && (g.line === l.line || (g.commit && g.commit === l.commit)))));
|
|
76
|
+
if (overlap) {
|
|
77
|
+
overlap.confirmedBy = 'gitleaks';
|
|
78
|
+
continue;
|
|
79
|
+
}
|
|
80
|
+
ctx.add(f);
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
if (opts.gitleaks === 'require' && !gl.status.ran) {
|
|
84
|
+
throw new Error(`Gitleaks is required (--gitleaks require) but ${gl.status.error || 'did not run'}.`);
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
const report = buildReport({ ctx, findings: sortFindings(findings), root, branch, headShort, durationMs: Date.now() - started });
|
|
88
|
+
return sanitizeReport(report, root);
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
function buildReport({ ctx, findings, root, branch, headShort, durationMs }) {
|
|
92
|
+
const counts = Object.fromEntries(SEVERITIES.map((s) => [s, 0]));
|
|
93
|
+
for (const f of findings) counts[f.severity]++;
|
|
94
|
+
const byCategory = Object.fromEntries(Object.keys(CATEGORIES).map((c) => [c, findings.filter((f) => f.category === c).length]));
|
|
95
|
+
const blockers = counts.critical + counts.high;
|
|
96
|
+
const toReview = counts.medium;
|
|
97
|
+
const score = Math.max(0, Math.round(100 - findings.reduce((s, f) => s + PENALTY[f.severity], 0)));
|
|
98
|
+
const level = blockers ? 'blocked' : toReview ? 'review' : 'clear';
|
|
99
|
+
const verdict = {
|
|
100
|
+
level,
|
|
101
|
+
label: { blocked: 'Not ready to publish', review: 'Review before publishing', clear: 'No blockers detected' }[level],
|
|
102
|
+
blockers, toReview,
|
|
103
|
+
note: 'Automated checks reduce risk; they cannot prove that a repository is safe to publish.',
|
|
104
|
+
};
|
|
105
|
+
|
|
106
|
+
return {
|
|
107
|
+
schema: 'prepublic/report@1',
|
|
108
|
+
tool: { name: 'Prepublic', version: VERSION },
|
|
109
|
+
generatedAt: new Date().toISOString(),
|
|
110
|
+
durationMs,
|
|
111
|
+
repo: {
|
|
112
|
+
name: basename(root),
|
|
113
|
+
branch,
|
|
114
|
+
head: headShort,
|
|
115
|
+
trackedFiles: ctx.tracked.length,
|
|
116
|
+
ecosystems: ctx.facts.ecosystems || [],
|
|
117
|
+
license: ctx.facts.licenseId || null,
|
|
118
|
+
},
|
|
119
|
+
verdict, score, counts, byCategory,
|
|
120
|
+
categories: CATEGORIES,
|
|
121
|
+
findings,
|
|
122
|
+
checklist: buildChecklist(ctx, findings),
|
|
123
|
+
coverage: ctx.coverage,
|
|
124
|
+
limitations: buildLimitations(ctx),
|
|
125
|
+
suppressed: { ...ctx.suppressed, config: ctx.config.source, configError: ctx.config.error },
|
|
126
|
+
options: { history: ctx.opts.history, gitleaks: ctx.opts.gitleaks, snippets: ctx.opts.snippets },
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function buildChecklist(ctx, findings) {
|
|
131
|
+
const any = (pred) => findings.filter(pred);
|
|
132
|
+
const worst = (list) => list.reduce((w, f) => Math.min(w, SEVERITY_RANK[f.severity]), 99);
|
|
133
|
+
const status = (list, failAt = 1) => (!list.length ? 'pass' : worst(list) <= failAt ? 'fail' : 'warn');
|
|
134
|
+
const ids = (prefix) => (f) => f.ruleId.startsWith(prefix);
|
|
135
|
+
const items = [];
|
|
136
|
+
const push = (id, label, st, detail, related = []) => items.push({ id, label, status: st, detail, related });
|
|
137
|
+
|
|
138
|
+
const sec = any((f) => f.category === 'secrets');
|
|
139
|
+
push('secrets', 'No secrets in the files you will publish', status(sec), sec.length ? `${sec.length} finding${sec.length > 1 ? 's' : ''}` : 'Built-in rules found nothing', sec.map((f) => f.id));
|
|
140
|
+
|
|
141
|
+
const hist = any((f) => f.category === 'history' && f.ruleId !== 'history-large-blob');
|
|
142
|
+
const h = ctx.coverage.history;
|
|
143
|
+
if (!h.enabled) push('history', 'No secrets or sensitive files in Git history', 'skipped', ctx.opts.history ? 'Repository has no commits yet' : 'History scan disabled (--no-history)');
|
|
144
|
+
else push('history', 'No secrets or sensitive files in Git history', hist.length ? status(hist) : h.truncated ? 'warn' : 'pass',
|
|
145
|
+
hist.length ? `${hist.length} finding${hist.length > 1 ? 's' : ''} across ${h.commits} commit${h.commits === 1 ? '' : 's'}` : h.truncated ? `Scan stopped after ${Math.round(h.patchBytes / 1048576)} MB of patches` : `${h.commitsScanned} commit${h.commitsScanned === 1 ? '' : 's'} on ${h.refs} ref${h.refs === 1 ? '' : 's'} scanned`, hist.map((f) => f.id));
|
|
146
|
+
|
|
147
|
+
const gl = ctx.coverage.gitleaks;
|
|
148
|
+
const glF = any((f) => f.source === 'gitleaks');
|
|
149
|
+
if (gl?.ran) push('gitleaks', 'Deep secret scan with Gitleaks', glF.length ? 'fail' : 'pass', `Gitleaks ${gl.version}: ${gl.findings} raw match${gl.findings === 1 ? '' : 'es'}`, glF.map((f) => f.id));
|
|
150
|
+
else push('gitleaks', 'Deep secret scan with Gitleaks', 'skipped', gl?.mode === 'off' ? 'Disabled (--gitleaks off)' : `Gitleaks ${gl?.error || 'not available'}. Install it for a broader rule set.`);
|
|
151
|
+
|
|
152
|
+
const files = any((f) => f.category === 'files');
|
|
153
|
+
push('files', 'No sensitive files tracked or left unignored', status(files), files.length ? `${files.length} finding${files.length > 1 ? 's' : ''}` : 'Nothing matched', files.map((f) => f.id));
|
|
154
|
+
|
|
155
|
+
const priv = any((f) => f.category === 'privacy' && f.ruleId !== 'author-emails');
|
|
156
|
+
push('privacy', 'No personal paths or internal references', priv.length ? 'warn' : 'pass', priv.length ? `${priv.length} finding${priv.length > 1 ? 's' : ''} to review` : 'Nothing matched', priv.map((f) => f.id));
|
|
157
|
+
|
|
158
|
+
const emails = any(ids('author-emails'));
|
|
159
|
+
push('emails', 'Commit emails are OK to publish', emails.length ? 'manual' : h.enabled ? 'pass' : 'skipped', emails.length ? 'Review the listed addresses' : h.enabled ? 'Only noreply addresses found' : 'Requires history scan', emails.map((f) => f.id));
|
|
160
|
+
|
|
161
|
+
const gi = any((f) => f.ruleId.startsWith('gitignore'));
|
|
162
|
+
push('gitignore', '.gitignore covers secrets and build output', gi.length ? status(gi, 1) : 'pass', gi.length ? gi.map((f) => f.title).join('; ') : 'Common patterns covered', gi.map((f) => f.id));
|
|
163
|
+
|
|
164
|
+
const readme = any(ids('readme'));
|
|
165
|
+
push('readme', 'README explains what, why and how', readme.some((f) => f.ruleId === 'readme-missing') ? 'fail' : readme.length ? 'warn' : 'pass', readme.length ? readme.map((f) => f.title).join('; ') : ctx.facts.readme, readme.map((f) => f.id));
|
|
166
|
+
|
|
167
|
+
const lic = any(ids('license'));
|
|
168
|
+
push('license', 'A license is present and consistent', lic.some((f) => f.ruleId === 'license-missing') ? 'fail' : lic.length ? 'warn' : 'pass', lic.length ? lic.map((f) => f.title).join('; ') : `${ctx.facts.licenseId || 'License'} in ${ctx.facts.license}`, lic.map((f) => f.id));
|
|
169
|
+
|
|
170
|
+
const comm = any((f) => ['contributing-missing', 'security-policy-missing'].includes(f.ruleId));
|
|
171
|
+
push('community', 'Contribution guide and security policy', comm.length ? 'warn' : 'pass', comm.length ? comm.map((f) => f.title).join('; ') : 'CONTRIBUTING and SECURITY present', comm.map((f) => f.id));
|
|
172
|
+
|
|
173
|
+
push('tests', 'Automated tests are present', ctx.facts.tests ? 'pass' : 'warn', ctx.facts.tests ? `${ctx.facts.tests} test file${ctx.facts.tests > 1 ? 's' : ''} detected` : 'No tests detected');
|
|
174
|
+
|
|
175
|
+
const everSecret = any((f) => f.category === 'secrets' || f.category === 'history');
|
|
176
|
+
if (everSecret.length) push('rotate', 'Rotate every credential that was ever committed', 'manual', 'Removing a secret does not un-leak it. Rotate first, then clean up.');
|
|
177
|
+
push('outside', 'Review what this scan cannot see', 'manual', 'Issues, pull requests, wiki, CI logs, release assets, packages, container images and remote-only branches.');
|
|
178
|
+
push('rights', 'Confirm you have the right to publish', 'manual', 'Employer or client ownership, third-party code and assets, dependency licences.');
|
|
179
|
+
return items;
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function buildLimitations(ctx) {
|
|
183
|
+
const w = ctx.coverage.worktree;
|
|
184
|
+
const h = ctx.coverage.history;
|
|
185
|
+
const gl = ctx.coverage.gitleaks;
|
|
186
|
+
const out = [
|
|
187
|
+
'Detection is pattern-based. Unknown token formats, encoded, split or low-entropy secrets can be missed, and some findings will be false positives.',
|
|
188
|
+
'Only tracked files (their working-tree versions) and history on local refs are inspected. Remote-only branches, pull requests, issues, wikis, releases, CI logs and published packages are not.',
|
|
189
|
+
];
|
|
190
|
+
if (w.binary || w.skippedLarge) out.push(`${w.binary} binary file${w.binary === 1 ? '' : 's'} and ${w.skippedLarge} file${w.skippedLarge === 1 ? '' : 's'} over ${Math.round(w.maxFileBytes / 1048576)} MB were not content-scanned.`);
|
|
191
|
+
if (h.enabled) out.push('History scanning reads lines added on every local ref; changes introduced only in merge commits are not content-scanned.');
|
|
192
|
+
if (h.truncated) out.push(`History scan stopped after ${Math.round(h.patchBytes / 1048576)} MB of patches; older commits were not content-scanned. Raise --max-history-mb to scan everything.`);
|
|
193
|
+
if (!gl?.ran) out.push('Gitleaks did not run, so only Prepublic’s built-in rules were applied.');
|
|
194
|
+
if (ctx.suppressed.paths || ctx.suppressed.rules) out.push(`${ctx.suppressed.paths} path${ctx.suppressed.paths === 1 ? '' : 's'} and ${ctx.suppressed.rules} finding${ctx.suppressed.rules === 1 ? '' : 's'} were suppressed by ${CONFIG_FILE}.`);
|
|
195
|
+
if (ctx.suppressed.lines) out.push(`${ctx.suppressed.lines} line${ctx.suppressed.lines === 1 ? ' was' : 's were'} skipped because of a prepublic:allow comment.`);
|
|
196
|
+
out.push('A clean result is not a guarantee of safety. Use this report as a review aid, not a certification.');
|
|
197
|
+
return out;
|
|
198
|
+
}
|
|
199
|
+
|
|
200
|
+
/**
|
|
201
|
+
* Defence in depth: walk every string in the report, re-redact anything that
|
|
202
|
+
* still looks like a secret, mask personal paths and remove the absolute
|
|
203
|
+
* repository path.
|
|
204
|
+
*/
|
|
205
|
+
export function sanitizeReport(report, root) {
|
|
206
|
+
const variants = [root, root.replace(/\//g, '\\'), root.replace(/\\/g, '/')].filter((v) => v && v.length > 3);
|
|
207
|
+
const clean = (s) => {
|
|
208
|
+
let out = s;
|
|
209
|
+
for (const v of variants) out = out.split(v).join('<repo>');
|
|
210
|
+
const hits = findSecretsInLine(out);
|
|
211
|
+
if (hits.some((h) => h.rule.id !== 'private-key')) out = redactLine(out, hits, Math.max(out.length, 160));
|
|
212
|
+
return maskPersonalPaths(out);
|
|
213
|
+
};
|
|
214
|
+
const walk = (v) => {
|
|
215
|
+
if (typeof v === 'string') return clean(v);
|
|
216
|
+
if (Array.isArray(v)) return v.map(walk);
|
|
217
|
+
if (v && typeof v === 'object') return Object.fromEntries(Object.entries(v).map(([k, x]) => [k, walk(x)]));
|
|
218
|
+
return v;
|
|
219
|
+
};
|
|
220
|
+
return walk(report);
|
|
221
|
+
}
|
package/src/version.js
ADDED