@arifbiswas/git-pre-push 1.0.20 → 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 +76 -8
- package/bin/cli.js +32 -21
- package/package.json +1 -1
- package/src/advancedScanner.js +2 -0
- package/src/doctor.js +4 -2
- package/src/fullScanner.js +11 -27
- package/src/inspect.js +39 -0
- package/src/menu.js +8 -2
- package/src/remoteDeepScan.js +120 -0
- package/src/shellIntegration.js +51 -4
package/README.md
CHANGED
|
@@ -36,7 +36,7 @@ That's it. Every git project on this computer is now protected.
|
|
|
36
36
|
|
|
37
37
|
- Use `-g`. Without it GitSafty only lands inside one project and the `gitsafty` command does not exist. If you forget, GitSafty asks to install itself globally the first time it runs.
|
|
38
38
|
- **Windows: `'gitsafty' is not recognized`?** Open a new terminal. Still not found? Add the folder shown by `npm config get prefix` to your `Path`.
|
|
39
|
-
-
|
|
39
|
+
- `init --global` also turns on the check for pulls that say *"Already up to date"*. Open a new terminal once so it takes effect.
|
|
40
40
|
|
|
41
41
|
Protect only one project instead:
|
|
42
42
|
|
|
@@ -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:
|
|
@@ -57,7 +123,7 @@ What do you want to do?
|
|
|
57
123
|
Protect your code
|
|
58
124
|
1. Protect this project Check every push, clone and pull in this project
|
|
59
125
|
2. Protect all projects on this PC Same, for every git project on this computer
|
|
60
|
-
3. Scan every git pull
|
|
126
|
+
3. Scan every git pull On by default, also "Already up to date". Turn off/on
|
|
61
127
|
4. Remove protection Uninstall GitSafty from this project or this PC
|
|
62
128
|
|
|
63
129
|
Scan and clean
|
|
@@ -99,19 +165,21 @@ After `gitsafty init --global` you don't need to do anything. Use git as usual:
|
|
|
99
165
|
|
|
100
166
|
When something is removed, you see what it was and where the backup is. Files inside a project are changed only in your working folder: check `git status`, then commit the clean version.
|
|
101
167
|
|
|
102
|
-
### Scan every pull
|
|
168
|
+
### Scan every pull (on by default)
|
|
169
|
+
|
|
170
|
+
Git runs nothing when a pull says *"Already up to date"*, so GitSafty adds a small `git` helper to your shell profile (`.zshrc`, `.bashrc`, fish or PowerShell) that checks those pulls too. It is **on by default** with the global install, and existing installs get it after updating. Open a new terminal once so it takes effect.
|
|
103
171
|
|
|
104
|
-
|
|
172
|
+
Don't want it? Turn it off. GitSafty remembers this and never turns it back on by itself:
|
|
105
173
|
|
|
106
174
|
```bash
|
|
107
|
-
gitsafty pull-scan
|
|
175
|
+
gitsafty pull-scan off
|
|
108
176
|
```
|
|
109
177
|
|
|
110
178
|
```bash
|
|
111
|
-
gitsafty pull-scan
|
|
179
|
+
gitsafty pull-scan on
|
|
112
180
|
```
|
|
113
181
|
|
|
114
|
-
|
|
182
|
+
Menu option **3** does the same. Pulls that bring new code are always checked, even with this off.
|
|
115
183
|
|
|
116
184
|
---
|
|
117
185
|
|
|
@@ -286,7 +354,7 @@ git config --global --remove-section credential.https://github.com
|
|
|
286
354
|
| `gitsafty init --global` | Protect every project on this computer |
|
|
287
355
|
| `gitsafty init` | Protect only this project |
|
|
288
356
|
| `gitsafty uninstall` | Remove protection from this project (`--global` for the whole computer) |
|
|
289
|
-
| `gitsafty pull-scan
|
|
357
|
+
| `gitsafty pull-scan off` / `on` | Check pulls that say "Already up to date" (on by default) |
|
|
290
358
|
| `gitsafty scan` | Scan this project and remove confirmed malware |
|
|
291
359
|
| `gitsafty scan-projects <folder>` | Scan all projects in a folder (`--clean`, `--deep`, `--json`) |
|
|
292
360
|
| `gitsafty full-scan <folder or file>` | Scan everything, including zip/rar files and non-git folders (`--clean`, `--json`) |
|
package/bin/cli.js
CHANGED
|
@@ -23,29 +23,24 @@ const args = process.argv.slice(2);
|
|
|
23
23
|
const command = args[0] ? args[0].toLowerCase() : 'menu';
|
|
24
24
|
const isGlobalFlag = args.includes('--global') || args.includes('-g');
|
|
25
25
|
|
|
26
|
-
/** After a global install:
|
|
27
|
-
|
|
26
|
+
/** After a global install: pull scan is on by default (also "Already up to date" pulls). */
|
|
27
|
+
function enablePullScan() {
|
|
28
28
|
const shell = require('../src/shellIntegration');
|
|
29
29
|
if (shell.shellIntegrationStatus().installed.length) {
|
|
30
30
|
shell.installShellIntegration(); // refresh with this version's paths
|
|
31
|
+
console.log(`${colors.green}✔ Every git pull is scanned${colors.reset} ${colors.dim}(also "Already up to date"). Turn off: gitsafty pull-scan off${colors.reset}\n`);
|
|
31
32
|
return;
|
|
32
33
|
}
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
console.log(`${colors.dim}GitSafty can add a small git function to your shell profile (.zshrc / .bashrc / PowerShell profile).${colors.reset}`);
|
|
36
|
-
if (!interactive) {
|
|
37
|
-
console.log(` Turn it on: ${colors.cyan}gitsafty pull-scan on${colors.reset}\n`);
|
|
34
|
+
if (shell.isOptedOut()) {
|
|
35
|
+
console.log(`${colors.dim}Pull scan for "Already up to date" pulls is off (you turned it off). Turn on: gitsafty pull-scan on${colors.reset}\n`);
|
|
38
36
|
return;
|
|
39
37
|
}
|
|
40
|
-
const
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
console.log(` ${colors.dim}
|
|
45
|
-
return;
|
|
38
|
+
const files = shell.enableByDefault();
|
|
39
|
+
if (files.length) {
|
|
40
|
+
console.log(`${colors.green}✔ Every git pull is scanned${colors.reset} ${colors.dim}(also "Already up to date"; added to ${files.join(', ')}).${colors.reset}`);
|
|
41
|
+
console.log(` ${colors.dim}Load it now:${colors.reset} ${colors.cyan}${shell.reloadHint()}${colors.reset}`);
|
|
42
|
+
console.log(` ${colors.dim}Turn off: gitsafty pull-scan off${colors.reset}\n`);
|
|
46
43
|
}
|
|
47
|
-
const res = shell.installShellIntegration();
|
|
48
|
-
console.log(`${colors.green}✔ Pull scan on${colors.reset} ${colors.dim}(${res.files.join(', ')})${colors.reset}. Load it now: ${colors.cyan}${shell.reloadHint()}${colors.reset}\n`);
|
|
49
44
|
}
|
|
50
45
|
|
|
51
46
|
async function main() {
|
|
@@ -56,10 +51,19 @@ async function main() {
|
|
|
56
51
|
if (command !== 'credential' && process.env.GITSAFTY_NO_SELF_REFRESH !== '1') {
|
|
57
52
|
try {
|
|
58
53
|
const refreshed = require('../src/installer').refreshOutdatedHooks();
|
|
59
|
-
const
|
|
54
|
+
const shell = require('../src/shellIntegration');
|
|
55
|
+
const shells = shell.refreshShellIntegration();
|
|
60
56
|
if ((refreshed.length || shells.length) && !hookCommands.includes(command)) {
|
|
61
57
|
console.log(`${colors.green}✔ GitSafty ${pkg.version}: updated ${[...refreshed.map(t => `${t} hook`), ...shells.map(f => require('path').basename(f))].join(', ')} to this version.${colors.reset}`);
|
|
62
58
|
}
|
|
59
|
+
// Pull scan is on by default: existing global installs get it on update too
|
|
60
|
+
// (only from the real global copy, and never if the user turned it off).
|
|
61
|
+
if (require('../src/installer').isPermanentGlobalInstall()) {
|
|
62
|
+
const added = shell.enableByDefault({ onlyIfGlobalHooks: true });
|
|
63
|
+
if (added.length && !hookCommands.includes(command)) {
|
|
64
|
+
console.log(`${colors.green}✔ Every git pull is now scanned${colors.reset} ${colors.dim}(also "Already up to date"; ${added.map(f => require('path').basename(f)).join(', ')}). Open a new terminal. Turn off: gitsafty pull-scan off${colors.reset}`);
|
|
65
|
+
}
|
|
66
|
+
}
|
|
63
67
|
} catch (_) {}
|
|
64
68
|
}
|
|
65
69
|
|
|
@@ -75,12 +79,18 @@ async function main() {
|
|
|
75
79
|
}
|
|
76
80
|
|
|
77
81
|
// `gitsafty update` does its own check below.
|
|
78
|
-
if (!hookCommands.includes(command) &&
|
|
82
|
+
if (!hookCommands.includes(command) && !['update', 'upgrade', 'version', '--version', '-v'].includes(command)) {
|
|
79
83
|
// Opening the menu always asks the registry, so a fresh release is never missed.
|
|
80
84
|
await notifyIfUpdateAvailable(pkg.version, { force: command === 'menu' || command === 'interactive' });
|
|
81
85
|
}
|
|
82
86
|
|
|
83
87
|
switch (command) {
|
|
88
|
+
case 'version':
|
|
89
|
+
case '--version':
|
|
90
|
+
case '-v':
|
|
91
|
+
console.log(pkg.version);
|
|
92
|
+
break;
|
|
93
|
+
|
|
84
94
|
case 'update':
|
|
85
95
|
case 'upgrade':
|
|
86
96
|
banner();
|
|
@@ -210,14 +220,14 @@ async function main() {
|
|
|
210
220
|
console.log(` Load it now: ${colors.cyan}${shell.reloadHint()}${colors.reset}\n`);
|
|
211
221
|
}
|
|
212
222
|
} else if (sub === 'off' || sub === 'remove' || sub === 'disable') {
|
|
213
|
-
const res = shell.removeShellIntegration();
|
|
214
|
-
console.log(`\n${colors.yellow}${colors.bold}✔ Pull scan
|
|
215
|
-
console.log(` ${colors.dim}Open a new terminal to finish. Pulls that bring changes are still scanned by the git hooks
|
|
223
|
+
const res = shell.removeShellIntegration({ optOut: true });
|
|
224
|
+
console.log(`\n${colors.yellow}${colors.bold}✔ Pull scan turned off${res.files.length ? ` (removed from ${res.files.join(', ')})` : ''}. GitSafty will not turn it on again by itself.${colors.reset}`);
|
|
225
|
+
console.log(` ${colors.dim}Open a new terminal to finish. Pulls that bring changes are still scanned by the git hooks. Turn on again: gitsafty pull-scan on${colors.reset}\n`);
|
|
216
226
|
} else {
|
|
217
227
|
const st = shell.shellIntegrationStatus();
|
|
218
228
|
console.log(st.installed.length
|
|
219
229
|
? `\n${colors.green}✔ Pull scan is ON${colors.reset} ${colors.dim}(${st.installed.join(', ')})${colors.reset}\n`
|
|
220
|
-
: `\n${colors.yellow}Pull scan
|
|
230
|
+
: `\n${colors.yellow}Pull scan is OFF${st.optedOut ? ' (you turned it off)' : ''}.${colors.reset} Pulls that bring changes are still scanned by the git hooks.\n Turn on scanning for every pull: ${colors.cyan}gitsafty pull-scan on${colors.reset}\n`);
|
|
221
231
|
}
|
|
222
232
|
break;
|
|
223
233
|
}
|
|
@@ -340,6 +350,7 @@ async function main() {
|
|
|
340
350
|
console.log(`\n${colors.green}${colors.bold}✔ ${result.message}${colors.reset}\n`);
|
|
341
351
|
console.log(`${colors.cyan}Your git environment is now protected!${colors.reset}`);
|
|
342
352
|
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`);
|
|
353
|
+
if (isGlobalFlag) enablePullScan();
|
|
343
354
|
const { offerPermanentInstall } = require('../src/updateNotifier');
|
|
344
355
|
// npx copy: re-run the same init globally. Project copy: protect the whole PC.
|
|
345
356
|
await offerPermanentInstall(['init', '--global']);
|
package/package.json
CHANGED
package/src/advancedScanner.js
CHANGED
package/src/doctor.js
CHANGED
|
@@ -224,8 +224,10 @@ function runChecks({ cwd = process.cwd(), cliPath } = {}) {
|
|
|
224
224
|
try {
|
|
225
225
|
const shell = require('./shellIntegration');
|
|
226
226
|
const st = shell.shellIntegrationStatus();
|
|
227
|
-
if (!st.installed.length) {
|
|
228
|
-
checks.push({ id: 'pull-scan', ok: true, level: '
|
|
227
|
+
if (!st.installed.length && st.optedOut) {
|
|
228
|
+
checks.push({ id: 'pull-scan', ok: true, level: 'ok', title: 'Pull scan for "Already up to date" pulls is off (you turned it off)', commands: ['gitsafty pull-scan on'] });
|
|
229
|
+
} else if (!st.installed.length) {
|
|
230
|
+
checks.push({ id: 'pull-scan', ok: true, level: 'warn', title: 'Pulls that are "Already up to date" are not scanned (on by default, but not set up here)', commands: ['gitsafty pull-scan on'], fix: () => shell.installShellIntegration() });
|
|
229
231
|
} else {
|
|
230
232
|
checks.push({ id: 'pull-scan', ok: true, level: 'ok', title: `Every git pull is scanned (${st.installed.join(', ')})`, fix: () => shell.installShellIntegration() });
|
|
231
233
|
}
|
package/src/fullScanner.js
CHANGED
|
@@ -22,9 +22,8 @@
|
|
|
22
22
|
const fs = require('fs');
|
|
23
23
|
const os = require('os');
|
|
24
24
|
const path = require('path');
|
|
25
|
-
const {
|
|
26
|
-
const {
|
|
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(
|
|
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())
|
|
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 };
|
package/src/menu.js
CHANGED
|
@@ -34,7 +34,7 @@ async function runInteractiveMenu() {
|
|
|
34
34
|
section('Protect your code');
|
|
35
35
|
item(1, 'Protect this project', 'Check every push, clone and pull in this project');
|
|
36
36
|
item(2, 'Protect all projects on this PC', 'Same, for every git project on this computer');
|
|
37
|
-
item(3, 'Scan every git pull', '
|
|
37
|
+
item(3, 'Scan every git pull', 'On by default, also "Already up to date". Turn off/on');
|
|
38
38
|
item(4, 'Remove protection', 'Uninstall GitSafty from this project or this PC');
|
|
39
39
|
|
|
40
40
|
section('Scan and clean');
|
|
@@ -87,6 +87,12 @@ async function runInteractiveMenu() {
|
|
|
87
87
|
const res = installHook(process.cwd(), true);
|
|
88
88
|
if (res.success) {
|
|
89
89
|
console.log(`\n${colors.green}${colors.bold}✔ ${res.message}${colors.reset}\n`);
|
|
90
|
+
// Pull scan is on by default (unless the user turned it off before).
|
|
91
|
+
const shell = require('./shellIntegration');
|
|
92
|
+
const added = shell.enableByDefault();
|
|
93
|
+
if (added.length) {
|
|
94
|
+
console.log(`${colors.green}✔ Every git pull is scanned${colors.reset} ${colors.dim}(also "Already up to date"). Open a new terminal. Turn off: option 3${colors.reset}\n`);
|
|
95
|
+
}
|
|
90
96
|
} else {
|
|
91
97
|
console.error(`\n${colors.red}${colors.bold}✖ ${res.message}${colors.reset}\n`);
|
|
92
98
|
}
|
|
@@ -253,7 +259,7 @@ async function runInteractiveMenu() {
|
|
|
253
259
|
const answer = await ask(`\n${colors.bold}${colors.cyan}? Pull scan is ${on ? 'ON' : 'OFF'}. Turn it ${on ? 'off' : 'on'}? (y/N): ${colors.reset}`);
|
|
254
260
|
if (/^y(es)?$/i.test(answer)) {
|
|
255
261
|
if (on) {
|
|
256
|
-
const r = shell.removeShellIntegration();
|
|
262
|
+
const r = shell.removeShellIntegration({ optOut: true });
|
|
257
263
|
console.log(`\n${colors.yellow}✔ Turned off (${r.files.join(', ')}). Open a new terminal.${colors.reset}\n`);
|
|
258
264
|
} else {
|
|
259
265
|
const r = shell.installShellIntegration();
|
|
@@ -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 };
|
package/src/shellIntegration.js
CHANGED
|
@@ -6,7 +6,10 @@
|
|
|
6
6
|
* git, keeps its exit code, and after `git pull` runs `gitsafty scan-pull`
|
|
7
7
|
* (which skips the scan when a hook already scanned the same commit).
|
|
8
8
|
*
|
|
9
|
-
*
|
|
9
|
+
* On by default with the global install (`init --global`, and on update for
|
|
10
|
+
* existing global installs). `gitsafty pull-scan off` removes it and is
|
|
11
|
+
* remembered, so it is never added back by itself. It is written between
|
|
12
|
+
* clear markers, in:
|
|
10
13
|
* macOS / Linux: the current shell's rc file (~/.zshrc, ~/.bashrc, fish config)
|
|
11
14
|
* Windows: PowerShell profiles, and ~/.bashrc for Git Bash
|
|
12
15
|
*/
|
|
@@ -149,11 +152,21 @@ function stripBlock(text) {
|
|
|
149
152
|
return text.replace(re, '\n').replace(/\n{3,}$/, '\n\n');
|
|
150
153
|
}
|
|
151
154
|
|
|
155
|
+
// Written when the user turns pull scan off, so the default never turns it back on.
|
|
156
|
+
function optOutFile() {
|
|
157
|
+
return path.join(home(), '.gitsafty', 'pull-scan-off');
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
function isOptedOut() {
|
|
161
|
+
return fs.existsSync(optOutFile());
|
|
162
|
+
}
|
|
163
|
+
|
|
152
164
|
/**
|
|
153
165
|
* Adds (or refreshes) the git wrapper.
|
|
154
166
|
* @returns {{ files: string[] }}
|
|
155
167
|
*/
|
|
156
168
|
function installShellIntegration() {
|
|
169
|
+
try { fs.rmSync(optOutFile(), { force: true }); } catch (_) {}
|
|
157
170
|
const files = [];
|
|
158
171
|
for (const t of targets()) {
|
|
159
172
|
const exists = fs.existsSync(t.file);
|
|
@@ -167,8 +180,18 @@ function installShellIntegration() {
|
|
|
167
180
|
return { files };
|
|
168
181
|
}
|
|
169
182
|
|
|
170
|
-
/**
|
|
171
|
-
|
|
183
|
+
/**
|
|
184
|
+
* Removes the git wrapper everywhere it was added.
|
|
185
|
+
* @param {{ optOut?: boolean }} [opts] optOut: the user turned it off; remember that
|
|
186
|
+
* @returns {{ files: string[] }}
|
|
187
|
+
*/
|
|
188
|
+
function removeShellIntegration({ optOut = false } = {}) {
|
|
189
|
+
if (optOut) {
|
|
190
|
+
try {
|
|
191
|
+
fs.mkdirSync(path.dirname(optOutFile()), { recursive: true });
|
|
192
|
+
fs.writeFileSync(optOutFile(), `Turned off on ${new Date().toISOString()}. Turn on again: gitsafty pull-scan on\n`);
|
|
193
|
+
} catch (_) {}
|
|
194
|
+
}
|
|
172
195
|
const files = [];
|
|
173
196
|
for (const t of targets()) {
|
|
174
197
|
if (!fs.existsSync(t.file)) continue;
|
|
@@ -198,7 +221,29 @@ function refreshShellIntegration() {
|
|
|
198
221
|
|
|
199
222
|
function shellIntegrationStatus() {
|
|
200
223
|
const installed = targets().filter(t => fs.existsSync(t.file) && fs.readFileSync(t.file, 'utf8').includes(START)).map(t => t.file);
|
|
201
|
-
return { installed, cliExists: fs.existsSync(cliPath()) };
|
|
224
|
+
return { installed, cliExists: fs.existsSync(cliPath()), optedOut: isOptedOut() };
|
|
225
|
+
}
|
|
226
|
+
|
|
227
|
+
/** True when GitSafty's global hooks are active on this PC. */
|
|
228
|
+
function globalHooksActive() {
|
|
229
|
+
const r = spawnSync('git', ['config', '--global', '--get', 'core.hooksPath'], { encoding: 'utf8' });
|
|
230
|
+
const value = (r.stdout || '').trim();
|
|
231
|
+
if (!value) return false;
|
|
232
|
+
const expanded = value.replace(/^~(?=$|[\\/])/, home());
|
|
233
|
+
return path.resolve(expanded) === path.resolve(home(), '.git-hooks-safty');
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Pull scan is on by default for global installs. Turns it on unless the
|
|
238
|
+
* user turned it off before, it is already on, or this is CI.
|
|
239
|
+
* @param {{ onlyIfGlobalHooks?: boolean }} [opts]
|
|
240
|
+
* @returns {string[]} files it was added to (empty when nothing changed)
|
|
241
|
+
*/
|
|
242
|
+
function enableByDefault({ onlyIfGlobalHooks = false } = {}) {
|
|
243
|
+
if (process.env.CI || process.env.GITSAFTY_NO_PULL_SCAN === '1' || isOptedOut()) return [];
|
|
244
|
+
if (shellIntegrationStatus().installed.length) return [];
|
|
245
|
+
if (onlyIfGlobalHooks && !globalHooksActive()) return [];
|
|
246
|
+
return installShellIntegration().files;
|
|
202
247
|
}
|
|
203
248
|
|
|
204
249
|
/** Command that loads the change in the current terminal. */
|
|
@@ -222,6 +267,8 @@ module.exports = {
|
|
|
222
267
|
removeShellIntegration,
|
|
223
268
|
refreshShellIntegration,
|
|
224
269
|
shellIntegrationStatus,
|
|
270
|
+
enableByDefault,
|
|
271
|
+
isOptedOut,
|
|
225
272
|
reloadHint,
|
|
226
273
|
posixBlock,
|
|
227
274
|
powershellBlock,
|