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.
@@ -0,0 +1,268 @@
1
+ // Inspect the files that would be published: tracked files in the working tree.
2
+
3
+ import { lstat, readFile, readlink } from 'node:fs/promises';
4
+ import { join, resolve, isAbsolute, relative, sep } from 'node:path';
5
+ import { createHash } from 'node:crypto';
6
+ import { findSecretsInLine, redactLine, maskValue, isLikelyFixturePath } from '../rules/secrets.js';
7
+ import { classifySensitive, classifyJunk, LARGE_FILE_WARN, LARGE_FILE_HIGH, LARGE_FILE_BLOCK } from '../rules/files.js';
8
+ import { findPersonalPaths, maskPersonalPaths, INTERNAL_MARKERS, findInternalNetworkRef } from '../rules/personal.js';
9
+ import { makeFinding, shq, REFS, SEVERITY_RANK } from '../findings.js';
10
+
11
+ export const secretKey = (ruleId, value) => `${ruleId}\0${createHash('sha256').update(value).digest('hex')}`;
12
+
13
+ const LOCKFILE = /(^|\/)(package-lock\.json|npm-shrinkwrap\.json|yarn\.lock|pnpm-lock\.yaml|poetry\.lock|Pipfile\.lock|Cargo\.lock|composer\.lock|Gemfile\.lock|go\.sum|bun\.lockb)$/;
14
+ const NOISY_FOR_NETWORK = /\.(min\.js|min\.css|svg|map|lock)$/i;
15
+
16
+ const fmtSize = (n) => (n >= 1024 * 1024 ? `${(n / 1024 / 1024).toFixed(1)} MB` : `${Math.round(n / 1024)} KB`);
17
+
18
+ function isBinary(buf) {
19
+ const n = Math.min(buf.length, 8000);
20
+ for (let i = 0; i < n; i++) if (buf[i] === 0) return true;
21
+ return false;
22
+ }
23
+
24
+ export async function scanWorktree(ctx) {
25
+ const { root, tracked, opts } = ctx;
26
+ const secretGroups = new Map(); // ruleId|path -> group
27
+ const junk = new Map(); // ruleId -> {rule, paths}
28
+ const personal = { locations: [], evidence: [], users: new Set(), count: 0 };
29
+ const markers = { locations: [], evidence: [], count: 0 };
30
+ const network = { locations: [], kinds: new Set(), count: 0 };
31
+ const large = [];
32
+
33
+ const cov = ctx.coverage.worktree;
34
+
35
+ for (let i = 0; i < tracked.length; i += 32) {
36
+ const batch = tracked.slice(i, i + 32);
37
+ const results = await Promise.all(batch.map((p) => readTracked(root, p, opts.maxFileBytes)));
38
+ for (const r of results) {
39
+ const { path } = r;
40
+ if (ctx.isIgnoredPath(path)) { ctx.suppressed.paths++; continue; }
41
+ if (r.missing) { cov.missing++; continue; }
42
+ if (r.symlink) {
43
+ cov.symlinks++;
44
+ if (r.outside) {
45
+ ctx.add(makeFinding({
46
+ ruleId: 'symlink-outside', category: 'hygiene', severity: 'low', title: 'Symlink points outside the repository',
47
+ summary: `${path} links to a location outside the repository.`,
48
+ why: 'Links to absolute or parent paths break for everyone else and can reveal your local directory layout.',
49
+ actions: ['Replace the link with a relative link inside the repository or remove it.'],
50
+ locations: [{ path }], key: path,
51
+ }));
52
+ }
53
+ continue;
54
+ }
55
+ if (r.directory) continue; // submodule gitlink
56
+ cov.files++;
57
+ cov.bytes += r.size;
58
+
59
+ // Size
60
+ if (r.size >= LARGE_FILE_WARN) large.push({ path, size: r.size });
61
+
62
+ // Path-based classification
63
+ const sens = classifySensitive(path);
64
+ if (sens) handleSensitive(ctx, sens, path, r);
65
+ const j = classifyJunk(path);
66
+ if (j) {
67
+ if (!junk.has(j.id)) junk.set(j.id, { rule: j, paths: [] });
68
+ junk.get(j.id).paths.push(path);
69
+ }
70
+
71
+ if (!r.content) {
72
+ if (r.binary) cov.binary++;
73
+ else if (r.tooLarge) cov.skippedLarge++;
74
+ continue;
75
+ }
76
+ cov.textFiles++;
77
+ const lines = r.content.split(/\r?\n/);
78
+ const lock = LOCKFILE.test(path);
79
+ for (let ln = 0; ln < lines.length; ln++) {
80
+ const line = lines[ln];
81
+ if (!line) continue;
82
+ if (/prepublic:allow/i.test(line)) { ctx.suppressed.lines++; continue; }
83
+ const hits = findSecretsInLine(line, { path });
84
+ if (hits.length) {
85
+ const evidence = opts.snippets ? maskPersonalPaths(redactLine(line, hits)) : null;
86
+ for (const h of hits) {
87
+ const key = `${h.rule.id}|${path}`;
88
+ let g = secretGroups.get(key);
89
+ if (!g) {
90
+ g = { rule: h.rule, path, lines: [], evidence: [], severity: h.severity, confidence: h.confidence, previews: new Set(), keys: new Set() };
91
+ secretGroups.set(key, g);
92
+ }
93
+ g.lines.push(ln + 1);
94
+ if (SEVERITY_RANK[h.severity] < SEVERITY_RANK[g.severity]) g.severity = h.severity;
95
+ if (evidence && g.evidence.length < 3) g.evidence.push(`L${ln + 1}: ${evidence}`);
96
+ g.previews.add(maskValue(h.rule, h.value));
97
+ const sk = secretKey(h.rule.id, h.value);
98
+ g.keys.add(sk);
99
+ ctx.worktreeSecrets.set(sk, g);
100
+ }
101
+ }
102
+ if (!lock) {
103
+ const pp = findPersonalPaths(line);
104
+ if (pp.length) {
105
+ personal.count++;
106
+ pp.forEach((p) => personal.users.add(p.user.toLowerCase()));
107
+ if (personal.locations.length < 50) personal.locations.push({ path, line: ln + 1 });
108
+ if (opts.snippets && personal.evidence.length < 5) personal.evidence.push(`${path}:${ln + 1}: ${clip(maskPersonalPaths(redactLine(line, findSecretsInLine(line))))}`);
109
+ }
110
+ if (INTERNAL_MARKERS.test(line) && !/prepublic|INTERNAL_MARKERS/.test(line)) {
111
+ markers.count++;
112
+ if (markers.locations.length < 50) markers.locations.push({ path, line: ln + 1 });
113
+ if (opts.snippets && markers.evidence.length < 5) markers.evidence.push(`${path}:${ln + 1}: ${clip(maskPersonalPaths(redactLine(line, findSecretsInLine(line))))}`);
114
+ }
115
+ if (!NOISY_FOR_NETWORK.test(path)) {
116
+ const net = findInternalNetworkRef(line);
117
+ if (net) {
118
+ network.count++;
119
+ network.kinds.add(net.kind);
120
+ if (network.locations.length < 50) network.locations.push({ path, line: ln + 1 });
121
+ }
122
+ }
123
+ }
124
+ }
125
+ }
126
+ }
127
+
128
+ for (const g of secretGroups.values()) {
129
+ const fixture = isLikelyFixturePath(g.path);
130
+ g.finding = ctx.add(makeFinding({
131
+ ruleId: `secret/${g.rule.id}`, category: 'secrets', severity: g.severity, confidence: g.confidence,
132
+ title: g.rule.title,
133
+ summary: `${g.lines.length} occurrence${g.lines.length > 1 ? 's' : ''} in ${g.path} (${[...g.previews].slice(0, 2).join(', ')}).${fixture ? ' The path looks like a test fixture or documentation; confirm the value is fake.' : ''}`,
134
+ why: 'Anyone who can read the repository can use a published credential. Bots scan new public repositories within minutes.',
135
+ actions: [
136
+ 'Revoke or rotate the credential at its provider first; deleting it from the file is not enough.',
137
+ 'Load the value from an environment variable or a secret manager instead of source code.',
138
+ 'If the value is a fake fixture, mark the line with a `prepublic:allow` comment or add the path to `.prepublic.json`.',
139
+ ],
140
+ locations: g.lines.map((line) => ({ path: g.path, line })),
141
+ evidence: g.evidence,
142
+ references: [REFS.rotate],
143
+ key: `${g.rule.id}|${g.path}`,
144
+ }));
145
+ }
146
+
147
+ for (const { rule, paths } of junk.values()) {
148
+ const dirs = [...new Set(paths.map((p) => topDir(p, rule.id)))];
149
+ ctx.add(makeFinding({
150
+ ruleId: `junk/${rule.id}`, category: 'hygiene', severity: rule.severity, title: rule.title,
151
+ summary: `${paths.length} tracked file${paths.length > 1 ? 's match' : ' matches'} this pattern.`,
152
+ why: rule.why,
153
+ actions: ['Stop tracking the files (they stay on disk).', 'Add a matching pattern to .gitignore.'],
154
+ commands: dirs.slice(0, 5).map((d) => `git rm -r --cached ${shq(d)}`),
155
+ locations: paths.map((path) => ({ path })), count: paths.length, references: [REFS.gitignore],
156
+ }));
157
+ }
158
+
159
+ for (const f of large) {
160
+ const severity = f.size > LARGE_FILE_BLOCK ? 'high' : f.size > LARGE_FILE_HIGH ? 'medium' : 'low';
161
+ ctx.add(makeFinding({
162
+ ruleId: 'large-file', category: 'hygiene', severity, title: 'Large tracked file',
163
+ summary: `${f.path} is ${fmtSize(f.size)}.${f.size > LARGE_FILE_BLOCK ? ' GitHub rejects files over 100 MB.' : ''}`,
164
+ why: 'Large files slow every clone forever and are often generated data, datasets or archives that were not meant to be shared.',
165
+ actions: ['Remove the file or move it to Git LFS or a release asset.', 'If it was committed earlier, it also stays in history until history is rewritten.'],
166
+ locations: [{ path: f.path, note: fmtSize(f.size) }], references: [REFS.largeFiles], key: f.path,
167
+ }));
168
+ }
169
+
170
+ if (personal.count) {
171
+ ctx.add(makeFinding({
172
+ ruleId: 'personal-path', category: 'privacy', severity: 'medium', confidence: 'medium',
173
+ title: 'Absolute paths into a personal home directory',
174
+ summary: `${personal.count} line${personal.count > 1 ? 's reference' : ' references'} a home folder (${personal.users.size} distinct user name${personal.users.size > 1 ? 's' : ''}, masked in this report).`,
175
+ why: 'Home-directory paths reveal your OS user name (often your real name), folder structure and tooling, and break the project for everyone else.',
176
+ actions: ['Replace absolute paths with paths relative to the project, `~`, or an environment variable.', 'Regenerate any build output or config that captured your local path.'],
177
+ locations: personal.locations, count: personal.count, evidence: personal.evidence,
178
+ }));
179
+ }
180
+ if (markers.count) {
181
+ ctx.add(makeFinding({
182
+ ruleId: 'internal-marker', category: 'privacy', severity: 'medium', confidence: 'medium',
183
+ title: 'Confidentiality markers in content',
184
+ summary: `${markers.count} line${markers.count > 1 ? 's contain' : ' contains'} phrases such as "internal use only" or "do not distribute".`, // prepublic:allow
185
+ why: 'These markers suggest the material was not cleared for public release. Publishing it may breach an agreement or policy.',
186
+ actions: ['Confirm you have the right to publish this material, or remove it.'],
187
+ locations: markers.locations, count: markers.count, evidence: markers.evidence,
188
+ }));
189
+ }
190
+ if (network.count) {
191
+ ctx.add(makeFinding({
192
+ ruleId: 'internal-network', category: 'privacy', severity: 'low', confidence: 'low',
193
+ title: 'Internal network references',
194
+ summary: `${network.count} line${network.count > 1 ? 's mention' : ' mentions'} a ${[...network.kinds].join(' or ')}.`,
195
+ why: 'Private addresses and internal hostnames map out infrastructure for an attacker. Often harmless in examples; worth a look.',
196
+ actions: ['Replace real internal addresses with documentation ranges (e.g. 192.0.2.0/24) or example hostnames.'],
197
+ locations: network.locations, count: network.count,
198
+ }));
199
+ }
200
+ }
201
+
202
+ function handleSensitive(ctx, rule, path, r) {
203
+ let severity = rule.severity;
204
+ let note = '';
205
+ if (rule.contentCheck) {
206
+ if (!r.content || !rule.contentCheck.test(r.content)) return; // config without credentials
207
+ note = ' It contains authentication settings.';
208
+ }
209
+ if (rule.id === 'private-key-file' && r.content && !/PRIVATE KEY/.test(r.content)) {
210
+ severity = 'low';
211
+ note = ' No private key block was found inside; it may be a certificate or an unrelated file.';
212
+ }
213
+ ctx.add(makeFinding({
214
+ ruleId: `file/${rule.id}`, category: 'files', severity, title: rule.title,
215
+ summary: `${path} is tracked.${note}`,
216
+ why: rule.why,
217
+ actions: [
218
+ 'Stop tracking the file and add it to .gitignore.',
219
+ 'Treat any credential it contains as exposed if the file was ever pushed anywhere, and rotate it.',
220
+ 'Commit a sanitized template instead (for example `.env.example`).',
221
+ ],
222
+ commands: [`git rm --cached ${shq(path)}`],
223
+ locations: [{ path }], references: [REFS.rotate], key: path,
224
+ }));
225
+ }
226
+
227
+ function topDir(path, ruleId) {
228
+ const m = path.match(/^(.*?(?:node_modules|bower_components|\.venv|venv|__pycache__|coverage|\.next|\.nuxt|\.idea|\.vs|\.gradle|\.pytest_cache|\.mypy_cache|\.nyc_output|\.turbo|\.parcel-cache|\.ruff_cache|\.pnpm-store))\//);
229
+ if (m && ruleId !== 'os-metadata') return m[1];
230
+ return path;
231
+ }
232
+
233
+ function clip(s, n = 160) {
234
+ return s.length > n ? `${s.slice(0, n)}…` : s;
235
+ }
236
+
237
+ async function readTracked(root, path, maxBytes) {
238
+ const abs = join(root, path);
239
+ let st;
240
+ try {
241
+ st = await lstat(abs);
242
+ } catch {
243
+ return { path, missing: true };
244
+ }
245
+ if (st.isSymbolicLink()) {
246
+ let outside = false;
247
+ try {
248
+ const target = await readlink(abs);
249
+ const resolved = isAbsolute(target) ? target : resolve(abs, '..', target);
250
+ const rel = relative(root, resolved);
251
+ outside = isAbsolute(target) || rel.startsWith('..') || rel.startsWith(`..${sep}`);
252
+ } catch { /* unreadable link */ }
253
+ return { path, symlink: true, outside };
254
+ }
255
+ if (st.isDirectory()) return { path, directory: true };
256
+ const out = { path, size: st.size };
257
+ if (st.size > maxBytes) {
258
+ out.tooLarge = true;
259
+ return out;
260
+ }
261
+ const buf = await readFile(abs);
262
+ if (isBinary(buf)) {
263
+ out.binary = true;
264
+ return out;
265
+ }
266
+ out.content = buf.toString('utf8');
267
+ return out;
268
+ }
package/src/cli.js ADDED
@@ -0,0 +1,203 @@
1
+ import { mkdir, writeFile, mkdtemp, rm } from 'node:fs/promises';
2
+ import { spawn } from 'node:child_process';
3
+ import { tmpdir } from 'node:os';
4
+ import { dirname, extname, join, relative, resolve, isAbsolute } from 'node:path';
5
+ import { scanRepository } from './scan.js';
6
+ import { renderHtml } from './report/html.js';
7
+ import { renderMarkdown } from './report/markdown.js';
8
+ import { SEVERITIES, SEVERITY_RANK } from './findings.js';
9
+ import { VERSION } from './version.js';
10
+
11
+ const HELP = `Prepublic ${VERSION}: check a Git repository before you make it public.
12
+
13
+ Usage
14
+ prepublic [path] [options]
15
+ prepublic --demo [leaky-service|almost-ready|release-ready]
16
+
17
+ Output
18
+ -o, --out <file> Write the report to <file>; format follows the extension (.html, .md, .json)
19
+ -f, --format <fmt> html (default), md or json
20
+ --stdout Print the md/json report to stdout instead of writing a file
21
+ --no-open Do not open the HTML report in your browser
22
+ -q, --quiet Only print errors and the report path
23
+
24
+ Scan
25
+ --no-history Skip Git history checks
26
+ --no-snippets Leave redacted evidence lines out of the report
27
+ --gitleaks <mode> auto (default: use if installed), off, or require
28
+ --gitleaks-path <bin> Path to a gitleaks executable
29
+ --max-file-mb <n> Skip content checks for files larger than n MB (default 2)
30
+ --max-history-mb <n> Stop the history content scan after n MB of patches (default 512)
31
+
32
+ CI
33
+ --fail-on <severity> Exit with code 1 if a finding is at or above: critical, high, medium, low, info
34
+
35
+ --demo [name] Scan a generated synthetic repository (default leaky-service)
36
+ -h, --help Show this help
37
+ -v, --version Show the version
38
+
39
+ Prepublic never modifies the repository, makes no network requests and never
40
+ writes raw secret values into reports. A clean report is not a guarantee.`;
41
+
42
+ export function parseArgs(argv) {
43
+ const o = { path: '.', format: null, out: null, stdout: false, open: true, quiet: false, history: true, snippets: true, gitleaks: 'auto', gitleaksPath: null, maxFileMb: 2, maxHistoryMb: 512, failOn: null, help: false, version: false, demo: null };
44
+ const need = (i, flag) => {
45
+ if (i >= argv.length || argv[i].startsWith('-')) throw new UsageError(`${flag} needs a value.`);
46
+ return argv[i];
47
+ };
48
+ let positional = 0;
49
+ for (let i = 0; i < argv.length; i++) {
50
+ const a = argv[i];
51
+ switch (a) {
52
+ case '-h': case '--help': o.help = true; break;
53
+ case '-v': case '--version': o.version = true; break;
54
+ case '-o': case '--out': o.out = need(++i, a); break;
55
+ case '-f': case '--format': o.format = need(++i, a); break;
56
+ case '--stdout': o.stdout = true; break;
57
+ case '--no-open': o.open = false; break;
58
+ case '-q': case '--quiet': o.quiet = true; break;
59
+ case '--no-history': o.history = false; break;
60
+ case '--no-snippets': o.snippets = false; break;
61
+ case '--gitleaks': o.gitleaks = need(++i, a); break;
62
+ case '--gitleaks-path': o.gitleaksPath = need(++i, a); break;
63
+ case '--max-file-mb': o.maxFileMb = Number(need(++i, a)); break;
64
+ case '--max-history-mb': o.maxHistoryMb = Number(need(++i, a)); break;
65
+ case '--fail-on': o.failOn = need(++i, a); break;
66
+ case '--demo':
67
+ o.demo = DEMOS.includes(argv[i + 1]) ? argv[++i] : 'leaky-service';
68
+ break;
69
+ default:
70
+ if (a.startsWith('-')) throw new UsageError(`Unknown option ${a}. Run prepublic --help.`);
71
+ if (positional++) throw new UsageError('Only one repository path can be given.');
72
+ o.path = a;
73
+ }
74
+ }
75
+ if (o.demo && positional) throw new UsageError('--demo scans a generated repository; do not pass a path as well.');
76
+ if (o.out && !o.format) {
77
+ const ext = extname(o.out).toLowerCase();
78
+ o.format = ext === '.md' || ext === '.markdown' ? 'md' : ext === '.json' ? 'json' : 'html';
79
+ }
80
+ o.format = o.format || (o.stdout ? 'json' : 'html');
81
+ if (!['html', 'md', 'json'].includes(o.format)) throw new UsageError('--format must be html, md or json.');
82
+ if (o.stdout && o.format === 'html') throw new UsageError('--stdout supports md and json only.');
83
+ if (!['auto', 'off', 'require'].includes(o.gitleaks)) throw new UsageError('--gitleaks must be auto, off or require.');
84
+ if (o.failOn && !SEVERITIES.includes(o.failOn)) throw new UsageError(`--fail-on must be one of ${SEVERITIES.join(', ')}.`);
85
+ for (const k of ['maxFileMb', 'maxHistoryMb']) if (!(o[k] > 0)) throw new UsageError(`--${k === 'maxFileMb' ? 'max-file-mb' : 'max-history-mb'} must be a positive number.`);
86
+ return o;
87
+ }
88
+
89
+ export class UsageError extends Error {}
90
+
91
+ const DEMOS = ['leaky-service', 'almost-ready', 'release-ready'];
92
+
93
+ const useColor = process.stdout.isTTY && !process.env.NO_COLOR && process.env.TERM !== 'dumb';
94
+ const paint = (code) => (s) => (useColor ? `\x1b[${code}m${s}\x1b[0m` : String(s));
95
+ const c = {
96
+ bold: paint('1'), dim: paint('2'), lime: paint('38;5;154'), red: paint('38;5;203'), orange: paint('38;5;215'),
97
+ yellow: paint('38;5;221'), blue: paint('38;5;117'), gray: paint('38;5;248'),
98
+ inv: (s, col) => (useColor ? `\x1b[1;48;5;${col};38;5;16m ${s} \x1b[0m` : `[${s}]`),
99
+ };
100
+ const SEVC = { critical: c.red, high: c.orange, medium: c.yellow, low: c.blue, info: c.gray };
101
+ const SEVMARK = { critical: '■', high: '▲', medium: '◆', low: '●', info: '○' };
102
+
103
+ export function summarize(r) {
104
+ const lines = [];
105
+ const meta = [r.repo.branch, r.repo.head].filter(Boolean).join(' @ ');
106
+ lines.push(`${c.lime(c.bold('Prepublic'))} ${c.dim(VERSION)} ${c.bold(r.repo.name)}${meta ? c.dim(` ${meta}`) : ''}`, '');
107
+ const col = { blocked: 203, review: 221, clear: 154 }[r.verdict.level];
108
+ lines.push(` ${c.inv(r.verdict.label.toUpperCase(), col)} score ${c.bold(r.score)}/100 · ${r.verdict.blockers} blocker${r.verdict.blockers === 1 ? '' : 's'} · ${r.verdict.toReview} to review`, '');
109
+ lines.push(` ${SEVERITIES.map((s) => SEVC[s](`${SEVMARK[s]} ${r.counts[s]} ${s}`)).join(' ')}`, '');
110
+ const top = r.findings.filter((f) => SEVERITY_RANK[f.severity] <= 2).slice(0, 12);
111
+ for (const f of top) {
112
+ const l = f.locations[0];
113
+ const where = l ? `${l.path}${l.line ? `:${l.line}` : ''}${l.commit ? ` @${l.commit}` : ''}` : '';
114
+ lines.push(` ${SEVC[f.severity](f.severity.toUpperCase().padEnd(8))} ${f.title.padEnd(46).slice(0, 46)} ${c.dim(where)}`);
115
+ }
116
+ const rest = r.findings.length - top.length;
117
+ if (rest > 0) lines.push(c.dim(` … and ${rest} more finding${rest === 1 ? '' : 's'} in the report`));
118
+ if (top.length || rest > 0) lines.push('');
119
+ const w = r.coverage.worktree;
120
+ const h = r.coverage.history;
121
+ const g = r.coverage.gitleaks;
122
+ lines.push(c.dim(` Coverage: ${w.files} files · ${h.enabled ? `${h.commitsScanned} commits${h.truncated ? ' (truncated)' : ''}` : 'history skipped'} · gitleaks ${g?.ran ? `v${g.version}` : g?.mode === 'off' ? 'off' : g?.error || 'not run'}`));
123
+ lines.push(c.dim(' A clean result is not a guarantee. Review the checklist and limitations in the report.'));
124
+ return lines.join('\n');
125
+ }
126
+
127
+ function defaultOut(r, format) {
128
+ const ts = r.generatedAt.replace(/[-:]/g, '').replace('T', '-').slice(0, 15);
129
+ const safe = r.repo.name.replace(/[^\w.-]+/g, '-');
130
+ return join(tmpdir(), 'prepublic', `${safe}-${ts}.${format}`);
131
+ }
132
+
133
+ function openInBrowser(file) {
134
+ const [cmd, args] = process.platform === 'win32' ? ['explorer.exe', [file]] : process.platform === 'darwin' ? ['open', [file]] : ['xdg-open', [file]];
135
+ try {
136
+ const child = spawn(cmd, args, { detached: true, stdio: 'ignore', windowsHide: true });
137
+ child.on('error', () => {});
138
+ child.unref();
139
+ } catch { /* best effort */ }
140
+ }
141
+
142
+ export async function main(argv, { stdout = process.stdout, stderr = process.stderr } = {}) {
143
+ let o;
144
+ try {
145
+ o = parseArgs(argv);
146
+ } catch (err) {
147
+ stderr.write(`prepublic: ${err.message}\n`);
148
+ return 2;
149
+ }
150
+ if (o.help) { stdout.write(`${HELP}\n`); return 0; }
151
+ if (o.version) { stdout.write(`${VERSION}\n`); return 0; }
152
+
153
+ let report;
154
+ let demoDir = null;
155
+ try {
156
+ if (o.demo) {
157
+ // The generator ships with the package and creates fake data only.
158
+ const { createExamples } = await import('../scripts/make-examples.mjs');
159
+ demoDir = await mkdtemp(join(tmpdir(), 'prepublic-demo-'));
160
+ o.path = createExamples(demoDir, { only: [o.demo] })[o.demo];
161
+ if (!o.quiet && !o.stdout) stderr.write(c.dim(`Demo: generated a synthetic repository with fake secrets (${o.demo}).\n`));
162
+ }
163
+ if (!o.quiet && !o.stdout) stderr.write(c.dim(`Scanning ${o.demo || (o.path === '.' ? 'current directory' : o.path)} (read-only)…\n`));
164
+ report = await scanRepository(resolve(o.path), {
165
+ history: o.history, snippets: o.snippets, gitleaks: o.gitleaks,
166
+ gitleaksCommand: o.gitleaksPath ? [o.gitleaksPath] : null,
167
+ maxFileBytes: Math.round(o.maxFileMb * 1024 * 1024), maxHistoryBytes: Math.round(o.maxHistoryMb * 1024 * 1024),
168
+ });
169
+ } catch (err) {
170
+ stderr.write(`prepublic: ${err.message}\n`);
171
+ return 2;
172
+ } finally {
173
+ if (demoDir) await rm(demoDir, { recursive: true, force: true }).catch(() => {});
174
+ }
175
+
176
+ const body = o.format === 'html' ? renderHtml(report) : o.format === 'md' ? renderMarkdown(report) : `${JSON.stringify(report, null, 2)}\n`;
177
+ if (o.stdout) {
178
+ stdout.write(body);
179
+ } else {
180
+ const out = o.out ? resolve(o.out) : defaultOut(report, o.format);
181
+ try {
182
+ await mkdir(dirname(out), { recursive: true });
183
+ await writeFile(out, body, { encoding: 'utf8', mode: 0o600 });
184
+ } catch (err) {
185
+ stderr.write(`prepublic: could not write report: ${err.message}\n`);
186
+ return 2;
187
+ }
188
+ if (!o.quiet) stdout.write(`${summarize(report)}\n\n`);
189
+ stdout.write(`${c.lime('Report')} ${out}\n`);
190
+ const repoRoot = resolve(o.path);
191
+ const rel = relative(repoRoot, out);
192
+ if (!o.demo && rel && !rel.startsWith('..') && !isAbsolute(rel) && !o.quiet) {
193
+ stderr.write(c.yellow('Note: the report is inside the repository. It contains no secret values, but keep it out of commits (add it to .gitignore).\n'));
194
+ }
195
+ if (o.format === 'html' && o.open && process.stdout.isTTY && !process.env.CI) openInBrowser(out);
196
+ }
197
+
198
+ if (o.failOn) {
199
+ const limit = SEVERITY_RANK[o.failOn];
200
+ if (report.findings.some((f) => SEVERITY_RANK[f.severity] <= limit)) return 1;
201
+ }
202
+ return 0;
203
+ }
package/src/config.js ADDED
@@ -0,0 +1,59 @@
1
+ import { readFile } from 'node:fs/promises';
2
+ import { join } from 'node:path';
3
+
4
+ export const CONFIG_FILE = '.prepublic.json';
5
+
6
+ /** Convert a gitignore-style glob (`*`, `**`, `?`) into a RegExp. */
7
+ export function globToRegExp(glob) {
8
+ let g = glob.trim().replace(/\\/g, '/');
9
+ const anchored = g.startsWith('/');
10
+ if (anchored) g = g.slice(1);
11
+ if (g.endsWith('/')) g += '**';
12
+ let re = '';
13
+ for (let i = 0; i < g.length; i++) {
14
+ const c = g[i];
15
+ if (c === '*') {
16
+ if (g[i + 1] === '*') {
17
+ const slash = g[i + 2] === '/';
18
+ re += slash ? '(?:.*/)?' : '.*';
19
+ i += slash ? 2 : 1;
20
+ } else {
21
+ re += '[^/]*';
22
+ }
23
+ } else if (c === '?') {
24
+ re += '[^/]';
25
+ } else {
26
+ re += c.replace(/[.+^${}()|[\]\\]/g, '\\$&');
27
+ }
28
+ }
29
+ const prefix = anchored || g.includes('/') ? '^' : '^(?:.*/)?';
30
+ return new RegExp(`${prefix}${re}$`);
31
+ }
32
+
33
+ /**
34
+ * Load optional `.prepublic.json` from the repository root. Invalid files are
35
+ * reported, never fatal.
36
+ */
37
+ export async function loadConfig(root) {
38
+ const config = { ignorePaths: [], ignoreRules: [], source: null, error: null };
39
+ let raw;
40
+ try {
41
+ raw = await readFile(join(root, CONFIG_FILE), 'utf8');
42
+ } catch {
43
+ return config;
44
+ }
45
+ config.source = CONFIG_FILE;
46
+ try {
47
+ const data = JSON.parse(raw);
48
+ if (Array.isArray(data.ignorePaths)) config.ignorePaths = data.ignorePaths.filter((s) => typeof s === 'string' && s.trim());
49
+ if (Array.isArray(data.ignoreRules)) config.ignoreRules = data.ignoreRules.filter((s) => typeof s === 'string');
50
+ } catch (err) {
51
+ config.error = `Could not parse ${CONFIG_FILE}: ${err.message}`;
52
+ }
53
+ return config;
54
+ }
55
+
56
+ export function makePathFilter(globs) {
57
+ const res = globs.map(globToRegExp);
58
+ return (path) => res.some((re) => re.test(path));
59
+ }
@@ -0,0 +1,53 @@
1
+ import { createHash } from 'node:crypto';
2
+
3
+ export const SEVERITIES = ['critical', 'high', 'medium', 'low', 'info'];
4
+ export const SEVERITY_RANK = Object.fromEntries(SEVERITIES.map((s, i) => [s, i]));
5
+
6
+ export const CATEGORIES = {
7
+ secrets: { label: 'Secrets', blurb: 'Credentials and tokens in the files you are about to publish.' },
8
+ history: { label: 'Git history', blurb: 'Everything ever committed becomes public with the repository.' },
9
+ files: { label: 'Sensitive files', blurb: 'Files that usually should never be tracked.' },
10
+ privacy: { label: 'Personal & internal data', blurb: 'Names, paths, emails and internal references.' },
11
+ hygiene: { label: 'Repository hygiene', blurb: 'Clutter and configuration that look unprofessional or leak context.' },
12
+ docs: { label: 'Docs & licensing', blurb: 'What users need before they can adopt your project.' },
13
+ };
14
+
15
+ export const MAX_LOCATIONS = 50;
16
+
17
+ /** Build a normalised finding. */
18
+ export function makeFinding({
19
+ ruleId, category, severity, title, summary, why = '', actions = [], commands = [], locations = [], evidence = [],
20
+ confidence = 'high', source = 'builtin', references = [], count, key,
21
+ }) {
22
+ const id = createHash('sha1').update(`${ruleId}\0${key ?? locations[0]?.path ?? ''}`).digest('hex').slice(0, 10);
23
+ return {
24
+ id, ruleId, category, severity, confidence, source, title, summary, why, actions, commands,
25
+ locations: locations.slice(0, MAX_LOCATIONS),
26
+ totalLocations: count ?? locations.length,
27
+ evidence: evidence.slice(0, 5),
28
+ references,
29
+ };
30
+ }
31
+
32
+ export function sortFindings(findings) {
33
+ return [...findings].sort((a, b) => SEVERITY_RANK[a.severity] - SEVERITY_RANK[b.severity]
34
+ || Object.keys(CATEGORIES).indexOf(a.category) - Object.keys(CATEGORIES).indexOf(b.category)
35
+ || a.title.localeCompare(b.title));
36
+ }
37
+
38
+ /** Quote a path for a POSIX-ish shell command shown to the user. */
39
+ export function shq(path) {
40
+ return /^[\w./@+-]+$/.test(path) ? path : `'${path.replace(/'/g, `'\\''`)}'`;
41
+ }
42
+
43
+ export const REFS = {
44
+ rotate: { label: 'GitHub: Remove sensitive data from a repository', url: 'https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/removing-sensitive-data-from-a-repository' },
45
+ filterRepo: { label: 'git-filter-repo', url: 'https://github.com/newren/git-filter-repo' },
46
+ gitignore: { label: 'github/gitignore templates', url: 'https://github.com/github/gitignore' },
47
+ license: { label: 'Choose a License', url: 'https://choosealicense.com/' },
48
+ noreply: { label: 'GitHub: Setting your commit email address', url: 'https://docs.github.com/en/account-and-profile/setting-up-and-managing-your-personal-account-on-github/managing-email-preferences/setting-your-commit-email-address' },
49
+ security: { label: 'GitHub: Adding a security policy', url: 'https://docs.github.com/en/code-security/getting-started/adding-a-security-policy-to-your-repository' },
50
+ contributing: { label: 'GitHub: Setting guidelines for contributors', url: 'https://docs.github.com/en/communities/setting-up-your-project-for-healthy-contributions/setting-guidelines-for-repository-contributors' },
51
+ largeFiles: { label: 'GitHub: About large files', url: 'https://docs.github.com/en/repositories/working-with-files/managing-large-files/about-large-files-on-github' },
52
+ gitleaks: { label: 'Gitleaks', url: 'https://github.com/gitleaks/gitleaks' },
53
+ };