@arifbiswas/git-pre-push 1.0.18 → 1.0.20

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
@@ -153,6 +153,19 @@ async function main() {
153
153
  break;
154
154
  }
155
155
 
156
+ case 'full-scan':
157
+ case 'fullscan':
158
+ case 'scan-folder': {
159
+ banner();
160
+ const { runFullScan } = require('../src/fullScanner');
161
+ const target = args.find((a, i) => i > 0 && !a.startsWith('-')) || process.cwd();
162
+ process.exit(runFullScan(target, {
163
+ clean: args.includes('--clean'),
164
+ json: args.includes('--json')
165
+ }));
166
+ break;
167
+ }
168
+
156
169
  case 'doctor':
157
170
  case 'fix-install': {
158
171
  banner();
@@ -379,6 +392,7 @@ ${colors.bold}Commands:${colors.reset}
379
392
  ${colors.green}vault test${colors.reset} Try one unlock (prompt) without using the token
380
393
  ${colors.green}vault remove${colors.reset} Turn the vault off and go back to normal git login
381
394
  ${colors.green}scan-projects${colors.reset} <folder> Advanced Scanner: audit EVERY project in a folder at once
395
+ ${colors.green}full-scan${colors.reset} <folder> Full Scan: EVERYTHING in a folder, also non-git projects and inside zip/jar/apk/tar/gz/7z/rar (--clean removes)
382
396
  (malware, git backdoors, IDE auto-run, secrets) [--clean] [--deep] [--json]
383
397
  ${colors.green}pull-scan${colors.reset} on|off Scan after EVERY git pull, also "Already up to date" (adds a git shell function)
384
398
  ${colors.green}doctor${colors.reset} Find broken/outdated installs and show the exact fix (--fix applies it)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arifbiswas/git-pre-push",
3
- "version": "1.0.18",
3
+ "version": "1.0.20",
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": {
@@ -237,6 +237,8 @@ function scanProject(dir, { deep = false } = {}) {
237
237
  path: dir,
238
238
  git: isGitRepo(dir),
239
239
  files: files.length,
240
+ // Archives are not opened here; Full Scan (gitsafty full-scan) looks inside them.
241
+ archives: files.filter(f => !inGeneratedDir(f) && require('./archive').isArchiveName(f)).length,
240
242
  durationMs: Date.now() - started,
241
243
  findings,
242
244
  summary: {
@@ -418,6 +420,10 @@ function runAdvancedScan(root, { clean = false, deep = false, json = false } = {
418
420
  console.log(` ${removedTotal ? colors.green : colors.dim}Files cleaned : ${removedTotal}${colors.reset}`);
419
421
  console.log(` ${colors.green}Clean projects : ${results.filter(r => !r.findings.length).length}${colors.reset}`);
420
422
  console.log(`\n ${colors.dim}Full report: ${reportPath}${colors.reset}`);
423
+ const archiveCount = results.reduce((n, r) => n + (r.archives || 0), 0);
424
+ if (archiveCount) {
425
+ console.log(` ${colors.yellow}${archiveCount} archive file(s) (zip/tar/7z/rar …) were not opened.${colors.reset} Look inside them: ${colors.cyan}gitsafty full-scan "${abs}"${colors.reset}`);
426
+ }
421
427
  if (infected.length && !clean) {
422
428
  console.log(`\n ${colors.bold}Remove the confirmed malware:${colors.reset} ${colors.cyan}gitsafty scan-projects "${abs}" --clean${colors.reset}`);
423
429
  }
package/src/archive.js ADDED
@@ -0,0 +1,352 @@
1
+ /**
2
+ * Reads the files inside archives WITHOUT extracting anything to disk and
3
+ * without running anything from them.
4
+ *
5
+ * zip family (zip, jar, war, apk, aab, aar, ipa, xpi, vsix, nupkg, whl, crx,
6
+ * docx/xlsx/pptx ...): parsed here (stored + deflate, zip64)
7
+ * tar, tar.gz / tgz, gz: parsed here
8
+ * 7z, rar, bz2, xz, and zip entries with other compression: read through the
9
+ * system `7z` / `tar` (bsdtar) one entry at a time to stdout, if available
10
+ *
11
+ * Archives are detected by their first bytes, not only by the file name, so a
12
+ * renamed archive is still opened. Nested archives are opened too (limited depth).
13
+ * Limits keep zip bombs harmless: per-entry size, total size and entry count.
14
+ */
15
+
16
+ const fs = require('fs');
17
+ const os = require('os');
18
+ const path = require('path');
19
+ const zlib = require('zlib');
20
+ const { spawnSync } = require('child_process');
21
+
22
+ const LIMITS = {
23
+ maxEntryBytes: 64 * 1024 * 1024, // one file inside an archive
24
+ maxTotalBytes: 1024 * 1024 * 1024, // all files of one top-level archive
25
+ maxEntries: 100000,
26
+ maxDepth: 4,
27
+ maxArchiveBytes: 1024 * 1024 * 1024 // archive file read into memory
28
+ };
29
+
30
+ const ZIP_EXT = /\.(zip|jar|war|ear|apk|aab|aar|ipa|xpi|vsix|nupkg|whl|egg|crx|docx|xlsx|pptx|odt|ods|odp|epub|appx|msix|jmod|kmz)$/i;
31
+ const ARCHIVE_EXT = /\.(zip|jar|war|ear|apk|aab|aar|ipa|xpi|vsix|nupkg|whl|egg|crx|appx|msix|jmod|kmz|tar|tgz|tbz2?|txz|gz|bz2|xz|7z|rar|cab|iso|cpio)$/i;
32
+
33
+ /** Archive type from the first bytes (and the name as a hint). */
34
+ function detectArchiveType(head, name = '') {
35
+ if (!head || head.length < 4) return null;
36
+ if (head[0] === 0x50 && head[1] === 0x4b && (head[2] === 3 || head[2] === 5 || head[2] === 7)) return 'zip';
37
+ if (head.toString('latin1', 0, 4) === 'Cr24') return 'crx';
38
+ if (head[0] === 0x1f && head[1] === 0x8b) return 'gzip';
39
+ if (head.length >= 262 && head.toString('latin1', 257, 262) === 'ustar') return 'tar';
40
+ if (head.toString('latin1', 0, 6) === '7z\xbc\xaf\x27\x1c') return '7z';
41
+ if (head.toString('latin1', 0, 4) === 'Rar!') return 'rar';
42
+ if (head.toString('latin1', 0, 3) === 'BZh') return 'bzip2';
43
+ if (head.length >= 6 && head[0] === 0xfd && head.toString('latin1', 1, 6) === '7zXZ\0') return 'xz';
44
+ if (head.toString('latin1', 0, 4) === 'MSCF') return 'cab';
45
+ // Old tar without "ustar" magic: only trust the name.
46
+ if (/\.tar$/i.test(name)) return 'tar';
47
+ return null;
48
+ }
49
+
50
+ function isArchiveName(name) {
51
+ return ARCHIVE_EXT.test(name);
52
+ }
53
+
54
+ // ---------------------------------------------------------------------------
55
+ // ZIP
56
+ // ---------------------------------------------------------------------------
57
+
58
+ function findEocd(buf) {
59
+ const min = Math.max(0, buf.length - 65557);
60
+ for (let i = buf.length - 22; i >= min; i--) {
61
+ if (buf.readUInt32LE(i) === 0x06054b50) return i;
62
+ }
63
+ return -1;
64
+ }
65
+
66
+ /**
67
+ * Lists zip entries.
68
+ * @returns {Array<{name, method, compSize, size, offset, encrypted, dir}>}
69
+ */
70
+ function zipEntries(buf) {
71
+ const eocd = findEocd(buf);
72
+ if (eocd < 0) throw new Error('not a valid zip (no end of central directory)');
73
+ let count = buf.readUInt16LE(eocd + 10);
74
+ let cdSize = buf.readUInt32LE(eocd + 12);
75
+ let cdOffset = buf.readUInt32LE(eocd + 16);
76
+
77
+ // zip64
78
+ if (eocd >= 20 && buf.readUInt32LE(eocd - 20) === 0x07064b50) {
79
+ const z64 = Number(buf.readBigUInt64LE(eocd - 20 + 8));
80
+ if (z64 + 56 <= buf.length && buf.readUInt32LE(z64) === 0x06064b50) {
81
+ count = Number(buf.readBigUInt64LE(z64 + 32));
82
+ cdSize = Number(buf.readBigUInt64LE(z64 + 40));
83
+ cdOffset = Number(buf.readBigUInt64LE(z64 + 48));
84
+ }
85
+ }
86
+ // Self-extracting / prefixed zips (e.g. crx): the central directory sits right before the EOCD.
87
+ const shift = eocd - cdSize - cdOffset > 0 ? eocd - cdSize - cdOffset : 0;
88
+
89
+ const entries = [];
90
+ let p = cdOffset + shift;
91
+ for (let i = 0; i < count && p + 46 <= buf.length; i++) {
92
+ if (buf.readUInt32LE(p) !== 0x02014b50) break;
93
+ const flags = buf.readUInt16LE(p + 8);
94
+ const method = buf.readUInt16LE(p + 10);
95
+ let compSize = buf.readUInt32LE(p + 20);
96
+ let size = buf.readUInt32LE(p + 24);
97
+ const nameLen = buf.readUInt16LE(p + 28);
98
+ const extraLen = buf.readUInt16LE(p + 30);
99
+ const commentLen = buf.readUInt16LE(p + 32);
100
+ let offset = buf.readUInt32LE(p + 42);
101
+ const name = buf.toString(flags & 0x800 ? 'utf8' : 'latin1', p + 46, p + 46 + nameLen);
102
+
103
+ // zip64 extra field
104
+ let e = p + 46 + nameLen;
105
+ const extraEnd = e + extraLen;
106
+ while (e + 4 <= extraEnd) {
107
+ const id = buf.readUInt16LE(e);
108
+ const len = buf.readUInt16LE(e + 2);
109
+ if (id === 0x0001) {
110
+ let q = e + 4;
111
+ if (size === 0xffffffff) { size = Number(buf.readBigUInt64LE(q)); q += 8; }
112
+ if (compSize === 0xffffffff) { compSize = Number(buf.readBigUInt64LE(q)); q += 8; }
113
+ if (offset === 0xffffffff) { offset = Number(buf.readBigUInt64LE(q)); }
114
+ }
115
+ e += 4 + len;
116
+ }
117
+
118
+ entries.push({ name, method, compSize, size, offset: offset + shift, encrypted: !!(flags & 1), dir: name.endsWith('/') });
119
+ p = extraEnd + commentLen;
120
+ }
121
+ return entries;
122
+ }
123
+
124
+ function zipEntryData(buf, entry, maxBytes) {
125
+ const lh = entry.offset;
126
+ if (lh + 30 > buf.length || buf.readUInt32LE(lh) !== 0x04034b50) throw new Error('broken local header');
127
+ const start = lh + 30 + buf.readUInt16LE(lh + 26) + buf.readUInt16LE(lh + 28);
128
+ const data = buf.subarray(start, start + entry.compSize);
129
+ if (entry.method === 0) return data.subarray(0, maxBytes);
130
+ if (entry.method === 8) return zlib.inflateRawSync(data, { maxOutputLength: maxBytes });
131
+ const err = new Error(`compression method ${entry.method}`);
132
+ err.code = 'UNSUPPORTED_METHOD';
133
+ throw err;
134
+ }
135
+
136
+ // ---------------------------------------------------------------------------
137
+ // TAR
138
+ // ---------------------------------------------------------------------------
139
+
140
+ function tarNumber(buf, off, len) {
141
+ if (buf[off] & 0x80) { // base-256
142
+ let n = 0;
143
+ for (let i = off + 1; i < off + len; i++) n = n * 256 + buf[i];
144
+ return n;
145
+ }
146
+ const s = buf.toString('latin1', off, off + len).replace(/\0.*$/, '').trim();
147
+ return s ? parseInt(s, 8) || 0 : 0;
148
+ }
149
+
150
+ function* tarEntries(buf) {
151
+ let p = 0;
152
+ let longName = null;
153
+ let paxPath = null;
154
+ while (p + 512 <= buf.length) {
155
+ const h = buf.subarray(p, p + 512);
156
+ if (h.every(b => b === 0)) break;
157
+ let name = h.toString('utf8', 0, 100).replace(/\0.*$/s, '');
158
+ const prefix = h.toString('latin1', 257, 262) === 'ustar' ? h.toString('utf8', 345, 500).replace(/\0.*$/s, '') : '';
159
+ if (prefix) name = `${prefix}/${name}`;
160
+ const size = tarNumber(h, 124, 12);
161
+ const type = String.fromCharCode(h[156] || 48);
162
+ const dataStart = p + 512;
163
+ const data = buf.subarray(dataStart, Math.min(buf.length, dataStart + size));
164
+ p = dataStart + Math.ceil(size / 512) * 512;
165
+
166
+ if (type === 'L') { longName = data.toString('utf8').replace(/\0.*$/s, ''); continue; }
167
+ if (type === 'x') {
168
+ const m = data.toString('utf8').match(/\d+ path=([^\n]*)\n/);
169
+ if (m) paxPath = m[1];
170
+ continue;
171
+ }
172
+ if (type === 'g') continue;
173
+ const finalName = paxPath || longName || name;
174
+ longName = null;
175
+ paxPath = null;
176
+ if (type === '0' || type === '\0' || type === '7') yield { name: finalName, size, data };
177
+ }
178
+ }
179
+
180
+ // ---------------------------------------------------------------------------
181
+ // External tools (7z, bsdtar) for formats Node can't read
182
+ // ---------------------------------------------------------------------------
183
+
184
+ let toolCache;
185
+ function externalTool() {
186
+ if (toolCache !== undefined) return toolCache;
187
+ const candidates = process.platform === 'win32'
188
+ ? [['7z'], [path.join(process.env.ProgramFiles || 'C:\\Program Files', '7-Zip', '7z.exe')], ['tar']]
189
+ : [['7zz'], ['7z'], ['bsdtar'], ['tar']];
190
+ for (const [bin] of candidates) {
191
+ const isTar = /tar(\.exe)?$/i.test(bin);
192
+ const r = spawnSync(bin, isTar ? ['--version'] : ['i'], { encoding: 'utf8', timeout: 10000 });
193
+ if (r.error) continue;
194
+ if (isTar && !/bsdtar|libarchive/i.test(r.stdout || '')) continue; // GNU tar can't read zip/7z/rar
195
+ toolCache = { bin, kind: isTar ? 'bsdtar' : '7z' };
196
+ return toolCache;
197
+ }
198
+ toolCache = null;
199
+ return null;
200
+ }
201
+
202
+ /** Writes an in-memory nested archive to a private temp file (only to read it, never executed). */
203
+ function withTempFile(buf, name, fn) {
204
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'gitsafty-arc-'));
205
+ const file = path.join(dir, `archive${path.extname(name) || ''}`);
206
+ try {
207
+ fs.writeFileSync(file, buf, { mode: 0o600 });
208
+ return fn(file);
209
+ } finally {
210
+ try { fs.rmSync(dir, { recursive: true, force: true }); } catch (_) {}
211
+ }
212
+ }
213
+
214
+ function externalList(tool, file) {
215
+ if (tool.kind === '7z') {
216
+ const r = spawnSync(tool.bin, ['l', '-slt', '-ba', '-p', '--', file], { encoding: 'utf8', maxBuffer: 256 * 1024 * 1024, timeout: 120000 });
217
+ if (r.status !== 0) return null;
218
+ const out = [];
219
+ for (const block of r.stdout.split(/\r?\n\r?\n/)) {
220
+ const get = (k) => { const m = block.match(new RegExp(`^${k} = (.*)$`, 'm')); return m ? m[1].trim() : ''; };
221
+ const name = get('Path');
222
+ if (!name || get('Folder') === '+' || /D/.test(get('Attributes').split(' ')[0] || '')) continue;
223
+ out.push({ name, size: Number(get('Size')) || 0, encrypted: get('Encrypted') === '+' });
224
+ }
225
+ return out;
226
+ }
227
+ const r = spawnSync(tool.bin, ['-tf', file], { encoding: 'utf8', maxBuffer: 256 * 1024 * 1024, timeout: 120000 });
228
+ if (r.status !== 0) return null;
229
+ return r.stdout.split(/\r?\n/).filter(n => n && !n.endsWith('/')).map(name => ({ name, size: 0, encrypted: false }));
230
+ }
231
+
232
+ function externalRead(tool, file, name, maxBytes) {
233
+ const args = tool.kind === '7z' ? ['e', '-so', '-p', '--', file, name] : ['-xOf', file, '--', name];
234
+ const r = spawnSync(tool.bin, args, { maxBuffer: maxBytes, timeout: 120000 });
235
+ if (r.error && r.error.code === 'ENOBUFS') return { tooLarge: true };
236
+ if (r.status !== 0 || r.error) return { error: (r.stderr || '').toString().trim().split('\n')[0] || 'could not read' };
237
+ return { data: r.stdout };
238
+ }
239
+
240
+ // ---------------------------------------------------------------------------
241
+ // Walker
242
+ // ---------------------------------------------------------------------------
243
+
244
+ /**
245
+ * Calls onFile(innerPath, buffer, info) for every file inside an archive,
246
+ * opening nested archives too.
247
+ *
248
+ * @param {Buffer} buf archive bytes
249
+ * @param {string} name archive name (for type hints)
250
+ * @param {(inner: string, data: Buffer) => void} onFile
251
+ * @param {{ skipEntry?: (inner: string) => boolean }} [opts]
252
+ * @returns {{ type, entries, scanned, problems: Array<{entry, reason}> }}
253
+ */
254
+ function walkArchive(buf, name, onFile, opts = {}) {
255
+ const stats = { type: null, entries: 0, scanned: 0, bytes: 0, problems: [], encrypted: [] };
256
+ const skip = opts.skipEntry || (() => false);
257
+
258
+ const visit = (data, label, prefix, depth) => {
259
+ const type = detectArchiveType(data.subarray(0, 512), label);
260
+ if (depth === 0) stats.type = type;
261
+ if (!type) return false;
262
+ if (depth >= LIMITS.maxDepth) {
263
+ stats.problems.push({ entry: prefix || label, reason: 'archive nested too deep, not opened' });
264
+ return true;
265
+ }
266
+
267
+ const emit = (inner, content) => {
268
+ stats.entries++;
269
+ const full = prefix ? `${prefix}!/${inner}` : inner;
270
+ if (stats.entries > LIMITS.maxEntries) return;
271
+ if (skip(inner)) return;
272
+ if (content == null) return;
273
+ stats.bytes += content.length;
274
+ if (stats.bytes > LIMITS.maxTotalBytes) {
275
+ if (!stats.totalLimitHit) stats.problems.push({ entry: label, reason: 'more than 1 GB unpacked, rest skipped' });
276
+ stats.totalLimitHit = true;
277
+ return;
278
+ }
279
+ if (detectArchiveType(content.subarray(0, 512), inner) && visit(content, inner, full, depth + 1)) {
280
+ // Also give the nested archive itself to the caller (hashes, names).
281
+ }
282
+ stats.scanned++;
283
+ onFile(full, content, { depth });
284
+ };
285
+
286
+ try {
287
+ if (type === 'zip' || type === 'crx') {
288
+ let tool = null;
289
+ for (const e of zipEntries(data)) {
290
+ if (e.dir) continue;
291
+ if (e.encrypted) { stats.encrypted.push(prefix ? `${prefix}!/${e.name}` : e.name); stats.entries++; continue; }
292
+ if (e.size > LIMITS.maxEntryBytes) { stats.problems.push({ entry: e.name, reason: 'file larger than 64 MB inside archive, skipped' }); continue; }
293
+ try {
294
+ emit(e.name, zipEntryData(data, e, LIMITS.maxEntryBytes));
295
+ } catch (err) {
296
+ if (err.code === 'UNSUPPORTED_METHOD' && (tool = tool || externalTool())) {
297
+ const r = withTempFile(data, label, f => externalRead(tool, f, e.name, LIMITS.maxEntryBytes));
298
+ if (r.data) emit(e.name, r.data);
299
+ else stats.problems.push({ entry: e.name, reason: r.tooLarge ? 'too large' : r.error });
300
+ } else {
301
+ stats.problems.push({ entry: e.name, reason: err.code === 'ERR_BUFFER_TOO_LARGE' || /larger than|maxOutputLength/i.test(err.message) ? 'unpacks to more than 64 MB, skipped' : err.message });
302
+ }
303
+ }
304
+ }
305
+ } else if (type === 'tar') {
306
+ for (const e of tarEntries(data)) {
307
+ if (e.size > LIMITS.maxEntryBytes) { stats.problems.push({ entry: e.name, reason: 'file larger than 64 MB inside archive, skipped' }); continue; }
308
+ emit(e.name, e.data);
309
+ }
310
+ } else if (type === 'gzip') {
311
+ const out = zlib.gunzipSync(data, { maxOutputLength: LIMITS.maxEntryBytes * 4 });
312
+ const inner = label.replace(/\.(tgz)$/i, '.tar').replace(/\.gz$/i, '') || 'content';
313
+ if (detectArchiveType(out.subarray(0, 512), inner) === 'tar') visit(out, inner, prefix || '', depth + (prefix ? 1 : 0));
314
+ else emit(path.basename(inner), out);
315
+ } else {
316
+ const tool = externalTool();
317
+ if (!tool) {
318
+ stats.problems.push({ entry: prefix || label, reason: `${type} archive: install 7-Zip (Windows) or p7zip to open it` });
319
+ return true;
320
+ }
321
+ withTempFile(data, label, (f) => {
322
+ const list = externalList(tool, f);
323
+ if (!list) { stats.problems.push({ entry: prefix || label, reason: `${type} archive could not be opened (damaged or password protected)` }); return; }
324
+ for (const e of list) {
325
+ if (e.encrypted) { stats.encrypted.push(prefix ? `${prefix}!/${e.name}` : e.name); stats.entries++; continue; }
326
+ if (e.size > LIMITS.maxEntryBytes) { stats.problems.push({ entry: e.name, reason: 'file larger than 64 MB inside archive, skipped' }); continue; }
327
+ const r = externalRead(tool, f, e.name, LIMITS.maxEntryBytes);
328
+ if (r.data) emit(e.name, r.data);
329
+ else stats.problems.push({ entry: e.name, reason: r.tooLarge ? 'unpacks to more than 64 MB, skipped' : (r.error || 'could not read') });
330
+ }
331
+ });
332
+ }
333
+ } catch (err) {
334
+ const tooBig = err.code === 'ERR_BUFFER_TOO_LARGE' || /larger than|maxOutputLength/i.test(err.message);
335
+ stats.problems.push({ entry: prefix || label, reason: tooBig ? 'unpacks to more than 256 MB, skipped' : `could not open: ${err.message}` });
336
+ }
337
+ return true;
338
+ };
339
+
340
+ visit(buf, name, '', 0);
341
+ return stats;
342
+ }
343
+
344
+ module.exports = {
345
+ LIMITS,
346
+ ZIP_EXT,
347
+ detectArchiveType,
348
+ isArchiveName,
349
+ walkArchive,
350
+ zipEntries,
351
+ externalTool
352
+ };
@@ -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
+ };