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,210 @@
|
|
|
1
|
+
// Inspect Git history: everything ever committed on any ref becomes public.
|
|
2
|
+
|
|
3
|
+
import { git, gitText, gitLines } from '../git.js';
|
|
4
|
+
import { findSecretsInLine, redactLine, maskValue } from '../rules/secrets.js';
|
|
5
|
+
import { classifySensitive, LARGE_FILE_HIGH, LARGE_FILE_BLOCK } from '../rules/files.js';
|
|
6
|
+
import { isNoreplyEmail, maskEmail, maskPersonalPaths } from '../rules/personal.js';
|
|
7
|
+
import { makeFinding, shq, REFS, SEVERITY_RANK } from '../findings.js';
|
|
8
|
+
import { secretKey } from './worktree.js';
|
|
9
|
+
|
|
10
|
+
const short = (sha) => sha.slice(0, 7);
|
|
11
|
+
const MAX_COMMITS_LISTED = 10;
|
|
12
|
+
|
|
13
|
+
function unquotePath(p) {
|
|
14
|
+
if (!p.startsWith('"')) return p;
|
|
15
|
+
try { return JSON.parse(p.replace(/\\([0-7]{3})/g, (_, o) => `\\u00${parseInt(o, 8).toString(16).padStart(2, '0')}`)); } catch { return p.slice(1, -1); }
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export async function scanHistory(ctx) {
|
|
19
|
+
const { root, opts } = ctx;
|
|
20
|
+
const cov = ctx.coverage.history;
|
|
21
|
+
cov.enabled = true;
|
|
22
|
+
|
|
23
|
+
cov.commits = Number((await gitText(['rev-list', '--all', '--count'], { cwd: root })).trim()) || 0;
|
|
24
|
+
cov.refs = (await gitText(['for-each-ref', '--format=%(refname)'], { cwd: root })).split('\n').filter(Boolean).length;
|
|
25
|
+
if (!cov.commits) return;
|
|
26
|
+
|
|
27
|
+
await authorEmails(ctx);
|
|
28
|
+
await historicalFiles(ctx);
|
|
29
|
+
await largeBlobs(ctx);
|
|
30
|
+
await patchSecrets(ctx, opts.maxHistoryBytes);
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
async function authorEmails(ctx) {
|
|
34
|
+
const out = await gitText(['log', '--all', '--format=%ae%x00%ce'], { cwd: ctx.root });
|
|
35
|
+
const emails = new Set();
|
|
36
|
+
for (const line of out.split('\n')) {
|
|
37
|
+
for (const e of line.split('\0')) if (e && e.includes('@')) emails.add(e.trim().toLowerCase());
|
|
38
|
+
}
|
|
39
|
+
const personal = [...emails].filter((e) => !isNoreplyEmail(e));
|
|
40
|
+
ctx.coverage.history.authorEmails = emails.size;
|
|
41
|
+
if (!personal.length) return;
|
|
42
|
+
ctx.add(makeFinding({
|
|
43
|
+
ruleId: 'author-emails', category: 'privacy', severity: 'low', confidence: 'high',
|
|
44
|
+
title: 'Commit author emails will become public',
|
|
45
|
+
summary: `${personal.length} non-noreply email address${personal.length > 1 ? 'es appear' : ' appears'} in commit metadata (masked here): ${personal.slice(0, 4).map(maskEmail).join(', ')}${personal.length > 4 ? ', …' : ''}.`,
|
|
46
|
+
why: 'Every commit carries an author and committer email. Once public they are harvested by spammers and link your identity to the project.',
|
|
47
|
+
actions: [
|
|
48
|
+
'Confirm each address is one you are comfortable publishing.',
|
|
49
|
+
'Use a noreply address for future commits (`git config user.email <id>+<user>@users.noreply.github.com`).',
|
|
50
|
+
'Existing commits keep their emails unless history is rewritten (for example with a git-filter-repo mailmap).',
|
|
51
|
+
],
|
|
52
|
+
locations: personal.slice(0, 20).map((e) => ({ path: maskEmail(e), note: 'commit metadata' })), count: personal.length,
|
|
53
|
+
references: [REFS.noreply],
|
|
54
|
+
}));
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
async function historicalFiles(ctx) {
|
|
58
|
+
const out = await gitText(['log', '--all', '--diff-filter=A', '--name-only', '--no-renames', '--format=%x01%H'], { cwd: ctx.root });
|
|
59
|
+
let commit = '';
|
|
60
|
+
const seen = new Map();
|
|
61
|
+
for (const raw of out.split('\n')) {
|
|
62
|
+
const line = raw.trim();
|
|
63
|
+
if (!line) continue;
|
|
64
|
+
if (line.startsWith('\x01')) { commit = line.slice(1); continue; }
|
|
65
|
+
const path = unquotePath(line);
|
|
66
|
+
ctx.historyPaths.add(path);
|
|
67
|
+
if (ctx.trackedSet.has(path) || ctx.isIgnoredPath(path)) continue;
|
|
68
|
+
const rule = classifySensitive(path);
|
|
69
|
+
if (!rule || rule.contentCheck) continue;
|
|
70
|
+
if (!seen.has(path)) seen.set(path, { rule, commits: [] });
|
|
71
|
+
seen.get(path).commits.push(commit);
|
|
72
|
+
}
|
|
73
|
+
for (const [path, { rule, commits }] of seen) {
|
|
74
|
+
ctx.add(makeFinding({
|
|
75
|
+
ruleId: `history-file/${rule.id}`, category: 'history', severity: SEVERITY_RANK[rule.severity] <= 1 ? rule.severity : 'medium',
|
|
76
|
+
title: `${rule.title} in history`,
|
|
77
|
+
summary: `${path} is no longer tracked, but it was committed in ${commits.length} commit${commits.length > 1 ? 's' : ''} and is still retrievable.`,
|
|
78
|
+
why: `${rule.why} Deleting a file does not remove it from Git history; anyone can check out the old commit.`,
|
|
79
|
+
actions: [
|
|
80
|
+
'Rotate every credential the file contained.',
|
|
81
|
+
'Rewrite history to purge the file before publishing, or publish a fresh repository without the old history.',
|
|
82
|
+
'After a rewrite, re-run Prepublic and make sure all collaborators re-clone.',
|
|
83
|
+
],
|
|
84
|
+
commands: [`git filter-repo --invert-paths --path ${shq(path)}`],
|
|
85
|
+
locations: commits.slice(0, MAX_COMMITS_LISTED).map((c) => ({ path, commit: short(c) })), count: commits.length,
|
|
86
|
+
references: [REFS.rotate, REFS.filterRepo], key: path,
|
|
87
|
+
}));
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async function largeBlobs(ctx) {
|
|
92
|
+
const objects = await gitText(['rev-list', '--objects', '--all'], { cwd: ctx.root, maxBytes: 64 * 1024 * 1024 });
|
|
93
|
+
const pathBySha = new Map();
|
|
94
|
+
const shas = [];
|
|
95
|
+
for (const line of objects.split('\n')) {
|
|
96
|
+
const sp = line.indexOf(' ');
|
|
97
|
+
if (sp === -1) continue;
|
|
98
|
+
const sha = line.slice(0, sp);
|
|
99
|
+
pathBySha.set(sha, line.slice(sp + 1));
|
|
100
|
+
shas.push(sha);
|
|
101
|
+
}
|
|
102
|
+
if (!shas.length) return;
|
|
103
|
+
const { stdout } = await git(['cat-file', '--batch-check=%(objectname) %(objecttype) %(objectsize)'], { cwd: ctx.root, input: `${shas.join('\n')}\n` });
|
|
104
|
+
const big = [];
|
|
105
|
+
for (const line of stdout.toString('utf8').split('\n')) {
|
|
106
|
+
const [sha, type, size] = line.split(' ');
|
|
107
|
+
if (type !== 'blob') continue;
|
|
108
|
+
const n = Number(size);
|
|
109
|
+
const path = pathBySha.get(sha);
|
|
110
|
+
if (n >= LARGE_FILE_HIGH && path && !ctx.trackedSet.has(path)) big.push({ path, size: n });
|
|
111
|
+
}
|
|
112
|
+
for (const b of big.slice(0, 20)) {
|
|
113
|
+
ctx.add(makeFinding({
|
|
114
|
+
ruleId: 'history-large-blob', category: 'history', severity: b.size > LARGE_FILE_BLOCK ? 'high' : 'medium',
|
|
115
|
+
title: 'Large file in history',
|
|
116
|
+
summary: `${b.path} (${(b.size / 1024 / 1024).toFixed(1)} MB) is not in the current tree but remains in history.`,
|
|
117
|
+
why: 'Hosting providers reject or warn on very large blobs, and every clone downloads them.',
|
|
118
|
+
actions: ['Purge the file from history before publishing, or start from a fresh history.'],
|
|
119
|
+
commands: [`git filter-repo --invert-paths --path ${shq(b.path)}`],
|
|
120
|
+
locations: [{ path: b.path }], references: [REFS.largeFiles, REFS.filterRepo], key: b.path,
|
|
121
|
+
}));
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
async function patchSecrets(ctx, maxBytes) {
|
|
126
|
+
const cov = ctx.coverage.history;
|
|
127
|
+
const groups = new Map();
|
|
128
|
+
let commit = '';
|
|
129
|
+
let path = null;
|
|
130
|
+
let inHunk = false;
|
|
131
|
+
const touched = new Set();
|
|
132
|
+
|
|
133
|
+
const result = await gitLines(
|
|
134
|
+
['log', '--all', '-p', '-U0', '--no-textconv', '--no-ext-diff', '--no-color', '--no-renames', '--format=%x01%H'],
|
|
135
|
+
{
|
|
136
|
+
cwd: ctx.root, maxBytes,
|
|
137
|
+
onLine(line) {
|
|
138
|
+
if (line.startsWith('\x01')) { commit = line.slice(1); touched.add(commit); path = null; inHunk = false; return; }
|
|
139
|
+
if (line.startsWith('diff --git ')) { path = null; inHunk = false; return; }
|
|
140
|
+
if (!inHunk) {
|
|
141
|
+
if (line.startsWith('+++ ')) {
|
|
142
|
+
const p = line.slice(4).replace(/\t$/, '');
|
|
143
|
+
path = p === '/dev/null' ? null : unquotePath(p).replace(/^b\//, '');
|
|
144
|
+
} else if (line.startsWith('@@')) {
|
|
145
|
+
inHunk = true;
|
|
146
|
+
}
|
|
147
|
+
return;
|
|
148
|
+
}
|
|
149
|
+
if (line.startsWith('@@')) return;
|
|
150
|
+
if (!path || line[0] !== '+') return;
|
|
151
|
+
if (ctx.isIgnoredPath(path)) return;
|
|
152
|
+
const content = line.slice(1);
|
|
153
|
+
const hits = findSecretsInLine(content, { path });
|
|
154
|
+
if (!hits.length) return;
|
|
155
|
+
for (const h of hits) {
|
|
156
|
+
const sk = secretKey(h.rule.id, h.value);
|
|
157
|
+
const wt = ctx.worktreeSecrets.get(sk);
|
|
158
|
+
if (wt) {
|
|
159
|
+
wt.historyCommits = wt.historyCommits || new Set();
|
|
160
|
+
wt.historyCommits.add(commit);
|
|
161
|
+
continue;
|
|
162
|
+
}
|
|
163
|
+
const key = `${h.rule.id}|${path}`;
|
|
164
|
+
let g = groups.get(key);
|
|
165
|
+
if (!g) {
|
|
166
|
+
g = { rule: h.rule, path, severity: h.severity, confidence: h.confidence, commits: [], evidence: [], previews: new Set(), values: new Set() };
|
|
167
|
+
groups.set(key, g);
|
|
168
|
+
}
|
|
169
|
+
if (SEVERITY_RANK[h.severity] < SEVERITY_RANK[g.severity]) g.severity = h.severity;
|
|
170
|
+
if (!g.commits.includes(commit)) g.commits.push(commit);
|
|
171
|
+
g.values.add(sk);
|
|
172
|
+
g.previews.add(maskValue(h.rule, h.value));
|
|
173
|
+
if (ctx.opts.snippets && g.evidence.length < 3) g.evidence.push(`${short(commit)}: ${maskPersonalPaths(redactLine(content, hits))}`);
|
|
174
|
+
}
|
|
175
|
+
},
|
|
176
|
+
},
|
|
177
|
+
);
|
|
178
|
+
cov.patchBytes = result.bytes;
|
|
179
|
+
cov.truncated = result.truncated;
|
|
180
|
+
cov.commitsScanned = touched.size;
|
|
181
|
+
|
|
182
|
+
// Annotate working-tree findings whose value is also in history.
|
|
183
|
+
for (const g of new Set(ctx.worktreeSecrets.values())) {
|
|
184
|
+
if (!g.historyCommits || !g.finding) continue;
|
|
185
|
+
const n = g.historyCommits.size;
|
|
186
|
+
g.finding.summary += ` The same value is already in ${n} commit${n > 1 ? 's' : ''} of history, so removing it from the file will not un-publish it.`;
|
|
187
|
+
g.finding.inHistory = true;
|
|
188
|
+
g.finding.commands = [`git log --all --oneline -- ${shq(g.path)}`];
|
|
189
|
+
g.finding.actions.push('Because the value is in history, purge it with git-filter-repo or publish a fresh repository after rotating it.');
|
|
190
|
+
g.finding.references.push(REFS.filterRepo);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
for (const g of groups.values()) {
|
|
194
|
+
const n = g.commits.length;
|
|
195
|
+
ctx.add(makeFinding({
|
|
196
|
+
ruleId: `history-secret/${g.rule.id}`, category: 'history', severity: g.severity, confidence: g.confidence,
|
|
197
|
+
title: `${g.rule.title} in history`,
|
|
198
|
+
summary: `${g.values.size} value${g.values.size > 1 ? 's' : ''} (${[...g.previews].slice(0, 2).join(', ')}) added to ${g.path} in ${n} commit${n > 1 ? 's' : ''}; not present in the current files.`,
|
|
199
|
+
why: 'The credential was removed from the current files, but Git keeps every past version. Publishing the repository publishes the secret.',
|
|
200
|
+
actions: [
|
|
201
|
+
'Assume the credential is compromised: revoke or rotate it at the provider.',
|
|
202
|
+
'Then either rewrite history to remove it or publish a fresh repository without the old history.',
|
|
203
|
+
'Rewriting history is not enough on its own: forks, clones and caches may already hold a copy.',
|
|
204
|
+
],
|
|
205
|
+
commands: [`git filter-repo --replace-text <file-with-the-secret-to-replace> # see git-filter-repo docs`],
|
|
206
|
+
locations: g.commits.slice(0, MAX_COMMITS_LISTED).map((c) => ({ path: g.path, commit: short(c) })), count: n,
|
|
207
|
+
evidence: g.evidence, references: [REFS.rotate, REFS.filterRepo], key: `${g.rule.id}|${g.path}`,
|
|
208
|
+
}));
|
|
209
|
+
}
|
|
210
|
+
}
|
|
@@ -0,0 +1,351 @@
|
|
|
1
|
+
// Project-level readiness: ignore rules, documentation, licensing, tests,
|
|
2
|
+
// untracked files and repository configuration.
|
|
3
|
+
|
|
4
|
+
import { readFile } from 'node:fs/promises';
|
|
5
|
+
import { join, posix } from 'node:path';
|
|
6
|
+
import { git, gitText } from '../git.js';
|
|
7
|
+
import { classifySensitive } from '../rules/files.js';
|
|
8
|
+
import { makeFinding, shq, REFS } from '../findings.js';
|
|
9
|
+
|
|
10
|
+
const findRoot = (tracked, re) => tracked.find((p) => re.test(p));
|
|
11
|
+
const read = (root, p) => readFile(join(root, p), 'utf8').catch(() => '');
|
|
12
|
+
|
|
13
|
+
export async function scanProject(ctx) {
|
|
14
|
+
const { tracked } = ctx;
|
|
15
|
+
const facts = {
|
|
16
|
+
ecosystems: detectEcosystems(tracked),
|
|
17
|
+
readme: findRoot(tracked, /^(readme)(\.(md|markdown|rst|txt|adoc|org))?$/i) || null,
|
|
18
|
+
license: findRoot(tracked, /^(licen[cs]e|copying|unlicense)(\.(md|txt|rst))?$/i) || null,
|
|
19
|
+
contributing: findRoot(tracked, /^(\.github\/|docs\/)?contributing(\.(md|rst|txt))?$/i) || null,
|
|
20
|
+
security: findRoot(tracked, /^(\.github\/|docs\/)?security(\.(md|rst|txt))?$/i) || null,
|
|
21
|
+
codeOfConduct: findRoot(tracked, /^(\.github\/|docs\/)?code[_-]of[_-]conduct(\.(md|rst|txt))?$/i) || null,
|
|
22
|
+
changelog: findRoot(tracked, /^(changelog|changes|history|releases?)(\.(md|rst|txt))?$/i) || null,
|
|
23
|
+
gitignore: tracked.includes('.gitignore') ? '.gitignore' : null,
|
|
24
|
+
tests: tracked.filter(isTestPath).length,
|
|
25
|
+
ci: findRoot(tracked, /^(\.github\/workflows\/.+\.ya?ml|\.gitlab-ci\.yml|\.circleci\/config\.yml|azure-pipelines\.yml|Jenkinsfile|\.travis\.yml|bitbucket-pipelines\.yml|\.woodpecker\.ya?ml|\.forgejo\/workflows\/.+)$/i) || null,
|
|
26
|
+
licenseId: null,
|
|
27
|
+
};
|
|
28
|
+
ctx.facts = facts;
|
|
29
|
+
|
|
30
|
+
await checkGitignore(ctx);
|
|
31
|
+
await checkReadme(ctx);
|
|
32
|
+
await checkLicense(ctx);
|
|
33
|
+
checkCommunityFiles(ctx);
|
|
34
|
+
await checkUntracked(ctx);
|
|
35
|
+
await checkConfigCredentials(ctx);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function detectEcosystems(tracked) {
|
|
39
|
+
const has = (re) => tracked.some((p) => re.test(p));
|
|
40
|
+
const eco = [];
|
|
41
|
+
if (has(/(^|\/)package\.json$/)) eco.push('node');
|
|
42
|
+
if (has(/(^|\/)(pyproject\.toml|setup\.py|requirements[^/]*\.txt|Pipfile)$/) || has(/\.py$/)) eco.push('python');
|
|
43
|
+
if (has(/(^|\/)Cargo\.toml$/)) eco.push('rust');
|
|
44
|
+
if (has(/(^|\/)go\.mod$/)) eco.push('go');
|
|
45
|
+
if (has(/(^|\/)(pom\.xml|build\.gradle(\.kts)?)$/)) eco.push('java');
|
|
46
|
+
if (has(/\.(csproj|sln)$/)) eco.push('dotnet');
|
|
47
|
+
if (has(/(^|\/)composer\.json$/)) eco.push('php');
|
|
48
|
+
if (has(/(^|\/)Gemfile$/)) eco.push('ruby');
|
|
49
|
+
if (has(/\.tf$/)) eco.push('terraform');
|
|
50
|
+
return eco;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function isTestPath(p) {
|
|
54
|
+
return /(^|\/)(tests?|__tests__|spec|specs)\//i.test(p)
|
|
55
|
+
|| /\.(test|spec)\.[cm]?[jt]sx?$/i.test(p)
|
|
56
|
+
|| /(^|\/)test_[^/]+\.py$/i.test(p) || /_test\.(py|go|rb|exs?)$/i.test(p)
|
|
57
|
+
|| /(Test|Tests|IT)\.(java|kt|cs|scala)$/.test(p) || /_spec\.rb$/.test(p);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
const PROBES = {
|
|
61
|
+
common: [['.env', 'environment files (.env)'], ['.DS_Store', 'macOS metadata (.DS_Store)'], ['debug.log', 'log files (*.log)']],
|
|
62
|
+
node: [['node_modules/x', 'node_modules/'], ['npm-debug.log', 'npm debug logs']],
|
|
63
|
+
python: [['__pycache__/x.pyc', '__pycache__/'], ['.venv/x', 'virtualenvs (.venv/)']],
|
|
64
|
+
rust: [['target/x', 'target/']],
|
|
65
|
+
go: [['x.test', 'Go test binaries (*.test)']],
|
|
66
|
+
java: [['x.class', 'compiled classes (*.class)']],
|
|
67
|
+
dotnet: [['bin/x', 'bin/'], ['obj/x', 'obj/']],
|
|
68
|
+
php: [['vendor/x', 'vendor/']],
|
|
69
|
+
terraform: [['.terraform/x', '.terraform/'], ['terraform.tfstate', 'Terraform state (*.tfstate)']],
|
|
70
|
+
};
|
|
71
|
+
|
|
72
|
+
async function checkGitignore(ctx) {
|
|
73
|
+
const { root, facts } = ctx;
|
|
74
|
+
if (!facts.gitignore) {
|
|
75
|
+
ctx.add(makeFinding({
|
|
76
|
+
ruleId: 'gitignore-missing', category: 'hygiene', severity: 'medium', title: 'No .gitignore file',
|
|
77
|
+
summary: 'The repository has no root .gitignore, so local secrets, logs and build output are one `git add .` away from being published.',
|
|
78
|
+
why: 'Contributors will run the project locally and generate files you never intended to share.',
|
|
79
|
+
actions: [`Add a .gitignore for your stack${facts.ecosystems.length ? ` (${facts.ecosystems.join(', ')})` : ''}, including \`.env\` and log files.`],
|
|
80
|
+
references: [REFS.gitignore],
|
|
81
|
+
}));
|
|
82
|
+
}
|
|
83
|
+
const probes = [...PROBES.common, ...facts.ecosystems.flatMap((e) => PROBES[e] || [])];
|
|
84
|
+
// check-ignore --no-index evaluates rules for hypothetical paths without touching the index.
|
|
85
|
+
const { stdout } = await git(['check-ignore', '--no-index', '-v', '-n', '--stdin'], {
|
|
86
|
+
cwd: root, input: `${probes.map(([p]) => p).join('\n')}\n`, allowFailure: true,
|
|
87
|
+
});
|
|
88
|
+
const missing = [];
|
|
89
|
+
const globalOnly = [];
|
|
90
|
+
for (const line of stdout.toString('utf8').split('\n')) {
|
|
91
|
+
if (!line.trim()) continue;
|
|
92
|
+
const tab = line.lastIndexOf('\t');
|
|
93
|
+
const m = line.slice(0, tab).match(/^(.*):(\d+):(.*)$/);
|
|
94
|
+
const source = m ? m[1] : '';
|
|
95
|
+
const negated = m ? m[3].startsWith('!') : false;
|
|
96
|
+
const path = line.slice(tab + 1);
|
|
97
|
+
const probe = probes.find(([p]) => p === path);
|
|
98
|
+
if (!probe) continue;
|
|
99
|
+
if (!source || negated) missing.push(probe[1]);
|
|
100
|
+
else if (!isRepoIgnoreSource(source)) globalOnly.push(probe[1]);
|
|
101
|
+
}
|
|
102
|
+
if (facts.gitignore && missing.length) {
|
|
103
|
+
ctx.add(makeFinding({
|
|
104
|
+
ruleId: 'gitignore-gaps', category: 'hygiene', severity: missing.some((m) => m.startsWith('environment')) ? 'medium' : 'low',
|
|
105
|
+
title: '.gitignore misses common patterns',
|
|
106
|
+
summary: `Not ignored: ${missing.join(', ')}.`,
|
|
107
|
+
why: 'Without these rules a contributor (or you, later) can accidentally commit credentials or generated files.',
|
|
108
|
+
actions: ['Add the missing patterns to .gitignore.'],
|
|
109
|
+
references: [REFS.gitignore],
|
|
110
|
+
}));
|
|
111
|
+
}
|
|
112
|
+
if (globalOnly.length) {
|
|
113
|
+
ctx.add(makeFinding({
|
|
114
|
+
ruleId: 'gitignore-global-only', category: 'hygiene', severity: 'low',
|
|
115
|
+
title: 'Some files are ignored only by your personal Git config',
|
|
116
|
+
summary: `Ignored on this machine but not by the repository: ${globalOnly.join(', ')}.`,
|
|
117
|
+
why: 'Your global excludes do not travel with the repository. Contributors will not be protected by them.',
|
|
118
|
+
actions: ['Copy those patterns into the repository .gitignore.'],
|
|
119
|
+
}));
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function isRepoIgnoreSource(source) {
|
|
124
|
+
const s = source.replace(/\\/g, '/');
|
|
125
|
+
return s === '.gitignore' || s.endsWith('/.gitignore') && !s.startsWith('/') && !/^[A-Za-z]:\//.test(s);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
async function checkReadme(ctx) {
|
|
129
|
+
const { root, facts, trackedSet } = ctx;
|
|
130
|
+
if (!facts.readme) {
|
|
131
|
+
ctx.add(makeFinding({
|
|
132
|
+
ruleId: 'readme-missing', category: 'docs', severity: 'medium', title: 'No README',
|
|
133
|
+
summary: 'Visitors will land on a file list with no explanation.',
|
|
134
|
+
why: 'The README is the landing page of a public repository: what it is, how to install it, how to use it.',
|
|
135
|
+
actions: ['Add a README.md with a one-line description, installation, usage and license sections.'],
|
|
136
|
+
}));
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
const text = await read(root, facts.readme);
|
|
140
|
+
const plain = text.replace(/<!--[\s\S]*?-->/g, '').trim();
|
|
141
|
+
facts.readmeLength = plain.length;
|
|
142
|
+
const problems = [];
|
|
143
|
+
if (plain.length < 250) problems.push(`it is very short (${plain.length} characters)`);
|
|
144
|
+
const lower = plain.toLowerCase();
|
|
145
|
+
if (!/(install|getting started|quick ?start|setup|usage|how to)/.test(lower)) problems.push('there is no installation or usage section');
|
|
146
|
+
if (/lorem ipsum|todo: ?write|coming soon|\[project name\]|your project name/i.test(plain)) problems.push('it still contains placeholder text');
|
|
147
|
+
if (problems.length) {
|
|
148
|
+
ctx.add(makeFinding({
|
|
149
|
+
ruleId: 'readme-thin', category: 'docs', severity: 'low', title: 'README needs work before launch',
|
|
150
|
+
summary: `${facts.readme}: ${problems.join('; ')}.`,
|
|
151
|
+
why: 'First-time visitors decide within seconds whether a project is usable. A thin README reads as unfinished.',
|
|
152
|
+
actions: ['Explain what the project does, who it is for, how to install and run it, and its license.'],
|
|
153
|
+
locations: [{ path: facts.readme }],
|
|
154
|
+
}));
|
|
155
|
+
}
|
|
156
|
+
// Broken relative links and images.
|
|
157
|
+
const broken = [];
|
|
158
|
+
const dir = posix.dirname(facts.readme);
|
|
159
|
+
for (const m of plain.matchAll(/!?\[[^\]]*\]\(([^)\s]+)(?:\s+"[^"]*")?\)/g)) {
|
|
160
|
+
const target = m[1];
|
|
161
|
+
if (/^([a-z][a-z0-9+.-]*:|#|\/\/|mailto:)/i.test(target)) continue;
|
|
162
|
+
const clean = decodeURIComponent(target.split('#')[0].split('?')[0]);
|
|
163
|
+
if (!clean) continue;
|
|
164
|
+
const resolved = posix.normalize(posix.join(dir === '.' ? '' : dir, clean)).replace(/^\.\//, '').replace(/\/$/, '');
|
|
165
|
+
if (trackedSet.has(resolved) || ctx.tracked.some((p) => p.startsWith(`${resolved}/`))) continue;
|
|
166
|
+
broken.push(clean);
|
|
167
|
+
}
|
|
168
|
+
if (broken.length) {
|
|
169
|
+
ctx.add(makeFinding({
|
|
170
|
+
ruleId: 'readme-broken-links', category: 'docs', severity: 'low', title: 'README links to files that are not tracked',
|
|
171
|
+
summary: `${broken.length} relative link${broken.length > 1 ? 's' : ''} point to missing or untracked files: ${broken.slice(0, 5).join(', ')}.`,
|
|
172
|
+
why: 'Links that work on your machine (untracked screenshots, local docs) will be broken for everyone else.',
|
|
173
|
+
actions: ['Commit the referenced files or fix the links.'],
|
|
174
|
+
locations: [{ path: facts.readme }],
|
|
175
|
+
}));
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
const LICENSES = [
|
|
180
|
+
['AGPL-3.0', /GNU AFFERO GENERAL PUBLIC LICENSE/i],
|
|
181
|
+
['LGPL-3.0', /GNU LESSER GENERAL PUBLIC LICENSE[\s\S]{0,200}Version 3/i],
|
|
182
|
+
['LGPL-2.1', /GNU LESSER GENERAL PUBLIC LICENSE[\s\S]{0,200}Version 2\.1/i],
|
|
183
|
+
['GPL-3.0', /GNU GENERAL PUBLIC LICENSE[\s\S]{0,200}Version 3/i],
|
|
184
|
+
['GPL-2.0', /GNU GENERAL PUBLIC LICENSE[\s\S]{0,200}Version 2/i],
|
|
185
|
+
['Apache-2.0', /Apache License[\s\S]{0,100}Version 2\.0/i],
|
|
186
|
+
['MPL-2.0', /Mozilla Public License,? (Version|v\.?) ?2\.0/i],
|
|
187
|
+
['BSL-1.0', /Boost Software License/i],
|
|
188
|
+
['Unlicense', /This is free and unencumbered software released into the public domain/i],
|
|
189
|
+
['BSD-3-Clause', /Redistribution and use in source and binary forms[\s\S]*Neither the name/i],
|
|
190
|
+
['BSD-2-Clause', /Redistribution and use in source and binary forms/i],
|
|
191
|
+
['ISC', /Permission to use, copy, modify, and\/or distribute this software for any purpose/i],
|
|
192
|
+
['MIT', /Permission is hereby granted, free of charge, to any person obtaining a copy/i],
|
|
193
|
+
['CC0-1.0', /CC0 1\.0 Universal/i],
|
|
194
|
+
];
|
|
195
|
+
|
|
196
|
+
async function checkLicense(ctx) {
|
|
197
|
+
const { root, facts } = ctx;
|
|
198
|
+
if (!facts.license) {
|
|
199
|
+
ctx.add(makeFinding({
|
|
200
|
+
ruleId: 'license-missing', category: 'docs', severity: 'high', title: 'No license',
|
|
201
|
+
summary: 'Without a license, nobody may legally use, copy, modify or distribute the code, even when it is public.',
|
|
202
|
+
why: 'Default copyright applies to unlicensed code. Companies and serious contributors will not touch it.',
|
|
203
|
+
actions: ['Choose a license (MIT, Apache-2.0 and GPL-3.0 are common) and add it as LICENSE in the repository root.', 'Declare the same license in your package manifest.'],
|
|
204
|
+
references: [REFS.license],
|
|
205
|
+
}));
|
|
206
|
+
return;
|
|
207
|
+
}
|
|
208
|
+
const text = await read(root, facts.license);
|
|
209
|
+
const id = LICENSES.find(([, re]) => re.test(text))?.[0] || null;
|
|
210
|
+
facts.licenseId = id;
|
|
211
|
+
if (!id) {
|
|
212
|
+
ctx.add(makeFinding({
|
|
213
|
+
ruleId: 'license-unrecognized', category: 'docs', severity: 'low', title: 'License text not recognised',
|
|
214
|
+
summary: `${facts.license} does not match a common open-source license text.`,
|
|
215
|
+
why: 'Custom or modified licenses make adoption harder and are easy to get wrong. This may be intentional.',
|
|
216
|
+
actions: ['Prefer an unmodified OSI-approved license text, or have a custom license reviewed.'],
|
|
217
|
+
locations: [{ path: facts.license }], references: [REFS.license],
|
|
218
|
+
}));
|
|
219
|
+
}
|
|
220
|
+
if (/\[(year|yyyy|fullname|name of copyright owner|copyright holders?)\]|<(year|copyright holders?|name of author)>|\{\{\s*(year|author)/i.test(text)) {
|
|
221
|
+
ctx.add(makeFinding({
|
|
222
|
+
ruleId: 'license-placeholder', category: 'docs', severity: 'medium', title: 'License still contains template placeholders',
|
|
223
|
+
summary: `${facts.license} contains unfilled fields such as [year] or [fullname].`,
|
|
224
|
+
why: 'An incomplete copyright line weakens the notice and looks unfinished.',
|
|
225
|
+
actions: ['Fill in the year and the copyright holder.'],
|
|
226
|
+
locations: [{ path: facts.license }],
|
|
227
|
+
}));
|
|
228
|
+
}
|
|
229
|
+
// Manifest consistency (package.json, pyproject, Cargo.toml).
|
|
230
|
+
const declared = [];
|
|
231
|
+
if (ctx.trackedSet.has('package.json')) {
|
|
232
|
+
try { const pkg = JSON.parse(await read(root, 'package.json')); if (typeof pkg.license === 'string') declared.push(['package.json', pkg.license]); } catch { /* ignore */ }
|
|
233
|
+
}
|
|
234
|
+
for (const f of ['pyproject.toml', 'Cargo.toml']) {
|
|
235
|
+
if (!ctx.trackedSet.has(f)) continue;
|
|
236
|
+
const m = (await read(root, f)).match(/^\s*license\s*=\s*(?:\{\s*text\s*=\s*)?["']([^"']+)["']/m);
|
|
237
|
+
if (m) declared.push([f, m[1]]);
|
|
238
|
+
}
|
|
239
|
+
const norm = (s) => s.toUpperCase().replace(/[^A-Z0-9.]/g, '').replace(/LICENSE$/, '');
|
|
240
|
+
for (const [file, lic] of declared) {
|
|
241
|
+
if (id && !norm(lic).includes(norm(id).replace(/CLAUSE$/, '')) && !/SEE LICENSE/i.test(lic)) {
|
|
242
|
+
ctx.add(makeFinding({
|
|
243
|
+
ruleId: 'license-mismatch', category: 'docs', severity: 'medium', title: 'Manifest license differs from LICENSE file',
|
|
244
|
+
summary: `${file} declares "${lic}" but ${facts.license} looks like ${id}.`,
|
|
245
|
+
why: 'Package registries display the manifest value. Conflicting declarations create legal ambiguity.',
|
|
246
|
+
actions: ['Make the manifest and the LICENSE file agree.'],
|
|
247
|
+
locations: [{ path: file }, { path: facts.license }], key: file,
|
|
248
|
+
}));
|
|
249
|
+
}
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
function checkCommunityFiles(ctx) {
|
|
254
|
+
const { facts } = ctx;
|
|
255
|
+
if (!facts.contributing) {
|
|
256
|
+
ctx.add(makeFinding({
|
|
257
|
+
ruleId: 'contributing-missing', category: 'docs', severity: 'low', title: 'No contribution guidelines',
|
|
258
|
+
summary: 'There is no CONTRIBUTING file explaining how to report issues or submit changes.',
|
|
259
|
+
why: 'Clear guidelines get you better issues and pull requests and fewer repeated questions.',
|
|
260
|
+
actions: ['Add CONTRIBUTING.md with setup, test and pull-request instructions.'], references: [REFS.contributing],
|
|
261
|
+
}));
|
|
262
|
+
}
|
|
263
|
+
if (!facts.security) {
|
|
264
|
+
ctx.add(makeFinding({
|
|
265
|
+
ruleId: 'security-policy-missing', category: 'docs', severity: 'low', title: 'No security policy',
|
|
266
|
+
summary: 'There is no SECURITY.md telling people how to report vulnerabilities privately.',
|
|
267
|
+
why: 'Without a private channel, vulnerabilities get reported in public issues.',
|
|
268
|
+
actions: ['Add SECURITY.md with a private contact or enable GitHub private vulnerability reporting.'], references: [REFS.security],
|
|
269
|
+
}));
|
|
270
|
+
}
|
|
271
|
+
if (!facts.tests) {
|
|
272
|
+
ctx.add(makeFinding({
|
|
273
|
+
ruleId: 'tests-missing', category: 'docs', severity: 'low', title: 'No automated tests found',
|
|
274
|
+
summary: 'No test files or test directories were detected.',
|
|
275
|
+
why: 'Tests signal quality to adopters and let contributors change code safely.',
|
|
276
|
+
actions: ['Add at least a smoke test suite and document how to run it.'],
|
|
277
|
+
}));
|
|
278
|
+
}
|
|
279
|
+
if (!facts.ci) {
|
|
280
|
+
ctx.add(makeFinding({
|
|
281
|
+
ruleId: 'ci-missing', category: 'docs', severity: 'info', title: 'No continuous integration configuration',
|
|
282
|
+
summary: 'No CI workflow (GitHub Actions, GitLab CI, …) was found.',
|
|
283
|
+
why: 'CI runs your tests on every pull request from contributors.',
|
|
284
|
+
actions: ['Add a minimal workflow that installs dependencies and runs the tests.'],
|
|
285
|
+
}));
|
|
286
|
+
}
|
|
287
|
+
if (!facts.codeOfConduct) {
|
|
288
|
+
ctx.add(makeFinding({
|
|
289
|
+
ruleId: 'code-of-conduct-missing', category: 'docs', severity: 'info', title: 'No code of conduct',
|
|
290
|
+
summary: 'Optional, but expected by many communities and required by some foundations.',
|
|
291
|
+
why: 'A code of conduct sets expectations for behaviour in issues and discussions.',
|
|
292
|
+
actions: ['Consider adopting the Contributor Covenant.'],
|
|
293
|
+
}));
|
|
294
|
+
}
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
async function checkUntracked(ctx) {
|
|
298
|
+
const { untracked } = ctx;
|
|
299
|
+
const risky = untracked.map((p) => [p, classifySensitive(p)]).filter(([p, r]) => r && !ctx.isIgnoredPath(p));
|
|
300
|
+
if (risky.length) {
|
|
301
|
+
ctx.add(makeFinding({
|
|
302
|
+
ruleId: 'untracked-sensitive', category: 'files', severity: 'medium',
|
|
303
|
+
title: 'Sensitive files are not ignored',
|
|
304
|
+
summary: `${risky.length} untracked file${risky.length > 1 ? 's' : ''} that look sensitive are not covered by .gitignore. They are not published yet, but \`git add .\` would publish them.`,
|
|
305
|
+
why: 'Accidental `git add -A` is the most common way secrets reach a public repository.',
|
|
306
|
+
actions: ['Add these paths (or their patterns) to .gitignore.'],
|
|
307
|
+
locations: risky.map(([path, r]) => ({ path, note: r.title })), count: risky.length,
|
|
308
|
+
}));
|
|
309
|
+
}
|
|
310
|
+
ctx.coverage.worktree.untracked = untracked.length;
|
|
311
|
+
if (ctx.modified.length) {
|
|
312
|
+
ctx.add(makeFinding({
|
|
313
|
+
ruleId: 'uncommitted-changes', category: 'hygiene', severity: 'info', title: 'Uncommitted changes',
|
|
314
|
+
summary: `${ctx.modified.length} tracked file${ctx.modified.length > 1 ? 's have' : ' has'} local modifications. Prepublic scanned the working-tree versions; re-run after committing.`,
|
|
315
|
+
why: 'What you publish is what is committed, not what is on disk.',
|
|
316
|
+
actions: ['Commit or discard the changes, then re-run Prepublic.'],
|
|
317
|
+
locations: ctx.modified.slice(0, 20).map((path) => ({ path })), count: ctx.modified.length,
|
|
318
|
+
}));
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
const CRED_URL = /^([a-z][a-z0-9+.-]*:\/\/)([^/@\s]+)@/i;
|
|
323
|
+
const maskUrl = (u) => u.replace(CRED_URL, '$1•••@').replace(/([?&](?:token|access_token|key)=)[^&\s]+/gi, '$1•••');
|
|
324
|
+
|
|
325
|
+
async function checkConfigCredentials(ctx) {
|
|
326
|
+
const { root } = ctx;
|
|
327
|
+
if (ctx.trackedSet.has('.gitmodules')) {
|
|
328
|
+
const text = await read(root, '.gitmodules');
|
|
329
|
+
const bad = [...text.matchAll(/url\s*=\s*(\S+)/g)].map((m) => m[1]).filter((u) => CRED_URL.test(u) && /:[^/@]+@/.test(u.replace(/^[a-z+]+:\/\//i, '')));
|
|
330
|
+
if (bad.length) {
|
|
331
|
+
ctx.add(makeFinding({
|
|
332
|
+
ruleId: 'submodule-credentials', category: 'secrets', severity: 'critical', title: 'Credentials in submodule URL',
|
|
333
|
+
summary: `.gitmodules contains ${bad.length} URL${bad.length > 1 ? 's' : ''} with embedded credentials (${bad.map(maskUrl).join(', ')}).`,
|
|
334
|
+
why: '.gitmodules is published with the repository; the embedded token is readable by everyone.',
|
|
335
|
+
actions: ['Rotate the token.', 'Use a plain HTTPS or SSH URL and let a credential helper supply authentication.'],
|
|
336
|
+
locations: [{ path: '.gitmodules' }], references: [REFS.rotate],
|
|
337
|
+
}));
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
const remotes = await gitText(['config', '--get-regexp', '^remote\\..*\\.url$'], { cwd: root }).catch(() => '');
|
|
341
|
+
const withCreds = remotes.split('\n').map((l) => l.split(' ')).filter(([, u]) => u && CRED_URL.test(u) && /:[^/@]+@/.test(u.replace(/^[a-z+]+:\/\//i, '')));
|
|
342
|
+
if (withCreds.length) {
|
|
343
|
+
ctx.add(makeFinding({
|
|
344
|
+
ruleId: 'remote-credentials', category: 'secrets', severity: 'medium', title: 'Token stored in a Git remote URL',
|
|
345
|
+
summary: `${withCreds.map(([k, u]) => `${k.replace(/^remote\.|\.url$/g, '')} → ${maskUrl(u)}`).join(', ')}. Local .git/config is not published, but the token sits in plain text and is easy to leak in logs or screenshots.`,
|
|
346
|
+
why: 'Plain-text tokens in remote URLs show up in terminal output, CI logs and support requests.',
|
|
347
|
+
actions: ['Rotate the token.', 'Reset the URL without credentials and use a credential helper.'],
|
|
348
|
+
commands: withCreds.map(([k, u]) => `git remote set-url ${k.replace(/^remote\.|\.url$/g, '')} ${shq(u.replace(CRED_URL, '$1'))}`),
|
|
349
|
+
}));
|
|
350
|
+
}
|
|
351
|
+
}
|