@arifbiswas/git-pre-push 1.0.9 → 1.0.11

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/vault.js ADDED
@@ -0,0 +1,737 @@
1
+ /**
2
+ * GitSafty Vault: "always logged out" Git credentials.
3
+ *
4
+ * The device never keeps a usable GitHub token:
5
+ * - The token lives only in ~/.gitsafty/vault.json, encrypted with
6
+ * AES-256-GCM. The key is derived from the user's passphrase with scrypt
7
+ * (N=2^17, r=8, p=1: ~128 MB RAM per guess, so offline brute force is slow).
8
+ * The vault metadata is bound as GCM additional data, so it can't be edited.
9
+ * - GitSafty is registered as the ONLY git credential helper for github.com.
10
+ * When git needs to push (or fetch a private repo), git asks GitSafty,
11
+ * GitSafty asks for the passphrase, decrypts the token in memory, hands it
12
+ * to git for that single command, and wipes it. Nothing is cached, so
13
+ * after the push finishes the device is logged out again.
14
+ * - Other stored GitHub logins (macOS Keychain, ~/.git-credentials,
15
+ * gh CLI helper) are removed during setup.
16
+ * - Every unlock and every wrong passphrase shows a desktop notification,
17
+ * so a push you did not start is visible immediately.
18
+ */
19
+
20
+ const fs = require('fs');
21
+ const os = require('os');
22
+ const path = require('path');
23
+ const https = require('https');
24
+ const crypto = require('crypto');
25
+ const { execFileSync, spawnSync } = require('child_process');
26
+
27
+ const VAULT_VERSION = 1;
28
+ const CIPHER = 'aes-256-gcm';
29
+ const KDF = { name: 'scrypt', N: 1 << 17, r: 8, p: 1, keyLen: 32 };
30
+ const SCRYPT_MAXMEM = 256 * 1024 * 1024;
31
+ const MIN_PASSPHRASE = 12;
32
+ const MAX_ATTEMPTS = 3;
33
+
34
+ function vaultDir() {
35
+ return path.join(process.env.HOME || os.homedir(), '.gitsafty');
36
+ }
37
+
38
+ function vaultPath() {
39
+ return path.join(vaultDir(), 'vault.json');
40
+ }
41
+
42
+ // ---------------------------------------------------------------------------
43
+ // Crypto
44
+ // ---------------------------------------------------------------------------
45
+
46
+ function deriveKey(passphrase, salt, kdf = KDF) {
47
+ if (kdf.name !== 'scrypt') throw new Error(`Unsupported KDF ${kdf.name}`);
48
+ return crypto.scryptSync(Buffer.from(passphrase.normalize('NFKC'), 'utf8'), salt, kdf.keyLen, {
49
+ N: kdf.N, r: kdf.r, p: kdf.p, maxmem: SCRYPT_MAXMEM
50
+ });
51
+ }
52
+
53
+ function aadOf(vault) {
54
+ return Buffer.from(JSON.stringify({ version: vault.version, cipher: vault.cipher, kdf: vault.kdf, meta: vault.meta }), 'utf8');
55
+ }
56
+
57
+ /**
58
+ * Encrypts a token into a vault object.
59
+ * @param {string} token
60
+ * @param {string} passphrase
61
+ * @param {object} meta { host, username, ... } (authenticated, not secret)
62
+ */
63
+ function encryptToken(token, passphrase, meta) {
64
+ const salt = crypto.randomBytes(32);
65
+ const iv = crypto.randomBytes(12);
66
+ const kdf = { ...KDF, salt: salt.toString('base64') };
67
+ const vault = { version: VAULT_VERSION, cipher: CIPHER, kdf, meta };
68
+
69
+ const key = deriveKey(passphrase, salt, kdf);
70
+ try {
71
+ const cipher = crypto.createCipheriv(CIPHER, key, iv);
72
+ cipher.setAAD(aadOf(vault));
73
+ const plain = Buffer.from(token, 'utf8');
74
+ const data = Buffer.concat([cipher.update(plain), cipher.final()]);
75
+ plain.fill(0);
76
+ return { ...vault, iv: iv.toString('base64'), tag: cipher.getAuthTag().toString('base64'), data: data.toString('base64') };
77
+ } finally {
78
+ key.fill(0);
79
+ }
80
+ }
81
+
82
+ /**
83
+ * Decrypts the token. Throws on wrong passphrase or tampering.
84
+ * @returns {Buffer} token bytes (caller must .fill(0) after use)
85
+ */
86
+ function decryptToken(vault, passphrase) {
87
+ if (!vault || vault.version !== VAULT_VERSION || vault.cipher !== CIPHER) {
88
+ throw new Error('Unsupported vault format');
89
+ }
90
+ const key = deriveKey(passphrase, Buffer.from(vault.kdf.salt, 'base64'), vault.kdf);
91
+ try {
92
+ const decipher = crypto.createDecipheriv(CIPHER, key, Buffer.from(vault.iv, 'base64'));
93
+ decipher.setAAD(aadOf(vault));
94
+ decipher.setAuthTag(Buffer.from(vault.tag, 'base64'));
95
+ return Buffer.concat([decipher.update(Buffer.from(vault.data, 'base64')), decipher.final()]);
96
+ } catch (_) {
97
+ throw new Error('Wrong passphrase (or the vault file was modified)');
98
+ } finally {
99
+ key.fill(0);
100
+ }
101
+ }
102
+
103
+ // --- v2: hardware-bound secret (Secure Enclave / Windows Hello) -----------
104
+
105
+ const VAULT_V2 = 2;
106
+
107
+ function aadOfV2(vault) {
108
+ return Buffer.from(JSON.stringify({ version: vault.version, cipher: vault.cipher, kdf: vault.kdf, protector: vault.protector, meta: vault.meta }), 'utf8');
109
+ }
110
+
111
+ function dataKeyFromSecret(secret, salt) {
112
+ return Buffer.from(crypto.hkdfSync('sha256', secret, salt, Buffer.from('gitsafty-vault-v2'), 32));
113
+ }
114
+
115
+ /** Encrypts the token with a 32-byte secret produced by a hardware key. */
116
+ function encryptWithSecret(token, secret, protector, meta) {
117
+ const salt = crypto.randomBytes(32);
118
+ const iv = crypto.randomBytes(12);
119
+ const vault = { version: VAULT_V2, cipher: CIPHER, kdf: { name: 'hkdf-sha256', salt: salt.toString('base64') }, protector, meta };
120
+ const key = dataKeyFromSecret(secret, salt);
121
+ try {
122
+ const cipher = crypto.createCipheriv(CIPHER, key, iv);
123
+ cipher.setAAD(aadOfV2(vault));
124
+ const plain = Buffer.from(token, 'utf8');
125
+ const data = Buffer.concat([cipher.update(plain), cipher.final()]);
126
+ plain.fill(0);
127
+ return { ...vault, iv: iv.toString('base64'), tag: cipher.getAuthTag().toString('base64'), data: data.toString('base64') };
128
+ } finally {
129
+ key.fill(0);
130
+ }
131
+ }
132
+
133
+ function decryptWithSecret(vault, secret) {
134
+ if (!vault || vault.version !== VAULT_V2 || vault.cipher !== CIPHER) throw new Error('Unsupported vault format');
135
+ const key = dataKeyFromSecret(secret, Buffer.from(vault.kdf.salt, 'base64'));
136
+ try {
137
+ const decipher = crypto.createDecipheriv(CIPHER, key, Buffer.from(vault.iv, 'base64'));
138
+ decipher.setAAD(aadOfV2(vault));
139
+ decipher.setAuthTag(Buffer.from(vault.tag, 'base64'));
140
+ return Buffer.concat([decipher.update(Buffer.from(vault.data, 'base64')), decipher.final()]);
141
+ } catch (_) {
142
+ throw new Error('Hardware key did not match (or the vault file was modified)');
143
+ } finally {
144
+ key.fill(0);
145
+ }
146
+ }
147
+
148
+ /** Unlocks a vault of any version. Prompts the user. Returns token Buffer. */
149
+ function unlockVault(vault, reason) {
150
+ if (vault.version === VAULT_V2) {
151
+ const { providerFor } = require('./hwkey');
152
+ const provider = providerFor(vault.protector && vault.protector.type);
153
+ if (!provider) throw new Error(`This vault is protected by ${vault.protector && vault.protector.type}, which is not available on this OS`);
154
+ const secret = provider.unlock(vault.protector, reason);
155
+ try {
156
+ return decryptWithSecret(vault, secret);
157
+ } finally {
158
+ secret.fill(0);
159
+ }
160
+ }
161
+ return null; // v1 handled by the passphrase loop
162
+ }
163
+
164
+ function readVault() {
165
+ try {
166
+ return JSON.parse(fs.readFileSync(vaultPath(), 'utf8'));
167
+ } catch (_) {
168
+ return null;
169
+ }
170
+ }
171
+
172
+ function writeVault(vault) {
173
+ fs.mkdirSync(vaultDir(), { recursive: true, mode: 0o700 });
174
+ try { fs.chmodSync(vaultDir(), 0o700); } catch (_) {}
175
+ const tmp = vaultPath() + '.tmp';
176
+ fs.writeFileSync(tmp, JSON.stringify(vault, null, 2), { mode: 0o600 });
177
+ fs.renameSync(tmp, vaultPath());
178
+ try { fs.chmodSync(vaultPath(), 0o600); } catch (_) {}
179
+ }
180
+
181
+ // ---------------------------------------------------------------------------
182
+ // Secret input (works while git owns stdin/stdout)
183
+ // ---------------------------------------------------------------------------
184
+
185
+ function readFromTty(prompt) {
186
+ if (process.platform === 'win32') return undefined;
187
+ let fd;
188
+ try {
189
+ fd = fs.openSync('/dev/tty', 'r+');
190
+ } catch (_) {
191
+ return undefined; // no terminal (IDE / GUI client)
192
+ }
193
+ try {
194
+ fs.writeSync(fd, prompt);
195
+ spawnSync('stty', ['-echo'], { stdio: [fd, 'ignore', 'ignore'] });
196
+ const bytes = [];
197
+ const one = Buffer.alloc(1);
198
+ for (;;) {
199
+ let n;
200
+ try { n = fs.readSync(fd, one, 0, 1, null); } catch (err) {
201
+ if (err.code === 'EAGAIN') continue;
202
+ break;
203
+ }
204
+ if (n === 0 || one[0] === 10 || one[0] === 13) break;
205
+ if (one[0] === 3) { bytes.length = 0; return null; } // Ctrl-C
206
+ bytes.push(one[0]);
207
+ }
208
+ const buf = Buffer.from(bytes);
209
+ const out = buf.toString('utf8');
210
+ buf.fill(0);
211
+ bytes.fill(0);
212
+ return out;
213
+ } finally {
214
+ spawnSync('stty', ['echo'], { stdio: [fd, 'ignore', 'ignore'] });
215
+ try { fs.writeSync(fd, '\n'); } catch (_) {}
216
+ try { fs.closeSync(fd); } catch (_) {}
217
+ }
218
+ }
219
+
220
+ function readFromWindowsConsole(prompt) {
221
+ if (process.platform !== 'win32') return undefined;
222
+ const root = process.env.SystemRoot || process.env.windir || 'C:\\Windows';
223
+ const ps = path.join(root, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
224
+ if (!fs.existsSync(ps)) return undefined;
225
+ // Read-Host talks to the console directly, so this works while git owns stdin.
226
+ const script = '$p = $env:GITSAFTY_PROMPT; $s = Read-Host -AsSecureString -Prompt $p; ' +
227
+ '$b = [Runtime.InteropServices.Marshal]::SecureStringToBSTR($s); ' +
228
+ 'try { [Console]::Out.Write([Runtime.InteropServices.Marshal]::PtrToStringBSTR($b)) } ' +
229
+ 'finally { [Runtime.InteropServices.Marshal]::ZeroFreeBSTR($b) }';
230
+ const r = spawnSync(ps, ['-NoProfile', '-NonInteractive', '-Command', script], {
231
+ encoding: 'utf8',
232
+ stdio: ['inherit', 'pipe', 'inherit'],
233
+ env: { ...process.env, GITSAFTY_PROMPT: prompt.replace(/:\s*$/, '') },
234
+ timeout: 300000
235
+ });
236
+ if (r.status !== 0) return undefined;
237
+ return r.stdout;
238
+ }
239
+
240
+ function readFromAskpass(prompt) {
241
+ const askpass = process.env.GIT_ASKPASS || process.env.SSH_ASKPASS;
242
+ if (!askpass) return undefined;
243
+ const r = spawnSync(askpass, [prompt], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 300000 });
244
+ if (r.status !== 0) return null;
245
+ return r.stdout.replace(/\r?\n$/, '');
246
+ }
247
+
248
+ function readFromDialog(prompt) {
249
+ if (process.platform !== 'darwin') return undefined;
250
+ try {
251
+ return execFileSync('osascript', [
252
+ '-e', 'on run argv',
253
+ '-e', 'display dialog (item 1 of argv) default answer "" with hidden answer with title "GitSafty Vault" with icon caution',
254
+ '-e', 'return text returned of result',
255
+ '-e', 'end run',
256
+ prompt
257
+ ], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], timeout: 300000 }).replace(/\r?\n$/, '');
258
+ } catch (_) {
259
+ return null;
260
+ }
261
+ }
262
+
263
+ /** Hidden prompt: terminal first, then IDE askpass, then a macOS dialog. */
264
+ function readSecret(prompt) {
265
+ for (const source of [readFromTty, readFromWindowsConsole, readFromAskpass, readFromDialog]) {
266
+ const value = source(prompt);
267
+ if (value !== undefined) return value;
268
+ }
269
+ return null;
270
+ }
271
+
272
+ function readLineFromTty(prompt) {
273
+ let fd;
274
+ try { fd = fs.openSync('/dev/tty', 'r+'); } catch (_) { return null; }
275
+ try {
276
+ fs.writeSync(fd, prompt);
277
+ const bytes = [];
278
+ const one = Buffer.alloc(1);
279
+ for (;;) {
280
+ const n = fs.readSync(fd, one, 0, 1, null);
281
+ if (n === 0 || one[0] === 10 || one[0] === 13) break;
282
+ bytes.push(one[0]);
283
+ }
284
+ return Buffer.from(bytes).toString('utf8').trim();
285
+ } finally {
286
+ try { fs.closeSync(fd); } catch (_) {}
287
+ }
288
+ }
289
+
290
+ function confirm(prompt) {
291
+ const ans = readLineFromTty(prompt);
292
+ return !!ans && /^y(es)?$/i.test(ans);
293
+ }
294
+
295
+ // ---------------------------------------------------------------------------
296
+ // Git configuration
297
+ // ---------------------------------------------------------------------------
298
+
299
+ function git(args, opts = {}) {
300
+ return execFileSync('git', args, { encoding: 'utf8', stdio: ['pipe', 'pipe', 'ignore'], ...opts });
301
+ }
302
+
303
+ function tryGit(args, opts) {
304
+ try { return git(args, opts); } catch (_) { return null; }
305
+ }
306
+
307
+ function cliPath() {
308
+ return path.resolve(__dirname, '..', 'bin', 'cli.js');
309
+ }
310
+
311
+ function shq(s) {
312
+ return `'${String(s).replace(/'/g, `'\\''`)}'`;
313
+ }
314
+
315
+ function helperCommand() {
316
+ // Absolute node + absolute CLI path: a PATH hijack can't swap the helper.
317
+ return `!${shq(process.execPath)} ${shq(cliPath())} credential`;
318
+ }
319
+
320
+ function helperSection(host) {
321
+ return `credential.https://${host}`;
322
+ }
323
+
324
+ /**
325
+ * Makes GitSafty the only credential helper for https://<host>.
326
+ * An empty helper entry first resets helpers inherited from system config
327
+ * (e.g. macOS osxkeychain). The section is recreated at the end of the
328
+ * global config so later generic helpers can't sneak in after it.
329
+ */
330
+ function installHelper(host) {
331
+ const section = helperSection(host);
332
+ tryGit(['config', '--global', '--remove-section', section]);
333
+ git(['config', '--global', '--add', `${section}.helper`, '']);
334
+ git(['config', '--global', '--add', `${section}.helper`, helperCommand()]);
335
+ }
336
+
337
+ function removeHelper(host) {
338
+ tryGit(['config', '--global', '--remove-section', helperSection(host)]);
339
+ }
340
+
341
+ /**
342
+ * Lists the helpers git will actually use for https://<host>, in order.
343
+ * Mirrors git's rule: an empty value resets the list.
344
+ */
345
+ function effectiveHelpers(host, cwd) {
346
+ const out = tryGit(['config', '--get-regexp', '^credential\\..*helper$'], { cwd }) || '';
347
+ let list = [];
348
+ for (const line of out.split('\n')) {
349
+ const m = line.match(/^credential\.(?:(.*)\.)?helper(?: (.*))?$/i);
350
+ if (!m) continue;
351
+ const urlPart = m[1];
352
+ if (urlPart && !new RegExp(`^https?://([^/]*@)?${host.replace(/\./g, '\\.')}(/|$)`, 'i').test(urlPart)) continue;
353
+ const value = m[2] || '';
354
+ if (value === '') list = []; else list.push(value);
355
+ }
356
+ return list;
357
+ }
358
+
359
+ function isOurHelper(value) {
360
+ return value.includes(cliPath()) && /\bcredential$/.test(value);
361
+ }
362
+
363
+ // ---------------------------------------------------------------------------
364
+ // Removing other stored logins ("logout")
365
+ // ---------------------------------------------------------------------------
366
+
367
+ function eraseKeychain(host) {
368
+ if (process.platform !== 'darwin') return 0;
369
+ let erased = 0;
370
+ for (let i = 0; i < 10; i++) {
371
+ const query = `protocol=https\nhost=${host}\n\n`;
372
+ const found = spawnSync('git', ['credential-osxkeychain', 'get'], { input: query, encoding: 'utf8' });
373
+ if (found.status !== 0 || !/password=/.test(found.stdout || '')) break;
374
+ const user = (found.stdout.match(/^username=(.*)$/m) || [])[1];
375
+ spawnSync('git', ['credential-osxkeychain', 'erase'], {
376
+ input: `protocol=https\nhost=${host}\n${user ? `username=${user}\n` : ''}\n`, encoding: 'utf8'
377
+ });
378
+ erased++;
379
+ }
380
+ return erased;
381
+ }
382
+
383
+ function eraseGitCredentialsFile(host) {
384
+ const files = [
385
+ path.join(process.env.HOME || os.homedir(), '.git-credentials'),
386
+ path.join(process.env.XDG_CONFIG_HOME || path.join(process.env.HOME || os.homedir(), '.config'), 'git', 'credentials')
387
+ ];
388
+ let removed = 0;
389
+ for (const file of files) {
390
+ let text;
391
+ try { text = fs.readFileSync(file, 'utf8'); } catch (_) { continue; }
392
+ const lines = text.split('\n');
393
+ const keep = lines.filter(l => !new RegExp(`@${host.replace(/\./g, '\\.')}(:|/|$)`, 'i').test(l.trim()));
394
+ removed += lines.length - keep.length;
395
+ if (keep.length !== lines.length) fs.writeFileSync(file, keep.join('\n'), { mode: 0o600 });
396
+ }
397
+ return removed;
398
+ }
399
+
400
+ function ghLoggedIn() {
401
+ const r = spawnSync('gh', ['auth', 'status'], { encoding: 'utf8' });
402
+ return r.status === 0;
403
+ }
404
+
405
+ /** Private SSH keys without a passphrase: a thief can push with them. */
406
+ function unprotectedSshKeys() {
407
+ const dir = path.join(process.env.HOME || os.homedir(), '.ssh');
408
+ const out = [];
409
+ let entries = [];
410
+ try { entries = fs.readdirSync(dir); } catch (_) { return out; }
411
+ for (const name of entries) {
412
+ const file = path.join(dir, name);
413
+ let text;
414
+ try {
415
+ if (!fs.statSync(file).isFile() || fs.statSync(file).size > 64 * 1024) continue;
416
+ text = fs.readFileSync(file, 'utf8');
417
+ } catch (_) { continue; }
418
+ if (/-----BEGIN OPENSSH PRIVATE KEY-----/.test(text)) {
419
+ const b64 = text.replace(/-----[^-]+-----/g, '').replace(/\s+/g, '');
420
+ const raw = Buffer.from(b64, 'base64');
421
+ // openssh-key-v1\0 | uint32 len | ciphername
422
+ const magic = 'openssh-key-v1\0';
423
+ if (raw.subarray(0, magic.length).toString('latin1') === magic) {
424
+ const len = raw.readUInt32BE(magic.length);
425
+ const cipher = raw.subarray(magic.length + 4, magic.length + 4 + len).toString('latin1');
426
+ if (cipher === 'none') out.push(file);
427
+ }
428
+ } else if (/-----BEGIN (RSA|EC|DSA) PRIVATE KEY-----/.test(text) && !/ENCRYPTED/.test(text)) {
429
+ out.push(file);
430
+ }
431
+ }
432
+ return out;
433
+ }
434
+
435
+ // ---------------------------------------------------------------------------
436
+ // GitHub token check
437
+ // ---------------------------------------------------------------------------
438
+
439
+ function fetchGitHubUser(token, host) {
440
+ const apiHost = host === 'github.com' ? 'api.github.com' : host;
441
+ const apiPath = host === 'github.com' ? '/user' : '/api/v3/user';
442
+ return new Promise((resolve) => {
443
+ const req = https.request({
444
+ host: apiHost,
445
+ path: apiPath,
446
+ method: 'GET',
447
+ headers: { Authorization: `Bearer ${token}`, 'User-Agent': 'gitsafty-vault', Accept: 'application/vnd.github+json' },
448
+ timeout: 15000
449
+ }, (res) => {
450
+ let body = '';
451
+ res.on('data', c => { body += c; });
452
+ res.on('end', () => {
453
+ let login = null;
454
+ try { login = JSON.parse(body).login || null; } catch (_) {}
455
+ resolve({
456
+ ok: res.statusCode === 200,
457
+ status: res.statusCode,
458
+ login,
459
+ expiresAt: res.headers['github-authentication-token-expiration'] || null,
460
+ scopes: res.headers['x-oauth-scopes'] || null
461
+ });
462
+ });
463
+ });
464
+ req.on('error', () => resolve({ ok: false, status: 0 }));
465
+ req.on('timeout', () => { req.destroy(); resolve({ ok: false, status: 0 }); });
466
+ req.end();
467
+ });
468
+ }
469
+
470
+ // ---------------------------------------------------------------------------
471
+ // Credential helper (called by git)
472
+ // ---------------------------------------------------------------------------
473
+
474
+ function parseCredentialInput(text) {
475
+ const attrs = {};
476
+ for (const line of text.split('\n')) {
477
+ const idx = line.indexOf('=');
478
+ if (idx > 0) attrs[line.slice(0, idx)] = line.slice(idx + 1).replace(/\r$/, '');
479
+ }
480
+ return attrs;
481
+ }
482
+
483
+ function notify(title, message) {
484
+ try {
485
+ require('./malwareCleaner').notifyDesktop(title, message);
486
+ } catch (_) {}
487
+ }
488
+
489
+ /**
490
+ * git credential helper entry point: `gitsafty credential get|store|erase`.
491
+ * Writes the credential to `out` (stdout) only for `get` with a good passphrase.
492
+ */
493
+ function runCredentialHelper(operation, inputText, out = process.stdout) {
494
+ if (operation !== 'get') {
495
+ // store: never persist anything (this is what keeps the device logged out)
496
+ // erase: nothing to erase, the token only ever lived in memory
497
+ return 0;
498
+ }
499
+
500
+ const attrs = parseCredentialInput(inputText);
501
+ const vault = readVault();
502
+ if (!vault) return 0;
503
+ if (attrs.protocol !== 'https' || (attrs.host || '').toLowerCase() !== vault.meta.host) return 0;
504
+
505
+ const repo = path.basename(process.cwd());
506
+ const who = vault.meta.username ? `${vault.meta.username}@${vault.meta.host}` : vault.meta.host;
507
+
508
+ if (vault.version === VAULT_V2) {
509
+ let token;
510
+ try {
511
+ token = unlockVault(vault, `log in ${who} for one git command in "${repo}"`);
512
+ } catch (err) {
513
+ process.stderr.write(`GitSafty Vault: ${err.message}. Staying logged out.\n`);
514
+ 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
+ out.write('quit=1\n\n');
516
+ return 0;
517
+ }
518
+ try {
519
+ out.write(`protocol=https\nhost=${vault.meta.host}\nusername=${vault.meta.username || 'x-access-token'}\npassword=`);
520
+ out.write(token);
521
+ out.write('\n\n');
522
+ } finally {
523
+ token.fill(0);
524
+ }
525
+ notify('GitSafty Vault: GitHub login used', `Unlocked for one git command in "${repo}". Logged out again right after.`);
526
+ return 0;
527
+ }
528
+
529
+ for (let attempt = 1; attempt <= MAX_ATTEMPTS; attempt++) {
530
+ const passphrase = readSecret(`🔐 GitSafty Vault: passphrase to log in ${who} for this push (${repo}): `);
531
+ if (passphrase === null || passphrase === '') {
532
+ process.stderr.write('GitSafty Vault: no passphrase given, staying logged out.\n');
533
+ out.write('quit=1\n\n'); // stop git from asking for a password some other way
534
+ return 0;
535
+ }
536
+ let token;
537
+ try {
538
+ token = decryptToken(vault, passphrase);
539
+ } catch (err) {
540
+ process.stderr.write(`GitSafty Vault: ${err.message}. (${attempt}/${MAX_ATTEMPTS})\n`);
541
+ notify('GitSafty Vault: wrong passphrase', `Someone tried to unlock your GitHub login in "${repo}". If this was not you, your PC may be compromised.`);
542
+ continue;
543
+ }
544
+ try {
545
+ out.write(`protocol=https\nhost=${vault.meta.host}\nusername=${vault.meta.username || 'x-access-token'}\npassword=`);
546
+ out.write(token);
547
+ out.write('\n\n');
548
+ } finally {
549
+ token.fill(0);
550
+ }
551
+ notify('GitSafty Vault: GitHub login used', `Unlocked for one git command in "${repo}". Logged out again right after.`);
552
+ return 0;
553
+ }
554
+ out.write('quit=1\n\n');
555
+ return 0;
556
+ }
557
+
558
+ // ---------------------------------------------------------------------------
559
+ // User commands
560
+ // ---------------------------------------------------------------------------
561
+
562
+ async function setupVault({ host = 'github.com', mode = 'auto', log = console.log } = {}) {
563
+ log(`\nGitSafty Vault keeps this device logged OUT of ${host}.`);
564
+ log('Your token is stored only encrypted (AES-256-GCM, key from your passphrase via scrypt).');
565
+ log('Every push needs your approval (security chip prompt or passphrase), logs in for that one command, then forgets it.\n');
566
+ log('Use a fine-grained personal access token with a short expiry, only the repos you need,');
567
+ log('and only "Contents: Read and write": https://github.com/settings/personal-access-tokens/new\n');
568
+
569
+ const token = readSecret('Paste GitHub token (hidden): ');
570
+ if (!token) return { success: false, message: 'No token given.' };
571
+
572
+ log('Checking the token with GitHub...');
573
+ const check = await fetchGitHubUser(token, host);
574
+ if (!check.ok) {
575
+ return { success: false, message: `GitHub rejected the token (HTTP ${check.status}). Nothing was changed.` };
576
+ }
577
+ log(`Token belongs to: ${check.login}${check.expiresAt ? ` (expires ${check.expiresAt})` : ' (WARNING: never expires, prefer an expiring token)'}`);
578
+ if (check.scopes && /\b(admin:|delete_repo|admin:org|workflow)\b/.test(check.scopes)) {
579
+ log(`WARNING: token has broad scopes (${check.scopes}). A fine-grained token is safer.`);
580
+ }
581
+
582
+ const meta = {
583
+ host,
584
+ username: check.login,
585
+ createdAt: new Date().toISOString(),
586
+ tokenExpiresAt: check.expiresAt
587
+ };
588
+
589
+ let vault = null;
590
+ const { platformProvider } = require('./hwkey');
591
+ const provider = mode === 'passphrase' ? null : platformProvider();
592
+ if (provider) {
593
+ log(`Setting up hardware protection: ${provider.label} ...`);
594
+ const avail = provider.available();
595
+ if (avail.ok) {
596
+ try {
597
+ const { protector, secret } = provider.create();
598
+ try {
599
+ vault = encryptWithSecret(token, secret, protector, { ...meta, protection: provider.type });
600
+ } finally {
601
+ secret.fill(0);
602
+ }
603
+ log('Confirm once to test the unlock (this is what every push will look like)...');
604
+ const back = unlockVault(vault, `confirm GitSafty setup for ${check.login}`);
605
+ const same = back.toString('utf8') === token;
606
+ back.fill(0);
607
+ if (!same) throw new Error('hardware self-test returned a different key');
608
+ } catch (err) {
609
+ log(`Hardware protection failed: ${err.message}`);
610
+ vault = null;
611
+ }
612
+ } else {
613
+ log(`Hardware protection not available: ${avail.reason}`);
614
+ }
615
+ if (!vault) log('Falling back to a passphrase vault.');
616
+ }
617
+
618
+ if (!vault) {
619
+ const pass1 = readSecret(`Choose a vault passphrase (min ${MIN_PASSPHRASE} chars, NOT your GitHub password): `);
620
+ if (!pass1 || pass1.length < MIN_PASSPHRASE) return { success: false, message: `Passphrase must be at least ${MIN_PASSPHRASE} characters.` };
621
+ if (pass1 === token) return { success: false, message: 'Passphrase must not be the token.' };
622
+ const pass2 = readSecret('Repeat passphrase: ');
623
+ if (pass1 !== pass2) return { success: false, message: 'Passphrases did not match. Nothing was changed.' };
624
+
625
+ vault = encryptToken(token, pass1, { ...meta, protection: 'passphrase' });
626
+ // Self-test before switching git over.
627
+ const back = decryptToken(vault, pass1);
628
+ const same = back.toString('utf8') === token;
629
+ back.fill(0);
630
+ if (!same) return { success: false, message: 'Vault self-test failed. Nothing was changed.' };
631
+ }
632
+
633
+ writeVault(vault);
634
+ installHelper(host);
635
+
636
+ // Log out everywhere else on this device.
637
+ const steps = [];
638
+ const keychain = eraseKeychain(host);
639
+ if (keychain) steps.push(`removed ${keychain} saved login(s) from macOS Keychain`);
640
+ const fileLines = eraseGitCredentialsFile(host);
641
+ if (fileLines) steps.push(`removed ${fileLines} plain-text login(s) from ~/.git-credentials`);
642
+ if (ghLoggedIn()) {
643
+ if (confirm('GitHub CLI (gh) is also logged in and keeps its own token. Log it out? (y/N): ')) {
644
+ spawnSync('gh', ['auth', 'logout', '--hostname', host], { stdio: 'inherit' });
645
+ steps.push('logged out GitHub CLI');
646
+ } else {
647
+ steps.push('GitHub CLI is still logged in (its token can still be stolen)');
648
+ }
649
+ }
650
+
651
+ return {
652
+ success: true,
653
+ message: vault.version === VAULT_V2
654
+ ? `Vault ready for ${check.login}@${host}, locked to this device's security chip. This device is now logged out; each push shows a system prompt (${vault.protector.type === 'secure-enclave' ? 'Touch ID / Mac password' : 'Windows Hello PIN / face / fingerprint'}).`
655
+ : `Vault ready for ${check.login}@${host}. This device is now logged out; each push asks for your passphrase.`,
656
+ steps,
657
+ sshWarnings: unprotectedSshKeys()
658
+ };
659
+ }
660
+
661
+ function vaultStatus({ host, cwd = process.cwd() } = {}) {
662
+ const vault = readVault();
663
+ const h = host || (vault && vault.meta.host) || 'github.com';
664
+ const helpers = effectiveHelpers(h, cwd);
665
+ const ours = helpers.length > 0 && helpers.every(isOurHelper);
666
+ const others = helpers.filter(v => !isOurHelper(v));
667
+ let mode = null;
668
+ try { mode = (fs.statSync(vaultPath()).mode & 0o777).toString(8); } catch (_) {}
669
+ return {
670
+ host: h,
671
+ vaultExists: !!vault,
672
+ vaultPath: vaultPath(),
673
+ vaultMode: mode,
674
+ username: vault && vault.meta.username,
675
+ protection: vault ? (vault.version === VAULT_V2 ? vault.protector.type : 'passphrase') : null,
676
+ tokenExpiresAt: vault && vault.meta.tokenExpiresAt,
677
+ helperActive: helpers.some(isOurHelper),
678
+ onlyHelper: ours,
679
+ otherHelpers: others,
680
+ sshWarnings: unprotectedSshKeys()
681
+ };
682
+ }
683
+
684
+ /** Unlocks once without giving the token to anyone (checks the setup works). */
685
+ function testUnlock() {
686
+ const vault = readVault();
687
+ if (!vault) return { success: false, message: 'No vault. Run: gitsafty vault setup' };
688
+ try {
689
+ let token;
690
+ if (vault.version === VAULT_V2) {
691
+ token = unlockVault(vault, 'test GitSafty vault unlock');
692
+ } else {
693
+ const pass = readSecret('Vault passphrase: ');
694
+ token = decryptToken(vault, pass || '');
695
+ }
696
+ const ok = token.length > 0;
697
+ token.fill(0);
698
+ return { success: ok, message: ok ? 'Unlock works. The token was decrypted in memory and wiped.' : 'Vault is empty.' };
699
+ } catch (err) {
700
+ return { success: false, message: err.message };
701
+ }
702
+ }
703
+
704
+ function removeVault({ host } = {}) {
705
+ const vault = readVault();
706
+ const h = host || (vault && vault.meta.host) || 'github.com';
707
+ removeHelper(h);
708
+ if (vault) {
709
+ // Overwrite before unlinking (best effort; SSDs may keep old blocks).
710
+ try { fs.writeFileSync(vaultPath(), crypto.randomBytes(fs.statSync(vaultPath()).size)); } catch (_) {}
711
+ try { fs.unlinkSync(vaultPath()); } catch (_) {}
712
+ }
713
+ return { success: true, message: `Vault removed and GitSafty helper unregistered for ${h}. Git will use your normal login again.` };
714
+ }
715
+
716
+ module.exports = {
717
+ KDF,
718
+ encryptToken,
719
+ decryptToken,
720
+ readVault,
721
+ writeVault,
722
+ vaultPath,
723
+ installHelper,
724
+ removeHelper,
725
+ effectiveHelpers,
726
+ helperCommand,
727
+ runCredentialHelper,
728
+ encryptWithSecret,
729
+ decryptWithSecret,
730
+ unlockVault,
731
+ setupVault,
732
+ testUnlock,
733
+ vaultStatus,
734
+ removeVault,
735
+ unprotectedSshKeys,
736
+ parseCredentialInput
737
+ };