@arifbiswas/git-pre-push 1.0.13 → 1.0.16
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/README.md +89 -2
- package/bin/cli.js +125 -11
- package/package.json +1 -1
- package/scripts/postinstall.js +13 -1
- package/src/advancedScanner.js +438 -0
- package/src/doctor.js +336 -0
- package/src/index.js +61 -5
- package/src/installer.js +111 -27
- package/src/menu.js +51 -3
- package/src/shellIntegration.js +212 -0
- package/src/updateNotifier.js +178 -10
- package/src/vault.js +4 -0
- package/src/vaultCli.js +4 -1
|
@@ -0,0 +1,438 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Advanced Scanner: audits every project inside a folder in one run.
|
|
3
|
+
*
|
|
4
|
+
* gitsafty scan-projects <folder> [--clean] [--deep] [--json]
|
|
5
|
+
*
|
|
6
|
+
* A "project" is every direct sub-folder (git repository or not), plus the
|
|
7
|
+
* folder itself if it is a git repository. For each project:
|
|
8
|
+
* - malware engine (confirmed + suspect) on every file
|
|
9
|
+
* - dangerous / disguised file names
|
|
10
|
+
* - IDE auto-run backdoors (.vscode, .idea)
|
|
11
|
+
* - hard-coded secrets (masked in the report)
|
|
12
|
+
* - git persistence tricks that run code on normal git commands:
|
|
13
|
+
* unknown hooks in .git/hooks, core.fsmonitor, core.hooksPath,
|
|
14
|
+
* core.sshCommand, filter drivers, diff.external, "!" aliases
|
|
15
|
+
* Files ignored by .gitignore and node_modules / build folders are skipped
|
|
16
|
+
* unless --deep is given. Confirmed malware is only removed with --clean.
|
|
17
|
+
* A JSON report is written to ~/.gitsafty/reports/.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
const fs = require('fs');
|
|
21
|
+
const os = require('os');
|
|
22
|
+
const path = require('path');
|
|
23
|
+
const { spawnSync } = require('child_process');
|
|
24
|
+
const { detectMalware, CONFIRMED } = require('./rules/malware');
|
|
25
|
+
const { checkFilename } = require('./rules/filenames');
|
|
26
|
+
const { inspectIdeConfig } = require('./rules/ideConfig');
|
|
27
|
+
const { scanSecrets } = require('./rules/secrets');
|
|
28
|
+
const { removeConfirmedMalware, printCleanResults, notifyDesktop } = require('./malwareCleaner');
|
|
29
|
+
const { colors } = require('./reporter');
|
|
30
|
+
|
|
31
|
+
const SKIP_DIRS = new Set(['node_modules', '.git', '.next', '.nuxt', 'dist', 'build', 'out', 'coverage', 'Pods', '.gradle',
|
|
32
|
+
'.dart_tool', '.expo', '.venv', 'venv', '__pycache__', '.idea-cache', 'DerivedData', '.turbo', '.cache', 'vendor', 'target',
|
|
33
|
+
'.cxx', '.externalNativeBuild', '.svelte-kit', '.parcel-cache']);
|
|
34
|
+
// Standard build-tool wrappers that are scripts by design.
|
|
35
|
+
const KNOWN_GOOD_SCRIPTS = new Set(['gradlew.bat', 'mvnw.cmd', 'gradlew', 'mvnw']);
|
|
36
|
+
|
|
37
|
+
/** True when a path is inside a dependency / build folder (only the malware engine runs there). */
|
|
38
|
+
function inGeneratedDir(rel) {
|
|
39
|
+
return rel.split('/').slice(0, -1).some(seg => SKIP_DIRS.has(seg));
|
|
40
|
+
}
|
|
41
|
+
const MAX_FILE = 8 * 1024 * 1024;
|
|
42
|
+
const MAX_TEXT_FOR_SECRETS = 1024 * 1024;
|
|
43
|
+
const SAMPLE_HOOK = /\.sample$/;
|
|
44
|
+
|
|
45
|
+
function git(args, cwd) {
|
|
46
|
+
const r = spawnSync('git', args, { cwd, encoding: 'utf8', maxBuffer: 256 * 1024 * 1024 });
|
|
47
|
+
return r.status === 0 ? r.stdout : null;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function isWin() {
|
|
51
|
+
return process.platform === 'win32';
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
function isGitRepo(dir) {
|
|
55
|
+
return fs.existsSync(path.join(dir, '.git'));
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
function listFilesGit(dir) {
|
|
59
|
+
const out = git(['ls-files', '-z', '--cached', '--others', '--exclude-standard'], dir);
|
|
60
|
+
return out ? out.split('\0').filter(Boolean) : [];
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Lists a project's files. Git repositories (also nested ones inside a plain
|
|
65
|
+
* folder) are listed with git so .gitignore is respected.
|
|
66
|
+
* @returns {{ files: string[], tracked: Set<string> }} tracked = files git tracks
|
|
67
|
+
*/
|
|
68
|
+
function listProjectFiles(dir, deep) {
|
|
69
|
+
const files = [];
|
|
70
|
+
const tracked = new Set();
|
|
71
|
+
|
|
72
|
+
const addRepo = (repoDir, prefix) => {
|
|
73
|
+
const trackedOut = git(['ls-files', '-z'], repoDir);
|
|
74
|
+
for (const f of (trackedOut || '').split('\0').filter(Boolean)) tracked.add(prefix + f);
|
|
75
|
+
if (deep) return false;
|
|
76
|
+
const all = listFilesGit(repoDir);
|
|
77
|
+
if (!all.length) return false;
|
|
78
|
+
for (const f of all) files.push(prefix + f);
|
|
79
|
+
return true;
|
|
80
|
+
};
|
|
81
|
+
|
|
82
|
+
const walk = (rel) => {
|
|
83
|
+
const abs = path.join(dir, rel);
|
|
84
|
+
if (fs.existsSync(path.join(abs, '.git')) && addRepo(abs, rel ? `${rel}/` : '')) return;
|
|
85
|
+
let entries;
|
|
86
|
+
try { entries = fs.readdirSync(abs, { withFileTypes: true }); } catch (_) { return; }
|
|
87
|
+
for (const e of entries) {
|
|
88
|
+
if (e.isSymbolicLink()) continue;
|
|
89
|
+
const r = rel ? `${rel}/${e.name}` : e.name;
|
|
90
|
+
if (e.isDirectory()) {
|
|
91
|
+
if (e.name === '.git' || (!deep && SKIP_DIRS.has(e.name))) continue;
|
|
92
|
+
walk(r);
|
|
93
|
+
} else if (e.isFile()) {
|
|
94
|
+
files.push(r);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
walk('');
|
|
99
|
+
return { files, tracked };
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function mask(text) {
|
|
103
|
+
return String(text).replace(/([A-Za-z0-9_\-]{4})[A-Za-z0-9_\-+/=]{8,}/g, '$1••••••••');
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// ---------------------------------------------------------------------------
|
|
107
|
+
// Git persistence checks
|
|
108
|
+
// ---------------------------------------------------------------------------
|
|
109
|
+
|
|
110
|
+
function gitPersistenceFindings(dir) {
|
|
111
|
+
const findings = [];
|
|
112
|
+
if (!isGitRepo(dir)) return findings;
|
|
113
|
+
const gitDir = path.join(dir, '.git');
|
|
114
|
+
|
|
115
|
+
// 1. Unknown executable hooks inside the repository
|
|
116
|
+
const hooksDir = path.join(gitDir, 'hooks');
|
|
117
|
+
let hooks = [];
|
|
118
|
+
try { hooks = fs.readdirSync(hooksDir); } catch (_) {}
|
|
119
|
+
for (const h of hooks) {
|
|
120
|
+
if (SAMPLE_HOOK.test(h)) continue;
|
|
121
|
+
const file = path.join(hooksDir, h);
|
|
122
|
+
let content = '';
|
|
123
|
+
try {
|
|
124
|
+
if (!fs.statSync(file).isFile()) continue;
|
|
125
|
+
content = fs.readFileSync(file, 'utf8');
|
|
126
|
+
} catch (_) { continue; }
|
|
127
|
+
if (content.includes('GIT-SAFTY SECURITY HOOK')) continue;
|
|
128
|
+
if (/husky|lint-staged|pre-commit\.com|lefthook|simple-git-hooks|git-lfs|gitleaks|talisman/i.test(content)) continue;
|
|
129
|
+
const malware = detectMalware(`.git/hooks/${h}`, Buffer.from(content));
|
|
130
|
+
const dangerous = /(curl|wget|Invoke-WebRequest|iwr)\b[^\n|]*\|\s*(ba|z)?sh|base64\s+(-d|--decode)|node\s+-e|python[0-9]?\s+-c|powershell[^\n]*-e(nc)?\s|\/dev\/tcp\/|nc\s+-e/i.test(content);
|
|
131
|
+
findings.push({
|
|
132
|
+
category: 'git-backdoor',
|
|
133
|
+
verdict: malware.some(f => f.verdict === CONFIRMED) ? CONFIRMED : 'SUSPECT',
|
|
134
|
+
name: `Unknown git hook: .git/hooks/${h}`,
|
|
135
|
+
description: dangerous
|
|
136
|
+
? 'Runs on normal git commands and downloads/decodes/executes code. Classic persistence trick.'
|
|
137
|
+
: 'Runs automatically on git commands. Hooks are not part of the repository, so something on this PC put it there. Check it is yours.',
|
|
138
|
+
filePath: `.git/hooks/${h}`,
|
|
139
|
+
fixCommand: isWin() ? `Remove-Item "${file}"` : `rm "${file}"`,
|
|
140
|
+
line: content.split('\n').find(l => l.trim() && !l.startsWith('#!')) || '',
|
|
141
|
+
severity: dangerous ? 'CRITICAL' : 'WARNING'
|
|
142
|
+
});
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// 2. Config keys that execute commands
|
|
146
|
+
const cfg = git(['config', '--local', '--list'], dir) || '';
|
|
147
|
+
const risky = [
|
|
148
|
+
[/^core\.fsmonitor=(?!true$|false$)(.+)/i, 'core.fsmonitor runs this command on every git status / git add'],
|
|
149
|
+
[/^core\.hookspath=(.+)/i, 'core.hooksPath moves hooks to another folder (often used to hide malicious hooks)'],
|
|
150
|
+
[/^core\.sshcommand=(.+)/i, 'core.sshCommand replaces ssh for every fetch/push'],
|
|
151
|
+
[/^core\.(editor|pager|askpass)=(.+)/i, 'Runs this program during normal git commands'],
|
|
152
|
+
[/^filter\.[^.]+\.(clean|smudge|process)=(.+)/i, 'Filter driver runs this command on checkout / add'],
|
|
153
|
+
[/^diff\.external=(.+)/i, 'diff.external runs this program on every git diff'],
|
|
154
|
+
[/^alias\.[^=]+=!(.+)/i, 'Alias that runs a shell command'],
|
|
155
|
+
[/^credential\.[^=]*helper=(.+)/i, 'Repository-local credential helper (can capture your GitHub login)']
|
|
156
|
+
];
|
|
157
|
+
for (const line of cfg.split('\n')) {
|
|
158
|
+
for (const [re, why] of risky) {
|
|
159
|
+
const m = line.match(re);
|
|
160
|
+
if (!m) continue;
|
|
161
|
+
if (/^core\.hookspath=\.husky/i.test(line) || /^filter\.lfs\./i.test(line)) continue;
|
|
162
|
+
const value = m[m.length - 1];
|
|
163
|
+
const dangerous = /(curl|wget|base64|\/dev\/tcp|node\s+-e|python[0-9]?\s+-c|powershell|nc\s+-e|\.woff2?|\.png|\.ttf)/i.test(value);
|
|
164
|
+
findings.push({
|
|
165
|
+
category: 'git-backdoor',
|
|
166
|
+
verdict: 'SUSPECT',
|
|
167
|
+
severity: dangerous ? 'CRITICAL' : 'WARNING',
|
|
168
|
+
name: `Git config: ${line.split('=')[0]}`,
|
|
169
|
+
description: why + '.',
|
|
170
|
+
filePath: '.git/config',
|
|
171
|
+
fixCommand: `git -C "${dir}" config --local --unset-all ${line.split('=')[0]}`,
|
|
172
|
+
line: value
|
|
173
|
+
});
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
return findings;
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
// ---------------------------------------------------------------------------
|
|
180
|
+
// Per-project scan
|
|
181
|
+
// ---------------------------------------------------------------------------
|
|
182
|
+
|
|
183
|
+
function scanProject(dir, { deep = false } = {}) {
|
|
184
|
+
const started = Date.now();
|
|
185
|
+
const { files, tracked } = listProjectFiles(dir, deep);
|
|
186
|
+
const findings = [];
|
|
187
|
+
// Project's own ignore list (.gitsafetyrc.json). It never turns off the malware engine.
|
|
188
|
+
const { loadConfig } = require('./config');
|
|
189
|
+
const ignore = (loadConfig(dir).ignoreFiles || []);
|
|
190
|
+
const ignored = (rel) => ignore.some(p => (p.startsWith('*') ? rel.endsWith(p.slice(1)) : rel === p || rel.endsWith('/' + p)));
|
|
191
|
+
|
|
192
|
+
for (const rel of files) {
|
|
193
|
+
const full = path.join(dir, rel);
|
|
194
|
+
let st;
|
|
195
|
+
try { st = fs.lstatSync(full); } catch (_) { continue; }
|
|
196
|
+
if (!st.isFile() || st.size === 0) continue;
|
|
197
|
+
|
|
198
|
+
const generated = inGeneratedDir(rel);
|
|
199
|
+
const skipRules = generated || ignored(rel);
|
|
200
|
+
const base = rel.split('/').pop();
|
|
201
|
+
const nameRule = skipRules || KNOWN_GOOD_SCRIPTS.has(base) ? null : checkFilename(rel);
|
|
202
|
+
if (nameRule) {
|
|
203
|
+
findings.push({ category: 'file', verdict: 'SUSPECT', severity: nameRule.severity, name: nameRule.rule, description: 'Dangerous, executable or disguised file name.', filePath: rel });
|
|
204
|
+
}
|
|
205
|
+
if (st.size > MAX_FILE) continue;
|
|
206
|
+
|
|
207
|
+
let buf;
|
|
208
|
+
try { buf = fs.readFileSync(full); } catch (_) { continue; }
|
|
209
|
+
|
|
210
|
+
for (const f of detectMalware(rel, buf)) {
|
|
211
|
+
findings.push({ category: 'malware', ...f });
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
if (skipRules) continue;
|
|
215
|
+
const norm = rel.replace(/\\/g, '/');
|
|
216
|
+
if (/(^|\/)\.vscode\/(tasks|settings)\.json$/.test(norm) || /(^|\/)\.idea\//.test(norm)) {
|
|
217
|
+
for (const f of inspectIdeConfig(rel, buf.toString('utf8'))) {
|
|
218
|
+
findings.push({ category: 'ide', verdict: 'SUSPECT', filePath: rel, ...f });
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
if (buf.length <= MAX_TEXT_FOR_SECRETS && !buf.subarray(0, 8000).includes(0)) {
|
|
223
|
+
const isEnv = /(^|\/)\.env(\.|$)/.test(norm);
|
|
224
|
+
// .env files only matter when git tracks them (otherwise they are local config).
|
|
225
|
+
if (isEnv && !tracked.has(rel)) continue;
|
|
226
|
+
for (const f of scanSecrets(buf.toString('utf8'), rel)) {
|
|
227
|
+
findings.push({ category: 'secret', verdict: 'SUSPECT', ...f, filePath: rel, line: mask(f.line || '') });
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
findings.push(...gitPersistenceFindings(dir));
|
|
233
|
+
|
|
234
|
+
const count = (pred) => findings.filter(pred).length;
|
|
235
|
+
return {
|
|
236
|
+
project: path.basename(dir),
|
|
237
|
+
path: dir,
|
|
238
|
+
git: isGitRepo(dir),
|
|
239
|
+
files: files.length,
|
|
240
|
+
durationMs: Date.now() - started,
|
|
241
|
+
findings,
|
|
242
|
+
summary: {
|
|
243
|
+
malware: count(f => f.verdict === CONFIRMED),
|
|
244
|
+
backdoors: count(f => f.category === 'git-backdoor' || f.category === 'ide'),
|
|
245
|
+
secrets: count(f => f.category === 'secret'),
|
|
246
|
+
suspicious: count(f => f.verdict !== CONFIRMED && f.category !== 'secret' && f.category !== 'git-backdoor' && f.category !== 'ide')
|
|
247
|
+
}
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
function findProjects(root) {
|
|
252
|
+
const projects = [];
|
|
253
|
+
if (isGitRepo(root)) projects.push(root);
|
|
254
|
+
let entries = [];
|
|
255
|
+
try { entries = fs.readdirSync(root, { withFileTypes: true }); } catch (_) {}
|
|
256
|
+
for (const e of entries) {
|
|
257
|
+
if (!e.isDirectory() || e.isSymbolicLink() || e.name.startsWith('.') || SKIP_DIRS.has(e.name)) continue;
|
|
258
|
+
projects.push(path.join(root, e.name));
|
|
259
|
+
}
|
|
260
|
+
return projects;
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
// ---------------------------------------------------------------------------
|
|
264
|
+
// Report
|
|
265
|
+
// ---------------------------------------------------------------------------
|
|
266
|
+
|
|
267
|
+
function statusOf(r) {
|
|
268
|
+
const open = r.findings.filter(f => !(f.action && f.action.removed));
|
|
269
|
+
if (r.summary.malware && open.every(f => f.verdict !== CONFIRMED) && r.findings.some(f => f.action)) {
|
|
270
|
+
if (!open.length) return { icon: '✔', label: 'CLEANED', color: colors.green };
|
|
271
|
+
} else if (r.summary.malware) {
|
|
272
|
+
return { icon: '✖', label: 'MALWARE', color: colors.red };
|
|
273
|
+
}
|
|
274
|
+
r = { ...r, findings: open };
|
|
275
|
+
if (r.findings.some(f => f.severity === 'CRITICAL' && f.category !== 'secret')) return { icon: '✖', label: 'DANGER', color: colors.red };
|
|
276
|
+
if (r.findings.some(f => f.category === 'secret')) return { icon: '⚠', label: 'SECRETS', color: colors.yellow };
|
|
277
|
+
if (r.findings.length) return { icon: '⚠', label: 'REVIEW', color: colors.yellow };
|
|
278
|
+
return { icon: '✔', label: 'CLEAN', color: colors.green };
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/** Marks every finding with what happened to it. */
|
|
282
|
+
function annotateActions(r, after) {
|
|
283
|
+
const stillThere = after ? new Set(after.findings.map(f => `${f.category}|${f.name}|${f.filePath}`)) : null;
|
|
284
|
+
const byFile = new Map();
|
|
285
|
+
for (const res of (r.clean && r.clean.results) || []) byFile.set(res.file, res);
|
|
286
|
+
for (const f of r.findings) {
|
|
287
|
+
const res = f.verdict === CONFIRMED && f.category === 'malware' ? byFile.get(f.filePath) : null;
|
|
288
|
+
if (res && res.ok && res.action === 'quarantined') f.action = { removed: true, text: 'Removed: whole file was malware (backup kept)' };
|
|
289
|
+
else if (res && res.ok && res.action === 'repaired') f.action = { removed: true, text: 'Removed: malware cut out, rest of the file kept' };
|
|
290
|
+
else if (res && !res.ok) f.action = { removed: false, text: res.action === 'manual' ? 'Needs manual removal' : `Could not remove: ${res.error || 'unknown error'}` };
|
|
291
|
+
else if (f.verdict === CONFIRMED) f.action = { removed: false, text: 'Not removed (report only; run with --clean)' };
|
|
292
|
+
else if (stillThere && !stillThere.has(`${f.category}|${f.name}|${f.filePath}`)) f.action = { removed: true, text: 'Resolved: gone after the malware was removed' };
|
|
293
|
+
else if (f.fixCommand) f.action = { removed: false, text: `Not yours? Remove it: ${f.fixCommand}` };
|
|
294
|
+
else if (f.category === 'secret') f.action = { removed: false, text: 'Rotate this secret and remove it from the code / git history' };
|
|
295
|
+
else f.action = { removed: false, text: 'Review it yourself (never removed automatically)' };
|
|
296
|
+
}
|
|
297
|
+
r.removedFiles = [...new Set(r.findings.filter(f => f.action && f.action.removed).map(f => f.filePath))];
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
function printProjectDetails(r) {
|
|
301
|
+
const order = { malware: 0, 'git-backdoor': 1, ide: 2, file: 3, secret: 4 };
|
|
302
|
+
const sorted = [...r.findings].sort((a, b) =>
|
|
303
|
+
(a.verdict === CONFIRMED ? -1 : 0) - (b.verdict === CONFIRMED ? -1 : 0) || (order[a.category] - order[b.category]));
|
|
304
|
+
const removed = sorted.filter(f => f.action.removed);
|
|
305
|
+
const open = sorted.filter(f => !f.action.removed);
|
|
306
|
+
const s = statusOf(r);
|
|
307
|
+
|
|
308
|
+
console.log(`\n${s.color}${colors.bold}📁 ${r.project}${colors.reset} ${colors.dim}${r.path}${colors.reset}`);
|
|
309
|
+
console.log(` Found ${sorted.length} issue(s)${removed.length ? `, ${colors.green}${colors.bold}removed ${removed.length}${colors.reset} (${r.removedFiles.length} file(s))` : ''}${open.length ? `, ${open.length} need attention` : ''}`);
|
|
310
|
+
|
|
311
|
+
const line = (f) => {
|
|
312
|
+
const tag = f.verdict === CONFIRMED ? `${colors.red}${colors.bold}MALWARE${colors.reset}`
|
|
313
|
+
: f.severity === 'CRITICAL' && f.category !== 'secret' ? `${colors.red}${colors.bold}DANGER${colors.reset}`
|
|
314
|
+
: f.category === 'secret' ? `${colors.yellow}SECRET${colors.reset}` : `${colors.yellow}${f.category.toUpperCase()}${colors.reset}`;
|
|
315
|
+
console.log(` ${tag} ${f.name}`);
|
|
316
|
+
console.log(` ${colors.dim}${f.filePath || ''}${f.lineNumber ? ':' + f.lineNumber : ''}${colors.reset}`);
|
|
317
|
+
if (f.line && f.category !== 'malware') console.log(` ${colors.dim}${String(f.line).slice(0, 100)}${colors.reset}`);
|
|
318
|
+
const c = f.action.removed ? colors.green : (f.verdict === CONFIRMED ? colors.red : colors.dim);
|
|
319
|
+
console.log(` ${c}→ ${f.action.text}${colors.reset}`);
|
|
320
|
+
};
|
|
321
|
+
|
|
322
|
+
if (removed.length) {
|
|
323
|
+
console.log(` ${colors.green}${colors.bold}✔ Removed${colors.reset}`);
|
|
324
|
+
removed.forEach(line);
|
|
325
|
+
}
|
|
326
|
+
if (open.length) {
|
|
327
|
+
console.log(` ${colors.yellow}${colors.bold}⚠ Still needs your attention${colors.reset}`);
|
|
328
|
+
open.slice(0, 25).forEach(line);
|
|
329
|
+
if (open.length > 25) console.log(` ${colors.dim}… ${open.length - 25} more in the JSON report${colors.reset}`);
|
|
330
|
+
}
|
|
331
|
+
if (r.clean && r.clean.quarantineDir) {
|
|
332
|
+
console.log(` ${colors.dim}Backups of removed files: ${r.clean.quarantineDir}${colors.reset}`);
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
function printResultsTable(results) {
|
|
337
|
+
const nameW = Math.min(30, Math.max(7, ...results.map(r => r.project.length)));
|
|
338
|
+
const pad = (v, w) => String(v).padEnd(w);
|
|
339
|
+
console.log(`\n${colors.bold}Results per project${colors.reset}`);
|
|
340
|
+
console.log(` ${colors.dim}${pad('Project', nameW)} ${pad('Status', 8)} ${pad('Found', 6)} ${pad('Removed', 8)} To review${colors.reset}`);
|
|
341
|
+
for (const r of results) {
|
|
342
|
+
const s = statusOf(r);
|
|
343
|
+
const removed = r.findings.filter(f => f.action && f.action.removed).length;
|
|
344
|
+
const review = r.findings.length - removed;
|
|
345
|
+
console.log(` ${pad(r.project.slice(0, nameW), nameW)} ${s.color}${pad(s.label, 8)}${colors.reset} ${pad(r.findings.length, 6)} ${removed ? colors.green : ''}${pad(removed, 8)}${colors.reset} ${review ? colors.yellow + review + colors.reset : '0'}`);
|
|
346
|
+
}
|
|
347
|
+
}
|
|
348
|
+
|
|
349
|
+
function writeReport(root, results) {
|
|
350
|
+
const dir = path.join(process.env.HOME || process.env.USERPROFILE || os.homedir(), '.gitsafty', 'reports');
|
|
351
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
352
|
+
const file = path.join(dir, `scan-${path.basename(path.resolve(root))}-${new Date().toISOString().replace(/[:.]/g, '-')}.json`);
|
|
353
|
+
fs.writeFileSync(file, JSON.stringify({ root: path.resolve(root), createdAt: new Date().toISOString(), results }, null, 2), { mode: 0o600 });
|
|
354
|
+
return file;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/**
|
|
358
|
+
* Runs the Advanced Scanner.
|
|
359
|
+
* @returns {number} exit code (1 if malware or critical findings)
|
|
360
|
+
*/
|
|
361
|
+
function runAdvancedScan(root, { clean = false, deep = false, json = false } = {}) {
|
|
362
|
+
const abs = path.resolve(root);
|
|
363
|
+
if (!fs.existsSync(abs) || !fs.statSync(abs).isDirectory()) {
|
|
364
|
+
console.error(`${colors.red}✖ Folder not found: ${abs}${colors.reset}`);
|
|
365
|
+
return 1;
|
|
366
|
+
}
|
|
367
|
+
const projects = findProjects(abs);
|
|
368
|
+
if (!json) {
|
|
369
|
+
console.log(`\n${colors.cyan}${colors.bold}🔬 Advanced Scanner${colors.reset} ${colors.dim}${abs}${colors.reset}`);
|
|
370
|
+
console.log(`${colors.dim}${projects.length} project(s) · ${deep ? 'deep (incl. node_modules & ignored files)' : 'skipping node_modules, build output and .gitignore\'d files'} · ${clean ? 'auto-remove confirmed malware' : 'report only'}${colors.reset}\n`);
|
|
371
|
+
}
|
|
372
|
+
|
|
373
|
+
const started = Date.now();
|
|
374
|
+
const results = [];
|
|
375
|
+
projects.forEach((dir, i) => {
|
|
376
|
+
const r = scanProject(dir, { deep });
|
|
377
|
+
results.push(r);
|
|
378
|
+
if (!json) {
|
|
379
|
+
const s = statusOf(r);
|
|
380
|
+
const parts = [];
|
|
381
|
+
if (r.summary.malware) parts.push(`${r.summary.malware} malware`);
|
|
382
|
+
if (r.summary.backdoors) parts.push(`${r.summary.backdoors} backdoor/IDE`);
|
|
383
|
+
if (r.summary.secrets) parts.push(`${r.summary.secrets} secret`);
|
|
384
|
+
if (r.summary.suspicious) parts.push(`${r.summary.suspicious} suspicious`);
|
|
385
|
+
const num = `[${String(i + 1).padStart(String(projects.length).length)}/${projects.length}]`;
|
|
386
|
+
console.log(`${colors.dim}${num}${colors.reset} ${s.color}${s.icon} ${s.label.padEnd(7)}${colors.reset} ${r.project.padEnd(32)} ${colors.dim}${String(r.files).padStart(6)} files${colors.reset} ${parts.join(', ')}`);
|
|
387
|
+
}
|
|
388
|
+
});
|
|
389
|
+
|
|
390
|
+
// Optional removal of confirmed malware
|
|
391
|
+
if (clean) {
|
|
392
|
+
for (const r of results) {
|
|
393
|
+
const files = [...new Set(r.findings.filter(f => f.verdict === CONFIRMED && f.category === 'malware').map(f => f.filePath))];
|
|
394
|
+
if (!files.length) continue;
|
|
395
|
+
r.clean = removeConfirmedMalware(files, r.path, { reason: 'advanced-scan' });
|
|
396
|
+
}
|
|
397
|
+
}
|
|
398
|
+
|
|
399
|
+
// Re-scan cleaned projects so issues that disappeared with the malware are shown as resolved.
|
|
400
|
+
results.forEach(r => annotateActions(r, r.clean ? scanProject(r.path, { deep }) : null));
|
|
401
|
+
const reportPath = writeReport(abs, results);
|
|
402
|
+
if (json) {
|
|
403
|
+
process.stdout.write(JSON.stringify({ root: abs, reportPath, results }, null, 2) + '\n');
|
|
404
|
+
} else {
|
|
405
|
+
console.log(`\n${colors.bold}${colors.cyan}━━━━━━━━━━━━━━━━━━ Scan finished: details per project ━━━━━━━━━━━━━━━━━━${colors.reset}`);
|
|
406
|
+
for (const r of results.filter(x => x.findings.length)) printProjectDetails(r);
|
|
407
|
+
printResultsTable(results);
|
|
408
|
+
|
|
409
|
+
const total = (k) => results.reduce((n, r) => n + r.summary[k], 0);
|
|
410
|
+
const infected = results.filter(r => r.summary.malware);
|
|
411
|
+
const removedTotal = results.reduce((n, r) => n + r.removedFiles.length, 0);
|
|
412
|
+
console.log(`\n${colors.bold}Summary${colors.reset} ${colors.dim}(${((Date.now() - started) / 1000).toFixed(1)}s)${colors.reset}`);
|
|
413
|
+
console.log(` Projects scanned : ${results.length} (${results.reduce((n, r) => n + r.files, 0)} files)`);
|
|
414
|
+
console.log(` ${infected.length ? colors.red : colors.green}Malware : ${total('malware')} in ${infected.length} project(s)${colors.reset}`);
|
|
415
|
+
console.log(` ${total('backdoors') ? colors.yellow : colors.green}Backdoors / IDE : ${total('backdoors')}${colors.reset}`);
|
|
416
|
+
console.log(` ${total('secrets') ? colors.yellow : colors.green}Exposed secrets : ${total('secrets')}${colors.reset}`);
|
|
417
|
+
console.log(` ${total('suspicious') ? colors.yellow : colors.green}Other suspicious : ${total('suspicious')}${colors.reset}`);
|
|
418
|
+
console.log(` ${removedTotal ? colors.green : colors.dim}Files cleaned : ${removedTotal}${colors.reset}`);
|
|
419
|
+
console.log(` ${colors.green}Clean projects : ${results.filter(r => !r.findings.length).length}${colors.reset}`);
|
|
420
|
+
console.log(`\n ${colors.dim}Full report: ${reportPath}${colors.reset}`);
|
|
421
|
+
if (infected.length && !clean) {
|
|
422
|
+
console.log(`\n ${colors.bold}Remove the confirmed malware:${colors.reset} ${colors.cyan}gitsafty scan-projects "${abs}" --clean${colors.reset}`);
|
|
423
|
+
}
|
|
424
|
+
console.log('');
|
|
425
|
+
if (infected.length) {
|
|
426
|
+
notifyDesktop('GitSafty Advanced Scanner', `Malware in ${infected.length} of ${results.length} projects. Check the terminal.`);
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
return results.some(r => r.summary.malware || r.findings.some(f => f.severity === 'CRITICAL' && f.category !== 'secret')) ? 1 : 0;
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
module.exports = {
|
|
434
|
+
runAdvancedScan,
|
|
435
|
+
scanProject,
|
|
436
|
+
findProjects,
|
|
437
|
+
gitPersistenceFindings
|
|
438
|
+
};
|