@arifbiswas/git-pre-push 1.0.10 → 1.0.12

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.
@@ -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,45 @@ 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
- 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.
8
+ const HOOK_TYPES = ['pre-push', 'post-checkout', 'post-merge'];
12
9
 
13
- run_scanner() {
14
- # 1. Try local node_modules
15
- if [ -f "./node_modules/@arifbiswas/git-pre-push/bin/cli.js" ]; then
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
+ // Forward slashes so Git for Windows' sh can test and run the path too.
13
+ const CLI_PATH = path.resolve(__dirname, '..', 'bin', 'cli.js').replace(/\\/g, '/');
27
14
 
28
- # 2. Try repository local bin
29
- if [ -f "./bin/cli.js" ]; then
30
- node "./bin/cli.js" scan-push "$@"
31
- return $?
32
- fi
15
+ function shellQuote(value) {
16
+ return `'${String(value).replace(/'/g, `'\\''`)}'`;
17
+ }
33
18
 
34
- # 3. Try global commands if in PATH
35
- if command -v git-pre-push >/dev/null 2>&1; then
36
- git-pre-push scan-push "$@"
37
- return $?
38
- fi
39
- if command -v git-safty >/dev/null 2>&1; then
40
- git-safty scan-push "$@"
19
+ function runnerFunction() {
20
+ return `GITSAFTY_CLI=${shellQuote(CLI_PATH)}
21
+
22
+ run_gitsafty() {
23
+ # 1. The exact GitSafty installation that installed this hook
24
+ if [ -f "$GITSAFTY_CLI" ] && command -v node >/dev/null 2>&1; then
25
+ node "$GITSAFTY_CLI" "$@"
41
26
  return $?
42
27
  fi
28
+ # 2. Globally installed command
29
+ for c in gitsafty git-safty git-pre-push; do
30
+ if command -v "$c" >/dev/null 2>&1; then
31
+ "$c" "$@"
32
+ return $?
33
+ fi
34
+ done
35
+ return 127
36
+ }
37
+ `;
38
+ }
39
+
40
+ function prePushBody() {
41
+ return `run_scanner() {
42
+ run_gitsafty scan-push "$@"
43
+ rc=$?
44
+ if [ $rc -ne 127 ]; then return $rc; fi
43
45
 
44
- # 4. Try bunx or npx with published package @arifbiswas/git-pre-push
46
+ # 3. Published package via bunx / npx
45
47
  if command -v bunx >/dev/null 2>&1; then
46
48
  bunx --yes @arifbiswas/git-pre-push scan-push "$@" 2>/dev/null
47
49
  if [ $? -eq 0 ]; then return 0; fi
@@ -51,11 +53,11 @@ run_scanner() {
51
53
  if [ $? -eq 0 ]; then return 0; fi
52
54
  fi
53
55
 
54
- # 5. Shell Fallback Guard (if Node/package is not available in current subshell)
56
+ # 4. Shell Fallback Guard (if Node/package is not available in current subshell)
55
57
  echo "[GitSafty Fallback] Scanning push payload..."
56
58
  ZERO_OID="0000000000000000000000000000000000000000"
57
59
  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"
60
+ SUSPICIOUS_PAYLOAD="powershell.*-enc|curl.*\\|.*bash|eval\\(base64_decode|cmd\\.exe.*\\/c|global\\[.!.\\]=.[0-9-]+.;(var|\\(function)"
59
61
 
60
62
  while read local_ref local_oid remote_ref remote_oid; do
61
63
  if [ "$local_oid" = "$ZERO_OID" ]; then continue; fi
@@ -88,11 +90,62 @@ EXIT_CODE=$?
88
90
 
89
91
  if [ $EXIT_CODE -ne 0 ]; then
90
92
  exit 1
93
+ fi`;
94
+ }
95
+
96
+ function postHookBody(hookType) {
97
+ const command = hookType === 'post-checkout' ? 'scan-checkout' : 'scan-merge';
98
+ return `# Runs after git clone / checkout / pull. Reports and removes confirmed
99
+ # malware. Never fails the git command itself.
100
+ run_gitsafty ${command} "$@"
101
+ if [ $? -eq 127 ]; then
102
+ # Fallback: GitSafty not reachable, at least warn about the known loader marker.
103
+ HITS=$(git grep -l -I -E 'global\\[.!.\\]=.[0-9-]+.;(var|\\(function)' 2>/dev/null | head -20)
104
+ if [ -n "$HITS" ]; then
105
+ echo "\\033[0;31m[GitSafty Fallback] MALWARE marker found. Do NOT open this folder in an IDE:\\033[0m"
106
+ echo "$HITS"
107
+ fi
91
108
  fi
109
+ exit 0`;
110
+ }
111
+
112
+ function generateHookContent(hookType = 'pre-push') {
113
+ const body = hookType === 'pre-push' ? prePushBody() : postHookBody(hookType);
114
+ return `${HOOK_MARKER}
115
+ # GitSafty: Malware & Secret Guard (${hookType})
116
+ # Scans pushed commits, cloned repositories and pulled changes for malware.
117
+
118
+ ${runnerFunction()}
119
+ ${body}
92
120
  ${HOOK_END_MARKER}
93
121
  `;
94
122
  }
95
123
 
124
+ function writeHook(hooksDir, hookType) {
125
+ const hookPath = path.join(hooksDir, hookType);
126
+ const newHookBlock = generateHookContent(hookType);
127
+
128
+ let finalContent = '';
129
+ if (fs.existsSync(hookPath)) {
130
+ // Make writable if previously locked
131
+ try { fs.chmodSync(hookPath, 0o755); } catch (_) {}
132
+
133
+ const existing = fs.readFileSync(hookPath, 'utf8');
134
+ if (existing.includes(HOOK_MARKER)) {
135
+ const regex = new RegExp(`${HOOK_MARKER}[\\s\\S]*?${HOOK_END_MARKER}`, 'm');
136
+ finalContent = existing.replace(regex, () => newHookBlock.trim());
137
+ } else {
138
+ finalContent = existing.trim() + '\n\n' + newHookBlock;
139
+ }
140
+ } else {
141
+ finalContent = '#!/bin/sh\n' + newHookBlock;
142
+ }
143
+
144
+ fs.writeFileSync(hookPath, finalContent, { mode: 0o755 });
145
+ try { fs.chmodSync(hookPath, 0o755); } catch (_) {}
146
+ return hookPath;
147
+ }
148
+
96
149
  /**
97
150
  * Installs pre-push hook into git repository or globally
98
151
  * @param {string} [cwd]
@@ -133,35 +186,13 @@ function installHook(cwd = process.cwd(), isGlobal = false) {
133
186
  fs.mkdirSync(hooksDir, { recursive: true });
134
187
  }
135
188
 
136
- const hookPath = path.join(hooksDir, 'pre-push');
137
- const newHookBlock = generateHookContent();
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 (_) {}
189
+ const written = HOOK_TYPES.map(type => writeHook(hooksDir, type));
190
+ const hookPath = written[0];
160
191
 
161
192
  const typeMsg = isGlobal ? 'GLOBAL Git hook for ALL repositories on this PC' : 'local pre-push hook';
162
193
  return {
163
194
  success: true,
164
- message: `Successfully installed GitSafty ${typeMsg} at: ${hookPath}`
195
+ message: `Successfully installed GitSafty ${typeMsg} (pre-push, post-checkout, post-merge) at: ${path.dirname(hookPath)}`
165
196
  };
166
197
  } catch (err) {
167
198
  return {
@@ -182,36 +213,55 @@ function uninstallHook(cwd = process.cwd()) {
182
213
  return { success: false, message: 'Git hooks directory not found.' };
183
214
  }
184
215
 
185
- const hookPath = path.join(hooksDir, 'pre-push');
186
- if (!fs.existsSync(hookPath)) {
187
- return { success: true, message: 'Hook was not installed.' };
188
- }
189
-
216
+ let removed = 0;
190
217
  try {
191
- const existing = fs.readFileSync(hookPath, 'utf8');
192
- if (!existing.includes(HOOK_MARKER)) {
193
- return { success: true, message: 'GitSafty hook not present in pre-push file.' };
194
- }
218
+ for (const type of HOOK_TYPES) {
219
+ const hookPath = path.join(hooksDir, type);
220
+ if (!fs.existsSync(hookPath)) continue;
221
+ const existing = fs.readFileSync(hookPath, 'utf8');
222
+ if (!existing.includes(HOOK_MARKER)) continue;
195
223
 
196
- const regex = new RegExp(`${HOOK_MARKER}[\\s\\S]*?${HOOK_END_MARKER}\\n?`, 'm');
197
- const cleaned = existing.replace(regex, '').trim();
224
+ const regex = new RegExp(`${HOOK_MARKER}[\\s\\S]*?${HOOK_END_MARKER}\\n?`, 'm');
225
+ const cleaned = existing.replace(regex, '').trim();
198
226
 
199
- if (cleaned === '' || cleaned === '#!/bin/sh' || cleaned === '#!/usr/bin/env bash') {
200
- fs.unlinkSync(hookPath);
201
- } else {
202
- fs.writeFileSync(hookPath, cleaned + '\n', { mode: 0o755 });
227
+ if (cleaned === '' || cleaned === '#!/bin/sh' || cleaned === '#!/usr/bin/env bash') {
228
+ fs.unlinkSync(hookPath);
229
+ } else {
230
+ fs.writeFileSync(hookPath, cleaned + '\n', { mode: 0o755 });
231
+ }
232
+ removed++;
203
233
  }
204
-
205
- return { success: true, message: 'GitSafty pre-push hook removed successfully.' };
206
234
  } catch (err) {
207
235
  return { success: false, message: `Failed to uninstall hook: ${err.message}` };
208
236
  }
237
+
238
+ if (!removed) return { success: true, message: 'GitSafty hook not present.' };
239
+ return { success: true, message: `GitSafty hooks removed successfully (${removed}).` };
240
+ }
241
+
242
+ /**
243
+ * Re-writes already installed GitSafty hooks with this version's content.
244
+ * Used after an update so every device gets the new clone/pull protection.
245
+ */
246
+ function refreshInstalledHooks() {
247
+ const homeDir = process.env.HOME || process.env.USERPROFILE || '';
248
+ const globalDir = path.join(homeDir, '.git-hooks-safty');
249
+ const prePush = path.join(globalDir, 'pre-push');
250
+ try {
251
+ if (fs.existsSync(prePush) && fs.readFileSync(prePush, 'utf8').includes(HOOK_MARKER)) {
252
+ HOOK_TYPES.forEach(type => writeHook(globalDir, type));
253
+ return globalDir;
254
+ }
255
+ } catch (_) {}
256
+ return null;
209
257
  }
210
258
 
211
259
  module.exports = {
212
260
  installHook,
213
261
  uninstallHook,
262
+ refreshInstalledHooks,
214
263
  generateHookContent,
264
+ HOOK_TYPES,
215
265
  HOOK_MARKER,
216
266
  HOOK_END_MARKER
217
267
  };