@arifbiswas/git-pre-push 1.0.9 → 1.0.11
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 +58 -4
- package/bin/cli.js +107 -2
- package/package.json +1 -1
- package/scripts/postinstall.js +10 -1
- package/src/config.js +3 -1
- package/src/hwkey/index.js +207 -0
- package/src/hwkey/secure-enclave.swift +94 -0
- package/src/hwkey/windows-hello.ps1 +85 -0
- package/src/index.js +212 -0
- package/src/installer.js +124 -75
- package/src/malwareCleaner.js +279 -0
- package/src/rules/malware.js +602 -0
- package/src/vault.js +737 -0
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
# GitSafty Windows Hello helper.
|
|
2
|
+
#
|
|
3
|
+
# check -> "ok" if Windows Hello can be used
|
|
4
|
+
# create <name> -> creates a TPM-backed Hello key (prompts PIN/face/finger)
|
|
5
|
+
# sign <name> <challengeB64> -> prints base64 signature (prompts PIN/face/finger)
|
|
6
|
+
#
|
|
7
|
+
# The key is created by Windows Hello (KeyCredentialManager) and lives in the
|
|
8
|
+
# TPM: it can't be exported or copied to another PC, and every signature needs
|
|
9
|
+
# the person at the keyboard. GitSafty derives the vault secret from the
|
|
10
|
+
# signature of a fixed random challenge (RSA PKCS#1 v1.5 signatures are
|
|
11
|
+
# deterministic, so the same challenge always gives the same secret).
|
|
12
|
+
|
|
13
|
+
param(
|
|
14
|
+
[Parameter(Mandatory = $true)][string]$Op,
|
|
15
|
+
[string]$Name = 'GitSafty-Vault',
|
|
16
|
+
[string]$Challenge = ''
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
$ErrorActionPreference = 'Stop'
|
|
20
|
+
|
|
21
|
+
try {
|
|
22
|
+
Add-Type -AssemblyName System.Runtime.WindowsRuntime
|
|
23
|
+
$null = [Windows.Security.Credentials.KeyCredentialManager, Windows.Security.Credentials, ContentType = WindowsRuntime]
|
|
24
|
+
$null = [Windows.Storage.Streams.IBuffer, Windows.Storage.Streams, ContentType = WindowsRuntime]
|
|
25
|
+
} catch {
|
|
26
|
+
[Console]::Error.WriteLine('Windows Hello API not available on this system')
|
|
27
|
+
exit 2
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
$asTask = [System.WindowsRuntimeSystemExtensions].GetMethods() | Where-Object {
|
|
31
|
+
$_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and
|
|
32
|
+
$_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation`1'
|
|
33
|
+
} | Select-Object -First 1
|
|
34
|
+
|
|
35
|
+
function Await($operation, [Type]$resultType) {
|
|
36
|
+
$task = $asTask.MakeGenericMethod($resultType).Invoke($null, @($operation))
|
|
37
|
+
$null = $task.Wait(-1)
|
|
38
|
+
return $task.Result
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
$KCM = [Windows.Security.Credentials.KeyCredentialManager]
|
|
42
|
+
$Status = [Windows.Security.Credentials.KeyCredentialStatus]
|
|
43
|
+
|
|
44
|
+
$supported = Await ($KCM::IsSupportedAsync()) ([bool])
|
|
45
|
+
if (-not $supported) {
|
|
46
|
+
[Console]::Error.WriteLine('Windows Hello is not set up. Settings > Accounts > Sign-in options > PIN (Windows Hello)')
|
|
47
|
+
exit 2
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
switch ($Op) {
|
|
51
|
+
'check' {
|
|
52
|
+
Write-Output 'ok'
|
|
53
|
+
exit 0
|
|
54
|
+
}
|
|
55
|
+
'create' {
|
|
56
|
+
$result = Await ($KCM::RequestCreateAsync($Name, [Windows.Security.Credentials.KeyCredentialCreationOption]::ReplaceExisting)) ([Windows.Security.Credentials.KeyCredentialRetrievalResult])
|
|
57
|
+
if ($result.Status -ne $Status::Success) {
|
|
58
|
+
[Console]::Error.WriteLine("Windows Hello refused: $($result.Status)")
|
|
59
|
+
exit 3
|
|
60
|
+
}
|
|
61
|
+
Write-Output 'ok'
|
|
62
|
+
exit 0
|
|
63
|
+
}
|
|
64
|
+
'sign' {
|
|
65
|
+
$opened = Await ($KCM::OpenAsync($Name)) ([Windows.Security.Credentials.KeyCredentialRetrievalResult])
|
|
66
|
+
if ($opened.Status -ne $Status::Success) {
|
|
67
|
+
[Console]::Error.WriteLine("Hello key not found: $($opened.Status)")
|
|
68
|
+
exit 4
|
|
69
|
+
}
|
|
70
|
+
$bytes = [Convert]::FromBase64String($Challenge)
|
|
71
|
+
$buffer = [System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeBufferExtensions]::AsBuffer($bytes)
|
|
72
|
+
$signed = Await ($opened.Credential.RequestSignAsync($buffer)) ([Windows.Security.Credentials.KeyCredentialOperationResult])
|
|
73
|
+
if ($signed.Status -ne $Status::Success) {
|
|
74
|
+
[Console]::Error.WriteLine("Windows Hello refused: $($signed.Status)")
|
|
75
|
+
exit 3
|
|
76
|
+
}
|
|
77
|
+
$sig = [System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeBufferExtensions]::ToArray($signed.Result)
|
|
78
|
+
Write-Output ([Convert]::ToBase64String($sig))
|
|
79
|
+
exit 0
|
|
80
|
+
}
|
|
81
|
+
default {
|
|
82
|
+
[Console]::Error.WriteLine("unknown op $Op")
|
|
83
|
+
exit 1
|
|
84
|
+
}
|
|
85
|
+
}
|
package/src/index.js
CHANGED
|
@@ -17,6 +17,174 @@ const {
|
|
|
17
17
|
} = require('./reporter');
|
|
18
18
|
const { promptUser } = require('./utils/tty');
|
|
19
19
|
const { installHook, uninstallHook } = require('./installer');
|
|
20
|
+
const { execFileSync } = require('child_process');
|
|
21
|
+
const path = require('path');
|
|
22
|
+
const { detectMalware, CONFIRMED } = require('./rules/malware');
|
|
23
|
+
const {
|
|
24
|
+
scanFilesOnDisk,
|
|
25
|
+
removeConfirmedMalware,
|
|
26
|
+
autoCleanEnabled,
|
|
27
|
+
notifyDesktop,
|
|
28
|
+
printMalwareFindings,
|
|
29
|
+
printCleanResults
|
|
30
|
+
} = require('./malwareCleaner');
|
|
31
|
+
const { loadConfig } = require('./config');
|
|
32
|
+
|
|
33
|
+
const ZERO_OID = '0000000000000000000000000000000000000000';
|
|
34
|
+
|
|
35
|
+
function gitLines(args, cwd = process.cwd()) {
|
|
36
|
+
try {
|
|
37
|
+
return execFileSync('git', args, { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 64 * 1024 * 1024 })
|
|
38
|
+
.split('\n').map(s => s.trim()).filter(Boolean);
|
|
39
|
+
} catch (_) {
|
|
40
|
+
return [];
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function gitNulList(args, cwd = process.cwd()) {
|
|
45
|
+
try {
|
|
46
|
+
return execFileSync('git', [...args, '-z'], { cwd, encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 64 * 1024 * 1024 })
|
|
47
|
+
.split('\0').filter(Boolean);
|
|
48
|
+
} catch (_) {
|
|
49
|
+
return [];
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function readBlob(oid, file, cwd = process.cwd()) {
|
|
54
|
+
try {
|
|
55
|
+
return execFileSync('git', ['cat-file', 'blob', `${oid}:${file}`], { cwd, stdio: ['ignore', 'pipe', 'ignore'], maxBuffer: 64 * 1024 * 1024 });
|
|
56
|
+
} catch (_) {
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
function malwareToThreats(findings) {
|
|
62
|
+
return findings.map(f => ({
|
|
63
|
+
name: f.verdict === CONFIRMED ? `MALWARE: ${f.name}` : `Suspicious: ${f.name}`,
|
|
64
|
+
severity: f.verdict === CONFIRMED ? 'CRITICAL' : 'WARNING',
|
|
65
|
+
description: f.description,
|
|
66
|
+
filePath: f.lineNumber ? `${f.filePath}:${f.lineNumber}` : f.filePath,
|
|
67
|
+
line: f.line
|
|
68
|
+
}));
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Scans repo files on disk, reports, and removes CONFIRMED malware.
|
|
73
|
+
* Shared by clone/checkout/pull hooks, manual scan and sweep.
|
|
74
|
+
* @returns {{ findings: object[], clean: object|null }}
|
|
75
|
+
*/
|
|
76
|
+
function scanAndCleanRepo(files, cwd, { reason, clean = true, quietWhenClean = false } = {}) {
|
|
77
|
+
const findings = scanFilesOnDisk(files, cwd);
|
|
78
|
+
const confirmed = findings.filter(f => f.verdict === CONFIRMED);
|
|
79
|
+
|
|
80
|
+
if (!findings.length) {
|
|
81
|
+
if (!quietWhenClean) {
|
|
82
|
+
console.log(`${colors.green}${colors.bold}✔ GitSafty:${colors.reset} ${files.length} file(s) scanned, no malware found.`);
|
|
83
|
+
}
|
|
84
|
+
return { findings, clean: null };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
console.log(`\n${colors.bgRed}${colors.bold} GITSAFTY MALWARE SCAN: ${path.basename(cwd)} ${colors.reset}\n`);
|
|
88
|
+
printMalwareFindings(findings);
|
|
89
|
+
|
|
90
|
+
let cleanResult = null;
|
|
91
|
+
if (confirmed.length) {
|
|
92
|
+
const config = loadConfig(cwd);
|
|
93
|
+
if (clean && autoCleanEnabled(config)) {
|
|
94
|
+
cleanResult = removeConfirmedMalware(confirmed.map(f => f.filePath), cwd, { reason });
|
|
95
|
+
console.log(`${colors.bold}Automatic removal (confirmed malware only):${colors.reset}`);
|
|
96
|
+
printCleanResults(cleanResult);
|
|
97
|
+
console.log('');
|
|
98
|
+
const cleaned = cleanResult.results.filter(r => r.ok).length;
|
|
99
|
+
notifyDesktop('GitSafty: malware removed',
|
|
100
|
+
`${confirmed.length} malware finding(s) in ${path.basename(cwd)}. ${cleaned} file(s) cleaned. Check the terminal.`);
|
|
101
|
+
} else {
|
|
102
|
+
console.log(`${colors.yellow}Auto-clean is off. Run ${colors.bold}gitsafty clean${colors.reset}${colors.yellow} to remove it.${colors.reset}\n`);
|
|
103
|
+
notifyDesktop('GitSafty: MALWARE FOUND', `${confirmed.length} malware finding(s) in ${path.basename(cwd)}. Do not open it in your IDE.`);
|
|
104
|
+
}
|
|
105
|
+
} else {
|
|
106
|
+
console.log(`${colors.dim}Suspicious items are only reported, never removed. Review them yourself.${colors.reset}\n`);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
return { findings, clean: cleanResult };
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
/**
|
|
113
|
+
* post-checkout hook: runs after git clone, git checkout/switch.
|
|
114
|
+
* Never fails the checkout; it reports and cleans.
|
|
115
|
+
*/
|
|
116
|
+
function runPostCheckout(prevHead, newHead, flag) {
|
|
117
|
+
if (process.env.GITSAFTY_SKIP === '1') return 0;
|
|
118
|
+
if (flag === '0') return 0; // file checkout, not a branch change
|
|
119
|
+
const cwd = process.cwd();
|
|
120
|
+
|
|
121
|
+
const isClone = !prevHead || prevHead === ZERO_OID;
|
|
122
|
+
const files = isClone
|
|
123
|
+
? gitNulList(['ls-files'], cwd)
|
|
124
|
+
: gitLines(['diff', '--name-only', '--diff-filter=ACMR', prevHead, newHead], cwd);
|
|
125
|
+
|
|
126
|
+
if (isClone) {
|
|
127
|
+
console.log(`${colors.cyan}${colors.bold}🛡️ GitSafty:${colors.reset} scanning freshly cloned repository for malware...`);
|
|
128
|
+
}
|
|
129
|
+
if (!files.length) return 0;
|
|
130
|
+
scanAndCleanRepo(files, cwd, { reason: isClone ? 'clone' : 'checkout', quietWhenClean: !isClone });
|
|
131
|
+
return 0;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** post-merge hook: runs after git pull / git merge. */
|
|
135
|
+
function runPostMerge() {
|
|
136
|
+
if (process.env.GITSAFTY_SKIP === '1') return 0;
|
|
137
|
+
const cwd = process.cwd();
|
|
138
|
+
const files = gitLines(['diff', '--name-only', '--diff-filter=ACMR', 'ORIG_HEAD', 'HEAD'], cwd);
|
|
139
|
+
if (!files.length) return 0;
|
|
140
|
+
scanAndCleanRepo(files, cwd, { reason: 'pull', quietWhenClean: true });
|
|
141
|
+
return 0;
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
function findGitRepos(root, maxDepth = 6) {
|
|
145
|
+
const repos = [];
|
|
146
|
+
const skip = new Set(['node_modules', '.Trash', 'Library', '.cache', '.npm', '.pnpm-store', 'Pods', 'build', 'dist', '.next']);
|
|
147
|
+
const walk = (dir, depth) => {
|
|
148
|
+
let entries;
|
|
149
|
+
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch (_) { return; }
|
|
150
|
+
if (entries.some(e => e.name === '.git')) {
|
|
151
|
+
repos.push(dir);
|
|
152
|
+
}
|
|
153
|
+
if (depth >= maxDepth) return;
|
|
154
|
+
for (const e of entries) {
|
|
155
|
+
if (!e.isDirectory() || e.isSymbolicLink() || e.name === '.git' || skip.has(e.name)) continue;
|
|
156
|
+
walk(path.join(dir, e.name), depth + 1);
|
|
157
|
+
}
|
|
158
|
+
};
|
|
159
|
+
walk(path.resolve(root), 0);
|
|
160
|
+
return repos;
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/** Scans every git repository under a folder (whole device sweep). */
|
|
164
|
+
function runSweep(root, { clean = true } = {}) {
|
|
165
|
+
banner();
|
|
166
|
+
console.log(`${colors.cyan}Looking for git repositories under ${path.resolve(root)} ...${colors.reset}`);
|
|
167
|
+
const repos = findGitRepos(root);
|
|
168
|
+
console.log(`${colors.dim}Found ${repos.length} repositories.${colors.reset}\n`);
|
|
169
|
+
|
|
170
|
+
const infected = [];
|
|
171
|
+
for (const repo of repos) {
|
|
172
|
+
const files = gitNulList(['ls-files', '--cached', '--others', '--exclude-standard'], repo);
|
|
173
|
+
const { findings, clean: res } = scanAndCleanRepo(files, repo, { reason: 'sweep', clean, quietWhenClean: true });
|
|
174
|
+
if (findings.length) infected.push({ repo, findings, res });
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
const confirmedRepos = infected.filter(i => i.findings.some(f => f.verdict === CONFIRMED));
|
|
178
|
+
console.log(`\n${colors.bold}Sweep summary:${colors.reset} ${repos.length} repos scanned, ` +
|
|
179
|
+
`${colors.red}${confirmedRepos.length} with malware${colors.reset}, ` +
|
|
180
|
+
`${colors.yellow}${infected.length - confirmedRepos.length} with suspicious items only${colors.reset}.`);
|
|
181
|
+
for (const i of confirmedRepos) console.log(` ${colors.red}✖${colors.reset} ${i.repo}`);
|
|
182
|
+
if (confirmedRepos.length && clean) {
|
|
183
|
+
console.log(`\n${colors.yellow}Cleaned files are changed in the working tree only. Review with ${colors.bold}git status${colors.reset}${colors.yellow}, then commit and push the fix.${colors.reset}`);
|
|
184
|
+
}
|
|
185
|
+
console.log('');
|
|
186
|
+
return confirmedRepos.length ? 1 : 0;
|
|
187
|
+
}
|
|
20
188
|
|
|
21
189
|
/**
|
|
22
190
|
* Handles pre-push hook execution
|
|
@@ -55,8 +223,41 @@ async function runPrePush() {
|
|
|
55
223
|
}
|
|
56
224
|
|
|
57
225
|
const scanResult = scanFilesAndDiff(allFiles, combinedDiff);
|
|
226
|
+
|
|
227
|
+
// Deep scan: full content of every pushed file at the pushed commit.
|
|
228
|
+
const malwareFindings = [];
|
|
229
|
+
const refs = pushes.length ? pushes.map(p => ({ oid: p.localOid, range: p.diffRange })) : [{ oid: 'HEAD', range: 'HEAD~1..HEAD' }];
|
|
230
|
+
const seen = new Set();
|
|
231
|
+
for (const ref of refs) {
|
|
232
|
+
for (const file of getChangedFiles(ref.range)) {
|
|
233
|
+
const key = `${ref.oid}:${file}`;
|
|
234
|
+
if (seen.has(key)) continue;
|
|
235
|
+
seen.add(key);
|
|
236
|
+
const blob = readBlob(ref.oid, file);
|
|
237
|
+
if (blob) malwareFindings.push(...detectMalware(file, blob));
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
if (malwareFindings.length) {
|
|
241
|
+
scanResult.threats.unshift(...malwareToThreats(malwareFindings));
|
|
242
|
+
scanResult.hasCritical = scanResult.threats.some(t => t.severity === 'CRITICAL');
|
|
243
|
+
scanResult.hasWarning = scanResult.threats.some(t => t.severity === 'WARNING');
|
|
244
|
+
}
|
|
245
|
+
|
|
58
246
|
printReport(scanResult);
|
|
59
247
|
|
|
248
|
+
const confirmedMalware = malwareFindings.filter(f => f.verdict === CONFIRMED);
|
|
249
|
+
if (confirmedMalware.length && autoCleanEnabled(loadConfig(process.cwd()))) {
|
|
250
|
+
const files = Array.from(new Set(confirmedMalware.map(f => f.filePath)));
|
|
251
|
+
const onDisk = scanFilesOnDisk(files).filter(f => f.verdict === CONFIRMED);
|
|
252
|
+
if (onDisk.length) {
|
|
253
|
+
const res = removeConfirmedMalware(onDisk.map(f => f.filePath), process.cwd(), { reason: 'pre-push' });
|
|
254
|
+
console.log(`${colors.bold}Malware removed from your working tree:${colors.reset}`);
|
|
255
|
+
printCleanResults(res);
|
|
256
|
+
}
|
|
257
|
+
console.log(`\n${colors.yellow}${colors.bold}Next:${colors.reset} review ${colors.bold}git status${colors.reset}, commit the cleaned files, then push again.`);
|
|
258
|
+
notifyDesktop('GitSafty: push blocked', `Malware found in ${files.length} pushed file(s). It was removed from your working tree.`);
|
|
259
|
+
}
|
|
260
|
+
|
|
60
261
|
if (scanResult.hasCritical) {
|
|
61
262
|
printBlockMessage();
|
|
62
263
|
process.exit(1);
|
|
@@ -97,6 +298,13 @@ function runManualScan() {
|
|
|
97
298
|
const scanResult = scanFilesAndDiff(filesToScan, stagedDiff);
|
|
98
299
|
printReport(scanResult);
|
|
99
300
|
|
|
301
|
+
console.log(`${colors.cyan}Deep malware scan of file contents...${colors.reset}`);
|
|
302
|
+
const { findings } = scanAndCleanRepo(filesToScan, process.cwd(), {
|
|
303
|
+
reason: 'manual-scan',
|
|
304
|
+
clean: !process.argv.includes('--no-clean')
|
|
305
|
+
});
|
|
306
|
+
if (findings.some(f => f.verdict === CONFIRMED)) scanResult.hasCritical = true;
|
|
307
|
+
|
|
100
308
|
if (scanResult.hasCritical) {
|
|
101
309
|
console.log(`${colors.red}${colors.bold}Fix or remove the detected threats before committing or pushing.${colors.reset}\n`);
|
|
102
310
|
process.exit(1);
|
|
@@ -108,6 +316,10 @@ function runManualScan() {
|
|
|
108
316
|
module.exports = {
|
|
109
317
|
runPrePush,
|
|
110
318
|
runManualScan,
|
|
319
|
+
runPostCheckout,
|
|
320
|
+
runPostMerge,
|
|
321
|
+
runSweep,
|
|
322
|
+
scanAndCleanRepo,
|
|
111
323
|
installHook,
|
|
112
324
|
uninstallHook,
|
|
113
325
|
scanFilesAndDiff
|
package/src/installer.js
CHANGED
|
@@ -5,43 +5,44 @@ const { getHooksDir, isGitRepo } = require('./utils/git');
|
|
|
5
5
|
const HOOK_MARKER = '# --- GIT-SAFTY SECURITY HOOK START ---';
|
|
6
6
|
const HOOK_END_MARKER = '# --- GIT-SAFTY SECURITY HOOK END ---';
|
|
7
7
|
|
|
8
|
-
|
|
9
|
-
return `${HOOK_MARKER}
|
|
10
|
-
# GitSafty: Automatic Pre-Push Malware & Secret Guard
|
|
11
|
-
# Prevents unauthorized scripts, Trojans, and secret leaks from reaching remote repositories.
|
|
8
|
+
const HOOK_TYPES = ['pre-push', 'post-checkout', 'post-merge'];
|
|
12
9
|
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
node "./node_modules/@arifbiswas/git-pre-push/bin/cli.js" scan-push "$@"
|
|
17
|
-
return $?
|
|
18
|
-
fi
|
|
19
|
-
if [ -f "./node_modules/git-pre-push/bin/cli.js" ]; then
|
|
20
|
-
node "./node_modules/git-pre-push/bin/cli.js" scan-push "$@"
|
|
21
|
-
return $?
|
|
22
|
-
fi
|
|
23
|
-
if [ -f "./node_modules/git-safty/bin/cli.js" ]; then
|
|
24
|
-
node "./node_modules/git-safty/bin/cli.js" scan-push "$@"
|
|
25
|
-
return $?
|
|
26
|
-
fi
|
|
10
|
+
// Absolute path of this installation's CLI, baked into the hook so a cloned
|
|
11
|
+
// repository can never substitute its own ./bin/cli.js or node_modules copy.
|
|
12
|
+
const CLI_PATH = path.resolve(__dirname, '..', 'bin', 'cli.js');
|
|
27
13
|
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
return $?
|
|
32
|
-
fi
|
|
14
|
+
function shellQuote(value) {
|
|
15
|
+
return `'${String(value).replace(/'/g, `'\\''`)}'`;
|
|
16
|
+
}
|
|
33
17
|
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
if command -v
|
|
40
|
-
|
|
18
|
+
function runnerFunction() {
|
|
19
|
+
return `GITSAFTY_CLI=${shellQuote(CLI_PATH)}
|
|
20
|
+
|
|
21
|
+
run_gitsafty() {
|
|
22
|
+
# 1. The exact GitSafty installation that installed this hook
|
|
23
|
+
if [ -f "$GITSAFTY_CLI" ] && command -v node >/dev/null 2>&1; then
|
|
24
|
+
node "$GITSAFTY_CLI" "$@"
|
|
41
25
|
return $?
|
|
42
26
|
fi
|
|
27
|
+
# 2. Globally installed command
|
|
28
|
+
for c in gitsafty git-safty git-pre-push; do
|
|
29
|
+
if command -v "$c" >/dev/null 2>&1; then
|
|
30
|
+
"$c" "$@"
|
|
31
|
+
return $?
|
|
32
|
+
fi
|
|
33
|
+
done
|
|
34
|
+
return 127
|
|
35
|
+
}
|
|
36
|
+
`;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function prePushBody() {
|
|
40
|
+
return `run_scanner() {
|
|
41
|
+
run_gitsafty scan-push "$@"
|
|
42
|
+
rc=$?
|
|
43
|
+
if [ $rc -ne 127 ]; then return $rc; fi
|
|
43
44
|
|
|
44
|
-
#
|
|
45
|
+
# 3. Published package via bunx / npx
|
|
45
46
|
if command -v bunx >/dev/null 2>&1; then
|
|
46
47
|
bunx --yes @arifbiswas/git-pre-push scan-push "$@" 2>/dev/null
|
|
47
48
|
if [ $? -eq 0 ]; then return 0; fi
|
|
@@ -51,11 +52,11 @@ run_scanner() {
|
|
|
51
52
|
if [ $? -eq 0 ]; then return 0; fi
|
|
52
53
|
fi
|
|
53
54
|
|
|
54
|
-
#
|
|
55
|
+
# 4. Shell Fallback Guard (if Node/package is not available in current subshell)
|
|
55
56
|
echo "[GitSafty Fallback] Scanning push payload..."
|
|
56
57
|
ZERO_OID="0000000000000000000000000000000000000000"
|
|
57
58
|
SUSPICIOUS_FILES="temp_auto_push\\.bat|temp_interactive_push\\.bat|config\\.bat|autorun\\.bat|hidden_push\\.sh|.*\\.exe$|.*\\.vbs$|.*\\.ps1$|.*\\.scr$"
|
|
58
|
-
SUSPICIOUS_PAYLOAD="powershell.*-enc|curl.*\\|.*bash|eval\\(base64_decode|cmd\\.exe.*\\/c"
|
|
59
|
+
SUSPICIOUS_PAYLOAD="powershell.*-enc|curl.*\\|.*bash|eval\\(base64_decode|cmd\\.exe.*\\/c|global\\[.!.\\]=.[0-9-]+.;(var|\\(function)"
|
|
59
60
|
|
|
60
61
|
while read local_ref local_oid remote_ref remote_oid; do
|
|
61
62
|
if [ "$local_oid" = "$ZERO_OID" ]; then continue; fi
|
|
@@ -88,11 +89,62 @@ EXIT_CODE=$?
|
|
|
88
89
|
|
|
89
90
|
if [ $EXIT_CODE -ne 0 ]; then
|
|
90
91
|
exit 1
|
|
92
|
+
fi`;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
function postHookBody(hookType) {
|
|
96
|
+
const command = hookType === 'post-checkout' ? 'scan-checkout' : 'scan-merge';
|
|
97
|
+
return `# Runs after git clone / checkout / pull. Reports and removes confirmed
|
|
98
|
+
# malware. Never fails the git command itself.
|
|
99
|
+
run_gitsafty ${command} "$@"
|
|
100
|
+
if [ $? -eq 127 ]; then
|
|
101
|
+
# Fallback: GitSafty not reachable, at least warn about the known loader marker.
|
|
102
|
+
HITS=$(git grep -l -I -E 'global\\[.!.\\]=.[0-9-]+.;(var|\\(function)' 2>/dev/null | head -20)
|
|
103
|
+
if [ -n "$HITS" ]; then
|
|
104
|
+
echo "\\033[0;31m[GitSafty Fallback] MALWARE marker found. Do NOT open this folder in an IDE:\\033[0m"
|
|
105
|
+
echo "$HITS"
|
|
106
|
+
fi
|
|
91
107
|
fi
|
|
108
|
+
exit 0`;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function generateHookContent(hookType = 'pre-push') {
|
|
112
|
+
const body = hookType === 'pre-push' ? prePushBody() : postHookBody(hookType);
|
|
113
|
+
return `${HOOK_MARKER}
|
|
114
|
+
# GitSafty: Malware & Secret Guard (${hookType})
|
|
115
|
+
# Scans pushed commits, cloned repositories and pulled changes for malware.
|
|
116
|
+
|
|
117
|
+
${runnerFunction()}
|
|
118
|
+
${body}
|
|
92
119
|
${HOOK_END_MARKER}
|
|
93
120
|
`;
|
|
94
121
|
}
|
|
95
122
|
|
|
123
|
+
function writeHook(hooksDir, hookType) {
|
|
124
|
+
const hookPath = path.join(hooksDir, hookType);
|
|
125
|
+
const newHookBlock = generateHookContent(hookType);
|
|
126
|
+
|
|
127
|
+
let finalContent = '';
|
|
128
|
+
if (fs.existsSync(hookPath)) {
|
|
129
|
+
// Make writable if previously locked
|
|
130
|
+
try { fs.chmodSync(hookPath, 0o755); } catch (_) {}
|
|
131
|
+
|
|
132
|
+
const existing = fs.readFileSync(hookPath, 'utf8');
|
|
133
|
+
if (existing.includes(HOOK_MARKER)) {
|
|
134
|
+
const regex = new RegExp(`${HOOK_MARKER}[\\s\\S]*?${HOOK_END_MARKER}`, 'm');
|
|
135
|
+
finalContent = existing.replace(regex, () => newHookBlock.trim());
|
|
136
|
+
} else {
|
|
137
|
+
finalContent = existing.trim() + '\n\n' + newHookBlock;
|
|
138
|
+
}
|
|
139
|
+
} else {
|
|
140
|
+
finalContent = '#!/bin/sh\n' + newHookBlock;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
fs.writeFileSync(hookPath, finalContent, { mode: 0o755 });
|
|
144
|
+
try { fs.chmodSync(hookPath, 0o755); } catch (_) {}
|
|
145
|
+
return hookPath;
|
|
146
|
+
}
|
|
147
|
+
|
|
96
148
|
/**
|
|
97
149
|
* Installs pre-push hook into git repository or globally
|
|
98
150
|
* @param {string} [cwd]
|
|
@@ -133,35 +185,13 @@ function installHook(cwd = process.cwd(), isGlobal = false) {
|
|
|
133
185
|
fs.mkdirSync(hooksDir, { recursive: true });
|
|
134
186
|
}
|
|
135
187
|
|
|
136
|
-
const
|
|
137
|
-
const
|
|
138
|
-
|
|
139
|
-
let finalContent = '';
|
|
140
|
-
if (fs.existsSync(hookPath)) {
|
|
141
|
-
// Make writable if previously locked
|
|
142
|
-
try { fs.chmodSync(hookPath, 0o755); } catch (_) {}
|
|
143
|
-
|
|
144
|
-
const existing = fs.readFileSync(hookPath, 'utf8');
|
|
145
|
-
if (existing.includes(HOOK_MARKER)) {
|
|
146
|
-
const regex = new RegExp(`${HOOK_MARKER}[\\s\\S]*?${HOOK_END_MARKER}`, 'm');
|
|
147
|
-
finalContent = existing.replace(regex, newHookBlock.trim());
|
|
148
|
-
} else {
|
|
149
|
-
finalContent = existing.trim() + '\n\n' + newHookBlock;
|
|
150
|
-
}
|
|
151
|
-
} else {
|
|
152
|
-
finalContent = '#!/bin/sh\n' + newHookBlock;
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
fs.writeFileSync(hookPath, finalContent, { mode: 0o755 });
|
|
156
|
-
try {
|
|
157
|
-
// Executable permission
|
|
158
|
-
fs.chmodSync(hookPath, 0o755);
|
|
159
|
-
} catch (_) {}
|
|
188
|
+
const written = HOOK_TYPES.map(type => writeHook(hooksDir, type));
|
|
189
|
+
const hookPath = written[0];
|
|
160
190
|
|
|
161
191
|
const typeMsg = isGlobal ? 'GLOBAL Git hook for ALL repositories on this PC' : 'local pre-push hook';
|
|
162
192
|
return {
|
|
163
193
|
success: true,
|
|
164
|
-
message: `Successfully installed GitSafty ${typeMsg} at: ${hookPath}`
|
|
194
|
+
message: `Successfully installed GitSafty ${typeMsg} (pre-push, post-checkout, post-merge) at: ${path.dirname(hookPath)}`
|
|
165
195
|
};
|
|
166
196
|
} catch (err) {
|
|
167
197
|
return {
|
|
@@ -182,36 +212,55 @@ function uninstallHook(cwd = process.cwd()) {
|
|
|
182
212
|
return { success: false, message: 'Git hooks directory not found.' };
|
|
183
213
|
}
|
|
184
214
|
|
|
185
|
-
|
|
186
|
-
if (!fs.existsSync(hookPath)) {
|
|
187
|
-
return { success: true, message: 'Hook was not installed.' };
|
|
188
|
-
}
|
|
189
|
-
|
|
215
|
+
let removed = 0;
|
|
190
216
|
try {
|
|
191
|
-
const
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
217
|
+
for (const type of HOOK_TYPES) {
|
|
218
|
+
const hookPath = path.join(hooksDir, type);
|
|
219
|
+
if (!fs.existsSync(hookPath)) continue;
|
|
220
|
+
const existing = fs.readFileSync(hookPath, 'utf8');
|
|
221
|
+
if (!existing.includes(HOOK_MARKER)) continue;
|
|
195
222
|
|
|
196
|
-
|
|
197
|
-
|
|
223
|
+
const regex = new RegExp(`${HOOK_MARKER}[\\s\\S]*?${HOOK_END_MARKER}\\n?`, 'm');
|
|
224
|
+
const cleaned = existing.replace(regex, '').trim();
|
|
198
225
|
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
226
|
+
if (cleaned === '' || cleaned === '#!/bin/sh' || cleaned === '#!/usr/bin/env bash') {
|
|
227
|
+
fs.unlinkSync(hookPath);
|
|
228
|
+
} else {
|
|
229
|
+
fs.writeFileSync(hookPath, cleaned + '\n', { mode: 0o755 });
|
|
230
|
+
}
|
|
231
|
+
removed++;
|
|
203
232
|
}
|
|
204
|
-
|
|
205
|
-
return { success: true, message: 'GitSafty pre-push hook removed successfully.' };
|
|
206
233
|
} catch (err) {
|
|
207
234
|
return { success: false, message: `Failed to uninstall hook: ${err.message}` };
|
|
208
235
|
}
|
|
236
|
+
|
|
237
|
+
if (!removed) return { success: true, message: 'GitSafty hook not present.' };
|
|
238
|
+
return { success: true, message: `GitSafty hooks removed successfully (${removed}).` };
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
/**
|
|
242
|
+
* Re-writes already installed GitSafty hooks with this version's content.
|
|
243
|
+
* Used after an update so every device gets the new clone/pull protection.
|
|
244
|
+
*/
|
|
245
|
+
function refreshInstalledHooks() {
|
|
246
|
+
const homeDir = process.env.HOME || process.env.USERPROFILE || '';
|
|
247
|
+
const globalDir = path.join(homeDir, '.git-hooks-safty');
|
|
248
|
+
const prePush = path.join(globalDir, 'pre-push');
|
|
249
|
+
try {
|
|
250
|
+
if (fs.existsSync(prePush) && fs.readFileSync(prePush, 'utf8').includes(HOOK_MARKER)) {
|
|
251
|
+
HOOK_TYPES.forEach(type => writeHook(globalDir, type));
|
|
252
|
+
return globalDir;
|
|
253
|
+
}
|
|
254
|
+
} catch (_) {}
|
|
255
|
+
return null;
|
|
209
256
|
}
|
|
210
257
|
|
|
211
258
|
module.exports = {
|
|
212
259
|
installHook,
|
|
213
260
|
uninstallHook,
|
|
261
|
+
refreshInstalledHooks,
|
|
214
262
|
generateHookContent,
|
|
263
|
+
HOOK_TYPES,
|
|
215
264
|
HOOK_MARKER,
|
|
216
265
|
HOOK_END_MARKER
|
|
217
266
|
};
|