@arifbiswas/git-pre-push 1.0.21 → 1.0.22

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
@@ -47,6 +47,72 @@ gitsafty init
47
47
 
48
48
  ---
49
49
 
50
+ ## Apps (desktop and Android)
51
+
52
+ Prefer a window to the terminal? GitSafty also has a desktop app and an Android app.
53
+
54
+ Download the latest version from the [GitHub Releases page](https://github.com/arifbiswas/git-pre-push/releases). Pick the file for your system:
55
+
56
+ | System | File |
57
+ |---|---|
58
+ | macOS, Apple Silicon | `GitSafty-<version>-mac-arm64.dmg` |
59
+ | macOS, Intel | `GitSafty-<version>-mac-x64.dmg` |
60
+ | Windows | `GitSafty-<version>-win-x64.exe` |
61
+ | Linux | the `.AppImage` file (any distro) or the `.deb` file (Ubuntu, Debian) |
62
+ | Android | `GitSafty-<version>-android.apk` |
63
+
64
+ There is no iOS app.
65
+
66
+ ### Desktop app
67
+
68
+ The app has four pages:
69
+
70
+ - **Protection**: turn protection for all projects on or off. Turn "scan every git pull" on or off. See if your GitHub login is safe.
71
+ - **Scan**: scan one project, all projects in a folder, everything in a folder (including zip and rar files), or files you pick. Press **Remove confirmed malware** to remove what GitSafty is sure about. Backups are kept.
72
+ - **GitHub repo**: check a repo by its link before you clone it. Nothing is downloaded to your disk.
73
+ - **Fix problems**: runs the doctor.
74
+
75
+ Safe GitHub login is still set up in a terminal:
76
+
77
+ ```bash
78
+ gitsafty vault setup
79
+ ```
80
+
81
+ Protection uses the `gitsafty` command. If it is missing, the app installs it with npm. So protection needs Node.js 18 or newer. Scanning works without Node.js.
82
+
83
+ ### Android app
84
+
85
+ - Scan files on your phone, for example a zip or apk you downloaded.
86
+ - Scan a GitHub repo by its link.
87
+
88
+ Phones cannot run git hooks. So the Android app has no push, clone or pull protection.
89
+
90
+ - 7z and rar files cannot be opened on a phone.
91
+ - The app does not delete malware on the phone. Delete the file yourself with the Files app.
92
+
93
+ ### First start warnings
94
+
95
+ The apps are not signed with a paid certificate. Your system shows a warning the first time you open them.
96
+
97
+ - **macOS**: "GitSafty can't be opened because it is from an unidentified developer." Right-click the app, then choose **Open**. Or go to **System Settings > Privacy & Security** and click **Open Anyway**. If macOS says the app "is damaged", run this in Terminal:
98
+
99
+ ```bash
100
+ xattr -cr /Applications/GitSafty.app
101
+ ```
102
+
103
+ - **Windows**: SmartScreen shows "Windows protected your PC". Click **More info**, then **Run anyway**.
104
+ - **Linux AppImage**: make the file runnable first, then run it:
105
+
106
+ ```bash
107
+ chmod +x GitSafty-*.AppImage
108
+ ```
109
+
110
+ - **Android**: when asked, allow "Install unknown apps" for your browser or Files app.
111
+
112
+ The apps are built automatically by GitHub Actions for every new version. To build them yourself, see `app/README.md`.
113
+
114
+ ---
115
+
50
116
  ## The menu
51
117
 
52
118
  Run `gitsafty` with nothing after it:
package/bin/cli.js CHANGED
@@ -79,12 +79,18 @@ async function main() {
79
79
  }
80
80
 
81
81
  // `gitsafty update` does its own check below.
82
- if (!hookCommands.includes(command) && command !== 'update' && command !== 'upgrade') {
82
+ if (!hookCommands.includes(command) && !['update', 'upgrade', 'version', '--version', '-v'].includes(command)) {
83
83
  // Opening the menu always asks the registry, so a fresh release is never missed.
84
84
  await notifyIfUpdateAvailable(pkg.version, { force: command === 'menu' || command === 'interactive' });
85
85
  }
86
86
 
87
87
  switch (command) {
88
+ case 'version':
89
+ case '--version':
90
+ case '-v':
91
+ console.log(pkg.version);
92
+ break;
93
+
88
94
  case 'update':
89
95
  case 'upgrade':
90
96
  banner();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arifbiswas/git-pre-push",
3
- "version": "1.0.21",
3
+ "version": "1.0.22",
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": {
@@ -439,6 +439,8 @@ function runAdvancedScan(root, { clean = false, deep = false, json = false } = {
439
439
  module.exports = {
440
440
  runAdvancedScan,
441
441
  scanProject,
442
+ annotateActions,
443
+ statusOf,
442
444
  findProjects,
443
445
  gitPersistenceFindings
444
446
  };
@@ -22,9 +22,8 @@
22
22
  const fs = require('fs');
23
23
  const os = require('os');
24
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');
25
+ const { sha256, CONFIRMED } = require('./rules/malware');
26
+ const { inspectContent } = require('./inspect');
28
27
  const { gitPersistenceFindings } = require('./advancedScanner');
29
28
  const { removeConfirmedMalware, notifyDesktop } = require('./malwareCleaner');
30
29
  const { walkArchive, detectArchiveType } = require('./archive');
@@ -47,9 +46,6 @@ const PACKAGE_FILES = new Set([
47
46
  'composer.lock', 'Gemfile.lock', 'Podfile.lock', 'Cargo.lock', 'poetry.lock', 'Pipfile.lock',
48
47
  'pubspec.lock', 'go.sum', 'packages.lock.json', 'gradle.lockfile', 'mix.lock', 'flake.lock'
49
48
  ]);
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
49
 
54
50
  const MAX_FILE = 32 * 1024 * 1024;
55
51
  const MAX_ARCHIVE = 1024 * 1024 * 1024;
@@ -81,25 +77,6 @@ function readHead(full, n = 512) {
81
77
  }
82
78
  }
83
79
 
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
80
  /**
104
81
  * Scans a folder. Pure: nothing is changed.
105
82
  * @returns {object} result
@@ -144,7 +121,7 @@ function fullScan(root, { onProgress } = {}) {
144
121
  };
145
122
 
146
123
  const scanFile = (full) => {
147
- const rel = path.relative(abs, full).replace(/\\/g, '/');
124
+ const rel = path.relative(result.root, full).replace(/\\/g, '/');
148
125
  let st;
149
126
  try { st = fs.statSync(full); } catch (_) { result.unreadable++; return; }
150
127
  if (!st.size) return;
@@ -191,7 +168,13 @@ function fullScan(root, { onProgress } = {}) {
191
168
  };
192
169
 
193
170
  const st = fs.statSync(abs);
194
- if (st.isFile()) scanFile(abs); else walk(abs);
171
+ if (st.isFile()) {
172
+ // A single file: paths are shown (and removed) relative to its folder.
173
+ result.root = path.dirname(abs);
174
+ scanFile(abs);
175
+ } else {
176
+ walk(abs);
177
+ }
195
178
  return result;
196
179
  }
197
180
 
@@ -365,6 +348,7 @@ function runFullScan(target, { clean = false, json = false } = {}) {
365
348
  module.exports = {
366
349
  fullScan,
367
350
  runFullScan,
351
+ annotate,
368
352
  removeFullScanMalware,
369
353
  DEPENDENCY_DIRS,
370
354
  PACKAGE_FILES
package/src/inspect.js ADDED
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Checks one piece of content (a file on disk, inside an archive, or fetched
3
+ * from GitHub). Pure: no file system or process access, so it also runs in
4
+ * the browser / Android app.
5
+ */
6
+
7
+ const { detectMalware } = require('./rules/malware');
8
+ const { checkFilename } = require('./rules/filenames');
9
+ const { inspectIdeConfig } = require('./rules/ideConfig');
10
+
11
+ // document.pdf.exe style names, and Windows script/screensaver types that are almost only used by malware.
12
+ 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;
13
+ const KNOWN_GOOD_SCRIPTS = new Set(['gradlew.bat', 'mvnw.cmd', 'gradlew', 'mvnw']);
14
+
15
+ /**
16
+ * @param {string} displayPath path shown to the user (may contain "archive.zip!/inner")
17
+ * @param {string} innerPath real file path, used for type checks
18
+ * @param {Buffer} buf content
19
+ * @returns {Array<object>} findings
20
+ */
21
+ function inspectContent(displayPath, innerPath, buf, { names = true } = {}) {
22
+ const out = [];
23
+ for (const f of detectMalware(innerPath, buf)) out.push({ category: 'malware', ...f, filePath: displayPath });
24
+ const base = innerPath.split('/').pop();
25
+ // Only names that are almost never legitimate: plain .exe/.dll/.bin are normal in downloads and app bundles.
26
+ const nameRule = names && !KNOWN_GOOD_SCRIPTS.has(base) ? checkFilename(innerPath) : null;
27
+ if (nameRule && (DECEPTIVE_NAME.test(base) || /^Known malicious/.test(nameRule.rule))) {
28
+ out.push({ category: 'file', verdict: 'SUSPECT', severity: 'CRITICAL', name: nameRule.rule, description: 'Disguised or known-malicious file name.', filePath: displayPath });
29
+ }
30
+ const norm = innerPath.replace(/\\/g, '/');
31
+ if (/(^|\/)\.vscode\/(tasks|settings)\.json$/.test(norm) || /(^|\/)\.idea\/workspace\.xml$/.test(norm)) {
32
+ for (const f of inspectIdeConfig(innerPath, buf.toString('utf8'))) {
33
+ out.push({ category: 'ide', verdict: 'SUSPECT', ...f, filePath: displayPath });
34
+ }
35
+ }
36
+ return out;
37
+ }
38
+
39
+ module.exports = { inspectContent, DECEPTIVE_NAME };
@@ -0,0 +1,120 @@
1
+ /**
2
+ * Deep scan of a GitHub repository without cloning it.
3
+ *
4
+ * Reads the file list with the GitHub API (2 requests), then downloads the
5
+ * files that can carry malware from raw.githubusercontent.com (not counted
6
+ * against the API rate limit) and runs the same engine as local scans,
7
+ * including inside archives. Nothing is written to disk.
8
+ *
9
+ * Uses only fetch + Buffer, so it runs in Node.js 18+ and in the browser /
10
+ * Android app.
11
+ */
12
+
13
+ const { inspectContent } = require('./inspect');
14
+ const { walkArchive, detectArchiveType, isArchiveName } = require('./archive');
15
+
16
+ const SKIP_DIR = /(^|\/)(node_modules|vendor|bower_components|Pods|\.yarn|dist|build|\.next|coverage|\.gradle|\.dart_tool)\//;
17
+ const LOCK_FILE = /(^|\/)(package-lock\.json|yarn\.lock|pnpm-lock\.yaml|composer\.lock|Podfile\.lock|Cargo\.lock|go\.sum|pubspec\.lock)$/;
18
+ // Files that can run code, or that malware disguises itself as.
19
+ const CODE_EXT = /\.(m?js|cjs|jsx|tsx?|json|sh|bash|zsh|bat|cmd|ps1|psm1|vbs|py|php|rb|pl|html?|ya?ml|xml|gradle|kts|plist|desktop|service)$/i;
20
+ const ASSET_EXT = /\.(woff2?|ttf|otf|eot|png|jpe?g|gif|ico|bmp|webp|svg|mp3|mp4|wav|pdf)$/i;
21
+ const SPECIAL = /(^|\/)(\.vscode\/[^/]+\.json|\.idea\/[^/]+\.xml|Makefile|Dockerfile|\.npmrc|\.env[^/]*)$/;
22
+
23
+ const LIMITS = { maxFiles: 3000, maxFileBytes: 2 * 1024 * 1024, maxArchiveBytes: 25 * 1024 * 1024, concurrency: 8 };
24
+
25
+ function parseGitHubUrl(input) {
26
+ if (!input) return null;
27
+ let clean = String(input).trim().replace(/\.git$/, '').replace(/\/+$/, '');
28
+ clean = clean.replace(/^git@github\.com:/, '').replace(/^https?:\/\/(www\.)?github\.com\//, '');
29
+ const parts = clean.split('/').filter(Boolean);
30
+ if (parts.length < 2) return null;
31
+ return { owner: parts[0], repo: parts[1], branch: parts[2] === 'tree' && parts[3] ? parts.slice(3).join('/') : undefined };
32
+ }
33
+
34
+ async function api(path, token) {
35
+ const res = await fetch(`https://api.github.com${path}`, {
36
+ headers: { Accept: 'application/vnd.github+json', ...(token ? { Authorization: `Bearer ${token}` } : {}) }
37
+ });
38
+ if (res.ok) return res.json();
39
+ if (res.status === 404) throw new Error('Repository not found. If it is private, add a GitHub token.');
40
+ if (res.status === 403 || res.status === 429) throw new Error('GitHub limit reached (60 requests per hour without a token). Add a GitHub token or try again later.');
41
+ throw new Error(`GitHub error ${res.status}`);
42
+ }
43
+
44
+ function wanted(item) {
45
+ const p = item.path;
46
+ if (SKIP_DIR.test(p) || LOCK_FILE.test(p)) return null;
47
+ if (isArchiveName(p)) return item.size <= LIMITS.maxArchiveBytes ? 'archive' : null;
48
+ if (item.size > LIMITS.maxFileBytes) return null;
49
+ if (CODE_EXT.test(p) || ASSET_EXT.test(p) || SPECIAL.test(p)) return 'file';
50
+ return null;
51
+ }
52
+
53
+ /**
54
+ * @param {string} url GitHub URL or owner/repo
55
+ * @param {{ token?: string, onProgress?: (done: number, total: number) => void }} [opts]
56
+ */
57
+ async function scanGitHubRepo(url, { token, onProgress } = {}) {
58
+ const started = Date.now();
59
+ const parsed = parseGitHubUrl(url);
60
+ if (!parsed) throw new Error('Enter a GitHub link like https://github.com/owner/repo');
61
+ const { owner, repo } = parsed;
62
+ let branch = parsed.branch;
63
+ if (!branch) branch = (await api(`/repos/${owner}/${repo}`, token)).default_branch || 'main';
64
+ const tree = await api(`/repos/${owner}/${repo}/git/trees/${encodeURIComponent(branch)}?recursive=1`, token);
65
+ const blobs = (tree.tree || []).filter(i => i.type === 'blob');
66
+
67
+ const findings = [];
68
+ // Every file name is checked, even files that are not downloaded.
69
+ for (const b of blobs) {
70
+ findings.push(...inspectContent(b.path, b.path, Buffer.alloc(0)).filter(f => f.category === 'file'));
71
+ }
72
+
73
+ const queue = blobs.map(b => ({ ...b, kind: wanted(b) })).filter(b => b.kind);
74
+ const skipped = Math.max(0, queue.length - LIMITS.maxFiles);
75
+ const todo = queue.slice(0, LIMITS.maxFiles);
76
+ let done = 0;
77
+ let failed = 0;
78
+ let archiveFiles = 0;
79
+
80
+ const raw = (p) => `https://raw.githubusercontent.com/${owner}/${repo}/${encodeURIComponent(branch).replace(/%2F/g, '/')}/${p.split('/').map(encodeURIComponent).join('/')}`;
81
+ const worker = async () => {
82
+ while (todo.length) {
83
+ const item = todo.shift();
84
+ try {
85
+ const res = await fetch(raw(item.path), token ? { headers: { Authorization: `Bearer ${token}` } } : undefined);
86
+ if (!res.ok) throw new Error(String(res.status));
87
+ const buf = Buffer.from(await res.arrayBuffer());
88
+ findings.push(...inspectContent(item.path, item.path, buf).filter(f => f.category !== 'file'));
89
+ if (detectArchiveType(buf.subarray(0, 512), item.path)) {
90
+ const stats = walkArchive(buf, item.path, (inner, data) => {
91
+ archiveFiles++;
92
+ findings.push(...inspectContent(`${item.path}!/${inner}`, inner.split('!/').pop(), data).map(f => ({ ...f, archive: item.path })));
93
+ });
94
+ if (stats.encrypted.length) {
95
+ findings.push({ category: 'archive', verdict: 'SUSPECT', severity: 'WARNING', name: 'Password-protected archive', description: `${stats.encrypted.length} file(s) inside could not be checked.`, filePath: item.path });
96
+ }
97
+ }
98
+ } catch (_) {
99
+ failed++;
100
+ }
101
+ done++;
102
+ if (onProgress) onProgress(done, done + todo.length);
103
+ }
104
+ };
105
+ await Promise.all(Array.from({ length: LIMITS.concurrency }, worker));
106
+
107
+ return {
108
+ owner, repo, branch,
109
+ totalFiles: blobs.length,
110
+ scannedFiles: done - failed,
111
+ archiveFiles,
112
+ failed,
113
+ skipped,
114
+ truncated: !!tree.truncated,
115
+ durationMs: Date.now() - started,
116
+ findings
117
+ };
118
+ }
119
+
120
+ module.exports = { scanGitHubRepo, parseGitHubUrl, LIMITS };