@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/menu.js CHANGED
@@ -34,10 +34,12 @@ async function runInteractiveMenu() {
34
34
  section('Protection');
35
35
  item(1, '๐Ÿ›ก๏ธ ', 'Install Local Hook', 'Protect current repo (push + checkout + pull)');
36
36
  item(2, '๐ŸŒ', 'Install Global Hook', 'Protect EVERY repo on this PC: scan on clone, pull & push');
37
- item(8, 'โŒ', 'Uninstall Hook', 'Remove GitSafty hooks');
37
+ item(17, '๐Ÿ”', 'Scan Every Pull', 'Also scan when git pull says "Already up to date"');
38
+ item(8, 'โŒ', 'Uninstall Hook', 'Remove GitSafty hooks (this repo or whole PC)');
38
39
 
39
40
  section('Malware scan & removal');
40
41
  item(3, '๐Ÿ”', 'Scan Local Workspace', 'Deep scan this repo, auto-remove confirmed malware');
42
+ item(16, '๐Ÿ”ฌ', 'Advanced Scanner', 'Audit ALL projects in a folder: malware, backdoors, secrets');
41
43
  item(10, '๐Ÿงน', 'Sweep All Repos', 'Scan every git repo in a folder (whole device)');
42
44
  item(5, '๐Ÿ—‘๏ธ ', 'Clean & Quarantine', 'Remove confirmed malware + trojan scripts here');
43
45
  item(4, '๐Ÿš€', 'Scan Remote GitHub Repo', 'Zero-clone audit (no download/clone)');
@@ -52,6 +54,7 @@ async function runInteractiveMenu() {
52
54
  item(6, 'โšก', 'Run Push Intercept Demo', 'Simulate a blocked malware push');
53
55
  item(7, '๐Ÿค–', 'Setup GitHub Action CI', 'Guard repository on GitHub server-side');
54
56
  item(9, '๐Ÿ”„', 'Check for Updates', 'Check if a new version is available on npm');
57
+ item(15, '๐Ÿฉบ', 'Doctor', 'Something broken? Find it and show/apply the fix');
55
58
  console.log(` ${colors.dim}[0] ๐Ÿšช Exit${colors.reset}\n`);
56
59
 
57
60
  const rl = readline.createInterface({
@@ -60,7 +63,7 @@ async function runInteractiveMenu() {
60
63
  });
61
64
 
62
65
  const choice = await new Promise((resolve) => {
63
- rl.question(`${colors.bold}${colors.yellow}Enter your choice (1-14, 0 to exit): ${colors.reset}`, (ans) => {
66
+ rl.question(`${colors.bold}${colors.yellow}Enter your choice (1-17, 0 to exit): ${colors.reset}`, (ans) => {
64
67
  rl.close();
65
68
  resolve(ans.trim());
66
69
  });
@@ -166,7 +169,13 @@ async function runInteractiveMenu() {
166
169
  }
167
170
 
168
171
  case '8': {
169
- const res = uninstallHook();
172
+ const { isGitRepo } = require('./utils/git');
173
+ let global = !isGitRepo(process.cwd());
174
+ if (!global) {
175
+ const scope = await ask(`\n${colors.bold}${colors.cyan}? Remove hooks from (1) this repository only, or (2) the whole PC (global)? [1/2]: ${colors.reset}`);
176
+ global = scope === '2';
177
+ }
178
+ const res = uninstallHook(process.cwd(), global);
170
179
  if (res.success) {
171
180
  console.log(`\n${colors.yellow}${colors.bold}โœ” ${res.message}${colors.reset}\n`);
172
181
  } else {
@@ -214,6 +223,45 @@ async function runInteractiveMenu() {
214
223
  break;
215
224
  }
216
225
 
226
+ case '15': {
227
+ const { runDoctor, runChecks } = require('./doctor');
228
+ runDoctor();
229
+ const fixable = runChecks().some(c => c.fix && c.level !== 'ok');
230
+ if (fixable) {
231
+ const fixIt = await ask(`${colors.bold}${colors.cyan}? Apply the safe fixes now? (y/N): ${colors.reset}`);
232
+ if (/^y(es)?$/i.test(fixIt)) runDoctor({ fix: true });
233
+ }
234
+ break;
235
+ }
236
+
237
+ case '16': {
238
+ const { runAdvancedScan } = require('./advancedScanner');
239
+ const folder = await ask(`\n${colors.bold}${colors.cyan}? Folder that contains your projects (Enter = ${process.cwd()}): ${colors.reset}`);
240
+ const deep = await ask(`${colors.bold}${colors.cyan}? Deep scan incl. node_modules & ignored files? Slower. (y/N): ${colors.reset}`);
241
+ const clean = await ask(`${colors.bold}${colors.cyan}? Automatically remove CONFIRMED malware? Everything else is only reported. (y/N): ${colors.reset}`);
242
+ runAdvancedScan(folder || process.cwd(), {
243
+ deep: /^y(es)?$/i.test(deep),
244
+ clean: /^y(es)?$/i.test(clean)
245
+ });
246
+ break;
247
+ }
248
+
249
+ case '17': {
250
+ const shell = require('./shellIntegration');
251
+ const on = shell.shellIntegrationStatus().installed.length > 0;
252
+ const answer = await ask(`\n${colors.bold}${colors.cyan}? Pull scan is ${on ? 'ON' : 'OFF'}. Turn it ${on ? 'off' : 'on'}? (y/N): ${colors.reset}`);
253
+ if (/^y(es)?$/i.test(answer)) {
254
+ if (on) {
255
+ const r = shell.removeShellIntegration();
256
+ console.log(`\n${colors.yellow}โœ” Turned off (${r.files.join(', ')}). Open a new terminal.${colors.reset}\n`);
257
+ } else {
258
+ const r = shell.installShellIntegration();
259
+ console.log(`\n${colors.green}โœ” Every git pull is now scanned (${r.files.join(', ')}).${colors.reset} Load it: ${colors.cyan}${shell.reloadHint()}${colors.reset}\n`);
260
+ }
261
+ }
262
+ break;
263
+ }
264
+
217
265
  case '0':
218
266
  default:
219
267
  console.log(`\n${colors.dim}Goodbye! ๐Ÿ›ก๏ธ${colors.reset}\n`);
@@ -0,0 +1,212 @@
1
+ /**
2
+ * Optional shell integration: scan after EVERY `git pull`.
3
+ *
4
+ * git runs no hook at all when a pull is "Already up to date", so hooks alone
5
+ * can't do this. This adds a small `git` shell function that runs the real
6
+ * git, keeps its exit code, and after `git pull` runs `gitsafty scan-pull`
7
+ * (which skips the scan when a hook already scanned the same commit).
8
+ *
9
+ * Installed only when the user agrees, between clear markers, in:
10
+ * macOS / Linux: the current shell's rc file (~/.zshrc, ~/.bashrc, fish config)
11
+ * Windows: PowerShell profiles, and ~/.bashrc for Git Bash
12
+ */
13
+
14
+ const fs = require('fs');
15
+ const os = require('os');
16
+ const path = require('path');
17
+ const { spawnSync } = require('child_process');
18
+
19
+ const START = '# >>> gitsafty pull scan >>>';
20
+ const END = '# <<< gitsafty pull scan <<<';
21
+ const isWin = process.platform === 'win32';
22
+
23
+ function home() {
24
+ return process.env.HOME || process.env.USERPROFILE || os.homedir();
25
+ }
26
+
27
+ function cliPath() {
28
+ return path.resolve(__dirname, '..', 'bin', 'cli.js').replace(/\\/g, '/');
29
+ }
30
+
31
+ function shQuote(s) {
32
+ return `'${String(s).replace(/'/g, `'\\''`)}'`;
33
+ }
34
+
35
+ function posixBlock() {
36
+ return `${START}
37
+ # Added by GitSafty: scan the repository after every git pull, also when it
38
+ # is "Already up to date". Remove with: gitsafty pull-scan off
39
+ git() {
40
+ command git "$@"
41
+ local __gs_rc=$?
42
+ local __gs_sub="" __gs_dir="" __gs_skip="" __gs_a
43
+ for __gs_a in "$@"; do
44
+ if [ -n "$__gs_skip" ]; then
45
+ [ "$__gs_skip" = "-C" ] && __gs_dir="$__gs_a"
46
+ __gs_skip=""
47
+ continue
48
+ fi
49
+ case "$__gs_a" in
50
+ -C|-c) __gs_skip="$__gs_a" ;;
51
+ -*) ;;
52
+ *) __gs_sub="$__gs_a"; break ;;
53
+ esac
54
+ done
55
+ if [ "$__gs_sub" = "pull" ] && [ $__gs_rc -eq 0 ]; then
56
+ (
57
+ [ -n "$__gs_dir" ] && cd "$__gs_dir"
58
+ if [ -f ${shQuote(cliPath())} ] && command -v node >/dev/null 2>&1; then
59
+ node ${shQuote(cliPath())} scan-pull
60
+ elif command -v gitsafty >/dev/null 2>&1; then
61
+ gitsafty scan-pull
62
+ fi
63
+ )
64
+ fi
65
+ return $__gs_rc
66
+ }
67
+ ${END}
68
+ `;
69
+ }
70
+
71
+ function fishBlock() {
72
+ return `${START}
73
+ # Added by GitSafty: scan after every git pull. Remove with: gitsafty pull-scan off
74
+ function git --wraps git
75
+ command git $argv
76
+ set -l __gs_rc $status
77
+ if test $__gs_rc -eq 0; and contains -- pull $argv[1]
78
+ if test -f '${cliPath()}'; and type -q node
79
+ node '${cliPath()}' scan-pull
80
+ else if type -q gitsafty
81
+ gitsafty scan-pull
82
+ end
83
+ end
84
+ return $__gs_rc
85
+ end
86
+ ${END}
87
+ `;
88
+ }
89
+
90
+ function powershellBlock() {
91
+ const cli = cliPath().replace(/'/g, "''");
92
+ return `${START}
93
+ # Added by GitSafty: scan after every git pull, also when "Already up to date".
94
+ # Remove with: gitsafty pull-scan off
95
+ function git {
96
+ $gsGit = (Get-Command git -CommandType Application -ErrorAction SilentlyContinue | Select-Object -First 1).Source
97
+ & $gsGit @args
98
+ $gsRc = $LASTEXITCODE
99
+ $gsSub = $null; $gsDir = $null; $gsSkip = $null
100
+ foreach ($gsA in $args) {
101
+ if ($gsSkip) { if ($gsSkip -eq '-C') { $gsDir = $gsA }; $gsSkip = $null; continue }
102
+ if ($gsA -in @('-C', '-c')) { $gsSkip = $gsA; continue }
103
+ if ("$gsA".StartsWith('-')) { continue }
104
+ $gsSub = $gsA; break
105
+ }
106
+ if ($gsSub -eq 'pull' -and $gsRc -eq 0) {
107
+ if ($gsDir) { Push-Location $gsDir }
108
+ try {
109
+ if ((Test-Path '${cli}') -and (Get-Command node -ErrorAction SilentlyContinue)) { & node '${cli}' scan-pull }
110
+ elseif (Get-Command gitsafty -ErrorAction SilentlyContinue) { gitsafty scan-pull }
111
+ } finally { if ($gsDir) { Pop-Location } }
112
+ }
113
+ $global:LASTEXITCODE = $gsRc
114
+ }
115
+ ${END}
116
+ `;
117
+ }
118
+
119
+ function powershellProfiles() {
120
+ const docs = path.join(home(), 'Documents');
121
+ return [
122
+ path.join(docs, 'WindowsPowerShell', 'Microsoft.PowerShell_profile.ps1'),
123
+ path.join(docs, 'PowerShell', 'Microsoft.PowerShell_profile.ps1')
124
+ ];
125
+ }
126
+
127
+ /** rc files GitSafty would write to, with the block flavour for each. */
128
+ function targets() {
129
+ const out = [];
130
+ const add = (file, kind, create) => out.push({ file, kind, create });
131
+ if (isWin) {
132
+ for (const p of powershellProfiles()) add(p, 'powershell', true);
133
+ add(path.join(home(), '.bashrc'), 'posix', false); // Git Bash, only if it exists
134
+ return out;
135
+ }
136
+ const shell = path.basename(process.env.SHELL || '');
137
+ add(path.join(home(), '.zshrc'), 'posix', shell === 'zsh' || process.platform === 'darwin');
138
+ add(path.join(home(), '.bashrc'), 'posix', shell === 'bash');
139
+ add(path.join(home(), '.config', 'fish', 'config.fish'), 'fish', shell === 'fish');
140
+ return out;
141
+ }
142
+
143
+ function blockFor(kind) {
144
+ return kind === 'powershell' ? powershellBlock() : kind === 'fish' ? fishBlock() : posixBlock();
145
+ }
146
+
147
+ function stripBlock(text) {
148
+ const re = new RegExp(`\\n?${START.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}[\\s\\S]*?${END.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\n?`, 'g');
149
+ return text.replace(re, '\n').replace(/\n{3,}$/, '\n\n');
150
+ }
151
+
152
+ /**
153
+ * Adds (or refreshes) the git wrapper.
154
+ * @returns {{ files: string[] }}
155
+ */
156
+ function installShellIntegration() {
157
+ const files = [];
158
+ for (const t of targets()) {
159
+ const exists = fs.existsSync(t.file);
160
+ if (!exists && !t.create) continue;
161
+ fs.mkdirSync(path.dirname(t.file), { recursive: true });
162
+ const current = exists ? fs.readFileSync(t.file, 'utf8') : '';
163
+ const cleaned = stripBlock(current).replace(/\s*$/, '');
164
+ fs.writeFileSync(t.file, (cleaned ? cleaned + '\n\n' : '') + blockFor(t.kind));
165
+ files.push(t.file);
166
+ }
167
+ return { files };
168
+ }
169
+
170
+ /** Removes the git wrapper everywhere it was added. @returns {{ files: string[] }} */
171
+ function removeShellIntegration() {
172
+ const files = [];
173
+ for (const t of targets()) {
174
+ if (!fs.existsSync(t.file)) continue;
175
+ const current = fs.readFileSync(t.file, 'utf8');
176
+ if (!current.includes(START)) continue;
177
+ fs.writeFileSync(t.file, stripBlock(current).replace(/\s*$/, '\n'));
178
+ files.push(t.file);
179
+ }
180
+ return { files };
181
+ }
182
+
183
+ function shellIntegrationStatus() {
184
+ const installed = targets().filter(t => fs.existsSync(t.file) && fs.readFileSync(t.file, 'utf8').includes(START)).map(t => t.file);
185
+ return { installed, cliExists: fs.existsSync(cliPath()) };
186
+ }
187
+
188
+ /** Command that loads the change in the current terminal. */
189
+ function reloadHint() {
190
+ if (isWin) return '. $PROFILE # or open a new terminal';
191
+ const shell = path.basename(process.env.SHELL || '');
192
+ if (shell === 'fish') return 'source ~/.config/fish/config.fish';
193
+ return `source ~/.${shell === 'bash' ? 'bashrc' : 'zshrc'} # or open a new terminal`;
194
+ }
195
+
196
+ /** Syntax-checks the generated POSIX function with the local sh, if any. */
197
+ function checkPosixSyntax() {
198
+ const r = spawnSync('sh', ['-n'], { input: posixBlock(), encoding: 'utf8' });
199
+ return r.status === 0;
200
+ }
201
+
202
+ module.exports = {
203
+ START,
204
+ END,
205
+ installShellIntegration,
206
+ removeShellIntegration,
207
+ shellIntegrationStatus,
208
+ reloadHint,
209
+ posixBlock,
210
+ powershellBlock,
211
+ checkPosixSyntax
212
+ };
@@ -4,7 +4,8 @@ const os = require('os');
4
4
  const { colors } = require('./reporter');
5
5
 
6
6
  const CACHE_FILE = path.join(os.homedir(), '.gitsafty-update.json');
7
- const CHECK_INTERVAL_MS = 12 * 60 * 60 * 1000; // Check at most once every 12 hours
7
+ const CHECK_INTERVAL_MS = 60 * 60 * 1000; // Check at most once an hour (menu/update always check)
8
+ const SKIP_PROMPT_MS = 24 * 60 * 60 * 1000; // "No" silences the prompt for that version for a day
8
9
  const PACKAGE_NAME = '@arifbiswas/git-pre-push';
9
10
 
10
11
  /**
@@ -43,16 +44,125 @@ function readCache() {
43
44
  * Writes cached update info
44
45
  * @param {string} latestVersion
45
46
  */
46
- function writeCache(latestVersion) {
47
+ function writeCache(latestVersion, extra = {}) {
47
48
  try {
49
+ const prev = readCache() || {};
48
50
  fs.writeFileSync(
49
51
  CACHE_FILE,
50
- JSON.stringify({ lastChecked: Date.now(), latestVersion }, null, 2),
52
+ JSON.stringify({ ...prev, lastChecked: Date.now(), latestVersion, ...extra }, null, 2),
51
53
  'utf8'
52
54
  );
53
55
  } catch (_) {}
54
56
  }
55
57
 
58
+ /**
59
+ * How this copy of GitSafty was installed.
60
+ * @returns {'global'|'npx'|'local-dependency'|'source'}
61
+ */
62
+ function installKind(cliFile = path.resolve(__dirname, '..', 'bin', 'cli.js')) {
63
+ const p = cliFile.replace(/\\/g, '/');
64
+ if (/\/_npx\//.test(p) || /\/npm-cache\//.test(p)) return 'npx';
65
+ if (process.env.npm_config_global === 'true') return 'global';
66
+ // Global installs live in <prefix>/lib/node_modules (unix) or <prefix>/node_modules (Windows npm prefix).
67
+ try {
68
+ const { execFileSync } = require('child_process');
69
+ const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm';
70
+ const root = execFileSync(npm, ['root', '-g'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 5000, shell: process.platform === 'win32' }).trim().replace(/\\/g, '/');
71
+ if (root && p.toLowerCase().startsWith(root.toLowerCase() + '/')) return 'global';
72
+ } catch (_) {}
73
+ if (/\/node_modules\//.test(p)) return 'local-dependency';
74
+ return 'source';
75
+ }
76
+
77
+ function isInteractive() {
78
+ return !!(process.stdin.isTTY && process.stdout.isTTY) && !process.env.CI && !process.env.CONTINUOUS_INTEGRATION;
79
+ }
80
+
81
+ function askYesNo(question, defaultYes = true) {
82
+ const readline = require('readline');
83
+ const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
84
+ return new Promise((resolve) => {
85
+ rl.question(question, (answer) => {
86
+ rl.close();
87
+ const a = answer.trim().toLowerCase();
88
+ resolve(a === '' ? defaultYes : (a === 'y' || a === 'yes'));
89
+ });
90
+ });
91
+ }
92
+
93
+ /**
94
+ * Installs <PACKAGE_NAME>@version globally. Shows npm's output live and
95
+ * explains what to do when it fails.
96
+ * @returns {boolean} success
97
+ */
98
+ function installVersion(version) {
99
+ const { spawnSync } = require('child_process');
100
+ const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm';
101
+ const spec = `${PACKAGE_NAME}@${version}`;
102
+ console.log(`\n${colors.cyan}Installing ${spec} ...${colors.reset}\n`);
103
+ const r = spawnSync(npm, ['install', '-g', spec, '--prefer-online', '--no-fund', '--no-audit'], {
104
+ stdio: ['inherit', 'inherit', 'pipe'],
105
+ encoding: 'utf8',
106
+ shell: process.platform === 'win32'
107
+ });
108
+ if (r.stderr) process.stderr.write(r.stderr);
109
+ if (r.status === 0) return true;
110
+
111
+ console.error(`\n${colors.red}${colors.bold}โœ– Update failed.${colors.reset}`);
112
+ try {
113
+ const { printHint, commands } = require('./doctor');
114
+ const err = new Error((r.error && r.error.message) || r.stderr || 'npm install failed');
115
+ if (r.error && r.error.code) err.code = r.error.code;
116
+ if (/EACCES|EPERM/.test(r.stderr || '')) err.code = 'EACCES';
117
+ const m = (r.stderr || '').match(/path (\S+)/);
118
+ if (m) err.path = m[1];
119
+ printHint(err, 'What to do');
120
+ console.error(` ${colors.dim}Can't update at all? Turn GitSafty off:${colors.reset}`);
121
+ for (const c of commands.removeHooks()) console.error(` ${colors.cyan}${c}${colors.reset}`);
122
+ console.error('');
123
+ } catch (_) {}
124
+ return false;
125
+ }
126
+
127
+ /**
128
+ * Re-runs the freshly installed CLI with the same arguments, then exits.
129
+ */
130
+ function relaunch() {
131
+ const { spawnSync } = require('child_process');
132
+ const cli = path.resolve(__dirname, '..', 'bin', 'cli.js');
133
+ const r = spawnSync(process.execPath, [cli, ...process.argv.slice(2)], {
134
+ stdio: 'inherit',
135
+ env: { ...process.env, GITSAFTY_JUST_UPDATED: '1' }
136
+ });
137
+ process.exit(r.status == null ? 0 : r.status);
138
+ }
139
+
140
+ /**
141
+ * Offers to install a newer version (interactive terminals only).
142
+ * @returns {Promise<boolean>} true if it updated (and relaunched)
143
+ */
144
+ async function offerUpdate(currentVersion, latestVersion) {
145
+ const kind = installKind();
146
+ printUpdateNotification(currentVersion, latestVersion, kind);
147
+ if (!isInteractive() || process.env.GITSAFTY_JUST_UPDATED === '1' || process.env.GITSAFTY_NO_UPDATE_PROMPT === '1') return false;
148
+ if (kind !== 'global') return false;
149
+
150
+ const cache = readCache() || {};
151
+ if (cache.skippedVersion === latestVersion && Date.now() - (cache.skippedAt || 0) < SKIP_PROMPT_MS) return false;
152
+
153
+ const yes = await askYesNo(`${colors.bold}${colors.cyan}? Install GitSafty ${latestVersion} now? (Y/n): ${colors.reset}`);
154
+ if (!yes) {
155
+ writeCache(latestVersion, { skippedVersion: latestVersion, skippedAt: Date.now() });
156
+ console.log(`${colors.dim}OK, I'll ask again tomorrow. Update any time with: gitsafty update${colors.reset}\n`);
157
+ return false;
158
+ }
159
+ if (!installVersion(latestVersion)) return false;
160
+
161
+ console.log(`\n${colors.green}${colors.bold}โœ” Updated to ${latestVersion}.${colors.reset} ${colors.dim}Global hooks were refreshed by the installer.${colors.reset}\n`);
162
+ relaunch();
163
+ return true;
164
+ }
165
+
56
166
  /**
57
167
  * Fetches latest version from npm registry with timeout
58
168
  * @returns {Promise<string | null>}
@@ -81,10 +191,14 @@ async function fetchLatestFromNpm() {
81
191
  * @param {string} currentVersion
82
192
  * @param {string} latestVersion
83
193
  */
84
- function printUpdateNotification(currentVersion, latestVersion) {
194
+ function printUpdateNotification(currentVersion, latestVersion, kind = 'global') {
85
195
  const line1 = ` Update available! ${colors.dim}${currentVersion}${colors.reset} โ†’ ${colors.green}${colors.bold}${latestVersion}${colors.reset}`;
86
- const line2 = ` Run ${colors.cyan}${colors.bold}npm install -g ${PACKAGE_NAME}${colors.reset} to update`;
87
- const line3 = ` Or in project: ${colors.cyan}npm install -D ${PACKAGE_NAME}${colors.reset}`;
196
+ const line2 = kind === 'npx'
197
+ ? ` Run ${colors.cyan}${colors.bold}npx ${PACKAGE_NAME}@latest${colors.reset} to use it`
198
+ : ` Run ${colors.cyan}${colors.bold}npm install -g ${PACKAGE_NAME}@latest${colors.reset} to update`;
199
+ const line3 = kind === 'local-dependency'
200
+ ? ` In this project: ${colors.cyan}npm install -D ${PACKAGE_NAME}@latest${colors.reset}`
201
+ : kind === 'source' ? ` ${colors.dim}(running from a source checkout: git pull to update)${colors.reset}` : ` ${colors.dim}What's new: https://www.npmjs.com/package/${PACKAGE_NAME}${colors.reset}`;
88
202
 
89
203
  console.log(`\n${colors.yellow}โ•ญโ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ”€โ•ฎ${colors.reset}`);
90
204
  console.log(`${colors.yellow}โ”‚${colors.reset}${line1}`);
@@ -97,12 +211,13 @@ function printUpdateNotification(currentVersion, latestVersion) {
97
211
  * Automatically checks for updates (non-blocking, cached)
98
212
  * @param {string} currentVersion
99
213
  */
100
- async function notifyIfUpdateAvailable(currentVersion) {
214
+ async function notifyIfUpdateAvailable(currentVersion, { force = false } = {}) {
215
+ if (process.env.NO_UPDATE_NOTIFIER || process.env.GITSAFTY_JUST_UPDATED === '1') return;
101
216
  const cache = readCache();
102
217
  const now = Date.now();
103
218
 
104
219
  let latestVersion = cache ? cache.latestVersion : null;
105
- const shouldCheckRegistry = !cache || (now - (cache.lastChecked || 0) > CHECK_INTERVAL_MS);
220
+ const shouldCheckRegistry = force || !cache || (now - (cache.lastChecked || 0) > CHECK_INTERVAL_MS);
106
221
 
107
222
  if (shouldCheckRegistry) {
108
223
  const fetched = await fetchLatestFromNpm();
@@ -113,7 +228,7 @@ async function notifyIfUpdateAvailable(currentVersion) {
113
228
  }
114
229
 
115
230
  if (latestVersion && isNewerVersion(currentVersion, latestVersion)) {
116
- printUpdateNotification(currentVersion, latestVersion);
231
+ await offerUpdate(currentVersion, latestVersion);
117
232
  }
118
233
  }
119
234
 
@@ -133,14 +248,67 @@ async function checkUpdateManual(currentVersion) {
133
248
  writeCache(latest);
134
249
 
135
250
  if (isNewerVersion(currentVersion, latest)) {
136
- printUpdateNotification(currentVersion, latest);
251
+ writeCache(latest, { skippedVersion: null });
252
+ await offerUpdate(currentVersion, latest);
137
253
  } else {
138
254
  console.log(`\n${colors.green}${colors.bold}โœ” You are on the latest version! (v${currentVersion})${colors.reset}\n`);
139
255
  }
140
256
  }
141
257
 
258
+ /** Path of the globally installed CLI (after `npm install -g`), or null. */
259
+ function globalCliPath() {
260
+ try {
261
+ const { execFileSync } = require('child_process');
262
+ const npm = process.platform === 'win32' ? 'npm.cmd' : 'npm';
263
+ const root = execFileSync(npm, ['root', '-g'], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 10000, shell: process.platform === 'win32' }).trim();
264
+ const cli = path.join(root, '@arifbiswas', 'git-pre-push', 'bin', 'cli.js');
265
+ return fs.existsSync(cli) ? cli : null;
266
+ } catch (_) {
267
+ return null;
268
+ }
269
+ }
270
+
271
+ /**
272
+ * Called after `npx ... init`: npx only runs GitSafty from a temporary cache,
273
+ * so there is no `gitsafty` command and the hooks point into that cache.
274
+ * Explains this and (interactively) installs GitSafty for real, then
275
+ * re-runs init with the permanent copy so the hooks point there.
276
+ * @param {string[]} initArgs e.g. ['init', '--global']
277
+ */
278
+ async function offerPermanentInstall(initArgs) {
279
+ if (installKind() !== 'npx') return;
280
+ const isWin = process.platform === 'win32';
281
+ console.log(`${colors.yellow}${colors.bold}โš  You ran GitSafty with npx.${colors.reset}`);
282
+ console.log(` npx only runs it from a temporary cache: the ${colors.bold}gitsafty${colors.reset} command is not installed,`);
283
+ console.log(` and the hooks point into that cache, which npm may delete later.`);
284
+ console.log(` ${colors.dim}Install it permanently:${colors.reset} ${colors.cyan}npm install -g ${PACKAGE_NAME}${colors.reset} ${colors.dim}then${colors.reset} ${colors.cyan}gitsafty ${initArgs.join(' ')}${colors.reset}\n`);
285
+
286
+ if (!isInteractive() || process.env.GITSAFTY_NO_UPDATE_PROMPT === '1') return;
287
+ const yes = await askYesNo(`${colors.bold}${colors.cyan}? Install GitSafty permanently now (adds the gitsafty command)? (Y/n): ${colors.reset}`);
288
+ if (!yes) return;
289
+ if (!installVersion('latest')) return;
290
+
291
+ const cli = globalCliPath();
292
+ if (!cli) {
293
+ console.log(`${colors.yellow}Installed, but could not locate the global copy. Run: gitsafty ${initArgs.join(' ')}${colors.reset}\n`);
294
+ return;
295
+ }
296
+ const { spawnSync } = require('child_process');
297
+ spawnSync(process.execPath, [cli, ...initArgs], { stdio: 'inherit', env: { ...process.env, GITSAFTY_JUST_UPDATED: '1' } });
298
+ console.log(`${colors.green}${colors.bold}โœ” Done.${colors.reset} Open a ${colors.bold}new${colors.reset} terminal${isWin ? ' window' : ''} and type ${colors.cyan}gitsafty${colors.reset}.`);
299
+ if (isWin) {
300
+ console.log(` ${colors.dim}Still "not recognized"? Add npm's folder to PATH: run ${colors.reset}${colors.cyan}npm config get prefix${colors.reset}${colors.dim} and add that folder in`);
301
+ console.log(` Settings > System > About > Advanced system settings > Environment Variables > Path.${colors.reset}`);
302
+ }
303
+ console.log('');
304
+ }
305
+
142
306
  module.exports = {
143
307
  isNewerVersion,
308
+ offerPermanentInstall,
309
+ globalCliPath,
310
+ installKind,
311
+ offerUpdate,
144
312
  notifyIfUpdateAvailable,
145
313
  checkUpdateManual,
146
314
  printUpdateNotification
package/src/vault.js CHANGED
@@ -511,6 +511,10 @@ function runCredentialHelper(operation, inputText, out = process.stdout) {
511
511
  token = unlockVault(vault, `log in ${who} for one git command in "${repo}"`);
512
512
  } catch (err) {
513
513
  process.stderr.write(`GitSafty Vault: ${err.message}. Staying logged out.\n`);
514
+ try {
515
+ const hint = require('./doctor').hintForError(err);
516
+ process.stderr.write(` What to do: ${hint.problem}\n${hint.commands.map(c => ` ${c}\n`).join('')}`);
517
+ } catch (_) {}
514
518
  notify('GitSafty Vault: login refused', `A git command in "${repo}" asked for your GitHub login and was refused. If you did not start it, your PC may be compromised.`);
515
519
  out.write('quit=1\n\n');
516
520
  return 0;
package/src/vaultCli.js CHANGED
@@ -3,6 +3,7 @@
3
3
  */
4
4
 
5
5
  const { colors } = require('./reporter');
6
+ const { printHint } = require('./doctor');
6
7
 
7
8
  /**
8
9
  * @param {string} sub setup | status | test | remove
@@ -16,7 +17,8 @@ async function runVaultCommand(sub = 'status', { host, passphrase = false } = {}
16
17
  if (sub === 'setup' || sub === 'on' || sub === 'enable') {
17
18
  const res = await vault.setupVault({ host: host || 'github.com', mode: passphrase ? 'passphrase' : 'auto' });
18
19
  if (!res.success) {
19
- console.error(`\n${colors.red}${colors.bold}โœ– ${res.message}${colors.reset}\n`);
20
+ console.error(`\n${colors.red}${colors.bold}โœ– ${res.message}${colors.reset}`);
21
+ printHint(new Error(res.message));
20
22
  return 1;
21
23
  }
22
24
  console.log(`\n${colors.green}${colors.bold}โœ” ${res.message}${colors.reset}`);
@@ -32,6 +34,7 @@ async function runVaultCommand(sub = 'status', { host, passphrase = false } = {}
32
34
  if (sub === 'test') {
33
35
  const res = vault.testUnlock();
34
36
  console.log(`\n${res.success ? colors.green + 'โœ”' : colors.red + 'โœ–'} ${res.message}${colors.reset}\n`);
37
+ if (!res.success) printHint(new Error(res.message));
35
38
  return res.success ? 0 : 1;
36
39
  }
37
40