@arifbiswas/git-pre-push 1.0.13 → 1.0.15

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/doctor.js ADDED
@@ -0,0 +1,336 @@
1
+ /**
2
+ * GitSafty doctor: finds broken or outdated installs and says exactly what to run.
3
+ *
4
+ * gitsafty doctor -> report problems + fix commands
5
+ * gitsafty doctor --fix -> also apply the safe fixes
6
+ *
7
+ * Also exports hintForError(), used everywhere GitSafty can fail, so every
8
+ * error message ends with a concrete next step.
9
+ */
10
+
11
+ const fs = require('fs');
12
+ const os = require('os');
13
+ const path = require('path');
14
+ const { spawnSync } = require('child_process');
15
+ const { colors } = require('./reporter');
16
+
17
+ const PACKAGE = '@arifbiswas/git-pre-push';
18
+ const isWin = process.platform === 'win32';
19
+
20
+ function homeDir() {
21
+ return process.env.HOME || process.env.USERPROFILE || os.homedir();
22
+ }
23
+
24
+ function globalHooksDir() {
25
+ return path.join(homeDir(), '.git-hooks-safty');
26
+ }
27
+
28
+ function gitOut(args, cwd) {
29
+ const r = spawnSync('git', args, { cwd, encoding: 'utf8' });
30
+ if (r.error || r.status !== 0) return null;
31
+ return (r.stdout || '').trim();
32
+ }
33
+
34
+ function onPath(cmd) {
35
+ const r = spawnSync(isWin ? 'where' : 'command', isWin ? [cmd] : ['-v', cmd], { encoding: 'utf8', shell: !isWin });
36
+ return r.status === 0;
37
+ }
38
+
39
+ // ---------------------------------------------------------------------------
40
+ // Ready-to-paste commands (per OS)
41
+ // ---------------------------------------------------------------------------
42
+
43
+ const commands = {
44
+ reinstall: () => [`npm install -g ${PACKAGE}`, 'gitsafty init --global'],
45
+ removeHooks: () => [
46
+ 'git config --global --unset core.hooksPath',
47
+ isWin ? 'Remove-Item -Recurse -Force "$HOME\\.git-hooks-safty"' : 'rm -rf ~/.git-hooks-safty'
48
+ ],
49
+ removeVaultHelper: (host = 'github.com') => [`git config --global --remove-section credential.https://${host}`],
50
+ npmPermission: () => isWin
51
+ ? ['Run the terminal as Administrator, or install Node.js with nvm-windows', `npm install -g ${PACKAGE}`]
52
+ : ['mkdir -p ~/.npm-global && npm config set prefix ~/.npm-global',
53
+ 'echo \'export PATH="$HOME/.npm-global/bin:$PATH"\' >> ~/.zshrc && source ~/.zshrc',
54
+ `npm install -g ${PACKAGE}`],
55
+ network: () => ['npm config get registry # should be https://registry.npmjs.org/', 'npm cache verify', `npm install -g ${PACKAGE}`]
56
+ };
57
+
58
+ function printCommands(title, cmds) {
59
+ console.log(` ${colors.bold}${title}${colors.reset}`);
60
+ for (const c of cmds) console.log(` ${colors.cyan}${c}${colors.reset}`);
61
+ }
62
+
63
+ /** The two "get me out of here" commands, shown whenever GitSafty itself is broken. */
64
+ function printEscapeHatch() {
65
+ printCommands('Reinstall GitSafty:', commands.reinstall());
66
+ printCommands('Or turn GitSafty off completely:', commands.removeHooks());
67
+ }
68
+
69
+ // ---------------------------------------------------------------------------
70
+ // Error -> hint
71
+ // ---------------------------------------------------------------------------
72
+
73
+ /**
74
+ * Maps an error (or message) to a short explanation + commands.
75
+ * @returns {{ problem: string, commands: string[] }}
76
+ */
77
+ function hintForError(err) {
78
+ const code = err && err.code;
79
+ const msg = String((err && err.message) || err || '');
80
+
81
+ if (code === 'EACCES' || code === 'EPERM' || /permission denied|EACCES|EPERM/i.test(msg)) {
82
+ const file = (err && err.path) || (msg.match(/'([^']+)'/) || [])[1];
83
+ if (file && /node_modules|npm/.test(file)) {
84
+ return { problem: 'npm has no permission to write its global folder.', commands: commands.npmPermission() };
85
+ }
86
+ return {
87
+ problem: `No permission to change ${file || 'a file'}. It may be read-only or owned by another user.`,
88
+ commands: file ? [isWin ? `icacls "${file}"` : `ls -l "${file}"`, isWin ? 'Run the terminal as your normal user' : `chmod u+w "${file}"`] : []
89
+ };
90
+ }
91
+ if (['ENOTFOUND', 'ETIMEDOUT', 'ECONNRESET', 'EAI_AGAIN', 'ECONNREFUSED'].includes(code) || /ENOTFOUND|ETIMEDOUT|ECONNRESET|EAI_AGAIN|network|socket hang up/i.test(msg)) {
92
+ return { problem: 'Network problem: GitSafty/npm could not reach the internet.', commands: commands.network() };
93
+ }
94
+ if ((code === 'ENOENT' && /\bgit\b/.test(msg)) || /git: command not found|'git' is not recognized/i.test(msg)) {
95
+ return { problem: 'git is not installed or not on PATH.', commands: [isWin ? 'winget install Git.Git' : (process.platform === 'darwin' ? 'xcode-select --install' : 'sudo apt install git')] };
96
+ }
97
+ if (err instanceof SyntaxError || /Unexpected token|SyntaxError|is not a function/i.test(msg)) {
98
+ return { problem: `This Node.js (${process.version}) may be too old for GitSafty (needs 16+).`, commands: ['node --version', isWin ? 'winget install OpenJS.NodeJS.LTS' : 'nvm install --lts && nvm use --lts', `npm install -g ${PACKAGE}`] };
99
+ }
100
+ if (/Cannot find module/i.test(msg)) {
101
+ return { problem: 'GitSafty files are missing (broken or half-finished install).', commands: commands.reinstall() };
102
+ }
103
+ if (/Swift compiler not found|xcode-select/i.test(msg)) {
104
+ return { problem: 'Touch ID / Secure Enclave mode needs Apple command line tools.', commands: ['xcode-select --install', 'gitsafty vault setup', 'gitsafty vault setup --passphrase # or use a passphrase instead'] };
105
+ }
106
+ if (/Windows Hello is not set up/i.test(msg)) {
107
+ return { problem: 'Windows Hello (PIN) is not set up on this PC.', commands: ['start ms-settings:signinoptions # add a PIN', 'gitsafty vault setup', 'gitsafty vault setup --passphrase # or use a passphrase instead'] };
108
+ }
109
+ if (/helper was modified|script changed since setup/i.test(msg)) {
110
+ return { problem: 'The vault unlock helper changed (GitSafty update, or tampering).', commands: ['gitsafty vault setup # re-create the vault with the current version'] };
111
+ }
112
+ if (/Wrong passphrase|did not match/i.test(msg)) {
113
+ return { problem: 'Wrong passphrase / key. Forgot it? Create a new vault with a new token.', commands: ['gitsafty vault setup'] };
114
+ }
115
+ return { problem: msg || 'Unexpected error.', commands: ['gitsafty doctor # find out what is wrong', 'gitsafty doctor --fix'] };
116
+ }
117
+
118
+ function printHint(err, prefix = 'What to do') {
119
+ const hint = hintForError(err);
120
+ console.error(`\n${colors.yellow}${colors.bold}💡 ${prefix}:${colors.reset} ${hint.problem}`);
121
+ for (const c of hint.commands) console.error(` ${colors.cyan}${c}${colors.reset}`);
122
+ console.error('');
123
+ }
124
+
125
+ // ---------------------------------------------------------------------------
126
+ // Checks
127
+ // ---------------------------------------------------------------------------
128
+
129
+ /**
130
+ * @param {{ cwd?: string, cliPath?: string }} [opts]
131
+ * @returns {Array<{ id: string, ok: boolean, level: 'ok'|'warn'|'error', title: string, detail?: string, commands?: string[], fix?: Function }>}
132
+ */
133
+ function runChecks({ cwd = process.cwd(), cliPath } = {}) {
134
+ const installer = require('./installer');
135
+ const checks = [];
136
+ const add = (c) => checks.push({ level: c.ok ? 'ok' : 'error', ...c });
137
+ const thisCli = (cliPath || path.resolve(__dirname, '..', 'bin', 'cli.js')).replace(/\\/g, '/');
138
+
139
+ // Node
140
+ const major = Number(process.versions.node.split('.')[0]);
141
+ add({
142
+ id: 'node', ok: major >= 16, title: `Node.js ${process.version}`,
143
+ detail: major >= 16 ? undefined : 'GitSafty needs Node.js 16 or newer.',
144
+ commands: major >= 16 ? undefined : hintForError(new SyntaxError('old node')).commands
145
+ });
146
+
147
+ // git
148
+ const gitVersion = gitOut(['--version'], cwd);
149
+ add({
150
+ id: 'git', ok: !!gitVersion, title: gitVersion || 'git not found',
151
+ commands: gitVersion ? undefined : hintForError(new Error("'git' is not recognized")).commands
152
+ });
153
+ if (!gitVersion) return checks;
154
+
155
+ // Global hooks
156
+ const hooksPath = gitOut(['config', '--global', 'core.hooksPath'], cwd);
157
+ const gdir = globalHooksDir();
158
+ const pointsToOurs = hooksPath && path.resolve(hooksPath.replace(/^~/, homeDir())).toLowerCase() === path.resolve(gdir).toLowerCase();
159
+
160
+ if (!hooksPath) {
161
+ checks.push({ id: 'global-hooks', ok: true, level: 'warn', title: 'Global protection is off (clone/pull/push on other repos are not scanned)', commands: ['gitsafty init --global'] });
162
+ } else if (pointsToOurs && !fs.existsSync(gdir)) {
163
+ add({
164
+ id: 'global-hooks-missing', ok: false,
165
+ title: 'git points to ~/.git-hooks-safty but the folder is missing (no repo runs any hook)',
166
+ commands: ['gitsafty init --global', ...commands.removeHooks().slice(0, 1)],
167
+ fix: () => installer.installHook(cwd, true)
168
+ });
169
+ } else if (pointsToOurs) {
170
+ const missing = [];
171
+ const broken = [];
172
+ const outdated = [];
173
+ let goneTarget = null;
174
+ for (const type of installer.HOOK_TYPES) {
175
+ const file = path.join(gdir, type);
176
+ if (!fs.existsSync(file)) { missing.push(type); continue; }
177
+ const content = fs.readFileSync(file, 'utf8');
178
+ if (!content.includes(installer.HOOK_MARKER)) continue; // user's own hook
179
+ const m = content.match(/^GITSAFTY_CLI='([^']*)'/m);
180
+ const target = m ? m[1] : null;
181
+ const reachable = (target && fs.existsSync(target)) || onPath('gitsafty');
182
+ if (!reachable) {
183
+ broken.push(type);
184
+ goneTarget = goneTarget || target;
185
+ } else if (!m || !content.includes(installer.generateHookContent(type).trim())) {
186
+ outdated.push(type);
187
+ }
188
+ }
189
+ const refresh = () => installer.installHook(cwd, true);
190
+ if (broken.length) {
191
+ add({
192
+ id: 'hook-broken', ok: false,
193
+ title: `Global hooks can't find GitSafty (${broken.join(', ')})${goneTarget ? `: ${goneTarget} is gone` : ''}`,
194
+ detail: 'GitSafty was uninstalled or moved, but git still runs its hooks, so nothing is scanned.',
195
+ commands: [...commands.reinstall(), '# or turn it off:', ...commands.removeHooks()],
196
+ fix: refresh
197
+ });
198
+ }
199
+ if (missing.length) {
200
+ add({
201
+ id: 'hook-missing', ok: false,
202
+ title: `Global hooks missing: ${missing.join(', ')}`,
203
+ detail: missing.includes('pre-push') ? 'Pushes are not scanned.' : 'Clones/pulls are not scanned.',
204
+ commands: ['gitsafty init --global'],
205
+ fix: refresh
206
+ });
207
+ }
208
+ if (outdated.length) {
209
+ checks.push({
210
+ id: 'hook-outdated', ok: true, level: 'warn',
211
+ title: `Global hooks are from another GitSafty version (${outdated.join(', ')})`,
212
+ commands: ['gitsafty init --global'],
213
+ fix: refresh
214
+ });
215
+ }
216
+ if (!checks.some(c => c.id.startsWith('hook-'))) {
217
+ checks.push({ id: 'global-hooks', ok: true, level: 'ok', title: `Global hooks OK (${gdir})` });
218
+ }
219
+ } else {
220
+ checks.push({ id: 'global-hooks-foreign', ok: true, level: 'warn', title: `core.hooksPath points to another tool's folder: ${hooksPath}`, detail: 'GitSafty global hooks are not active.' });
221
+ }
222
+
223
+ // Shell pull-scan function
224
+ try {
225
+ const shell = require('./shellIntegration');
226
+ const st = shell.shellIntegrationStatus();
227
+ if (!st.installed.length) {
228
+ checks.push({ id: 'pull-scan', ok: true, level: 'warn', title: 'Pulls that are "Already up to date" are not scanned (git runs no hook then)', commands: ['gitsafty pull-scan on'] });
229
+ } else {
230
+ checks.push({ id: 'pull-scan', ok: true, level: 'ok', title: `Every git pull is scanned (${st.installed.join(', ')})`, fix: () => shell.installShellIntegration() });
231
+ }
232
+ } catch (_) {}
233
+
234
+ // Credential helper / vault
235
+ try {
236
+ const vault = require('./vault');
237
+ const v = vault.readVault();
238
+ const host = (v && v.meta && v.meta.host) || 'github.com';
239
+ const helpers = vault.effectiveHelpers(host, cwd);
240
+ const ours = helpers.filter(h => /\bcredential$/.test(h) && /cli\.js/.test(h));
241
+ for (const h of ours) {
242
+ const paths = [...h.matchAll(/'([^']+)'/g)].map(x => x[1]);
243
+ const missing = paths.filter(p => !fs.existsSync(p));
244
+ if (missing.length) {
245
+ add({
246
+ id: 'vault-helper-broken', ok: false,
247
+ title: `GitHub login helper points to a missing file: ${missing.join(', ')}`,
248
+ detail: 'Every git push to GitHub will fail or ask for a password (Node version changed, or GitSafty moved).',
249
+ commands: v ? ['gitsafty vault setup # re-register with the current paths'] : commands.removeVaultHelper(host),
250
+ fix: () => {
251
+ if (v) {
252
+ vault.installHelper(host);
253
+ } else {
254
+ vault.removeHelper(host);
255
+ }
256
+ }
257
+ });
258
+ }
259
+ }
260
+ if (ours.length && !v) {
261
+ add({
262
+ id: 'vault-missing', ok: false,
263
+ title: `GitSafty is the GitHub login helper but there is no vault (${vault.vaultPath()})`,
264
+ detail: 'git can not get a login for github.com.',
265
+ commands: ['gitsafty vault setup', '# or go back to normal login:', ...commands.removeVaultHelper(host)],
266
+ fix: () => vault.removeHelper(host)
267
+ });
268
+ } else if (v && !ours.length) {
269
+ checks.push({ id: 'vault-inactive', ok: true, level: 'warn', title: 'A vault exists but git is not using it', commands: ['gitsafty vault setup'] });
270
+ } else if (v && ours.length && !checks.some(c => c.id.startsWith('vault'))) {
271
+ checks.push({ id: 'vault', ok: true, level: 'ok', title: `GitHub login vault OK (${v.meta.username || host}, ${v.version === 2 ? v.protector.type : 'passphrase'})` });
272
+ }
273
+ } catch (_) {}
274
+
275
+ return checks;
276
+ }
277
+
278
+ /**
279
+ * Prints the doctor report. With fix=true, applies the safe fixes.
280
+ * @returns {number} exit code (1 if errors remain)
281
+ */
282
+ function runDoctor({ fix = false, cwd = process.cwd() } = {}) {
283
+ console.log(`\n${colors.bold}GitSafty doctor${colors.reset} ${colors.dim}(${process.platform}, ${path.resolve(__dirname, '..')})${colors.reset}\n`);
284
+ let checks = runChecks({ cwd });
285
+
286
+ if (fix) {
287
+ const fixable = checks.filter(c => c.fix && c.level !== 'ok');
288
+ const done = new Set();
289
+ for (const c of fixable) {
290
+ const key = c.fix.toString();
291
+ if (done.has(key)) continue;
292
+ done.add(key);
293
+ try {
294
+ c.fix();
295
+ console.log(` ${colors.green}🔧 Fixed:${colors.reset} ${c.title}`);
296
+ } catch (err) {
297
+ console.log(` ${colors.red}✖ Could not fix:${colors.reset} ${c.title}: ${err.message}`);
298
+ }
299
+ }
300
+ if (fixable.length) console.log('');
301
+ checks = runChecks({ cwd });
302
+ }
303
+
304
+ for (const c of checks) {
305
+ const icon = c.level === 'ok' ? `${colors.green}✔` : c.level === 'warn' ? `${colors.yellow}⚠` : `${colors.red}✖`;
306
+ console.log(` ${icon}${colors.reset} ${c.title}`);
307
+ if (c.detail) console.log(` ${colors.dim}${c.detail}${colors.reset}`);
308
+ if (c.level !== 'ok' && c.commands) {
309
+ for (const cmd of c.commands) console.log(` ${colors.cyan}${cmd}${colors.reset}`);
310
+ }
311
+ }
312
+
313
+ const errors = checks.filter(c => c.level === 'error');
314
+ const fixable = checks.filter(c => c.fix && c.level !== 'ok');
315
+ console.log('');
316
+ if (!errors.length && !checks.some(c => c.level === 'warn')) {
317
+ console.log(`${colors.green}${colors.bold}✔ Everything looks good.${colors.reset}\n`);
318
+ } else if (fixable.length && !fix) {
319
+ console.log(`${colors.bold}Fix automatically:${colors.reset} ${colors.cyan}gitsafty doctor --fix${colors.reset}\n`);
320
+ }
321
+ if (errors.length) {
322
+ const helperSet = checks.some(c => c.id.startsWith('vault'));
323
+ printCommands('If nothing helps, turn GitSafty off completely:', [...commands.removeHooks(), ...(helperSet ? commands.removeVaultHelper() : [])]);
324
+ console.log('');
325
+ }
326
+ return errors.length ? 1 : 0;
327
+ }
328
+
329
+ module.exports = {
330
+ runDoctor,
331
+ runChecks,
332
+ hintForError,
333
+ printHint,
334
+ printEscapeHatch,
335
+ commands
336
+ };
package/src/index.js CHANGED
@@ -128,17 +128,71 @@ function runPostCheckout(prevHead, newHead, flag) {
128
128
  }
129
129
  if (!files.length) return 0;
130
130
  scanAndCleanRepo(files, cwd, { reason: isClone ? 'clone' : 'checkout', quietWhenClean: !isClone });
131
+ if (isClone) recordScan(cwd);
131
132
  return 0;
132
133
  }
133
134
 
134
- /** post-merge hook: runs after git pull / git merge. */
135
+ const LAST_SCAN_FILE = 'gitsafty-last-scan.json';
136
+ // Only to avoid scanning twice in ONE pull (hook + shell function run seconds apart).
137
+ const RECENT_SCAN_MS = 5 * 1000;
138
+
139
+ function gitDirOf(cwd) {
140
+ const d = gitLines(['rev-parse', '--git-dir'], cwd)[0];
141
+ return d ? path.resolve(cwd, d) : null;
142
+ }
143
+
144
+ function headOf(cwd) {
145
+ return gitLines(['rev-parse', 'HEAD'], cwd)[0] || '';
146
+ }
147
+
148
+ function recordScan(cwd) {
149
+ const dir = gitDirOf(cwd);
150
+ if (!dir) return;
151
+ try { fs.writeFileSync(path.join(dir, LAST_SCAN_FILE), JSON.stringify({ head: headOf(cwd), at: Date.now() })); } catch (_) {}
152
+ }
153
+
154
+ function scannedRecently(cwd) {
155
+ const dir = gitDirOf(cwd);
156
+ if (!dir) return false;
157
+ try {
158
+ const last = JSON.parse(fs.readFileSync(path.join(dir, LAST_SCAN_FILE), 'utf8'));
159
+ return last.head === headOf(cwd) && Date.now() - last.at < RECENT_SCAN_MS;
160
+ } catch (_) {
161
+ return false;
162
+ }
163
+ }
164
+
165
+ /** Scans every tracked file, like after a clone, and always prints the result. */
166
+ function scanWholeRepo(cwd, reason, label) {
167
+ const files = gitNulList(['ls-files'], cwd);
168
+ console.log(`${colors.cyan}${colors.bold}🛡️ GitSafty:${colors.reset} scanning repository after ${label}...`);
169
+ if (files.length) scanAndCleanRepo(files, cwd, { reason, quietWhenClean: false });
170
+ recordScan(cwd);
171
+ return 0;
172
+ }
173
+
174
+ /** post-merge hook: runs after git pull (merge / fast-forward) and git merge. */
135
175
  function runPostMerge() {
176
+ if (process.env.GITSAFTY_SKIP === '1') return 0;
177
+ return scanWholeRepo(process.cwd(), 'pull', 'git pull');
178
+ }
179
+
180
+ /** post-rewrite hook: `git pull --rebase` (and git rebase) never run post-merge. */
181
+ function runPostRewrite(kind) {
182
+ if (process.env.GITSAFTY_SKIP === '1' || kind !== 'rebase') return 0;
183
+ return scanWholeRepo(process.cwd(), 'pull', 'git pull --rebase');
184
+ }
185
+
186
+ /**
187
+ * Called by the optional shell `git` wrapper after every `git pull`, also when
188
+ * git says "Already up to date" (git runs no hook at all in that case).
189
+ * Skips when a hook already scanned this exact commit a moment ago.
190
+ */
191
+ function runScanPull() {
136
192
  if (process.env.GITSAFTY_SKIP === '1') return 0;
137
193
  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;
194
+ if (!gitDirOf(cwd) || scannedRecently(cwd)) return 0;
195
+ return scanWholeRepo(cwd, 'pull', 'git pull');
142
196
  }
143
197
 
144
198
  function findGitRepos(root, maxDepth = 6) {
@@ -318,6 +372,8 @@ module.exports = {
318
372
  runManualScan,
319
373
  runPostCheckout,
320
374
  runPostMerge,
375
+ runPostRewrite,
376
+ runScanPull,
321
377
  runSweep,
322
378
  scanAndCleanRepo,
323
379
  installHook,
package/src/installer.js CHANGED
@@ -5,7 +5,7 @@ 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
- const HOOK_TYPES = ['pre-push', 'post-checkout', 'post-merge'];
8
+ const HOOK_TYPES = ['pre-push', 'post-checkout', 'post-merge', 'post-rewrite'];
9
9
 
10
10
  // Absolute path of this installation's CLI, baked into the hook so a cloned
11
11
  // repository can never substitute its own ./bin/cli.js or node_modules copy.
@@ -34,6 +34,22 @@ run_gitsafty() {
34
34
  done
35
35
  return 127
36
36
  }
37
+
38
+ # Shown when GitSafty itself can't be found, so git never fails silently.
39
+ gitsafty_missing() {
40
+ HOOK_DIR=$(cd "$(dirname "$0")" 2>/dev/null && pwd)
41
+ echo "" >&2
42
+ echo "⚠ GitSafty is not reachable (\$GITSAFTY_CLI is missing and no gitsafty command on PATH)." >&2
43
+ echo " git still runs GitSafty's hooks, so protection is OFF until you fix this:" >&2
44
+ echo " Reinstall: npm install -g @arifbiswas/git-pre-push && gitsafty init --global" >&2
45
+ case "$HOOK_DIR" in
46
+ *.git-hooks-safty)
47
+ echo " Or turn off: git config --global --unset core.hooksPath && rm -rf ~/.git-hooks-safty" >&2 ;;
48
+ *)
49
+ echo " Or turn off: rm \\"$HOOK_DIR/pre-push\\" \\"$HOOK_DIR/post-checkout\\" \\"$HOOK_DIR/post-merge\\" \\"$HOOK_DIR/post-rewrite\\"" >&2 ;;
50
+ esac
51
+ echo "" >&2
52
+ }
37
53
  `;
38
54
  }
39
55
 
@@ -42,6 +58,7 @@ function prePushBody() {
42
58
  run_gitsafty scan-push "$@"
43
59
  rc=$?
44
60
  if [ $rc -ne 127 ]; then return $rc; fi
61
+ gitsafty_missing
45
62
 
46
63
  # 3. Published package via bunx / npx
47
64
  if command -v bunx >/dev/null 2>&1; then
@@ -94,11 +111,12 @@ fi`;
94
111
  }
95
112
 
96
113
  function postHookBody(hookType) {
97
- const command = hookType === 'post-checkout' ? 'scan-checkout' : 'scan-merge';
114
+ const command = { 'post-checkout': 'scan-checkout', 'post-merge': 'scan-merge', 'post-rewrite': 'scan-rewrite' }[hookType];
98
115
  return `# Runs after git clone / checkout / pull. Reports and removes confirmed
99
116
  # malware. Never fails the git command itself.
100
117
  run_gitsafty ${command} "$@"
101
118
  if [ $? -eq 127 ]; then
119
+ gitsafty_missing
102
120
  # Fallback: GitSafty not reachable, at least warn about the known loader marker.
103
121
  HITS=$(git grep -l -I -E 'global\\[.!.\\]=.[0-9-]+.;(var|\\(function)' 2>/dev/null | head -20)
104
122
  if [ -n "$HITS" ]; then
@@ -192,7 +210,7 @@ function installHook(cwd = process.cwd(), isGlobal = false) {
192
210
  const typeMsg = isGlobal ? 'GLOBAL Git hook for ALL repositories on this PC' : 'local pre-push hook';
193
211
  return {
194
212
  success: true,
195
- message: `Successfully installed GitSafty ${typeMsg} (pre-push, post-checkout, post-merge) at: ${path.dirname(hookPath)}`
213
+ message: `Successfully installed GitSafty ${typeMsg} (pre-push, post-checkout, post-merge, post-rewrite) at: ${path.dirname(hookPath)}`
196
214
  };
197
215
  } catch (err) {
198
216
  return {
@@ -202,41 +220,106 @@ function installHook(cwd = process.cwd(), isGlobal = false) {
202
220
  }
203
221
  }
204
222
 
223
+ function globalHooksDir() {
224
+ const homeDir = process.env.HOME || process.env.USERPROFILE || '';
225
+ return path.join(homeDir, '.git-hooks-safty');
226
+ }
227
+
228
+ /** Removes the GitSafty block from every hook in a directory. */
229
+ function stripHooksIn(hooksDir) {
230
+ let removed = 0;
231
+ for (const type of HOOK_TYPES) {
232
+ const hookPath = path.join(hooksDir, type);
233
+ if (!fs.existsSync(hookPath)) continue;
234
+ try { fs.chmodSync(hookPath, 0o755); } catch (_) {}
235
+ const existing = fs.readFileSync(hookPath, 'utf8');
236
+ if (!existing.includes(HOOK_MARKER)) continue;
237
+
238
+ const regex = new RegExp(`${HOOK_MARKER}[\\s\\S]*?${HOOK_END_MARKER}\\n?`, 'm');
239
+ const cleaned = existing.replace(regex, '').trim();
240
+
241
+ if (cleaned === '' || cleaned === '#!/bin/sh' || cleaned === '#!/usr/bin/env bash') {
242
+ fs.unlinkSync(hookPath);
243
+ } else {
244
+ fs.writeFileSync(hookPath, cleaned + '\n', { mode: 0o755 });
245
+ }
246
+ removed++;
247
+ }
248
+ return removed;
249
+ }
250
+
251
+ function samePath(a, b) {
252
+ if (!a || !b) return false;
253
+ const norm = (p) => path.resolve(p.replace(/^~(?=$|[\\/])/, process.env.HOME || process.env.USERPROFILE || '~'));
254
+ const x = norm(a);
255
+ const y = norm(b);
256
+ return process.platform === 'win32' || process.platform === 'darwin' ? x.toLowerCase() === y.toLowerCase() : x === y;
257
+ }
258
+
205
259
  /**
206
- * Removes GitSafty hook
207
- * @param {string} [cwd]
208
- * @returns {{ success: boolean, message: string }}
260
+ * Removes the GitSafty global hooks (~/.git-hooks-safty) and, when nothing
261
+ * else is left there, the global core.hooksPath that points to it.
209
262
  */
210
- function uninstallHook(cwd = process.cwd()) {
211
- const hooksDir = getHooksDir(cwd);
212
- if (!hooksDir) {
213
- return { success: false, message: 'Git hooks directory not found.' };
263
+ function uninstallGlobalHook() {
264
+ const { runGit } = require('./utils/git');
265
+ const dir = globalHooksDir();
266
+ const configured = runGit('config --global core.hooksPath');
267
+ const ours = samePath(configured, dir);
268
+
269
+ if (!fs.existsSync(dir) && !ours) {
270
+ return { success: true, message: 'GitSafty global hooks are not installed.' };
214
271
  }
215
272
 
216
273
  let removed = 0;
217
274
  try {
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;
223
-
224
- const regex = new RegExp(`${HOOK_MARKER}[\\s\\S]*?${HOOK_END_MARKER}\\n?`, 'm');
225
- const cleaned = existing.replace(regex, '').trim();
226
-
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++;
275
+ if (fs.existsSync(dir)) {
276
+ removed = stripHooksIn(dir);
277
+ if (fs.readdirSync(dir).length === 0) fs.rmdirSync(dir);
233
278
  }
279
+ } catch (err) {
280
+ return { success: false, message: `Failed to remove global hooks: ${err.message}` };
281
+ }
282
+
283
+ let unset = false;
284
+ if (ours && !fs.existsSync(dir)) {
285
+ runGit('config --global --unset core.hooksPath');
286
+ unset = true;
287
+ }
288
+
289
+ const parts = [`Removed ${removed} GitSafty global hook(s)`];
290
+ if (unset) parts.push('and reset git core.hooksPath');
291
+ else if (ours) parts.push(`(kept core.hooksPath: ${dir} still holds other hooks)`);
292
+ return { success: true, message: parts.join(' ') + '. Repositories on this PC are no longer scanned by GitSafty.' };
293
+ }
294
+
295
+ /**
296
+ * Removes GitSafty hooks.
297
+ * - isGlobal, or run outside a git repository: removes the global hooks.
298
+ * - inside a repository: removes this repository's own hooks.
299
+ * @param {string} [cwd]
300
+ * @param {boolean} [isGlobal=false]
301
+ * @returns {{ success: boolean, message: string }}
302
+ */
303
+ function uninstallHook(cwd = process.cwd(), isGlobal = false) {
304
+ if (isGlobal || !isGitRepo(cwd)) return uninstallGlobalHook();
305
+
306
+ const { runGit } = require('./utils/git');
307
+ // The repository's own hooks dir, NOT the global core.hooksPath.
308
+ const localHooksPath = runGit('config --local core.hooksPath', cwd);
309
+ const gitDir = runGit('rev-parse --git-dir', cwd);
310
+ const hooksDir = localHooksPath ? path.resolve(cwd, localHooksPath) : path.resolve(cwd, gitDir, 'hooks');
311
+
312
+ let removed = 0;
313
+ try {
314
+ if (fs.existsSync(hooksDir)) removed = stripHooksIn(hooksDir);
234
315
  } catch (err) {
235
316
  return { success: false, message: `Failed to uninstall hook: ${err.message}` };
236
317
  }
237
318
 
238
- if (!removed) return { success: true, message: 'GitSafty hook not present.' };
239
- return { success: true, message: `GitSafty hooks removed successfully (${removed}).` };
319
+ const globalActive = samePath(runGit('config --global core.hooksPath', cwd), globalHooksDir());
320
+ const note = globalActive ? ' Global GitSafty hooks are still active for all repos (remove with: gitsafty uninstall --global).' : '';
321
+ if (!removed) return { success: true, message: `No GitSafty hooks in this repository.${note}` };
322
+ return { success: true, message: `GitSafty hooks removed from this repository (${removed}).${note}` };
240
323
  }
241
324
 
242
325
  /**
@@ -259,6 +342,7 @@ function refreshInstalledHooks() {
259
342
  module.exports = {
260
343
  installHook,
261
344
  uninstallHook,
345
+ uninstallGlobalHook,
262
346
  refreshInstalledHooks,
263
347
  generateHookContent,
264
348
  HOOK_TYPES,