@arifbiswas/git-pre-push 1.0.19 → 1.0.21

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/bin/cli.js CHANGED
@@ -23,29 +23,24 @@ const args = process.argv.slice(2);
23
23
  const command = args[0] ? args[0].toLowerCase() : 'menu';
24
24
  const isGlobalFlag = args.includes('--global') || args.includes('-g');
25
25
 
26
- /** After a global install: offer the shell function that scans every git pull. */
27
- async function offerPullScan() {
26
+ /** After a global install: pull scan is on by default (also "Already up to date" pulls). */
27
+ function enablePullScan() {
28
28
  const shell = require('../src/shellIntegration');
29
29
  if (shell.shellIntegrationStatus().installed.length) {
30
30
  shell.installShellIntegration(); // refresh with this version's paths
31
+ console.log(`${colors.green}✔ Every git pull is scanned${colors.reset} ${colors.dim}(also "Already up to date"). Turn off: gitsafty pull-scan off${colors.reset}\n`);
31
32
  return;
32
33
  }
33
- const interactive = process.stdin.isTTY && process.stdout.isTTY && !process.env.CI;
34
- console.log(`${colors.dim}git runs no hook when a pull is "Already up to date". To scan after EVERY git pull,${colors.reset}`);
35
- console.log(`${colors.dim}GitSafty can add a small git function to your shell profile (.zshrc / .bashrc / PowerShell profile).${colors.reset}`);
36
- if (!interactive) {
37
- console.log(` Turn it on: ${colors.cyan}gitsafty pull-scan on${colors.reset}\n`);
34
+ if (shell.isOptedOut()) {
35
+ console.log(`${colors.dim}Pull scan for "Already up to date" pulls is off (you turned it off). Turn on: gitsafty pull-scan on${colors.reset}\n`);
38
36
  return;
39
37
  }
40
- const readline = require('readline');
41
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
42
- const answer = await new Promise(r => rl.question(`${colors.bold}${colors.cyan}? Scan after every git pull? (Y/n): ${colors.reset}`, a => { rl.close(); r(a.trim()); }));
43
- if (/^n(o)?$/i.test(answer)) {
44
- console.log(` ${colors.dim}Skipped. Turn it on later: gitsafty pull-scan on${colors.reset}\n`);
45
- return;
38
+ const files = shell.enableByDefault();
39
+ if (files.length) {
40
+ console.log(`${colors.green}✔ Every git pull is scanned${colors.reset} ${colors.dim}(also "Already up to date"; added to ${files.join(', ')}).${colors.reset}`);
41
+ console.log(` ${colors.dim}Load it now:${colors.reset} ${colors.cyan}${shell.reloadHint()}${colors.reset}`);
42
+ console.log(` ${colors.dim}Turn off: gitsafty pull-scan off${colors.reset}\n`);
46
43
  }
47
- const res = shell.installShellIntegration();
48
- console.log(`${colors.green}✔ Pull scan on${colors.reset} ${colors.dim}(${res.files.join(', ')})${colors.reset}. Load it now: ${colors.cyan}${shell.reloadHint()}${colors.reset}\n`);
49
44
  }
50
45
 
51
46
  async function main() {
@@ -56,10 +51,19 @@ async function main() {
56
51
  if (command !== 'credential' && process.env.GITSAFTY_NO_SELF_REFRESH !== '1') {
57
52
  try {
58
53
  const refreshed = require('../src/installer').refreshOutdatedHooks();
59
- const shells = require('../src/shellIntegration').refreshShellIntegration();
54
+ const shell = require('../src/shellIntegration');
55
+ const shells = shell.refreshShellIntegration();
60
56
  if ((refreshed.length || shells.length) && !hookCommands.includes(command)) {
61
57
  console.log(`${colors.green}✔ GitSafty ${pkg.version}: updated ${[...refreshed.map(t => `${t} hook`), ...shells.map(f => require('path').basename(f))].join(', ')} to this version.${colors.reset}`);
62
58
  }
59
+ // Pull scan is on by default: existing global installs get it on update too
60
+ // (only from the real global copy, and never if the user turned it off).
61
+ if (require('../src/installer').isPermanentGlobalInstall()) {
62
+ const added = shell.enableByDefault({ onlyIfGlobalHooks: true });
63
+ if (added.length && !hookCommands.includes(command)) {
64
+ console.log(`${colors.green}✔ Every git pull is now scanned${colors.reset} ${colors.dim}(also "Already up to date"; ${added.map(f => require('path').basename(f)).join(', ')}). Open a new terminal. Turn off: gitsafty pull-scan off${colors.reset}`);
65
+ }
66
+ }
63
67
  } catch (_) {}
64
68
  }
65
69
 
@@ -210,14 +214,14 @@ async function main() {
210
214
  console.log(` Load it now: ${colors.cyan}${shell.reloadHint()}${colors.reset}\n`);
211
215
  }
212
216
  } else if (sub === 'off' || sub === 'remove' || sub === 'disable') {
213
- const res = shell.removeShellIntegration();
214
- console.log(`\n${colors.yellow}${colors.bold}✔ Pull scan shell function removed${res.files.length ? ` from ${res.files.join(', ')}` : ' (was not installed)'}.${colors.reset}`);
215
- console.log(` ${colors.dim}Open a new terminal to finish. Pulls that bring changes are still scanned by the git hooks.${colors.reset}\n`);
217
+ const res = shell.removeShellIntegration({ optOut: true });
218
+ console.log(`\n${colors.yellow}${colors.bold}✔ Pull scan turned off${res.files.length ? ` (removed from ${res.files.join(', ')})` : ''}. GitSafty will not turn it on again by itself.${colors.reset}`);
219
+ console.log(` ${colors.dim}Open a new terminal to finish. Pulls that bring changes are still scanned by the git hooks. Turn on again: gitsafty pull-scan on${colors.reset}\n`);
216
220
  } else {
217
221
  const st = shell.shellIntegrationStatus();
218
222
  console.log(st.installed.length
219
223
  ? `\n${colors.green}✔ Pull scan is ON${colors.reset} ${colors.dim}(${st.installed.join(', ')})${colors.reset}\n`
220
- : `\n${colors.yellow}Pull scan shell function is OFF.${colors.reset} Pulls that bring changes are still scanned by the git hooks.\n Turn on scanning for every pull: ${colors.cyan}gitsafty pull-scan on${colors.reset}\n`);
224
+ : `\n${colors.yellow}Pull scan is OFF${st.optedOut ? ' (you turned it off)' : ''}.${colors.reset} Pulls that bring changes are still scanned by the git hooks.\n Turn on scanning for every pull: ${colors.cyan}gitsafty pull-scan on${colors.reset}\n`);
221
225
  }
222
226
  break;
223
227
  }
@@ -340,6 +344,7 @@ async function main() {
340
344
  console.log(`\n${colors.green}${colors.bold}✔ ${result.message}${colors.reset}\n`);
341
345
  console.log(`${colors.cyan}Your git environment is now protected!${colors.reset}`);
342
346
  console.log(`${colors.dim}Every git push, clone and pull${isGlobalFlag ? ' on this PC' : ' in this repository'} is scanned for malware & secret leaks.${colors.reset}\n`);
347
+ if (isGlobalFlag) enablePullScan();
343
348
  const { offerPermanentInstall } = require('../src/updateNotifier');
344
349
  // npx copy: re-run the same init globally. Project copy: protect the whole PC.
345
350
  await offerPermanentInstall(['init', '--global']);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arifbiswas/git-pre-push",
3
- "version": "1.0.19",
3
+ "version": "1.0.21",
4
4
  "description": "Zero-dependency pre-push security guard that stops malware, injected scripts, and leaked secrets from reaching GitHub.",
5
5
  "main": "src/index.js",
6
6
  "bin": {
package/src/doctor.js CHANGED
@@ -224,8 +224,10 @@ function runChecks({ cwd = process.cwd(), cliPath } = {}) {
224
224
  try {
225
225
  const shell = require('./shellIntegration');
226
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'] });
227
+ if (!st.installed.length && st.optedOut) {
228
+ checks.push({ id: 'pull-scan', ok: true, level: 'ok', title: 'Pull scan for "Already up to date" pulls is off (you turned it off)', commands: ['gitsafty pull-scan on'] });
229
+ } else if (!st.installed.length) {
230
+ checks.push({ id: 'pull-scan', ok: true, level: 'warn', title: 'Pulls that are "Already up to date" are not scanned (on by default, but not set up here)', commands: ['gitsafty pull-scan on'], fix: () => shell.installShellIntegration() });
229
231
  } else {
230
232
  checks.push({ id: 'pull-scan', ok: true, level: 'ok', title: `Every git pull is scanned (${st.installed.join(', ')})`, fix: () => shell.installShellIntegration() });
231
233
  }
@@ -0,0 +1,262 @@
1
+ /**
2
+ * .env guard for git push.
3
+ *
4
+ * A .env file must never reach the remote. When a push contains one:
5
+ * 1. The push is blocked.
6
+ * 2. .env patterns are added to .gitignore (examples/templates stay allowed).
7
+ * 3. The .env file is removed from every commit that is not on the remote yet
8
+ * (only local, unpushed commits are rewritten, so no force push is needed).
9
+ * The file itself stays on your disk, now ignored.
10
+ * 4. .env that git still tracks ("cached", even if .gitignore lists it) is
11
+ * untracked with `git rm --cached`, and the .gitignore change is committed.
12
+ * 5. The cleaned branch is pushed right away (the original push, which still
13
+ * had the .env, is the one git reports as failed).
14
+ *
15
+ * Rewriting uses git plumbing on a temporary index, so it works with
16
+ * uncommitted changes in the working tree and never touches them.
17
+ * Merge commits in the unpushed range are not rewritten: the user gets the
18
+ * exact commands instead.
19
+ */
20
+
21
+ const fs = require('fs');
22
+ const os = require('os');
23
+ const path = require('path');
24
+ const { spawnSync } = require('child_process');
25
+
26
+ const ZERO_OID = '0000000000000000000000000000000000000000';
27
+ const GITIGNORE_LINES = ['.env', '.env.*', '!.env.example', '!.env.sample', '!.env.template', '!.env.dist', '!.env.defaults'];
28
+
29
+ /** True for .env, .env.local, .env.production …, but not for examples / templates. */
30
+ function isEnvFile(filePath) {
31
+ const base = String(filePath).replace(/\\/g, '/').split('/').pop().toLowerCase();
32
+ if (!/^\.env(\.[^/]+)?$/.test(base)) return false;
33
+ return !/(example|sample|template|dist|defaults?|schema)/.test(base);
34
+ }
35
+
36
+ function git(args, cwd, opts = {}) {
37
+ const r = spawnSync('git', args, { cwd, encoding: 'utf8', maxBuffer: 256 * 1024 * 1024, ...opts });
38
+ return { ok: r.status === 0, out: (r.stdout || '').toString(), err: (r.stderr || '').toString() };
39
+ }
40
+
41
+ function must(args, cwd, opts) {
42
+ const r = git(args, cwd, opts);
43
+ if (!r.ok) throw new Error(`git ${args.join(' ')}: ${r.err.trim()}`);
44
+ return r.out;
45
+ }
46
+
47
+ function lines(text) {
48
+ return text.split(/\r?\n/).map(s => s.trim()).filter(Boolean);
49
+ }
50
+
51
+ /** Commits being pushed that the remote does not have yet, oldest first. */
52
+ function unpushedCommits(localOid, cwd) {
53
+ const r = git(['rev-list', '--reverse', '--topo-order', localOid, '--not', '--remotes'], cwd);
54
+ return r.ok ? lines(r.out) : [];
55
+ }
56
+
57
+ /** .env files the push would put on the remote (in the pushed tip, or added by an unpushed commit). */
58
+ function envFilesInPush(push, cwd) {
59
+ const found = new Set();
60
+ for (const f of lines(git(['ls-tree', '-r', '--name-only', push.localOid], cwd).out)) {
61
+ if (isEnvFile(f)) found.add(f);
62
+ }
63
+ const commits = unpushedCommits(push.localOid, cwd);
64
+ if (commits.length) {
65
+ const r = git(['log', '--format=', '--name-only', '--diff-filter=ACMR', push.localOid, '--not', '--remotes'], cwd);
66
+ for (const f of lines(r.out)) if (isEnvFile(f)) found.add(f);
67
+ }
68
+ return [...found];
69
+ }
70
+
71
+ function tmpIndex() {
72
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gitsafty-idx-'));
73
+ return { file: path.join(dir, 'index'), done: () => fs.rmSync(dir, { recursive: true, force: true }) };
74
+ }
75
+
76
+ /** Raw commit -> { tree, parents, author, committer, message } */
77
+ function readCommit(oid, cwd) {
78
+ const raw = must(['cat-file', 'commit', oid], cwd);
79
+ const split = raw.indexOf('\n\n');
80
+ const header = raw.slice(0, split);
81
+ const message = raw.slice(split + 2);
82
+ const get = (k) => (header.match(new RegExp(`^${k} (.*)$`, 'm')) || [])[1];
83
+ const parents = [...header.matchAll(/^parent (\S+)$/gm)].map(m => m[1]);
84
+ return { tree: get('tree'), parents, author: get('author'), committer: get('committer'), message, signed: /^gpgsig /m.test(header) };
85
+ }
86
+
87
+ function identityEnv(ident, prefix) {
88
+ const m = String(ident).match(/^(.*) <(.*)> (\d+ [+-]\d{4})$/);
89
+ if (!m) return {};
90
+ return { [`GIT_${prefix}_NAME`]: m[1], [`GIT_${prefix}_EMAIL`]: m[2], [`GIT_${prefix}_DATE`]: m[3] };
91
+ }
92
+
93
+ /** Tree of `oid` without the given paths. */
94
+ function treeWithout(treeish, files, cwd) {
95
+ const idx = tmpIndex();
96
+ try {
97
+ const env = { ...process.env, GIT_INDEX_FILE: idx.file };
98
+ must(['read-tree', treeish], cwd, { env });
99
+ must(['rm', '--cached', '--ignore-unmatch', '-q', '--', ...files], cwd, { env });
100
+ return must(['write-tree'], cwd, { env }).trim();
101
+ } finally {
102
+ idx.done();
103
+ }
104
+ }
105
+
106
+ /**
107
+ * Rewrites the unpushed commits of `ref` without `files`.
108
+ * @returns {{ ok: boolean, newTip?: string, rewritten?: number, dropped?: number, reason?: string, signed?: boolean }}
109
+ */
110
+ function rewriteUnpushed(ref, localOid, files, cwd) {
111
+ const commits = unpushedCommits(localOid, cwd);
112
+ if (!commits.length) return { ok: true, newTip: localOid, rewritten: 0, dropped: 0 };
113
+ const map = new Map();
114
+ let dropped = 0;
115
+ let signed = false;
116
+ for (const oid of commits) {
117
+ const c = readCommit(oid, cwd);
118
+ if (c.parents.length > 1) return { ok: false, reason: 'merge commits in the unpushed range' };
119
+ signed = signed || c.signed;
120
+ const parent = c.parents[0] ? (map.get(c.parents[0]) || c.parents[0]) : null;
121
+ const tree = treeWithout(oid, files, cwd);
122
+ const parentTree = parent ? must(['rev-parse', `${parent}^{tree}`], cwd).trim() : null;
123
+ const origParentTree = c.parents[0] ? must(['rev-parse', `${c.parents[0]}^{tree}`], cwd).trim() : null;
124
+ // A commit that only added the .env file becomes empty: drop it.
125
+ if (parent && tree === parentTree && c.tree !== origParentTree) {
126
+ map.set(oid, parent);
127
+ dropped++;
128
+ continue;
129
+ }
130
+ const env = { ...process.env, ...identityEnv(c.author, 'AUTHOR'), ...identityEnv(c.committer, 'COMMITTER') };
131
+ const args = ['commit-tree', tree];
132
+ if (parent) args.push('-p', parent);
133
+ const newOid = must(args, cwd, { env, input: c.message }).trim();
134
+ map.set(oid, newOid);
135
+ }
136
+ const newTip = map.get(localOid);
137
+ must(['update-ref', '-m', 'GitSafty: remove .env from unpushed commits', ref, newTip, localOid], cwd);
138
+ return { ok: true, newTip, rewritten: commits.length - dropped, dropped, signed };
139
+ }
140
+
141
+ /** Lines of GITIGNORE_LINES that .gitignore does not have yet. */
142
+ function missingIgnoreLines(text) {
143
+ const have = new Set(lines(text));
144
+ return GITIGNORE_LINES.filter(l => !have.has(l));
145
+ }
146
+
147
+ function appendLines(text, add) {
148
+ if (!add.length) return text;
149
+ const base = text && !text.endsWith('\n') ? text + '\n' : text;
150
+ return `${base}${base ? '\n' : ''}# Environment files: never commit (added by GitSafty)\n${add.join('\n')}\n`;
151
+ }
152
+
153
+ /**
154
+ * Commits the .gitignore update on top of `ref` (only for the checked-out branch),
155
+ * and updates the working tree / index copy without touching other changes.
156
+ */
157
+ function commitGitignore(ref, cwd, files = []) {
158
+ const head = must(['rev-parse', ref], cwd).trim();
159
+ const inHead = git(['show', `${head}:.gitignore`], cwd);
160
+ const headText = inHead.ok ? inHead.out : '';
161
+ const add = missingIgnoreLines(headText);
162
+
163
+ // Working tree copy (may contain the user's own unstaged edits: keep them).
164
+ const wtFile = path.join(cwd, '.gitignore');
165
+ const wtText = fs.existsSync(wtFile) ? fs.readFileSync(wtFile, 'utf8') : '';
166
+ const wtAdd = missingIgnoreLines(wtText);
167
+ if (wtAdd.length) fs.writeFileSync(wtFile, appendLines(wtText, wtAdd));
168
+ // .env files still in the tip (e.g. pushed earlier): this commit removes them too.
169
+ const stillThere = lines(git(['ls-tree', '-r', '--name-only', head, '--', ...files], cwd).out);
170
+ if (!add.length && !stillThere.length) return null;
171
+
172
+ const blob = must(['hash-object', '-w', '--stdin'], cwd, { input: appendLines(headText, add) }).trim();
173
+ const idx = tmpIndex();
174
+ let commit;
175
+ try {
176
+ const env = { ...process.env, GIT_INDEX_FILE: idx.file };
177
+ must(['read-tree', head], cwd, { env });
178
+ if (stillThere.length) must(['rm', '--cached', '-q', '--', ...stillThere], cwd, { env });
179
+ if (add.length) must(['update-index', '--add', '--cacheinfo', `100644,${blob},.gitignore`], cwd, { env });
180
+ const tree = must(['write-tree'], cwd, { env }).trim();
181
+ const msg = stillThere.length ? 'chore: stop tracking .env files' : 'chore: never commit .env files';
182
+ commit = must(['commit-tree', tree, '-p', head], cwd, { input: `${msg}\n\nAdded by GitSafty: .env files are ignored and kept out of git.\n` }).trim();
183
+ } finally {
184
+ idx.done();
185
+ }
186
+ must(['update-ref', '-m', 'GitSafty: ignore .env files', ref, commit, head], cwd);
187
+
188
+ // Real index: if it had HEAD's .gitignore (nothing staged there), move it to the new one.
189
+ const staged = git(['ls-files', '-s', '--', '.gitignore'], cwd).out.split(/\s+/)[1];
190
+ const oldBlob = inHead.ok ? must(['rev-parse', `${head}:.gitignore`], cwd).trim() : undefined;
191
+ if (add.length && (staged === oldBlob || (!staged && !oldBlob))) {
192
+ must(['update-index', '--add', '--cacheinfo', `100644,${blob},.gitignore`], cwd);
193
+ }
194
+ return commit;
195
+ }
196
+
197
+ /**
198
+ * Runs the guard for a pre-push.
199
+ * @param {Array<{localRef, localOid, remoteRef, remoteOid}>} pushes
200
+ * @returns {{ blocked: boolean, files: string[], fixes: string[], manual: string[], alreadyOnRemote: boolean, repush: Array<{ref, remoteRef}> }}
201
+ */
202
+ function guardEnvOnPush(pushes, cwd = process.cwd()) {
203
+ const result = { blocked: false, files: [], fixes: [], manual: [], alreadyOnRemote: false, repush: [] };
204
+ const currentRef = git(['symbolic-ref', '-q', 'HEAD'], cwd).out.trim();
205
+
206
+ for (const push of pushes) {
207
+ if (!push || push.localOid === ZERO_OID) continue;
208
+ const files = envFilesInPush(push, cwd);
209
+ if (!files.length) continue;
210
+ result.blocked = true;
211
+ result.files.push(...files.filter(f => !result.files.includes(f)));
212
+
213
+ if (push.remoteOid && push.remoteOid !== ZERO_OID && git(['cat-file', '-e', push.remoteOid], cwd).ok) {
214
+ const onRemote = lines(git(['ls-tree', '-r', '--name-only', push.remoteOid], cwd).out).filter(isEnvFile);
215
+ if (onRemote.length) result.alreadyOnRemote = true;
216
+ }
217
+
218
+ const ref = push.localRef;
219
+ const refNow = ref.startsWith('refs/heads/') ? git(['rev-parse', '-q', '--verify', ref], cwd).out.trim() : '';
220
+ if (!ref.startsWith('refs/heads/') || refNow !== push.localOid) {
221
+ result.manual.push(`Pushed ${push.localRef || push.localOid} is not a local branch tip, so it was not rewritten. Remove the file: git rm --cached ${files.map(f => `"${f}"`).join(' ')} && git commit --amend`);
222
+ continue;
223
+ }
224
+
225
+ const rw = rewriteUnpushed(ref, push.localOid, files, cwd);
226
+ if (!rw.ok) {
227
+ result.manual.push(`Could not rewrite ${ref.replace('refs/heads/', '')} automatically (${rw.reason}). Run: git rm --cached ${files.map(f => `"${f}"`).join(' ')} && git commit -m "Remove .env" ; then remove it from history with git rebase -i or git filter-repo`);
228
+ continue;
229
+ }
230
+ if (rw.rewritten || rw.dropped) {
231
+ result.fixes.push(`Removed ${files.join(', ')} from ${rw.rewritten + rw.dropped} unpushed commit(s) on ${ref.replace('refs/heads/', '')}${rw.dropped ? ` (${rw.dropped} commit(s) that only added it were dropped)` : ''}. New commit ids.`);
232
+ if (rw.signed) result.fixes.push('Some of those commits were GPG/SSH signed; the rewritten ones are not signed anymore.');
233
+ }
234
+
235
+ if (ref === currentRef) {
236
+ // Keep the files on disk, but out of the index.
237
+ const tracked = lines(git(['ls-files', '--', ...files], cwd).out);
238
+ if (tracked.length) must(['rm', '--cached', '-q', '--', ...tracked], cwd);
239
+ if (commitGitignore(ref, cwd, files)) result.fixes.push('Added .env patterns to .gitignore and committed it.');
240
+ else result.fixes.push('.gitignore already ignores .env files.');
241
+ } else {
242
+ const left = lines(git(['ls-tree', '-r', '--name-only', ref, '--', ...files], cwd).out);
243
+ if (left.length) {
244
+ result.manual.push(`${ref.replace('refs/heads/', '')} is not checked out. Switch to it and push again, GitSafty will finish the fix: git switch ${ref.replace('refs/heads/', '')}`);
245
+ continue;
246
+ }
247
+ }
248
+ // Fully fixed: safe to push the cleaned branch.
249
+ result.repush.push({ ref, remoteRef: push.remoteRef });
250
+ }
251
+ if (result.blocked && result.files.length) {
252
+ result.fixes.push(`Your ${result.files.join(', ')} is still on your disk, now ignored by git.`);
253
+ }
254
+ return result;
255
+ }
256
+
257
+ module.exports = {
258
+ isEnvFile,
259
+ guardEnvOnPush,
260
+ envFilesInPush,
261
+ GITIGNORE_LINES
262
+ };
package/src/index.js CHANGED
@@ -259,6 +259,46 @@ async function runPrePush() {
259
259
 
260
260
  const pushes = parsePrePushInput(stdinData);
261
261
 
262
+ // .env must never reach the remote: block, then fix (ignore + remove from unpushed commits).
263
+ if (pushes.length && loadConfig(process.cwd()).envGuard !== false) {
264
+ const { guardEnvOnPush } = require('./envGuard');
265
+ let env;
266
+ try {
267
+ env = guardEnvOnPush(pushes, process.cwd());
268
+ } catch (err) {
269
+ env = { blocked: true, files: ['.env'], fixes: [], manual: [`Automatic fix failed (${err.message}). Run: git rm --cached .env && echo .env >> .gitignore && git commit -am "Remove .env"`] };
270
+ }
271
+ if (env.blocked) {
272
+ console.log(`\n${colors.red}${colors.bold}✖ PUSH BLOCKED: .env file in this push${colors.reset} ${colors.dim}(${env.files.join(', ')})${colors.reset}`);
273
+ console.log(`${colors.dim}.env files hold passwords and API keys. GitSafty never lets them reach the remote.${colors.reset}\n`);
274
+ for (const f of env.fixes) console.log(` ${colors.green}✔${colors.reset} ${f}`);
275
+ for (const m of env.manual) console.log(` ${colors.yellow}⚠${colors.reset} ${m}`);
276
+ if (env.alreadyOnRemote) {
277
+ console.log(` ${colors.yellow}⚠ The remote already had a .env from an earlier push. This push removes it, but it is still in the remote's history: change (rotate) every key in it.${colors.reset}`);
278
+ }
279
+ // Push the cleaned commits now (once; the inner push runs the hooks again).
280
+ const remote = process.argv[3];
281
+ const config = loadConfig(process.cwd());
282
+ let pushed = false;
283
+ if (remote && !env.manual.length && env.repush.length && !process.env.GITSAFTY_ENV_REPUSH && config.envGuardAutoPush !== false) {
284
+ console.log(`\n${colors.cyan}Pushing the fixed commits (without .env) to ${remote}...${colors.reset}`);
285
+ const r = require('child_process').spawnSync('git', ['push', remote, ...env.repush.map(p => `${p.ref}:${p.remoteRef}`)], {
286
+ stdio: 'inherit',
287
+ env: { ...process.env, GITSAFTY_ENV_REPUSH: '1' }
288
+ });
289
+ pushed = r.status === 0;
290
+ }
291
+ if (pushed) {
292
+ console.log(`\n${colors.green}${colors.bold}✔ Fixed and pushed without .env.${colors.reset}`);
293
+ console.log(`${colors.dim}Git prints "failed to push" below for the ORIGINAL push (the one with .env). That one was stopped on purpose; your code is on the remote.${colors.reset}\n`);
294
+ } else {
295
+ console.log(`\n${colors.bold}Now run ${colors.cyan}git push${colors.reset}${colors.bold} again.${colors.reset}${env.manual.length ? '' : ' Nothing else to do.'}\n`);
296
+ }
297
+ notifyDesktop('GitSafty: .env blocked', pushed ? '.env was removed and your code was pushed without it.' : `.env was kept out of the push${env.manual.length ? '' : ' and fixed automatically'}.`);
298
+ process.exit(1);
299
+ }
300
+ }
301
+
262
302
  let allFiles = [];
263
303
  let combinedDiff = '';
264
304
 
package/src/menu.js CHANGED
@@ -25,38 +25,38 @@ function ask(question) {
25
25
  async function runInteractiveMenu() {
26
26
  banner();
27
27
 
28
- const item = (n, icon, title, desc) =>
29
- console.log(` ${colors.green}[${n}]${colors.reset}${String(n).length === 1 ? ' ' : ''} ${icon} ${colors.bold}${title.padEnd(24)}${colors.reset} - ${desc}`);
30
- const section = (title) => console.log(`\n ${colors.dim}── ${title} ──${colors.reset}`);
31
-
32
- console.log(`\n${colors.bold}${colors.cyan}Select an action to perform:${colors.reset}`);
33
-
34
- section('Protection');
35
- item(1, '🛡️ ', 'Install Local Hook', 'Protect current repo (push + checkout + pull)');
36
- item(2, '🌐', 'Install Global Hook', 'Protect EVERY repo on this PC: scan on clone, pull & push');
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)');
39
-
40
- section('Malware scan & removal');
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');
43
- item(18, '🧪', 'Full Scan', 'EVERYTHING in a folder: non-git projects + zip/tar/7z/rar');
44
- item(10, '🧹', 'Sweep All Repos', 'Scan every git repo in a folder (whole device)');
45
- item(5, '🗑️ ', 'Clean & Quarantine', 'Remove confirmed malware + trojan scripts here');
46
- item(4, '🚀', 'Scan Remote GitHub Repo', 'Zero-clone audit (no download/clone)');
47
-
48
- section('GitHub login vault (device stays logged out)');
49
- item(11, '🔐', 'Vault Setup', 'Encrypt token with Touch ID / Windows Hello / passphrase');
50
- item(12, '📋', 'Vault Status', 'Check vault, credential helper & SSH keys');
51
- item(13, '🔓', 'Vault Test Unlock', 'Try one unlock prompt (token is not used)');
52
- item(14, '🚫', 'Vault Remove', 'Back to normal git login');
53
-
54
- section('Other');
55
- item(6, '⚡', 'Run Push Intercept Demo', 'Simulate a blocked malware push');
56
- item(7, '🤖', 'Setup GitHub Action CI', 'Guard repository on GitHub server-side');
57
- item(9, '🔄', 'Check for Updates', 'Check if a new version is available on npm');
58
- item(15, '🩺', 'Doctor', 'Something broken? Find it and show/apply the fix');
59
- console.log(` ${colors.dim}[0] 🚪 Exit${colors.reset}\n`);
28
+ const item = (n, title, desc) =>
29
+ console.log(` ${colors.green}${String(n).padStart(2)}.${colors.reset} ${colors.bold}${title.padEnd(34)}${colors.reset} ${colors.dim}${desc}${colors.reset}`);
30
+ const section = (title) => console.log(`\n ${colors.cyan}${title}${colors.reset}`);
31
+
32
+ console.log(`\n${colors.bold}What do you want to do?${colors.reset}`);
33
+
34
+ section('Protect your code');
35
+ item(1, 'Protect this project', 'Check every push, clone and pull in this project');
36
+ item(2, 'Protect all projects on this PC', 'Same, for every git project on this computer');
37
+ item(3, 'Scan every git pull', 'On by default, also "Already up to date". Turn off/on');
38
+ item(4, 'Remove protection', 'Uninstall GitSafty from this project or this PC');
39
+
40
+ section('Scan and clean');
41
+ item(5, 'Scan this project', 'Find malware here and remove it automatically');
42
+ item(6, 'Scan all projects in a folder', 'Malware, hidden backdoors and leaked passwords/keys');
43
+ item(7, 'Scan everything in a folder', 'Also zip/rar files and folders that are not git projects');
44
+ item(8, 'Scan all git repos under a folder', 'Quick malware check, e.g. your whole disk');
45
+ item(9, 'Clean this project', 'Move malware files in this project to quarantine');
46
+ item(10, 'Scan a GitHub repo before cloning', 'Check a GitHub link without downloading it');
47
+
48
+ section('Safe GitHub login (stay logged out)');
49
+ item(11, 'Turn on safe GitHub login', 'Touch ID / Windows Hello / password before every push');
50
+ item(12, 'Check safe login status', 'See if your GitHub login is protected');
51
+ item(13, 'Test safe login', 'Try the unlock prompt once');
52
+ item(14, 'Turn off safe login', 'Go back to normal git login');
53
+
54
+ section('Help and tools');
55
+ item(15, 'Fix problems', 'Find what is broken and how to fix it');
56
+ item(16, 'Check for updates', 'Install the newest GitSafty');
57
+ item(17, 'Add GitSafty to GitHub Actions', 'Check every push on GitHub too');
58
+ item(18, 'See a demo', 'Show what a blocked push looks like');
59
+ console.log(`\n ${colors.dim} 0. Exit${colors.reset}\n`);
60
60
 
61
61
  const rl = readline.createInterface({
62
62
  input: process.stdin,
@@ -64,7 +64,7 @@ async function runInteractiveMenu() {
64
64
  });
65
65
 
66
66
  const choice = await new Promise((resolve) => {
67
- rl.question(`${colors.bold}${colors.yellow}Enter your choice (1-18, 0 to exit): ${colors.reset}`, (ans) => {
67
+ rl.question(`${colors.bold}${colors.yellow}Enter a number (0-18): ${colors.reset}`, (ans) => {
68
68
  rl.close();
69
69
  resolve(ans.trim());
70
70
  });
@@ -87,18 +87,24 @@ async function runInteractiveMenu() {
87
87
  const res = installHook(process.cwd(), true);
88
88
  if (res.success) {
89
89
  console.log(`\n${colors.green}${colors.bold}✔ ${res.message}${colors.reset}\n`);
90
+ // Pull scan is on by default (unless the user turned it off before).
91
+ const shell = require('./shellIntegration');
92
+ const added = shell.enableByDefault();
93
+ if (added.length) {
94
+ console.log(`${colors.green}✔ Every git pull is scanned${colors.reset} ${colors.dim}(also "Already up to date"). Open a new terminal. Turn off: option 3${colors.reset}\n`);
95
+ }
90
96
  } else {
91
97
  console.error(`\n${colors.red}${colors.bold}✖ ${res.message}${colors.reset}\n`);
92
98
  }
93
99
  break;
94
100
  }
95
101
 
96
- case '3': {
102
+ case '5': {
97
103
  runManualScan();
98
104
  break;
99
105
  }
100
106
 
101
- case '4': {
107
+ case '10': {
102
108
  const askRl = readline.createInterface({
103
109
  input: process.stdin,
104
110
  output: process.stdout
@@ -128,7 +134,7 @@ async function runInteractiveMenu() {
128
134
  break;
129
135
  }
130
136
 
131
- case '5': {
137
+ case '9': {
132
138
  console.log(`\n${colors.cyan}Scanning workspace for injected malware scripts to quarantine...${colors.reset}`);
133
139
  const { getAllRepoFiles } = require('./utils/git');
134
140
  scanAndCleanRepo(getAllRepoFiles(), process.cwd(), { reason: 'clean' });
@@ -145,7 +151,7 @@ async function runInteractiveMenu() {
145
151
  break;
146
152
  }
147
153
 
148
- case '6': {
154
+ case '18': {
149
155
  console.log(`\n${colors.cyan}Simulating a malicious push intercept test...${colors.reset}\n`);
150
156
  const mockFiles = ['src/app.js', 'temp_auto_push.bat', '.vscode/tasks.json'];
151
157
  const mockDiff = `+ powershell.exe -enc SQBFAFgAIAAoAE4AZQB3...
@@ -159,7 +165,7 @@ async function runInteractiveMenu() {
159
165
  break;
160
166
  }
161
167
 
162
- case '7': {
168
+ case '17': {
163
169
  const res = setupGitHubAction();
164
170
  if (res.success) {
165
171
  console.log(`\n${colors.green}${colors.bold}✔ ${res.message}${colors.reset}\n`);
@@ -169,7 +175,7 @@ async function runInteractiveMenu() {
169
175
  break;
170
176
  }
171
177
 
172
- case '8': {
178
+ case '4': {
173
179
  const { isGitRepo } = require('./utils/git');
174
180
  let global = !isGitRepo(process.cwd());
175
181
  if (!global) {
@@ -185,14 +191,14 @@ async function runInteractiveMenu() {
185
191
  break;
186
192
  }
187
193
 
188
- case '9': {
194
+ case '16': {
189
195
  const pkg = require('../package.json');
190
196
  const { checkUpdateManual } = require('./updateNotifier');
191
197
  await checkUpdateManual(pkg.version);
192
198
  break;
193
199
  }
194
200
 
195
- case '10': {
201
+ case '8': {
196
202
  const folder = await ask(`\n${colors.bold}${colors.cyan}? Folder to sweep (Enter = ${process.cwd()}): ${colors.reset}`);
197
203
  const removeAnswer = await ask(`${colors.bold}${colors.cyan}? Automatically remove CONFIRMED malware? Suspicious items are never touched. (Y/n): ${colors.reset}`);
198
204
  const clean = !/^n(o)?$/i.test(removeAnswer);
@@ -235,7 +241,7 @@ async function runInteractiveMenu() {
235
241
  break;
236
242
  }
237
243
 
238
- case '16': {
244
+ case '6': {
239
245
  const { runAdvancedScan } = require('./advancedScanner');
240
246
  const folder = await ask(`\n${colors.bold}${colors.cyan}? Folder that contains your projects (Enter = ${process.cwd()}): ${colors.reset}`);
241
247
  const deep = await ask(`${colors.bold}${colors.cyan}? Deep scan incl. node_modules & ignored files? Slower. (y/N): ${colors.reset}`);
@@ -247,13 +253,13 @@ async function runInteractiveMenu() {
247
253
  break;
248
254
  }
249
255
 
250
- case '17': {
256
+ case '3': {
251
257
  const shell = require('./shellIntegration');
252
258
  const on = shell.shellIntegrationStatus().installed.length > 0;
253
259
  const answer = await ask(`\n${colors.bold}${colors.cyan}? Pull scan is ${on ? 'ON' : 'OFF'}. Turn it ${on ? 'off' : 'on'}? (y/N): ${colors.reset}`);
254
260
  if (/^y(es)?$/i.test(answer)) {
255
261
  if (on) {
256
- const r = shell.removeShellIntegration();
262
+ const r = shell.removeShellIntegration({ optOut: true });
257
263
  console.log(`\n${colors.yellow}✔ Turned off (${r.files.join(', ')}). Open a new terminal.${colors.reset}\n`);
258
264
  } else {
259
265
  const r = shell.installShellIntegration();
@@ -263,7 +269,7 @@ async function runInteractiveMenu() {
263
269
  break;
264
270
  }
265
271
 
266
- case '18': {
272
+ case '7': {
267
273
  const { runFullScan } = require('./fullScanner');
268
274
  const folder = await ask(`\n${colors.bold}${colors.cyan}? Folder to scan completely (Enter = ${process.cwd()}): ${colors.reset}`);
269
275
  const clean = await ask(`${colors.bold}${colors.cyan}? Automatically remove CONFIRMED malware? An infected archive is moved to quarantine whole (backup kept). (Y/n): ${colors.reset}`);
@@ -273,7 +279,7 @@ async function runInteractiveMenu() {
273
279
 
274
280
  case '0':
275
281
  default:
276
- console.log(`\n${colors.dim}Goodbye! 🛡️${colors.reset}\n`);
282
+ console.log(`\n${colors.dim}Goodbye!${colors.reset}\n`);
277
283
  break;
278
284
  }
279
285
  }
package/src/reporter.js CHANGED
@@ -28,7 +28,7 @@ const symbols = {
28
28
 
29
29
  function banner() {
30
30
  console.log(`\n${colors.cyan}${colors.bold}================================================================${colors.reset}`);
31
- console.log(`${colors.cyan}${colors.bold} ${symbols.shield} GitSafty: Pre-Push Malware & Secret Guard ${colors.reset}`);
31
+ console.log(`${colors.cyan}${colors.bold} GitSafty: Malware & Secret Guard for Git${colors.reset}`);
32
32
  console.log(`${colors.cyan}${colors.bold}================================================================${colors.reset}`);
33
33
  }
34
34