@arifbiswas/git-pre-push 0.0.0-stage → 1.0.0

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/src/index.js ADDED
@@ -0,0 +1,114 @@
1
+ const fs = require('fs');
2
+ const {
3
+ isGitRepo,
4
+ parsePrePushInput,
5
+ getChangedFiles,
6
+ getDiffContent,
7
+ getStagedFiles,
8
+ getStagedDiff,
9
+ getAllRepoFiles
10
+ } = require('./utils/git');
11
+ const { scanFilesAndDiff } = require('./scanner');
12
+ const {
13
+ banner,
14
+ printReport,
15
+ printBlockMessage,
16
+ colors
17
+ } = require('./reporter');
18
+ const { promptUser } = require('./utils/tty');
19
+ const { installHook, uninstallHook } = require('./installer');
20
+
21
+ /**
22
+ * Handles pre-push hook execution
23
+ * Reads refs from stdin, scans diffs and blocks malicious pushes
24
+ */
25
+ async function runPrePush() {
26
+ banner();
27
+
28
+ // Read stdin passed by git pre-push hook (only if piped, not TTY)
29
+ let stdinData = '';
30
+ if (!process.stdin.isTTY) {
31
+ try {
32
+ stdinData = fs.readFileSync(0, 'utf8');
33
+ } catch (_) {
34
+ stdinData = '';
35
+ }
36
+ }
37
+
38
+ const pushes = parsePrePushInput(stdinData);
39
+
40
+ let allFiles = [];
41
+ let combinedDiff = '';
42
+
43
+ if (pushes.length === 0) {
44
+ // If hook triggered without stdin or for current HEAD commit
45
+ const headDiffRange = 'HEAD~1..HEAD';
46
+ allFiles = getChangedFiles(headDiffRange);
47
+ combinedDiff = getDiffContent(headDiffRange);
48
+ } else {
49
+ for (const push of pushes) {
50
+ const files = getChangedFiles(push.diffRange);
51
+ const diff = getDiffContent(push.diffRange);
52
+ allFiles.push(...files);
53
+ combinedDiff += '\n' + diff;
54
+ }
55
+ }
56
+
57
+ const scanResult = scanFilesAndDiff(allFiles, combinedDiff);
58
+ printReport(scanResult);
59
+
60
+ if (scanResult.hasCritical) {
61
+ printBlockMessage();
62
+ process.exit(1);
63
+ }
64
+
65
+ if (scanResult.hasWarning) {
66
+ const proceed = await promptUser(`${colors.yellow}${colors.bold}⚠️ Security warnings detected above. Proceed with git push? (y/N): ${colors.reset}`);
67
+ if (!proceed) {
68
+ console.log(`\n${colors.red}[ABORTED] Push canceled by user.${colors.reset}\n`);
69
+ process.exit(1);
70
+ }
71
+ }
72
+
73
+ process.exit(0);
74
+ }
75
+
76
+ /**
77
+ * Handles manual scan (npx git-safty scan)
78
+ */
79
+ function runManualScan() {
80
+ banner();
81
+
82
+ if (!isGitRepo()) {
83
+ console.error(`${colors.red}Error: Current directory is not a git repository.${colors.reset}`);
84
+ process.exit(1);
85
+ }
86
+
87
+ console.log(`${colors.cyan}Inspecting repository working directory & staged changes...${colors.reset}`);
88
+
89
+ // Staged files & diff
90
+ const stagedFiles = getStagedFiles();
91
+ const stagedDiff = getStagedDiff();
92
+
93
+ // All tracked & untracked repository files
94
+ const allRepoFiles = getAllRepoFiles();
95
+ const filesToScan = Array.from(new Set([...stagedFiles, ...allRepoFiles]));
96
+
97
+ const scanResult = scanFilesAndDiff(filesToScan, stagedDiff);
98
+ printReport(scanResult);
99
+
100
+ if (scanResult.hasCritical) {
101
+ console.log(`${colors.red}${colors.bold}Fix or remove the detected threats before committing or pushing.${colors.reset}\n`);
102
+ process.exit(1);
103
+ }
104
+
105
+ process.exit(0);
106
+ }
107
+
108
+ module.exports = {
109
+ runPrePush,
110
+ runManualScan,
111
+ installHook,
112
+ uninstallHook,
113
+ scanFilesAndDiff
114
+ };
@@ -0,0 +1,202 @@
1
+ const fs = require('fs');
2
+ const path = require('path');
3
+ const { getHooksDir, isGitRepo } = require('./utils/git');
4
+
5
+ const HOOK_MARKER = '# --- GIT-SAFTY SECURITY HOOK START ---';
6
+ const HOOK_END_MARKER = '# --- GIT-SAFTY SECURITY HOOK END ---';
7
+
8
+ function generateHookContent() {
9
+ return `${HOOK_MARKER}
10
+ # GitSafty: Automatic Pre-Push Malware & Secret Guard
11
+ # Prevents unauthorized scripts, Trojans, and secret leaks from reaching remote repositories.
12
+
13
+ run_scanner() {
14
+ # 1. Try local node_modules
15
+ if [ -f "./node_modules/git-safty/bin/cli.js" ]; then
16
+ node "./node_modules/git-safty/bin/cli.js" scan-push "$@"
17
+ return $?
18
+ fi
19
+
20
+ # 2. Try repository local bin
21
+ if [ -f "./bin/cli.js" ]; then
22
+ node "./bin/cli.js" scan-push "$@"
23
+ return $?
24
+ fi
25
+
26
+ # 3. Try npx
27
+ if command -v npx >/dev/null 2>&1; then
28
+ npx --no-install git-safty scan-push "$@"
29
+ return $?
30
+ fi
31
+
32
+ # 4. Try global command
33
+ if command -v git-safty >/dev/null 2>&1; then
34
+ git-safty scan-push "$@"
35
+ return $?
36
+ fi
37
+
38
+ # 5. Shell Fallback Guard (if Node is not available in current subshell)
39
+ echo "[GitSafty Fallback] Scanning push payload..."
40
+ ZERO_OID="0000000000000000000000000000000000000000"
41
+ SUSPICIOUS_FILES="temp_auto_push\\.bat|temp_interactive_push\\.bat|config\\.bat|autorun\\.bat|hidden_push\\.sh|.*\\.exe$|.*\\.vbs$|.*\\.ps1$|.*\\.scr$"
42
+ SUSPICIOUS_PAYLOAD="powershell.*-enc|curl.*\\|.*bash|eval\\(base64_decode|cmd\\.exe.*\\/c"
43
+
44
+ while read local_ref local_oid remote_ref remote_oid; do
45
+ if [ "$local_oid" = "$ZERO_OID" ]; then continue; fi
46
+ if [ "$remote_oid" = "$ZERO_OID" ]; then
47
+ DIFF_COMMITS="$local_oid"
48
+ else
49
+ DIFF_COMMITS="$remote_oid..$local_oid"
50
+ fi
51
+
52
+ CHANGED_FILES=$(git log "$DIFF_COMMITS" --name-only --oneline | grep -v '^[a-f0-9]' | sort -u)
53
+ MATCHED=$(echo "$CHANGED_FILES" | grep -Ei "$SUSPICIOUS_FILES")
54
+ if [ -n "$MATCHED" ]; then
55
+ echo "\\033[0;31m[BLOCKED] GitSafty blocked push due to malicious file pattern:\\033[0m"
56
+ echo "$MATCHED"
57
+ return 1
58
+ fi
59
+
60
+ DIFF_CONTENT=$(git diff "$DIFF_COMMITS")
61
+ if echo "$DIFF_CONTENT" | grep -Eiq "$SUSPICIOUS_PAYLOAD"; then
62
+ echo "\\033[0;31m[BLOCKED] GitSafty detected suspicious execution signature in commit diff!\\033[0m"
63
+ return 1
64
+ fi
65
+ done
66
+
67
+ return 0
68
+ }
69
+
70
+ run_scanner "$@"
71
+ EXIT_CODE=$?
72
+
73
+ if [ $EXIT_CODE -ne 0 ]; then
74
+ exit 1
75
+ fi
76
+ ${HOOK_END_MARKER}
77
+ `;
78
+ }
79
+
80
+ /**
81
+ * Installs pre-push hook into git repository or globally
82
+ * @param {string} [cwd]
83
+ * @param {boolean} [isGlobal=false]
84
+ * @returns {{ success: boolean, message: string }}
85
+ */
86
+ function installHook(cwd = process.cwd(), isGlobal = false) {
87
+ let hooksDir;
88
+
89
+ if (isGlobal) {
90
+ const homeDir = process.env.HOME || process.env.USERPROFILE || '';
91
+ hooksDir = path.join(homeDir, '.git-hooks-safty');
92
+ if (!fs.existsSync(hooksDir)) {
93
+ fs.mkdirSync(hooksDir, { recursive: true });
94
+ }
95
+ // Set global core.hooksPath
96
+ const { runGit } = require('./utils/git');
97
+ runGit(`config --global core.hooksPath "${hooksDir}"`);
98
+ } else {
99
+ if (!isGitRepo(cwd)) {
100
+ return {
101
+ success: false,
102
+ message: 'Not a git repository. Run "git init" first or use --global.'
103
+ };
104
+ }
105
+ hooksDir = getHooksDir(cwd);
106
+ }
107
+
108
+ if (!hooksDir) {
109
+ return {
110
+ success: false,
111
+ message: 'Could not resolve git hooks directory.'
112
+ };
113
+ }
114
+
115
+ try {
116
+ if (!fs.existsSync(hooksDir)) {
117
+ fs.mkdirSync(hooksDir, { recursive: true });
118
+ }
119
+
120
+ const hookPath = path.join(hooksDir, 'pre-push');
121
+ const newHookBlock = generateHookContent();
122
+
123
+ let finalContent = '';
124
+ if (fs.existsSync(hookPath)) {
125
+ // Make writable if previously locked
126
+ try { fs.chmodSync(hookPath, 0o755); } catch (_) {}
127
+
128
+ const existing = fs.readFileSync(hookPath, 'utf8');
129
+ if (existing.includes(HOOK_MARKER)) {
130
+ const regex = new RegExp(`${HOOK_MARKER}[\\s\\S]*?${HOOK_END_MARKER}`, 'm');
131
+ finalContent = existing.replace(regex, newHookBlock.trim());
132
+ } else {
133
+ finalContent = existing.trim() + '\n\n' + newHookBlock;
134
+ }
135
+ } else {
136
+ finalContent = '#!/bin/sh\n' + newHookBlock;
137
+ }
138
+
139
+ fs.writeFileSync(hookPath, finalContent, { mode: 0o755 });
140
+ try {
141
+ // Executable permission
142
+ fs.chmodSync(hookPath, 0o755);
143
+ } catch (_) {}
144
+
145
+ const typeMsg = isGlobal ? 'GLOBAL Git hook for ALL repositories on this PC' : 'local pre-push hook';
146
+ return {
147
+ success: true,
148
+ message: `Successfully installed GitSafty ${typeMsg} at: ${hookPath}`
149
+ };
150
+ } catch (err) {
151
+ return {
152
+ success: false,
153
+ message: `Failed to install hook: ${err.message}`
154
+ };
155
+ }
156
+ }
157
+
158
+ /**
159
+ * Removes GitSafty hook
160
+ * @param {string} [cwd]
161
+ * @returns {{ success: boolean, message: string }}
162
+ */
163
+ function uninstallHook(cwd = process.cwd()) {
164
+ const hooksDir = getHooksDir(cwd);
165
+ if (!hooksDir) {
166
+ return { success: false, message: 'Git hooks directory not found.' };
167
+ }
168
+
169
+ const hookPath = path.join(hooksDir, 'pre-push');
170
+ if (!fs.existsSync(hookPath)) {
171
+ return { success: true, message: 'Hook was not installed.' };
172
+ }
173
+
174
+ try {
175
+ const existing = fs.readFileSync(hookPath, 'utf8');
176
+ if (!existing.includes(HOOK_MARKER)) {
177
+ return { success: true, message: 'GitSafty hook not present in pre-push file.' };
178
+ }
179
+
180
+ const regex = new RegExp(`${HOOK_MARKER}[\\s\\S]*?${HOOK_END_MARKER}\\n?`, 'm');
181
+ const cleaned = existing.replace(regex, '').trim();
182
+
183
+ if (cleaned === '' || cleaned === '#!/bin/sh' || cleaned === '#!/usr/bin/env bash') {
184
+ fs.unlinkSync(hookPath);
185
+ } else {
186
+ fs.writeFileSync(hookPath, cleaned + '\n', { mode: 0o755 });
187
+ }
188
+
189
+ return { success: true, message: 'GitSafty pre-push hook removed successfully.' };
190
+ } catch (err) {
191
+ return { success: false, message: `Failed to uninstall hook: ${err.message}` };
192
+ }
193
+ }
194
+
195
+ module.exports = {
196
+ installHook,
197
+ uninstallHook,
198
+ generateHookContent,
199
+ HOOK_MARKER,
200
+ HOOK_END_MARKER
201
+ };
202
+
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Terminal UI and report formatter (Zero-dependency ANSI colors)
3
+ */
4
+
5
+ const colors = {
6
+ reset: '\x1b[0m',
7
+ bold: '\x1b[1m',
8
+ dim: '\x1b[2m',
9
+ red: '\x1b[31m',
10
+ green: '\x1b[32m',
11
+ yellow: '\x1b[33m',
12
+ blue: '\x1b[34m',
13
+ magenta: '\x1b[35m',
14
+ cyan: '\x1b[36m',
15
+ white: '\x1b[37m',
16
+ bgRed: '\x1b[41m',
17
+ bgGreen: '\x1b[42m',
18
+ bgYellow: '\x1b[43m'
19
+ };
20
+
21
+ const symbols = {
22
+ pass: '✔',
23
+ fail: '✖',
24
+ warn: '⚠',
25
+ info: 'ℹ',
26
+ shield: '🛡️ '
27
+ };
28
+
29
+ function banner() {
30
+ console.log(`\n${colors.cyan}${colors.bold}================================================================${colors.reset}`);
31
+ console.log(`${colors.cyan}${colors.bold} ${symbols.shield} GitSafty: Pre-Push Malware & Secret Guard ${colors.reset}`);
32
+ console.log(`${colors.cyan}${colors.bold}================================================================${colors.reset}`);
33
+ }
34
+
35
+ /**
36
+ * Prints scan summary
37
+ * @param {{ totalFiles: number, threats: Array<any>, durationMs: number }} result
38
+ */
39
+ function printReport(result) {
40
+ const { totalFiles, threats, durationMs } = result;
41
+
42
+ console.log(`\n${colors.dim}Scanned ${totalFiles} file(s) in ${durationMs}ms${colors.reset}`);
43
+
44
+ if (threats.length === 0) {
45
+ console.log(`\n${colors.bgGreen}${colors.bold} PASSED ${colors.reset} ${colors.green}${colors.bold}No malware, suspicious files, or leaked secrets found.${colors.reset}\n`);
46
+ return;
47
+ }
48
+
49
+ const criticalThreats = threats.filter(t => t.severity === 'CRITICAL');
50
+ const warnings = threats.filter(t => t.severity === 'WARNING');
51
+
52
+ console.log(`\n${colors.bgRed}${colors.bold} SECURITY THREATS DETECTED ${colors.reset}\n`);
53
+
54
+ for (const threat of threats) {
55
+ const isCrit = threat.severity === 'CRITICAL';
56
+ const tag = isCrit
57
+ ? `${colors.bgRed}${colors.white}${colors.bold} CRITICAL ${colors.reset}`
58
+ : `${colors.bgYellow}${colors.white}${colors.bold} WARNING ${colors.reset}`;
59
+
60
+ console.log(`${tag} ${colors.bold}${threat.name || threat.rule}${colors.reset}`);
61
+ if (threat.filePath) {
62
+ console.log(` ${colors.dim}File:${colors.reset} ${colors.yellow}${threat.filePath}${colors.reset}`);
63
+ }
64
+ if (threat.description) {
65
+ console.log(` ${colors.dim}Reason:${colors.reset} ${threat.description}`);
66
+ }
67
+ if (threat.line) {
68
+ console.log(` ${colors.dim}Code:${colors.reset} ${colors.red}${threat.line}${colors.reset}`);
69
+ }
70
+ console.log('');
71
+ }
72
+
73
+ console.log(`${colors.bold}Summary:${colors.reset} ${colors.red}${criticalThreats.length} Critical${colors.reset}, ${colors.yellow}${warnings.length} Warnings${colors.reset}`);
74
+ }
75
+
76
+ function printBlockMessage() {
77
+ console.log(`\n${colors.bgRed}${colors.bold} PUSH BLOCKED BY GITSAFTY ${colors.reset}`);
78
+ console.log(`${colors.red}Malware signatures or critical secrets were found in your outgoing commits.${colors.reset}`);
79
+ console.log(`${colors.red}These files or changes will NOT be allowed to reach GitHub.${colors.reset}`);
80
+ console.log(`${colors.dim}Please remove the malicious scripts/keys and unstage/recommit before pushing.${colors.reset}\n`);
81
+ }
82
+
83
+ module.exports = {
84
+ colors,
85
+ symbols,
86
+ banner,
87
+ printReport,
88
+ printBlockMessage
89
+ };
90
+
@@ -0,0 +1,85 @@
1
+ /**
2
+ * Filename and extension blacklist rules
3
+ */
4
+
5
+ const SUSPICIOUS_EXACT_NAMES = [
6
+ 'temp_auto_push.bat',
7
+ 'temp_interactive_push.bat',
8
+ 'config.bat',
9
+ 'autorun.bat',
10
+ 'hidden_push.sh',
11
+ 'auto_push.bat',
12
+ 'git_push.bat',
13
+ 'run_hidden.vbs',
14
+ 'payload.ps1',
15
+ 'injector.bat'
16
+ ];
17
+
18
+ const BLOCKED_EXTENSIONS = [
19
+ /\.(exe|scr|pif|cpl|hta|vbs|wsf)$/i,
20
+ /\.(msi|dll|bin|iso|dmg)$/i,
21
+ /\.(bat|cmd|ps1)$/i
22
+ ];
23
+
24
+ const SUSPICIOUS_PATH_PATTERNS = [
25
+ // Double extension deception like document.pdf.exe
26
+ /\.[a-z0-9]+\.(exe|bat|cmd|vbs|ps1|scr)$/i,
27
+ // Executables or scripts hidden inside dot directories or node_modules directly staged
28
+ /\/\.(cache|tmp|temp)\/.*(\.bat|\.ps1|\.sh|\.exe)$/i,
29
+ // Tampering with .git inside staged files
30
+ /^\.git\/hooks\//i
31
+ ];
32
+
33
+ /**
34
+ * Checks a file path against filename rules
35
+ * @param {string} filePath
36
+ * @returns {{ matched: boolean, rule: string, severity: 'CRITICAL' | 'WARNING' } | null}
37
+ */
38
+ function checkFilename(filePath) {
39
+ const normalized = filePath.replace(/\\/g, '/');
40
+ const basename = normalized.split('/').pop() || '';
41
+
42
+ // 1. Exact match check
43
+ for (const suspiciousName of SUSPICIOUS_EXACT_NAMES) {
44
+ if (basename.toLowerCase() === suspiciousName.toLowerCase()) {
45
+ return {
46
+ matched: true,
47
+ rule: `Known malicious or unauthorized script filename: "${basename}"`,
48
+ severity: 'CRITICAL'
49
+ };
50
+ }
51
+ }
52
+
53
+ // 2. Dangerous executable extension check
54
+ for (const regex of BLOCKED_EXTENSIONS) {
55
+ if (regex.test(basename)) {
56
+ // Allow scripts only if in specific recognized script folders if user whitelist, otherwise warn/block
57
+ const isCritical = /\.(exe|scr|pif|cpl|hta|vbs|msi|dll|bin)$/i.test(basename);
58
+ return {
59
+ matched: true,
60
+ rule: `Executable or script extension detected: "${basename}"`,
61
+ severity: isCritical ? 'CRITICAL' : 'WARNING'
62
+ };
63
+ }
64
+ }
65
+
66
+ // 3. Pattern / double extension check
67
+ for (const regex of SUSPICIOUS_PATH_PATTERNS) {
68
+ if (regex.test(normalized)) {
69
+ return {
70
+ matched: true,
71
+ rule: `Suspicious or disguised path pattern: "${normalized}"`,
72
+ severity: 'CRITICAL'
73
+ };
74
+ }
75
+ }
76
+
77
+ return null;
78
+ }
79
+
80
+ module.exports = {
81
+ checkFilename,
82
+ SUSPICIOUS_EXACT_NAMES,
83
+ BLOCKED_EXTENSIONS
84
+ };
85
+
@@ -0,0 +1,81 @@
1
+ /**
2
+ * IDE Configuration inspection (.vscode/tasks.json, .vscode/settings.json, .idea/workspace.xml)
3
+ */
4
+
5
+ /**
6
+ * Inspects IDE config files for malware injection hooks
7
+ * @param {string} filePath
8
+ * @param {string} content
9
+ * @returns {Array<{ name: string, severity: 'CRITICAL' | 'WARNING', description: string, line: string }>}
10
+ */
11
+ function inspectIdeConfig(filePath, content) {
12
+ const findings = [];
13
+ if (!content) return findings;
14
+
15
+ const normalized = filePath.replace(/\\/g, '/');
16
+
17
+ // 1. VS Code tasks.json check
18
+ if (normalized.endsWith('.vscode/tasks.json')) {
19
+ // Check for auto-run tasks triggered on folder open
20
+ if (/folderOpen/i.test(content)) {
21
+ findings.push({
22
+ name: 'Auto-Run Task on Folder Open (.vscode/tasks.json)',
23
+ severity: 'CRITICAL',
24
+ description: 'Auto-executing task triggered immediately upon opening the project in VS Code.',
25
+ line: 'runOptions: { runOn: "folderOpen" }'
26
+ });
27
+ }
28
+
29
+ // Check for suspicious shell commands in tasks
30
+ if (/(\.bat|\.ps1|\.vbs|curl|powershell|cmd\.exe|wget|certutil)/i.test(content)) {
31
+ findings.push({
32
+ name: 'Suspicious Command in VS Code Task',
33
+ severity: 'CRITICAL',
34
+ description: 'Shell task executes suspicious external script or utility.',
35
+ line: filePath
36
+ });
37
+ }
38
+ }
39
+
40
+ // 2. VS Code settings.json check
41
+ if (normalized.endsWith('.vscode/settings.json')) {
42
+ // Malicious terminal overrides
43
+ if (/terminal\.integrated\.env\./i.test(content) || /terminal\.integrated\.profiles\./i.test(content)) {
44
+ findings.push({
45
+ name: 'VS Code Terminal Environment Override',
46
+ severity: 'WARNING',
47
+ description: 'Project settings override developer terminal environment or profiles.',
48
+ line: filePath
49
+ });
50
+ }
51
+
52
+ // Executable path overrides like git.path or node path hijacking
53
+ if (/(git\.path|terminal\.integrated\.shell\.|terminal\.integrated\.automationProfile)/i.test(content)) {
54
+ findings.push({
55
+ name: 'VS Code Shell/Binary Path Redirection',
56
+ severity: 'CRITICAL',
57
+ description: 'Project overrides local binary execution path (potential binary hijack).',
58
+ line: filePath
59
+ });
60
+ }
61
+ }
62
+
63
+ // 3. JetBrains .idea/workspace.xml or tasks
64
+ if (normalized.includes('.idea/') && (normalized.endsWith('workspace.xml') || normalized.endsWith('tasks.xml'))) {
65
+ if (/(powershell|cmd\.exe|bash\s+-c|curl|certutil|\.bat|\.ps1)/i.test(content)) {
66
+ findings.push({
67
+ name: 'Suspicious External Tool in JetBrains Config',
68
+ severity: 'WARNING',
69
+ description: 'JetBrains IDE configuration includes external shell command or script trigger.',
70
+ line: filePath
71
+ });
72
+ }
73
+ }
74
+
75
+ return findings;
76
+ }
77
+
78
+ module.exports = {
79
+ inspectIdeConfig
80
+ };
81
+
@@ -0,0 +1,12 @@
1
+ const { checkFilename } = require('./filenames');
2
+ const { scanPayloads } = require('./payloads');
3
+ const { scanSecrets } = require('./secrets');
4
+ const { inspectIdeConfig } = require('./ideConfig');
5
+
6
+ module.exports = {
7
+ checkFilename,
8
+ scanPayloads,
9
+ scanSecrets,
10
+ inspectIdeConfig
11
+ };
12
+