@arifbiswas/git-pre-push 1.0.17 → 1.0.19

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 CHANGED
@@ -30,6 +30,14 @@ Whenever `git push` is invoked—from terminal, VS Code UI, or any Git GUI—it
30
30
 
31
31
  ## 🚀 Quick Start
32
32
 
33
+ > **Install globally (`-g`).** `npm i @arifbiswas/git-pre-push` without `-g` only puts GitSafty into that project's `node_modules`: there is no `gitsafty` command and other repos stay unprotected. npm does not let a package install itself globally, so when GitSafty notices it is running from a project (or from `npx`) it asks *"Install GitSafty globally now? (Y/n)"* and does it for you. The recommended command is:
34
+ >
35
+ > ```bash
36
+ > npm install -g @arifbiswas/git-pre-push
37
+ > gitsafty init --global
38
+ > ```
39
+
40
+
33
41
  ### Option 1: Automatic Setup via npm (Recommended)
34
42
 
35
43
  Add `git-pre-push` to your project:
@@ -78,6 +86,7 @@ Select an action to perform:
78
86
  ── Malware scan & removal ──
79
87
  [3] 🔍 Scan Local Workspace - Deep scan this repo, auto-remove confirmed malware
80
88
  [16] 🔬 Advanced Scanner - Audit ALL projects in a folder: malware, backdoors, secrets
89
+ [18] 🧪 Full Scan - EVERYTHING in a folder: non-git projects + zip/tar/7z/rar
81
90
  [10] 🧹 Sweep All Repos - Scan every git repo in a folder (whole device)
82
91
  [5] 🗑️ Clean & Quarantine - Remove confirmed malware + trojan scripts here
83
92
  [4] 🚀 Scan Remote GitHub Repo - Zero-clone audit (no download/clone)
@@ -232,6 +241,28 @@ Limits, honestly: the chip stops token theft (copying files, Keychain or browser
232
241
 
233
242
  ---
234
243
 
244
+ ## 🧪 Full Scan (everything in a folder, archives too)
245
+
246
+ The normal scan and the Advanced Scanner work on projects. **Full Scan** checks *everything* in a folder: projects that were never connected to git, downloads, backups, and the files **inside archives**.
247
+
248
+ ```bash
249
+ gitsafty full-scan ~/Downloads # report only
250
+ gitsafty full-scan ~/Downloads --clean # also remove CONFIRMED malware
251
+ gitsafty full-scan ./some-file.zip # a single archive
252
+ gitsafty full-scan ~/projects --json # machine-readable output
253
+ ```
254
+
255
+ - **Every file**, git repository or not. Git backdoors are checked in every repository it passes.
256
+ - **Inside archives**: zip, jar, war, apk, aab, aar, ipa, xpi, vsix, nupkg, whl, crx, docx/xlsx/pptx, tar, tar.gz/tgz, gz, and also archives inside archives. Archives are found by their first bytes, so a renamed one is still opened. Nothing is extracted to disk and nothing inside is run.
257
+ - **7z, rar, bz2, xz, cab**: read through the system `bsdtar` (built into macOS and Windows 10+) or 7-Zip if it is installed. If neither can open it, the report says so.
258
+ - **Password-protected archives** can't be read. One that contains programs (`.exe`, `.js`, `.bat` …) is flagged, because malware is often sent that way.
259
+ - **Skipped**: `node_modules`, composer `vendor`, `Pods`, virtualenvs, `.gradle`, package caches and lock files (`package-lock.json`, `composer.lock` …). These are downloaded packages, not your code. `package.json` and `composer.json` are still checked, because malicious install scripts live there.
260
+ - Zip-bomb safe: at most 64 MB per file inside an archive, 1 GB per archive, 4 levels of nesting.
261
+
262
+ With `--clean`, a loose file is repaired or removed exactly like on clone and pull. An **archive with malware inside is moved to quarantine whole**, because an archive can't be safely rewritten. Read-only backups and a report go to `~/.gitsafty/quarantine/full-scan-<time>/`. At the end you see each infected archive or folder, what was found, what was removed, and what still needs review. Menu option **[18]**.
263
+
264
+ ---
265
+
235
266
  ## 🔬 Advanced Scanner (many projects at once)
236
267
 
237
268
  Got a folder with 20 projects? Audit all of them in one go:
@@ -309,6 +340,7 @@ git config --global --remove-section credential.https://github.com # only if y
309
340
  | `npx @arifbiswas/git-pre-push demo` | Simulates a blocked push in terminal |
310
341
  | `npx @arifbiswas/git-pre-push action` | Generates a `.github/workflows/git-safty.yml` CI workflow |
311
342
  | `npx @arifbiswas/git-pre-push scan-projects <folder>` | **Advanced Scanner**: audit every project in a folder (malware, git backdoors, IDE, secrets) |
343
+ | `npx @arifbiswas/git-pre-push full-scan <folder> [--clean]` | **Full Scan**: everything in a folder, also non-git projects and inside zip/jar/apk/tar/gz/7z/rar |
312
344
  | `npx @arifbiswas/git-pre-push pull-scan on\|off` | Scan after every `git pull`, also when "Already up to date" (adds a shell `git` function) |
313
345
  | `npx @arifbiswas/git-pre-push doctor [--fix]` | Finds broken/outdated installs and shows (or applies) the exact fix |
314
346
  | `npx @arifbiswas/git-pre-push uninstall` | Cleanly removes the hook from `.git/hooks` |
package/bin/cli.js CHANGED
@@ -63,6 +63,17 @@ async function main() {
63
63
  } catch (_) {}
64
64
  }
65
65
 
66
+ // Installed as a project dependency (`npm i` without -g)? Offer the global
67
+ // install once per command run (remembered for 30 days when declined).
68
+ if (!hookCommands.includes(command) && command !== 'init' && command !== 'install') {
69
+ try {
70
+ const un = require('../src/updateNotifier');
71
+ if (un.looksLikeProjectCopy() && un.installKind() === 'local-dependency') {
72
+ await un.offerPermanentInstall(['init', '--global'], { kind: 'local-dependency', remember: true });
73
+ }
74
+ } catch (_) {}
75
+ }
76
+
66
77
  // `gitsafty update` does its own check below.
67
78
  if (!hookCommands.includes(command) && command !== 'update' && command !== 'upgrade') {
68
79
  // Opening the menu always asks the registry, so a fresh release is never missed.
@@ -142,6 +153,19 @@ async function main() {
142
153
  break;
143
154
  }
144
155
 
156
+ case 'full-scan':
157
+ case 'fullscan':
158
+ case 'scan-folder': {
159
+ banner();
160
+ const { runFullScan } = require('../src/fullScanner');
161
+ const target = args.find((a, i) => i > 0 && !a.startsWith('-')) || process.cwd();
162
+ process.exit(runFullScan(target, {
163
+ clean: args.includes('--clean'),
164
+ json: args.includes('--json')
165
+ }));
166
+ break;
167
+ }
168
+
145
169
  case 'doctor':
146
170
  case 'fix-install': {
147
171
  banner();
@@ -317,7 +341,8 @@ async function main() {
317
341
  console.log(`${colors.cyan}Your git environment is now protected!${colors.reset}`);
318
342
  console.log(`${colors.dim}Every git push, clone and pull${isGlobalFlag ? ' on this PC' : ' in this repository'} is scanned for malware & secret leaks.${colors.reset}\n`);
319
343
  const { offerPermanentInstall } = require('../src/updateNotifier');
320
- await offerPermanentInstall(['init', ...(isGlobalFlag ? ['--global'] : [])]);
344
+ // npx copy: re-run the same init globally. Project copy: protect the whole PC.
345
+ await offerPermanentInstall(['init', '--global']);
321
346
  } else {
322
347
  console.error(`\n${colors.red}${colors.bold}✖ ${result.message}${colors.reset}\n`);
323
348
  process.exit(1);
@@ -367,6 +392,7 @@ ${colors.bold}Commands:${colors.reset}
367
392
  ${colors.green}vault test${colors.reset} Try one unlock (prompt) without using the token
368
393
  ${colors.green}vault remove${colors.reset} Turn the vault off and go back to normal git login
369
394
  ${colors.green}scan-projects${colors.reset} <folder> Advanced Scanner: audit EVERY project in a folder at once
395
+ ${colors.green}full-scan${colors.reset} <folder> Full Scan: EVERYTHING in a folder, also non-git projects and inside zip/jar/apk/tar/gz/7z/rar (--clean removes)
370
396
  (malware, git backdoors, IDE auto-run, secrets) [--clean] [--deep] [--json]
371
397
  ${colors.green}pull-scan${colors.reset} on|off Scan after EVERY git pull, also "Already up to date" (adds a git shell function)
372
398
  ${colors.green}doctor${colors.reset} Find broken/outdated installs and show the exact fix (--fix applies it)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arifbiswas/git-pre-push",
3
- "version": "1.0.17",
3
+ "version": "1.0.19",
4
4
  "description": "Zero-dependency pre-push security guard that stops malware, injected scripts, and leaked secrets from reaching GitHub.",
5
5
  "main": "src/index.js",
6
6
  "bin": {
@@ -20,6 +20,12 @@ function main() {
20
20
  console.log(`[git-safty] 🛡️ Global hooks updated (push + clone + pull malware scan) in ${refreshed}`);
21
21
  }
22
22
 
23
+ if (!isGlobalInstall) {
24
+ // npm can't make a package install globally on its own; say it clearly.
25
+ console.log('[git-safty] Installed in this project only. To protect every repo on this PC and get the `gitsafty` command:');
26
+ console.log('[git-safty] npm install -g @arifbiswas/git-pre-push && gitsafty init --global');
27
+ }
28
+
23
29
  // When installed as a dependency, process.env.INIT_CWD points to the parent project
24
30
  const targetDir = process.env.INIT_CWD || process.cwd();
25
31
 
@@ -237,6 +237,8 @@ function scanProject(dir, { deep = false } = {}) {
237
237
  path: dir,
238
238
  git: isGitRepo(dir),
239
239
  files: files.length,
240
+ // Archives are not opened here; Full Scan (gitsafty full-scan) looks inside them.
241
+ archives: files.filter(f => !inGeneratedDir(f) && require('./archive').isArchiveName(f)).length,
240
242
  durationMs: Date.now() - started,
241
243
  findings,
242
244
  summary: {
@@ -418,6 +420,10 @@ function runAdvancedScan(root, { clean = false, deep = false, json = false } = {
418
420
  console.log(` ${removedTotal ? colors.green : colors.dim}Files cleaned : ${removedTotal}${colors.reset}`);
419
421
  console.log(` ${colors.green}Clean projects : ${results.filter(r => !r.findings.length).length}${colors.reset}`);
420
422
  console.log(`\n ${colors.dim}Full report: ${reportPath}${colors.reset}`);
423
+ const archiveCount = results.reduce((n, r) => n + (r.archives || 0), 0);
424
+ if (archiveCount) {
425
+ console.log(` ${colors.yellow}${archiveCount} archive file(s) (zip/tar/7z/rar …) were not opened.${colors.reset} Look inside them: ${colors.cyan}gitsafty full-scan "${abs}"${colors.reset}`);
426
+ }
421
427
  if (infected.length && !clean) {
422
428
  console.log(`\n ${colors.bold}Remove the confirmed malware:${colors.reset} ${colors.cyan}gitsafty scan-projects "${abs}" --clean${colors.reset}`);
423
429
  }
package/src/archive.js ADDED
@@ -0,0 +1,352 @@
1
+ /**
2
+ * Reads the files inside archives WITHOUT extracting anything to disk and
3
+ * without running anything from them.
4
+ *
5
+ * zip family (zip, jar, war, apk, aab, aar, ipa, xpi, vsix, nupkg, whl, crx,
6
+ * docx/xlsx/pptx ...): parsed here (stored + deflate, zip64)
7
+ * tar, tar.gz / tgz, gz: parsed here
8
+ * 7z, rar, bz2, xz, and zip entries with other compression: read through the
9
+ * system `7z` / `tar` (bsdtar) one entry at a time to stdout, if available
10
+ *
11
+ * Archives are detected by their first bytes, not only by the file name, so a
12
+ * renamed archive is still opened. Nested archives are opened too (limited depth).
13
+ * Limits keep zip bombs harmless: per-entry size, total size and entry count.
14
+ */
15
+
16
+ const fs = require('fs');
17
+ const os = require('os');
18
+ const path = require('path');
19
+ const zlib = require('zlib');
20
+ const { spawnSync } = require('child_process');
21
+
22
+ const LIMITS = {
23
+ maxEntryBytes: 64 * 1024 * 1024, // one file inside an archive
24
+ maxTotalBytes: 1024 * 1024 * 1024, // all files of one top-level archive
25
+ maxEntries: 100000,
26
+ maxDepth: 4,
27
+ maxArchiveBytes: 1024 * 1024 * 1024 // archive file read into memory
28
+ };
29
+
30
+ const ZIP_EXT = /\.(zip|jar|war|ear|apk|aab|aar|ipa|xpi|vsix|nupkg|whl|egg|crx|docx|xlsx|pptx|odt|ods|odp|epub|appx|msix|jmod|kmz)$/i;
31
+ const ARCHIVE_EXT = /\.(zip|jar|war|ear|apk|aab|aar|ipa|xpi|vsix|nupkg|whl|egg|crx|appx|msix|jmod|kmz|tar|tgz|tbz2?|txz|gz|bz2|xz|7z|rar|cab|iso|cpio)$/i;
32
+
33
+ /** Archive type from the first bytes (and the name as a hint). */
34
+ function detectArchiveType(head, name = '') {
35
+ if (!head || head.length < 4) return null;
36
+ if (head[0] === 0x50 && head[1] === 0x4b && (head[2] === 3 || head[2] === 5 || head[2] === 7)) return 'zip';
37
+ if (head.toString('latin1', 0, 4) === 'Cr24') return 'crx';
38
+ if (head[0] === 0x1f && head[1] === 0x8b) return 'gzip';
39
+ if (head.length >= 262 && head.toString('latin1', 257, 262) === 'ustar') return 'tar';
40
+ if (head.toString('latin1', 0, 6) === '7z\xbc\xaf\x27\x1c') return '7z';
41
+ if (head.toString('latin1', 0, 4) === 'Rar!') return 'rar';
42
+ if (head.toString('latin1', 0, 3) === 'BZh') return 'bzip2';
43
+ if (head.length >= 6 && head[0] === 0xfd && head.toString('latin1', 1, 6) === '7zXZ\0') return 'xz';
44
+ if (head.toString('latin1', 0, 4) === 'MSCF') return 'cab';
45
+ // Old tar without "ustar" magic: only trust the name.
46
+ if (/\.tar$/i.test(name)) return 'tar';
47
+ return null;
48
+ }
49
+
50
+ function isArchiveName(name) {
51
+ return ARCHIVE_EXT.test(name);
52
+ }
53
+
54
+ // ---------------------------------------------------------------------------
55
+ // ZIP
56
+ // ---------------------------------------------------------------------------
57
+
58
+ function findEocd(buf) {
59
+ const min = Math.max(0, buf.length - 65557);
60
+ for (let i = buf.length - 22; i >= min; i--) {
61
+ if (buf.readUInt32LE(i) === 0x06054b50) return i;
62
+ }
63
+ return -1;
64
+ }
65
+
66
+ /**
67
+ * Lists zip entries.
68
+ * @returns {Array<{name, method, compSize, size, offset, encrypted, dir}>}
69
+ */
70
+ function zipEntries(buf) {
71
+ const eocd = findEocd(buf);
72
+ if (eocd < 0) throw new Error('not a valid zip (no end of central directory)');
73
+ let count = buf.readUInt16LE(eocd + 10);
74
+ let cdSize = buf.readUInt32LE(eocd + 12);
75
+ let cdOffset = buf.readUInt32LE(eocd + 16);
76
+
77
+ // zip64
78
+ if (eocd >= 20 && buf.readUInt32LE(eocd - 20) === 0x07064b50) {
79
+ const z64 = Number(buf.readBigUInt64LE(eocd - 20 + 8));
80
+ if (z64 + 56 <= buf.length && buf.readUInt32LE(z64) === 0x06064b50) {
81
+ count = Number(buf.readBigUInt64LE(z64 + 32));
82
+ cdSize = Number(buf.readBigUInt64LE(z64 + 40));
83
+ cdOffset = Number(buf.readBigUInt64LE(z64 + 48));
84
+ }
85
+ }
86
+ // Self-extracting / prefixed zips (e.g. crx): the central directory sits right before the EOCD.
87
+ const shift = eocd - cdSize - cdOffset > 0 ? eocd - cdSize - cdOffset : 0;
88
+
89
+ const entries = [];
90
+ let p = cdOffset + shift;
91
+ for (let i = 0; i < count && p + 46 <= buf.length; i++) {
92
+ if (buf.readUInt32LE(p) !== 0x02014b50) break;
93
+ const flags = buf.readUInt16LE(p + 8);
94
+ const method = buf.readUInt16LE(p + 10);
95
+ let compSize = buf.readUInt32LE(p + 20);
96
+ let size = buf.readUInt32LE(p + 24);
97
+ const nameLen = buf.readUInt16LE(p + 28);
98
+ const extraLen = buf.readUInt16LE(p + 30);
99
+ const commentLen = buf.readUInt16LE(p + 32);
100
+ let offset = buf.readUInt32LE(p + 42);
101
+ const name = buf.toString(flags & 0x800 ? 'utf8' : 'latin1', p + 46, p + 46 + nameLen);
102
+
103
+ // zip64 extra field
104
+ let e = p + 46 + nameLen;
105
+ const extraEnd = e + extraLen;
106
+ while (e + 4 <= extraEnd) {
107
+ const id = buf.readUInt16LE(e);
108
+ const len = buf.readUInt16LE(e + 2);
109
+ if (id === 0x0001) {
110
+ let q = e + 4;
111
+ if (size === 0xffffffff) { size = Number(buf.readBigUInt64LE(q)); q += 8; }
112
+ if (compSize === 0xffffffff) { compSize = Number(buf.readBigUInt64LE(q)); q += 8; }
113
+ if (offset === 0xffffffff) { offset = Number(buf.readBigUInt64LE(q)); }
114
+ }
115
+ e += 4 + len;
116
+ }
117
+
118
+ entries.push({ name, method, compSize, size, offset: offset + shift, encrypted: !!(flags & 1), dir: name.endsWith('/') });
119
+ p = extraEnd + commentLen;
120
+ }
121
+ return entries;
122
+ }
123
+
124
+ function zipEntryData(buf, entry, maxBytes) {
125
+ const lh = entry.offset;
126
+ if (lh + 30 > buf.length || buf.readUInt32LE(lh) !== 0x04034b50) throw new Error('broken local header');
127
+ const start = lh + 30 + buf.readUInt16LE(lh + 26) + buf.readUInt16LE(lh + 28);
128
+ const data = buf.subarray(start, start + entry.compSize);
129
+ if (entry.method === 0) return data.subarray(0, maxBytes);
130
+ if (entry.method === 8) return zlib.inflateRawSync(data, { maxOutputLength: maxBytes });
131
+ const err = new Error(`compression method ${entry.method}`);
132
+ err.code = 'UNSUPPORTED_METHOD';
133
+ throw err;
134
+ }
135
+
136
+ // ---------------------------------------------------------------------------
137
+ // TAR
138
+ // ---------------------------------------------------------------------------
139
+
140
+ function tarNumber(buf, off, len) {
141
+ if (buf[off] & 0x80) { // base-256
142
+ let n = 0;
143
+ for (let i = off + 1; i < off + len; i++) n = n * 256 + buf[i];
144
+ return n;
145
+ }
146
+ const s = buf.toString('latin1', off, off + len).replace(/\0.*$/, '').trim();
147
+ return s ? parseInt(s, 8) || 0 : 0;
148
+ }
149
+
150
+ function* tarEntries(buf) {
151
+ let p = 0;
152
+ let longName = null;
153
+ let paxPath = null;
154
+ while (p + 512 <= buf.length) {
155
+ const h = buf.subarray(p, p + 512);
156
+ if (h.every(b => b === 0)) break;
157
+ let name = h.toString('utf8', 0, 100).replace(/\0.*$/s, '');
158
+ const prefix = h.toString('latin1', 257, 262) === 'ustar' ? h.toString('utf8', 345, 500).replace(/\0.*$/s, '') : '';
159
+ if (prefix) name = `${prefix}/${name}`;
160
+ const size = tarNumber(h, 124, 12);
161
+ const type = String.fromCharCode(h[156] || 48);
162
+ const dataStart = p + 512;
163
+ const data = buf.subarray(dataStart, Math.min(buf.length, dataStart + size));
164
+ p = dataStart + Math.ceil(size / 512) * 512;
165
+
166
+ if (type === 'L') { longName = data.toString('utf8').replace(/\0.*$/s, ''); continue; }
167
+ if (type === 'x') {
168
+ const m = data.toString('utf8').match(/\d+ path=([^\n]*)\n/);
169
+ if (m) paxPath = m[1];
170
+ continue;
171
+ }
172
+ if (type === 'g') continue;
173
+ const finalName = paxPath || longName || name;
174
+ longName = null;
175
+ paxPath = null;
176
+ if (type === '0' || type === '\0' || type === '7') yield { name: finalName, size, data };
177
+ }
178
+ }
179
+
180
+ // ---------------------------------------------------------------------------
181
+ // External tools (7z, bsdtar) for formats Node can't read
182
+ // ---------------------------------------------------------------------------
183
+
184
+ let toolCache;
185
+ function externalTool() {
186
+ if (toolCache !== undefined) return toolCache;
187
+ const candidates = process.platform === 'win32'
188
+ ? [['7z'], [path.join(process.env.ProgramFiles || 'C:\\Program Files', '7-Zip', '7z.exe')], ['tar']]
189
+ : [['7zz'], ['7z'], ['bsdtar'], ['tar']];
190
+ for (const [bin] of candidates) {
191
+ const isTar = /tar(\.exe)?$/i.test(bin);
192
+ const r = spawnSync(bin, isTar ? ['--version'] : ['i'], { encoding: 'utf8', timeout: 10000 });
193
+ if (r.error) continue;
194
+ if (isTar && !/bsdtar|libarchive/i.test(r.stdout || '')) continue; // GNU tar can't read zip/7z/rar
195
+ toolCache = { bin, kind: isTar ? 'bsdtar' : '7z' };
196
+ return toolCache;
197
+ }
198
+ toolCache = null;
199
+ return null;
200
+ }
201
+
202
+ /** Writes an in-memory nested archive to a private temp file (only to read it, never executed). */
203
+ function withTempFile(buf, name, fn) {
204
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gitsafty-arc-'));
205
+ const file = path.join(dir, `archive${path.extname(name) || ''}`);
206
+ try {
207
+ fs.writeFileSync(file, buf, { mode: 0o600 });
208
+ return fn(file);
209
+ } finally {
210
+ try { fs.rmSync(dir, { recursive: true, force: true }); } catch (_) {}
211
+ }
212
+ }
213
+
214
+ function externalList(tool, file) {
215
+ if (tool.kind === '7z') {
216
+ const r = spawnSync(tool.bin, ['l', '-slt', '-ba', '-p', '--', file], { encoding: 'utf8', maxBuffer: 256 * 1024 * 1024, timeout: 120000 });
217
+ if (r.status !== 0) return null;
218
+ const out = [];
219
+ for (const block of r.stdout.split(/\r?\n\r?\n/)) {
220
+ const get = (k) => { const m = block.match(new RegExp(`^${k} = (.*)$`, 'm')); return m ? m[1].trim() : ''; };
221
+ const name = get('Path');
222
+ if (!name || get('Folder') === '+' || /D/.test(get('Attributes').split(' ')[0] || '')) continue;
223
+ out.push({ name, size: Number(get('Size')) || 0, encrypted: get('Encrypted') === '+' });
224
+ }
225
+ return out;
226
+ }
227
+ const r = spawnSync(tool.bin, ['-tf', file], { encoding: 'utf8', maxBuffer: 256 * 1024 * 1024, timeout: 120000 });
228
+ if (r.status !== 0) return null;
229
+ return r.stdout.split(/\r?\n/).filter(n => n && !n.endsWith('/')).map(name => ({ name, size: 0, encrypted: false }));
230
+ }
231
+
232
+ function externalRead(tool, file, name, maxBytes) {
233
+ const args = tool.kind === '7z' ? ['e', '-so', '-p', '--', file, name] : ['-xOf', file, '--', name];
234
+ const r = spawnSync(tool.bin, args, { maxBuffer: maxBytes, timeout: 120000 });
235
+ if (r.error && r.error.code === 'ENOBUFS') return { tooLarge: true };
236
+ if (r.status !== 0 || r.error) return { error: (r.stderr || '').toString().trim().split('\n')[0] || 'could not read' };
237
+ return { data: r.stdout };
238
+ }
239
+
240
+ // ---------------------------------------------------------------------------
241
+ // Walker
242
+ // ---------------------------------------------------------------------------
243
+
244
+ /**
245
+ * Calls onFile(innerPath, buffer, info) for every file inside an archive,
246
+ * opening nested archives too.
247
+ *
248
+ * @param {Buffer} buf archive bytes
249
+ * @param {string} name archive name (for type hints)
250
+ * @param {(inner: string, data: Buffer) => void} onFile
251
+ * @param {{ skipEntry?: (inner: string) => boolean }} [opts]
252
+ * @returns {{ type, entries, scanned, problems: Array<{entry, reason}> }}
253
+ */
254
+ function walkArchive(buf, name, onFile, opts = {}) {
255
+ const stats = { type: null, entries: 0, scanned: 0, bytes: 0, problems: [], encrypted: [] };
256
+ const skip = opts.skipEntry || (() => false);
257
+
258
+ const visit = (data, label, prefix, depth) => {
259
+ const type = detectArchiveType(data.subarray(0, 512), label);
260
+ if (depth === 0) stats.type = type;
261
+ if (!type) return false;
262
+ if (depth >= LIMITS.maxDepth) {
263
+ stats.problems.push({ entry: prefix || label, reason: 'archive nested too deep, not opened' });
264
+ return true;
265
+ }
266
+
267
+ const emit = (inner, content) => {
268
+ stats.entries++;
269
+ const full = prefix ? `${prefix}!/${inner}` : inner;
270
+ if (stats.entries > LIMITS.maxEntries) return;
271
+ if (skip(inner)) return;
272
+ if (content == null) return;
273
+ stats.bytes += content.length;
274
+ if (stats.bytes > LIMITS.maxTotalBytes) {
275
+ if (!stats.totalLimitHit) stats.problems.push({ entry: label, reason: 'more than 1 GB unpacked, rest skipped' });
276
+ stats.totalLimitHit = true;
277
+ return;
278
+ }
279
+ if (detectArchiveType(content.subarray(0, 512), inner) && visit(content, inner, full, depth + 1)) {
280
+ // Also give the nested archive itself to the caller (hashes, names).
281
+ }
282
+ stats.scanned++;
283
+ onFile(full, content, { depth });
284
+ };
285
+
286
+ try {
287
+ if (type === 'zip' || type === 'crx') {
288
+ let tool = null;
289
+ for (const e of zipEntries(data)) {
290
+ if (e.dir) continue;
291
+ if (e.encrypted) { stats.encrypted.push(prefix ? `${prefix}!/${e.name}` : e.name); stats.entries++; continue; }
292
+ if (e.size > LIMITS.maxEntryBytes) { stats.problems.push({ entry: e.name, reason: 'file larger than 64 MB inside archive, skipped' }); continue; }
293
+ try {
294
+ emit(e.name, zipEntryData(data, e, LIMITS.maxEntryBytes));
295
+ } catch (err) {
296
+ if (err.code === 'UNSUPPORTED_METHOD' && (tool = tool || externalTool())) {
297
+ const r = withTempFile(data, label, f => externalRead(tool, f, e.name, LIMITS.maxEntryBytes));
298
+ if (r.data) emit(e.name, r.data);
299
+ else stats.problems.push({ entry: e.name, reason: r.tooLarge ? 'too large' : r.error });
300
+ } else {
301
+ stats.problems.push({ entry: e.name, reason: err.code === 'ERR_BUFFER_TOO_LARGE' || /larger than|maxOutputLength/i.test(err.message) ? 'unpacks to more than 64 MB, skipped' : err.message });
302
+ }
303
+ }
304
+ }
305
+ } else if (type === 'tar') {
306
+ for (const e of tarEntries(data)) {
307
+ if (e.size > LIMITS.maxEntryBytes) { stats.problems.push({ entry: e.name, reason: 'file larger than 64 MB inside archive, skipped' }); continue; }
308
+ emit(e.name, e.data);
309
+ }
310
+ } else if (type === 'gzip') {
311
+ const out = zlib.gunzipSync(data, { maxOutputLength: LIMITS.maxEntryBytes * 4 });
312
+ const inner = label.replace(/\.(tgz)$/i, '.tar').replace(/\.gz$/i, '') || 'content';
313
+ if (detectArchiveType(out.subarray(0, 512), inner) === 'tar') visit(out, inner, prefix || '', depth + (prefix ? 1 : 0));
314
+ else emit(path.basename(inner), out);
315
+ } else {
316
+ const tool = externalTool();
317
+ if (!tool) {
318
+ stats.problems.push({ entry: prefix || label, reason: `${type} archive: install 7-Zip (Windows) or p7zip to open it` });
319
+ return true;
320
+ }
321
+ withTempFile(data, label, (f) => {
322
+ const list = externalList(tool, f);
323
+ if (!list) { stats.problems.push({ entry: prefix || label, reason: `${type} archive could not be opened (damaged or password protected)` }); return; }
324
+ for (const e of list) {
325
+ if (e.encrypted) { stats.encrypted.push(prefix ? `${prefix}!/${e.name}` : e.name); stats.entries++; continue; }
326
+ if (e.size > LIMITS.maxEntryBytes) { stats.problems.push({ entry: e.name, reason: 'file larger than 64 MB inside archive, skipped' }); continue; }
327
+ const r = externalRead(tool, f, e.name, LIMITS.maxEntryBytes);
328
+ if (r.data) emit(e.name, r.data);
329
+ else stats.problems.push({ entry: e.name, reason: r.tooLarge ? 'unpacks to more than 64 MB, skipped' : (r.error || 'could not read') });
330
+ }
331
+ });
332
+ }
333
+ } catch (err) {
334
+ const tooBig = err.code === 'ERR_BUFFER_TOO_LARGE' || /larger than|maxOutputLength/i.test(err.message);
335
+ stats.problems.push({ entry: prefix || label, reason: tooBig ? 'unpacks to more than 256 MB, skipped' : `could not open: ${err.message}` });
336
+ }
337
+ return true;
338
+ };
339
+
340
+ visit(buf, name, '', 0);
341
+ return stats;
342
+ }
343
+
344
+ module.exports = {
345
+ LIMITS,
346
+ ZIP_EXT,
347
+ detectArchiveType,
348
+ isArchiveName,
349
+ walkArchive,
350
+ zipEntries,
351
+ externalTool
352
+ };
@@ -0,0 +1,371 @@
1
+ /**
2
+ * Full Scan: scans EVERYTHING in a folder, not only git repositories.
3
+ *
4
+ * gitsafty full-scan <folder> [--clean] [--json]
5
+ *
6
+ * - every file in every sub-folder, git repository or not
7
+ * - inside archives (zip, jar, apk, ipa, vsix, tar, tar.gz, gz, 7z, rar, ...),
8
+ * also archives inside archives, read in memory (nothing is extracted)
9
+ * - git persistence tricks in every repository it passes (.git/hooks, config)
10
+ * - IDE auto-run tasks and disguised / executable file names
11
+ *
12
+ * Dependency folders (node_modules, composer vendor, Pods, virtualenvs, package
13
+ * caches ...) are skipped: they are downloaded packages, not your code.
14
+ *
15
+ * Confirmed malware is removed only with --clean:
16
+ * loose file -> repaired or removed (backup kept)
17
+ * inside archive -> the whole archive is moved to quarantine (backup kept),
18
+ * because an archive can't be safely rewritten
19
+ * Backups go to ~/.gitsafty/quarantine/<time>/ (read-only), with report.json.
20
+ */
21
+
22
+ const fs = require('fs');
23
+ const os = require('os');
24
+ const path = require('path');
25
+ const { detectMalware, sha256, CONFIRMED } = require('./rules/malware');
26
+ const { checkFilename } = require('./rules/filenames');
27
+ const { inspectIdeConfig } = require('./rules/ideConfig');
28
+ const { gitPersistenceFindings } = require('./advancedScanner');
29
+ const { removeConfirmedMalware, notifyDesktop } = require('./malwareCleaner');
30
+ const { walkArchive, detectArchiveType } = require('./archive');
31
+ const { colors } = require('./reporter');
32
+
33
+ // Downloaded packages and caches: never scanned by Full Scan.
34
+ const DEPENDENCY_DIRS = new Set([
35
+ 'node_modules', 'bower_components', 'jspm_packages', '.pnpm-store', '.yarn', '.npm', '.bun',
36
+ 'vendor', // composer (PHP), bundler, go
37
+ 'Pods', 'Carthage', '.gradle', '.m2', '.ivy2', '.dart_tool', '.pub-cache', '.pub',
38
+ '.venv', 'venv', 'site-packages', '__pycache__', '.tox', '.mypy_cache', '.pytest_cache',
39
+ '.nuget', '.cargo', '.rustup', '.cache', 'DerivedData', '.expo', '.next', '.nuxt',
40
+ '.turbo', '.parcel-cache', '.svelte-kit', '.angular', '.git',
41
+ // GitSafty's own quarantine (backups of removed malware) and the trash
42
+ '.gitsafty', 'gitsafty-quarantine', '.Trash', '$RECYCLE.BIN'
43
+ ]);
44
+ // Package manager files: lock files and manifests of dependencies, not code that runs.
45
+ const PACKAGE_FILES = new Set([
46
+ 'package-lock.json', 'yarn.lock', 'pnpm-lock.yaml', 'bun.lockb', 'npm-shrinkwrap.json',
47
+ 'composer.lock', 'Gemfile.lock', 'Podfile.lock', 'Cargo.lock', 'poetry.lock', 'Pipfile.lock',
48
+ 'pubspec.lock', 'go.sum', 'packages.lock.json', 'gradle.lockfile', 'mix.lock', 'flake.lock'
49
+ ]);
50
+ // document.pdf.exe style names, and Windows script/screensaver types that are almost only used by malware.
51
+ const DECEPTIVE_NAME = /\.(pdf|docx?|xlsx?|pptx?|txt|jpe?g|png|gif|mp4|mp3|zip|rar)\.(exe|scr|com|bat|cmd|vbs|js|jse|ps1|hta|lnk)$|\.(scr|pif|cpl|hta|vbe|jse|wsf)$/i;
52
+ const KNOWN_GOOD_SCRIPTS = new Set(['gradlew.bat', 'mvnw.cmd', 'gradlew', 'mvnw']);
53
+
54
+ const MAX_FILE = 32 * 1024 * 1024;
55
+ const MAX_ARCHIVE = 1024 * 1024 * 1024;
56
+
57
+ function home() {
58
+ return process.env.HOME || process.env.USERPROFILE || os.homedir();
59
+ }
60
+
61
+ function isWin() {
62
+ return process.platform === 'win32';
63
+ }
64
+
65
+ function skipEntry(inner) {
66
+ const norm = inner.replace(/\\/g, '/');
67
+ return PACKAGE_FILES.has(norm.split('/').pop()) || norm.split('/').slice(0, -1).some(s => DEPENDENCY_DIRS.has(s));
68
+ }
69
+
70
+ function readHead(full, n = 512) {
71
+ let fd;
72
+ try {
73
+ fd = fs.openSync(full, 'r');
74
+ const b = Buffer.alloc(n);
75
+ const len = fs.readSync(fd, b, 0, n, 0);
76
+ return b.subarray(0, len);
77
+ } catch (_) {
78
+ return null;
79
+ } finally {
80
+ if (fd !== undefined) try { fs.closeSync(fd); } catch (_) {}
81
+ }
82
+ }
83
+
84
+ /** Findings for one piece of content (loose file or archive entry). */
85
+ function inspectContent(displayPath, innerPath, buf, { names = true } = {}) {
86
+ const out = [];
87
+ for (const f of detectMalware(innerPath, buf)) out.push({ category: 'malware', ...f, filePath: displayPath });
88
+ const base = innerPath.split('/').pop();
89
+ // Only names that are almost never legitimate: plain .exe/.dll/.bin are normal in downloads and app bundles.
90
+ const nameRule = names && !KNOWN_GOOD_SCRIPTS.has(base) ? checkFilename(innerPath) : null;
91
+ if (nameRule && (DECEPTIVE_NAME.test(base) || /^Known malicious/.test(nameRule.rule))) {
92
+ out.push({ category: 'file', verdict: 'SUSPECT', severity: 'CRITICAL', name: nameRule.rule, description: 'Disguised or known-malicious file name.', filePath: displayPath });
93
+ }
94
+ const norm = innerPath.replace(/\\/g, '/');
95
+ if (/(^|\/)\.vscode\/(tasks|settings)\.json$/.test(norm) || /(^|\/)\.idea\/workspace\.xml$/.test(norm)) {
96
+ for (const f of inspectIdeConfig(innerPath, buf.toString('utf8'))) {
97
+ out.push({ category: 'ide', verdict: 'SUSPECT', ...f, filePath: displayPath });
98
+ }
99
+ }
100
+ return out;
101
+ }
102
+
103
+ /**
104
+ * Scans a folder. Pure: nothing is changed.
105
+ * @returns {object} result
106
+ */
107
+ function fullScan(root, { onProgress } = {}) {
108
+ const abs = path.resolve(root);
109
+ const result = {
110
+ root: abs,
111
+ files: 0,
112
+ archives: [],
113
+ repos: [],
114
+ skippedDirs: 0,
115
+ tooLarge: [],
116
+ unreadable: 0,
117
+ findings: []
118
+ };
119
+
120
+ const walk = (dir) => {
121
+ let entries;
122
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch (_) { result.unreadable++; return; }
123
+ if (entries.some(e => e.name === '.git')) {
124
+ result.repos.push(dir);
125
+ const rel = path.relative(abs, dir).replace(/\\/g, '/');
126
+ for (const f of gitPersistenceFindings(dir)) {
127
+ result.findings.push({ ...f, filePath: rel ? `${rel}/${f.filePath}` : f.filePath, repo: dir });
128
+ }
129
+ }
130
+ for (const e of entries) {
131
+ if (e.isSymbolicLink()) continue;
132
+ const full = path.join(dir, e.name);
133
+ if (e.isDirectory()) {
134
+ if (DEPENDENCY_DIRS.has(e.name)) {
135
+ if (e.name !== '.git' && e.name !== '.gitsafty' && e.name !== 'gitsafty-quarantine') result.skippedDirs++;
136
+ continue;
137
+ }
138
+ walk(full);
139
+ } else if (e.isFile()) {
140
+ if (PACKAGE_FILES.has(e.name)) continue;
141
+ scanFile(full);
142
+ }
143
+ }
144
+ };
145
+
146
+ const scanFile = (full) => {
147
+ const rel = path.relative(abs, full).replace(/\\/g, '/');
148
+ let st;
149
+ try { st = fs.statSync(full); } catch (_) { result.unreadable++; return; }
150
+ if (!st.size) return;
151
+ result.files++;
152
+ if (onProgress && result.files % 200 === 0) onProgress(result);
153
+
154
+ const head = readHead(full);
155
+ if (!head) { result.unreadable++; return; }
156
+ const type = detectArchiveType(head, full);
157
+ const limit = type ? MAX_ARCHIVE : MAX_FILE;
158
+ if (st.size > limit) { result.tooLarge.push(rel); return; }
159
+
160
+ let buf;
161
+ try { buf = fs.readFileSync(full); } catch (_) { result.unreadable++; return; }
162
+ result.findings.push(...inspectContent(rel, rel, buf));
163
+
164
+ if (!type) return;
165
+ if (/\.(docx|xlsx|pptx|odt|ods|odp|epub)$/i.test(full) && st.size > 64 * 1024 * 1024) return;
166
+ const before = result.findings.length;
167
+ const stats = walkArchive(buf, path.basename(full), (inner, data) => {
168
+ const innerName = inner.split('!/').pop();
169
+ result.findings.push(...inspectContent(`${rel}!/${inner}`, innerName, data).map(f => ({ ...f, archive: rel })));
170
+ }, { skipEntry });
171
+ const own = result.findings.slice(before);
172
+ result.archives.push({
173
+ path: rel,
174
+ type: stats.type,
175
+ entries: stats.entries,
176
+ scanned: stats.scanned,
177
+ encrypted: stats.encrypted,
178
+ problems: stats.problems,
179
+ sha256: sha256(buf),
180
+ malware: own.filter(f => f.verdict === CONFIRMED).length
181
+ });
182
+ // Password-protected archives with programs inside: a common way to sneak malware past scanners.
183
+ const risky = stats.encrypted.filter(n => /\.(exe|scr|com|bat|cmd|ps1|vbs|js|jse|hta|msi|dll|lnk|jar|apk|sh|py)$/i.test(n));
184
+ if (risky.length) {
185
+ result.findings.push({
186
+ category: 'archive', verdict: 'SUSPECT', severity: 'CRITICAL', archive: rel, filePath: rel,
187
+ name: 'Password-protected archive with programs inside',
188
+ description: `Could not be scanned (encrypted): ${risky.slice(0, 3).join(', ')}${risky.length > 3 ? ' …' : ''}. Malware is often sent like this. Do not open it unless you trust the sender.`
189
+ });
190
+ }
191
+ };
192
+
193
+ const st = fs.statSync(abs);
194
+ if (st.isFile()) scanFile(abs); else walk(abs);
195
+ return result;
196
+ }
197
+
198
+ /** Copies a file to the quarantine folder (read-only) and deletes it. */
199
+ function quarantineWhole(full, rel, quarantineDir) {
200
+ const target = path.join(quarantineDir, 'files', `${rel.replace(/\.\./g, '_')}.quarantined`);
201
+ fs.mkdirSync(path.dirname(target), { recursive: true });
202
+ fs.copyFileSync(full, target);
203
+ try { fs.chmodSync(target, 0o400); } catch (_) {}
204
+ fs.unlinkSync(full);
205
+ return target;
206
+ }
207
+
208
+ /**
209
+ * Removes confirmed malware found by fullScan().
210
+ * @returns {{ quarantineDir: string|null, results: Array<{file, action, ok, error?}> }}
211
+ */
212
+ function removeFullScanMalware(result) {
213
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-');
214
+ const quarantineDir = path.join(home(), '.gitsafty', 'quarantine', `full-scan-${stamp}`);
215
+ const confirmed = result.findings.filter(f => f.verdict === CONFIRMED && f.category === 'malware');
216
+ const results = [];
217
+
218
+ // 1. Archives with malware inside: quarantine the whole archive.
219
+ const archives = [...new Set(confirmed.filter(f => f.archive).map(f => f.archive))];
220
+ for (const rel of archives) {
221
+ const full = path.join(result.root, rel);
222
+ try {
223
+ const backup = quarantineWhole(full, rel, quarantineDir);
224
+ results.push({ file: rel, action: 'archive-quarantined', ok: true, backup });
225
+ } catch (err) {
226
+ results.push({ file: rel, action: 'failed', ok: false, error: err.message });
227
+ }
228
+ }
229
+
230
+ // 2. Loose files: same repair engine as clone/pull (strip, remove task/script, or remove file).
231
+ const loose = [...new Set(confirmed.filter(f => !f.archive && !archives.includes(f.filePath)).map(f => f.filePath))];
232
+ if (loose.length) {
233
+ const r = removeConfirmedMalware(loose, result.root, { reason: 'full-scan', quarantineDir });
234
+ results.push(...r.results);
235
+ }
236
+
237
+ if (results.length) {
238
+ fs.mkdirSync(quarantineDir, { recursive: true });
239
+ const reportPath = path.join(quarantineDir, 'full-scan-report.json');
240
+ fs.writeFileSync(reportPath, JSON.stringify({ createdAt: new Date().toISOString(), root: result.root, results }, null, 2), { mode: 0o600 });
241
+ }
242
+ return { quarantineDir: results.length ? quarantineDir : null, results };
243
+ }
244
+
245
+ function annotate(result, clean) {
246
+ const byFile = new Map();
247
+ for (const r of (clean && clean.results) || []) byFile.set(r.file, r);
248
+ for (const f of result.findings) {
249
+ const res = f.verdict === CONFIRMED && f.category === 'malware' ? (byFile.get(f.archive) || byFile.get(f.filePath)) : null;
250
+ if (res && res.ok && res.action === 'archive-quarantined') f.action = { removed: true, text: 'Removed: the whole archive was moved to quarantine (backup kept)' };
251
+ else if (res && res.ok && res.action === 'quarantined') f.action = { removed: true, text: 'Removed: whole file was malware (backup kept)' };
252
+ else if (res && res.ok && res.action === 'repaired') f.action = { removed: true, text: 'Removed: malware cut out, rest of the file kept' };
253
+ else if (res && !res.ok) f.action = { removed: false, text: res.action === 'manual' ? 'Needs manual removal' : `Could not remove: ${res.error || 'unknown error'}` };
254
+ else if (f.verdict === CONFIRMED) f.action = { removed: false, text: 'Not removed (report only; run with --clean)' };
255
+ else if (f.fixCommand) f.action = { removed: false, text: `Not yours? Remove it: ${f.fixCommand}` };
256
+ else f.action = { removed: false, text: 'Review it yourself (never removed automatically)' };
257
+ }
258
+ }
259
+
260
+ function writeReport(result) {
261
+ const dir = path.join(home(), '.gitsafty', 'reports');
262
+ fs.mkdirSync(dir, { recursive: true });
263
+ const file = path.join(dir, `full-scan-${path.basename(result.root)}-${new Date().toISOString().replace(/[:.]/g, '-')}.json`);
264
+ fs.writeFileSync(file, JSON.stringify({ createdAt: new Date().toISOString(), ...result }, null, 2), { mode: 0o600 });
265
+ return file;
266
+ }
267
+
268
+ function printFindings(result) {
269
+ const groups = new Map();
270
+ for (const f of result.findings) {
271
+ const key = f.archive || f.filePath.split('/')[0];
272
+ if (!groups.has(key)) groups.set(key, []);
273
+ groups.get(key).push(f);
274
+ }
275
+ for (const [key, list] of groups) {
276
+ const malware = list.some(f => f.verdict === CONFIRMED);
277
+ const allRemoved = list.every(f => f.action.removed);
278
+ const color = malware && !allRemoved ? colors.red : allRemoved ? colors.green : colors.yellow;
279
+ const isArchive = list.some(f => f.archive === key);
280
+ console.log(`\n${color}${colors.bold}${isArchive ? '🗜️ ' : '📁'} ${key}${colors.reset}`);
281
+ for (const f of list.slice(0, 30)) {
282
+ const tag = f.verdict === CONFIRMED ? `${colors.red}${colors.bold}MALWARE${colors.reset}`
283
+ : f.severity === 'CRITICAL' ? `${colors.red}${colors.bold}DANGER${colors.reset}` : `${colors.yellow}${(f.category || 'review').toUpperCase()}${colors.reset}`;
284
+ console.log(` ${tag} ${f.name}`);
285
+ console.log(` ${colors.dim}${f.filePath}${f.lineNumber ? ':' + f.lineNumber : ''}${colors.reset}`);
286
+ if (f.description && f.category === 'archive') console.log(` ${colors.dim}${f.description}${colors.reset}`);
287
+ const c = f.action.removed ? colors.green : (f.verdict === CONFIRMED ? colors.red : colors.dim);
288
+ console.log(` ${c}→ ${f.action.text}${colors.reset}`);
289
+ }
290
+ if (list.length > 30) console.log(` ${colors.dim}… ${list.length - 30} more in the JSON report${colors.reset}`);
291
+ }
292
+ }
293
+
294
+ /**
295
+ * Runs Full Scan and prints the result.
296
+ * @returns {number} exit code (1 when malware or critical findings remain)
297
+ */
298
+ function runFullScan(target, { clean = false, json = false } = {}) {
299
+ const abs = path.resolve(target || process.cwd());
300
+ if (!fs.existsSync(abs)) {
301
+ console.error(`${colors.red}✖ Not found: ${abs}${colors.reset}`);
302
+ return 1;
303
+ }
304
+ const started = Date.now();
305
+ const tty = !json && process.stdout.isTTY;
306
+ if (!json) {
307
+ console.log(`\n${colors.cyan}${colors.bold}🧪 Full Scan${colors.reset} ${colors.dim}${abs}${colors.reset}`);
308
+ console.log(`${colors.dim}Every file and every archive (zip, jar, apk, tar, gz, 7z, rar …), git repository or not · skipping node_modules, vendor & package caches · ${clean ? 'auto-remove confirmed malware' : 'report only'}${colors.reset}\n`);
309
+ }
310
+
311
+ const result = fullScan(abs, {
312
+ onProgress: tty ? (r) => process.stdout.write(`\r${colors.dim} scanned ${r.files} files, ${r.archives.length} archives…${colors.reset}`) : null
313
+ });
314
+ if (tty) process.stdout.write('\r\x1b[K');
315
+
316
+ const clean_ = clean && result.findings.some(f => f.verdict === CONFIRMED && f.category === 'malware') ? removeFullScanMalware(result) : null;
317
+ annotate(result, clean_);
318
+ result.clean = clean_;
319
+ const reportPath = writeReport(result);
320
+
321
+ if (json) {
322
+ process.stdout.write(JSON.stringify({ reportPath, ...result }, null, 2) + '\n');
323
+ } else {
324
+ if (result.findings.length) {
325
+ console.log(`${colors.bold}${colors.cyan}━━━━━━━━━━━━━━━━━━ What was found ━━━━━━━━━━━━━━━━━━${colors.reset}`);
326
+ printFindings(result);
327
+ }
328
+ const problemArchives = result.archives.filter(a => a.problems.length || a.encrypted.length);
329
+ if (problemArchives.length) {
330
+ console.log(`\n${colors.yellow}${colors.bold}Archives that could not be fully checked${colors.reset}`);
331
+ for (const a of problemArchives.slice(0, 20)) {
332
+ const why = [...(a.encrypted.length ? [`${a.encrypted.length} encrypted file(s)`] : []), ...a.problems.slice(0, 2).map(p => `${p.entry}: ${p.reason}`)];
333
+ console.log(` ${colors.yellow}⚠${colors.reset} ${a.path} ${colors.dim}${why.join('; ')}${colors.reset}`);
334
+ }
335
+ }
336
+
337
+ const confirmed = result.findings.filter(f => f.verdict === CONFIRMED);
338
+ const removed = result.findings.filter(f => f.action.removed);
339
+ const review = result.findings.filter(f => !f.action.removed && f.verdict !== CONFIRMED);
340
+ const infectedArchives = result.archives.filter(a => a.malware);
341
+ console.log(`\n${colors.bold}Summary${colors.reset} ${colors.dim}(${((Date.now() - started) / 1000).toFixed(1)}s)${colors.reset}`);
342
+ console.log(` Files scanned : ${result.files} (${result.repos.length} git repo(s) inside; non-git folders included)`);
343
+ console.log(` Archives opened : ${result.archives.length} (${result.archives.reduce((n, a) => n + a.scanned, 0)} files inside)`);
344
+ console.log(` ${confirmed.length ? colors.red : colors.green}Malware : ${confirmed.length}${infectedArchives.length ? ` (${infectedArchives.length} archive(s))` : ''}${colors.reset}`);
345
+ console.log(` ${removed.length ? colors.green : colors.dim}Removed : ${removed.length}${colors.reset}`);
346
+ console.log(` ${review.length ? colors.yellow : colors.green}To review : ${review.length}${colors.reset}`);
347
+ console.log(` ${colors.dim}Skipped : ${result.skippedDirs} dependency folder(s) (node_modules, vendor …)${result.tooLarge.length ? `, ${result.tooLarge.length} file(s) too large` : ''}${colors.reset}`);
348
+ if (clean_ && clean_.quarantineDir) console.log(` ${colors.dim}Backups : ${clean_.quarantineDir}${colors.reset}`);
349
+ console.log(`\n ${colors.dim}Full report: ${reportPath}${colors.reset}`);
350
+ const left = confirmed.filter(f => !f.action.removed);
351
+ if (left.length && !clean) {
352
+ console.log(`\n ${colors.bold}Remove the confirmed malware:${colors.reset} ${colors.cyan}gitsafty full-scan "${abs}" --clean${colors.reset}`);
353
+ }
354
+ if (removed.length && result.repos.length) {
355
+ console.log(` ${colors.dim}Files inside git repositories changed in the working tree only: check git status there and commit the fix.${colors.reset}`);
356
+ }
357
+ console.log('');
358
+ if (confirmed.length) notifyDesktop('GitSafty Full Scan', `${confirmed.length} malware finding(s) in ${path.basename(abs)}. Check the terminal.`);
359
+ }
360
+
361
+ const open = result.findings.filter(f => !f.action.removed && (f.verdict === CONFIRMED || f.severity === 'CRITICAL'));
362
+ return open.length ? 1 : 0;
363
+ }
364
+
365
+ module.exports = {
366
+ fullScan,
367
+ runFullScan,
368
+ removeFullScanMalware,
369
+ DEPENDENCY_DIRS,
370
+ PACKAGE_FILES
371
+ };
package/src/index.js CHANGED
@@ -336,6 +336,8 @@ function runManualScan() {
336
336
 
337
337
  if (!isGitRepo()) {
338
338
  console.error(`${colors.red}Error: Current directory is not a git repository.${colors.reset}`);
339
+ console.error(`${colors.dim}To scan a plain folder, zip files or projects that are not git repositories, use Full Scan:${colors.reset}`);
340
+ console.error(` ${colors.cyan}gitsafty full-scan .${colors.reset} ${colors.dim}(add --clean to remove confirmed malware)${colors.reset}\n`);
339
341
  process.exit(1);
340
342
  }
341
343
 
package/src/installer.js CHANGED
@@ -348,7 +348,9 @@ function isPermanentGlobalInstall(cli = CLI_PATH) {
348
348
  return /\/node_modules\/@arifbiswas\/git-pre-push\/bin\/cli\.js$/.test(cli) &&
349
349
  !/\/_npx\//.test(cli) &&
350
350
  !/\/node_modules\/.+\/node_modules\//.test(cli) &&
351
- /\/lib\/node_modules\/|\/npm\/node_modules\/|\/nodejs\/node_modules\/|^[A-Za-z]:\/.*\/node_modules\//.test(cli);
351
+ // unix prefix (nvm, Homebrew, /usr/local), Windows npm prefix (AppData/Roaming/npm),
352
+ // Program Files/nodejs, nvm-windows (AppData/Roaming/nvm/v20.x/node_modules).
353
+ /\/lib\/node_modules\/|\/npm\/node_modules\/|\/nodejs\/node_modules\/|\/nvm\/v[0-9][^/]*\/node_modules\//i.test(cli);
352
354
  }
353
355
 
354
356
  /**
@@ -116,12 +116,13 @@ function applyRepairs(relPath, original, findings) {
116
116
  *
117
117
  * @param {string[]} files repo-relative paths that had CONFIRMED findings
118
118
  * @param {string} cwd repo root
119
- * @param {{ reason?: string }} [options]
119
+ * @param {{ reason?: string, quarantineDir?: string }} [options]
120
120
  */
121
121
  function removeConfirmedMalware(files, cwd = process.cwd(), options = {}) {
122
- const gitDir = gitDirOf(cwd) || path.join(cwd, '.git');
123
122
  const stamp = new Date().toISOString().replace(/[:.]/g, '-');
124
- const quarantineDir = path.join(gitDir, 'gitsafty-quarantine', stamp);
123
+ // Outside a git repository (Full Scan) the caller gives its own quarantine folder.
124
+ const quarantineDir = options.quarantineDir ||
125
+ path.join(gitDirOf(cwd) || path.join(cwd, '.git'), 'gitsafty-quarantine', stamp);
125
126
 
126
127
  const results = [];
127
128
 
package/src/menu.js CHANGED
@@ -40,6 +40,7 @@ async function runInteractiveMenu() {
40
40
  section('Malware scan & removal');
41
41
  item(3, '🔍', 'Scan Local Workspace', 'Deep scan this repo, auto-remove confirmed malware');
42
42
  item(16, '🔬', 'Advanced Scanner', 'Audit ALL projects in a folder: malware, backdoors, secrets');
43
+ item(18, '🧪', 'Full Scan', 'EVERYTHING in a folder: non-git projects + zip/tar/7z/rar');
43
44
  item(10, '🧹', 'Sweep All Repos', 'Scan every git repo in a folder (whole device)');
44
45
  item(5, '🗑️ ', 'Clean & Quarantine', 'Remove confirmed malware + trojan scripts here');
45
46
  item(4, '🚀', 'Scan Remote GitHub Repo', 'Zero-clone audit (no download/clone)');
@@ -63,7 +64,7 @@ async function runInteractiveMenu() {
63
64
  });
64
65
 
65
66
  const choice = await new Promise((resolve) => {
66
- rl.question(`${colors.bold}${colors.yellow}Enter your choice (1-17, 0 to exit): ${colors.reset}`, (ans) => {
67
+ rl.question(`${colors.bold}${colors.yellow}Enter your choice (1-18, 0 to exit): ${colors.reset}`, (ans) => {
67
68
  rl.close();
68
69
  resolve(ans.trim());
69
70
  });
@@ -262,6 +263,14 @@ async function runInteractiveMenu() {
262
263
  break;
263
264
  }
264
265
 
266
+ case '18': {
267
+ const { runFullScan } = require('./fullScanner');
268
+ const folder = await ask(`\n${colors.bold}${colors.cyan}? Folder to scan completely (Enter = ${process.cwd()}): ${colors.reset}`);
269
+ const clean = await ask(`${colors.bold}${colors.cyan}? Automatically remove CONFIRMED malware? An infected archive is moved to quarantine whole (backup kept). (Y/n): ${colors.reset}`);
270
+ runFullScan(folder || process.cwd(), { clean: !/^n(o)?$/i.test(clean) });
271
+ break;
272
+ }
273
+
265
274
  case '0':
266
275
  default:
267
276
  console.log(`\n${colors.dim}Goodbye! 🛡️${colors.reset}\n`);
@@ -275,17 +275,44 @@ function globalCliPath() {
275
275
  * re-runs init with the permanent copy so the hooks point there.
276
276
  * @param {string[]} initArgs e.g. ['init', '--global']
277
277
  */
278
- async function offerPermanentInstall(initArgs) {
279
- if (installKind() !== 'npx') return;
278
+ /**
279
+ * Offers to install GitSafty globally when this copy is not a global install:
280
+ * - npx: runs from a temporary cache, no `gitsafty` command, hooks point
281
+ * into that cache (which npm may delete)
282
+ * - project dependency (`npm i @arifbiswas/git-pre-push` without -g):
283
+ * only this project has it, no `gitsafty` command, other repos unprotected
284
+ * npm can't make a package install globally by itself, so GitSafty asks.
285
+ * Yes runs `npm install -g` and then `init` with the global copy.
286
+ * @param {string[]} initArgs init arguments to re-run with the global copy
287
+ * @param {{ kind?: string, remember?: boolean }} [opts]
288
+ */
289
+ async function offerPermanentInstall(initArgs, opts = {}) {
290
+ const kind = opts.kind || installKind();
291
+ if (kind !== 'npx' && kind !== 'local-dependency') return;
280
292
  const isWin = process.platform === 'win32';
281
- console.log(`${colors.yellow}${colors.bold}⚠ You ran GitSafty with npx.${colors.reset}`);
282
- console.log(` npx only runs it from a temporary cache: the ${colors.bold}gitsafty${colors.reset} command is not installed,`);
283
- console.log(` and the hooks point into that cache, which npm may delete later.`);
284
- console.log(` ${colors.dim}Install it permanently:${colors.reset} ${colors.cyan}npm install -g ${PACKAGE_NAME}${colors.reset} ${colors.dim}then${colors.reset} ${colors.cyan}gitsafty ${initArgs.join(' ')}${colors.reset}\n`);
293
+ const cache = readCache() || {};
294
+ const declinedRecently = opts.remember && cache.declinedGlobalAt && Date.now() - cache.declinedGlobalAt < 30 * 24 * 60 * 60 * 1000;
295
+ if (declinedRecently) return;
296
+
297
+ if (kind === 'npx') {
298
+ console.log(`${colors.yellow}${colors.bold}⚠ You ran GitSafty with npx.${colors.reset}`);
299
+ console.log(` npx only runs it from a temporary cache: the ${colors.bold}gitsafty${colors.reset} command is not installed,`);
300
+ console.log(` and the hooks point into that cache, which npm may delete later.`);
301
+ } else {
302
+ console.log(`${colors.yellow}${colors.bold}⚠ GitSafty is installed in this project only${colors.reset} ${colors.dim}(${path.resolve(__dirname, '..')})${colors.reset}`);
303
+ console.log(` \`npm i\` without -g puts it in node_modules: no ${colors.bold}gitsafty${colors.reset} command, and other repos on this PC are not protected.`);
304
+ }
305
+ console.log(` ${colors.dim}Install it for the whole PC:${colors.reset} ${colors.cyan}npm install -g ${PACKAGE_NAME}${colors.reset} ${colors.dim}then${colors.reset} ${colors.cyan}gitsafty ${initArgs.join(' ')}${colors.reset}\n`);
285
306
 
286
307
  if (!isInteractive() || process.env.GITSAFTY_NO_UPDATE_PROMPT === '1') return;
287
- const yes = await askYesNo(`${colors.bold}${colors.cyan}? Install GitSafty permanently now (adds the gitsafty command)? (Y/n): ${colors.reset}`);
288
- if (!yes) return;
308
+ const yes = await askYesNo(`${colors.bold}${colors.cyan}? Install GitSafty globally now (gitsafty command + protect every repo)? (Y/n): ${colors.reset}`);
309
+ if (!yes) {
310
+ if (opts.remember) {
311
+ writeCache(cache.latestVersion || null, { declinedGlobalAt: Date.now() });
312
+ console.log(`${colors.dim}OK, I won't ask again for 30 days.${colors.reset}\n`);
313
+ }
314
+ return;
315
+ }
289
316
  if (!installVersion('latest')) return;
290
317
 
291
318
  const cli = globalCliPath();
@@ -303,9 +330,24 @@ async function offerPermanentInstall(initArgs) {
303
330
  console.log('');
304
331
  }
305
332
 
333
+ /**
334
+ * Fast check (no npm call) whether this copy might be a project dependency.
335
+ * Confirmed with installKind() before asking anything.
336
+ */
337
+ function looksLikeProjectCopy() {
338
+ const cli = path.resolve(__dirname, '..', 'bin', 'cli.js').replace(/\\/g, '/');
339
+ if (!/\/node_modules\/@arifbiswas\/git-pre-push\/bin\/cli\.js$/.test(cli) || /\/_npx\//.test(cli)) return false;
340
+ try {
341
+ return !require('./installer').isPermanentGlobalInstall(cli);
342
+ } catch (_) {
343
+ return true;
344
+ }
345
+ }
346
+
306
347
  module.exports = {
307
348
  isNewerVersion,
308
349
  offerPermanentInstall,
350
+ looksLikeProjectCopy,
309
351
  globalCliPath,
310
352
  installKind,
311
353
  offerUpdate,