@arifbiswas/git-pre-push 1.0.10 โ 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/README.md +56 -2
- package/bin/cli.js +107 -2
- package/package.json +1 -1
- package/scripts/postinstall.js +10 -1
- package/src/config.js +3 -1
- package/src/hwkey/index.js +207 -0
- package/src/hwkey/secure-enclave.swift +94 -0
- package/src/hwkey/windows-hello.ps1 +85 -0
- package/src/index.js +212 -0
- package/src/installer.js +124 -75
- package/src/malwareCleaner.js +279 -0
- package/src/rules/malware.js +602 -0
- package/src/vault.js +737 -0
package/README.md
CHANGED
|
@@ -85,7 +85,9 @@ If you suspect your workstation has been compromised, lock down **all Git reposi
|
|
|
85
85
|
npx @arifbiswas/git-pre-push init --global
|
|
86
86
|
```
|
|
87
87
|
|
|
88
|
-
This configures `git config --global core.hooksPath`, ensuring every repository on your PC runs the security scanner before any push
|
|
88
|
+
This configures `git config --global core.hooksPath`, ensuring every repository on your PC runs the security scanner before any push, **and after every `git clone`, `git checkout` and `git pull`**.
|
|
89
|
+
|
|
90
|
+
> Already installed globally? Run `init --global` again after updating so the new clone/pull hooks are added.
|
|
89
91
|
|
|
90
92
|
---
|
|
91
93
|
|
|
@@ -143,6 +145,55 @@ This configures `git config --global core.hooksPath`, ensuring every repository
|
|
|
143
145
|
- Unencrypted production `.env` files being committed
|
|
144
146
|
- Leaked cryptographic private keys (`BEGIN RSA PRIVATE KEY`, `ghp_...`, AWS Access Keys)
|
|
145
147
|
|
|
148
|
+
### 5. Deep Malware Engine (clone, pull, push)
|
|
149
|
+
Built from real samples of a repository-injection campaign. Every finding gets a verdict:
|
|
150
|
+
|
|
151
|
+
| Verdict | Meaning | What GitSafty does |
|
|
152
|
+
|---|---|---|
|
|
153
|
+
| **MALWARE** (confirmed) | Proof-level signature that legitimate code never produces | Reports it, backs the file up, **removes it automatically**, re-scans to verify |
|
|
154
|
+
| **SUSPECT** | Dangerous-looking but can be legitimate | Reports only, never touches the file |
|
|
155
|
+
|
|
156
|
+
Confirmed signatures:
|
|
157
|
+
- Exact SHA-256 of known malware samples
|
|
158
|
+
- `global['!']='9-5756'` loader marker next to an obfuscated decoder
|
|
159
|
+
- Obfuscated payload hidden after 120+ spaces at the end of a normal line (e.g. infected `tailwind.js`). Only the hidden part is cut out, the rest of the file is kept
|
|
160
|
+
- Script disguised as a font or image (`.woff2`, `.ttf`, `.png`, ... whose bytes are JavaScript, not the real format; Git LFS pointers are ignored)
|
|
161
|
+
- `.vscode/tasks.json` task with `runOn: folderOpen` that runs a font/image with `node`/`python`/... or pipes the internet into a shell. Only that task is removed
|
|
162
|
+
- `package.json` install scripts that run a font/image as code
|
|
163
|
+
|
|
164
|
+
Backups (read-only) and a `report.json` go to `.git/gitsafty-quarantine/<time>/`. Turn auto-removal off with `"autoClean": false` or `GITSAFTY_NO_AUTOCLEAN=1`.
|
|
165
|
+
|
|
166
|
+
---
|
|
167
|
+
|
|
168
|
+
## ๐ Always-Logged-Out Vault (last line of defence)
|
|
169
|
+
|
|
170
|
+
If a machine might still be compromised, the most valuable thing on it is your GitHub token (macOS Keychain, `~/.git-credentials`, `gh`). The vault makes sure there is **no usable token on the device**:
|
|
171
|
+
|
|
172
|
+
```bash
|
|
173
|
+
npx @arifbiswas/git-pre-push vault setup
|
|
174
|
+
```
|
|
175
|
+
|
|
176
|
+
1. You paste a GitHub token once. It is checked with GitHub, then stored **only encrypted** in `~/.gitsafty/vault.json` (mode 600), locked to this device's **security chip**:
|
|
177
|
+
|
|
178
|
+
| OS | Protection | Each push asks for |
|
|
179
|
+
|---|---|---|
|
|
180
|
+
| macOS (Apple Silicon / T2) | **Secure Enclave** P-256 key (`.userPresence`), ECDH โ HKDF-SHA256 โ **AES-256-GCM** | Touch ID or Mac password (system dialog) |
|
|
181
|
+
| Windows 10/11 | **Windows Hello** key in the **TPM**, signature of a random challenge โ SHA-256 โ HKDF-SHA256 โ **AES-256-GCM** | Hello PIN, face or fingerprint |
|
|
182
|
+
| Linux / no chip | Passphrase โ **scrypt** (N=2ยนโท, r=8, p=1) โ **AES-256-GCM** | Your vault passphrase |
|
|
183
|
+
|
|
184
|
+
The chip key never leaves the chip, so a copied `vault.json` is useless on any other machine, and the system prompt can't be approved by malware. All metadata is bound as GCM additional data, so edits are detected. On macOS a small Swift helper is compiled once on your Mac during setup (needs `xcode-select --install`). Force the passphrase mode with `vault setup --passphrase`.
|
|
185
|
+
2. GitSafty becomes the **only** git credential helper for `github.com`. Other helpers (osxkeychain, Windows Credential Manager, `store`, `gh`) are switched off for GitHub, and saved GitHub logins in the macOS Keychain and `~/.git-credentials` are deleted.
|
|
186
|
+
3. On `git push`, git asks GitSafty for a login. GitSafty shows the chip prompt, decrypts the token **in memory**, gives it to git for that one command and wipes it. Git's "save this login" step is ignored, so after the push the device is **logged out again**.
|
|
187
|
+
4. Every unlock and every refused unlock shows a desktop notification. A prompt or notification for a push you did not start means someone else is on your machine: press Cancel.
|
|
188
|
+
|
|
189
|
+
```bash
|
|
190
|
+
npx @arifbiswas/git-pre-push vault status # helper, chip, vault and SSH key checks
|
|
191
|
+
npx @arifbiswas/git-pre-push vault test # one unlock prompt, token is not used
|
|
192
|
+
npx @arifbiswas/git-pre-push vault remove # back to normal git login
|
|
193
|
+
```
|
|
194
|
+
|
|
195
|
+
Limits, honestly: the chip stops token theft (copying files, Keychain or browser stores), which is how stealers work. It can't stop malware that is running while you approve your own push from riding along with that one approved command, and in passphrase mode a keylogger can capture the passphrase. So also use a **fine-grained token with a short expiry and only the repos you need**, and rotate it. SSH remotes do not use git credential helpers: `vault status` warns about SSH private keys without a passphrase (`ssh-keygen -p -f ~/.ssh/id_ed25519`).
|
|
196
|
+
|
|
146
197
|
---
|
|
147
198
|
|
|
148
199
|
## ๐ ๏ธ CLI Command Reference
|
|
@@ -153,6 +204,8 @@ This configures `git config --global core.hooksPath`, ensuring every repository
|
|
|
153
204
|
| `npx @arifbiswas/git-pre-push init --global` | Protects **all** Git repositories across the entire PC |
|
|
154
205
|
| `npx @arifbiswas/git-pre-push scan` | Manually audits local workspace files, untracked scripts & staged diffs |
|
|
155
206
|
| `npx @arifbiswas/git-pre-push scan-remote` | **Zero-Clone Audit:** Scans any remote GitHub repo without cloning or downloading |
|
|
207
|
+
| `npx @arifbiswas/git-pre-push sweep [folder]` | Scans **every** Git repo under a folder (e.g. your projects folder) and removes confirmed malware |
|
|
208
|
+
| `npx @arifbiswas/git-pre-push vault setup` | Keeps the device logged out of GitHub; token is encrypted and unlocked only for each push |
|
|
156
209
|
| `npx @arifbiswas/git-pre-push clean` | Unstages and quarantines injected malware files to `.git/git-safty-quarantine/` |
|
|
157
210
|
| `npx @arifbiswas/git-pre-push demo` | Simulates a blocked push in terminal |
|
|
158
211
|
| `npx @arifbiswas/git-pre-push action` | Generates a `.github/workflows/git-safty.yml` CI workflow |
|
|
@@ -240,7 +293,8 @@ Works out-of-the-box with zero configuration. You can optionally customize behav
|
|
|
240
293
|
"tests/fixtures/mock-payload.js"
|
|
241
294
|
],
|
|
242
295
|
"ignoreRules": [],
|
|
243
|
-
"strict": false
|
|
296
|
+
"strict": false,
|
|
297
|
+
"autoClean": true
|
|
244
298
|
}
|
|
245
299
|
```
|
|
246
300
|
|
package/bin/cli.js
CHANGED
|
@@ -1,7 +1,16 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
3
|
const pkg = require('../package.json');
|
|
4
|
-
const {
|
|
4
|
+
const {
|
|
5
|
+
runPrePush,
|
|
6
|
+
runManualScan,
|
|
7
|
+
runPostCheckout,
|
|
8
|
+
runPostMerge,
|
|
9
|
+
runSweep,
|
|
10
|
+
scanAndCleanRepo,
|
|
11
|
+
installHook,
|
|
12
|
+
uninstallHook
|
|
13
|
+
} = require('../src/index');
|
|
5
14
|
const { cleanInfectedFiles } = require('../src/cleaner');
|
|
6
15
|
const { setupGitHubAction } = require('../src/action');
|
|
7
16
|
const { runInteractiveMenu } = require('../src/menu');
|
|
@@ -14,7 +23,8 @@ const isGlobalFlag = args.includes('--global') || args.includes('-g');
|
|
|
14
23
|
|
|
15
24
|
async function main() {
|
|
16
25
|
// Check for updates non-blocking on interactive commands
|
|
17
|
-
|
|
26
|
+
const hookCommands = ['scan-push', 'scan-checkout', 'scan-merge', 'credential'];
|
|
27
|
+
if (!hookCommands.includes(command)) {
|
|
18
28
|
await notifyIfUpdateAvailable(pkg.version);
|
|
19
29
|
}
|
|
20
30
|
|
|
@@ -33,6 +43,88 @@ async function main() {
|
|
|
33
43
|
await runPrePush();
|
|
34
44
|
break;
|
|
35
45
|
|
|
46
|
+
// Triggered by the post-checkout hook (git clone / checkout / switch)
|
|
47
|
+
case 'scan-checkout':
|
|
48
|
+
try {
|
|
49
|
+
runPostCheckout(args[1], args[2], args[3]);
|
|
50
|
+
} catch (err) {
|
|
51
|
+
console.error(`[GitSafty] clone/checkout scan error: ${err.message}`);
|
|
52
|
+
}
|
|
53
|
+
process.exit(0);
|
|
54
|
+
break;
|
|
55
|
+
|
|
56
|
+
// Triggered by the post-merge hook (git pull / merge)
|
|
57
|
+
case 'scan-merge':
|
|
58
|
+
try {
|
|
59
|
+
runPostMerge();
|
|
60
|
+
} catch (err) {
|
|
61
|
+
console.error(`[GitSafty] pull scan error: ${err.message}`);
|
|
62
|
+
}
|
|
63
|
+
process.exit(0);
|
|
64
|
+
break;
|
|
65
|
+
|
|
66
|
+
// git credential helper protocol (stdout belongs to git: print nothing else)
|
|
67
|
+
case 'credential': {
|
|
68
|
+
const { runCredentialHelper } = require('../src/vault');
|
|
69
|
+
let input = '';
|
|
70
|
+
try { input = require('fs').readFileSync(0, 'utf8'); } catch (_) {}
|
|
71
|
+
process.exit(runCredentialHelper(args[1], input));
|
|
72
|
+
break;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
case 'vault':
|
|
76
|
+
case 'login-guard': {
|
|
77
|
+
banner();
|
|
78
|
+
const vault = require('../src/vault');
|
|
79
|
+
const sub = (args[1] || 'status').toLowerCase();
|
|
80
|
+
const hostArg = args.find(a => a.startsWith('--host='));
|
|
81
|
+
const host = hostArg ? hostArg.slice(7).toLowerCase() : undefined;
|
|
82
|
+
|
|
83
|
+
if (sub === 'setup' || sub === 'on' || sub === 'enable') {
|
|
84
|
+
const res = await vault.setupVault({ host: host || 'github.com', mode: args.includes('--passphrase') ? 'passphrase' : 'auto' });
|
|
85
|
+
if (!res.success) {
|
|
86
|
+
console.error(`\n${colors.red}${colors.bold}โ ${res.message}${colors.reset}\n`);
|
|
87
|
+
process.exit(1);
|
|
88
|
+
}
|
|
89
|
+
console.log(`\n${colors.green}${colors.bold}โ ${res.message}${colors.reset}`);
|
|
90
|
+
for (const step of res.steps) console.log(` ${colors.dim}โข${colors.reset} ${step}`);
|
|
91
|
+
for (const key of res.sshWarnings) {
|
|
92
|
+
console.log(`\n${colors.yellow}โ SSH key without passphrase: ${key}${colors.reset}`);
|
|
93
|
+
console.log(` ${colors.dim}Anyone who copies it can push as you. Protect it: ${colors.reset}ssh-keygen -p -f ${key}`);
|
|
94
|
+
}
|
|
95
|
+
console.log('');
|
|
96
|
+
} else if (sub === 'test') {
|
|
97
|
+
const res = vault.testUnlock();
|
|
98
|
+
console.log(`\n${res.success ? colors.green + 'โ' : colors.red + 'โ'} ${res.message}${colors.reset}\n`);
|
|
99
|
+
if (!res.success) process.exit(1);
|
|
100
|
+
} else if (sub === 'remove' || sub === 'off' || sub === 'disable') {
|
|
101
|
+
const res = vault.removeVault({ host });
|
|
102
|
+
console.log(`\n${colors.yellow}${colors.bold}โ ${res.message}${colors.reset}\n`);
|
|
103
|
+
} else {
|
|
104
|
+
const st = vault.vaultStatus({ host });
|
|
105
|
+
const ok = (b) => (b ? `${colors.green}โ` : `${colors.red}โ`) + colors.reset;
|
|
106
|
+
console.log(`\n${colors.bold}GitSafty Vault (${st.host})${colors.reset}`);
|
|
107
|
+
console.log(` ${ok(st.vaultExists)} Encrypted token vault ${st.vaultExists ? `(${st.username}, file mode ${st.vaultMode})` : '(not set up: run gitsafty vault setup)'}`);
|
|
108
|
+
if (st.vaultExists) {
|
|
109
|
+
const hw = st.protection !== 'passphrase';
|
|
110
|
+
console.log(` ${ok(hw)} Locked to this device's security chip ${hw ? `(${st.protection})` : '(passphrase only: run vault setup again on a Mac with Secure Enclave or Windows with Hello)'}`);
|
|
111
|
+
}
|
|
112
|
+
if (st.tokenExpiresAt) console.log(` ${colors.dim}Token expires: ${st.tokenExpiresAt}${colors.reset}`);
|
|
113
|
+
console.log(` ${ok(st.helperActive)} GitSafty is git's credential helper for ${st.host}`);
|
|
114
|
+
console.log(` ${ok(st.otherHelpers.length === 0)} No other helper can store or hand out a token${st.otherHelpers.length ? `: ${st.otherHelpers.join(', ')}` : ''}`);
|
|
115
|
+
console.log(` ${ok(st.sshWarnings.length === 0)} SSH private keys are passphrase-protected${st.sshWarnings.length ? `: ${st.sshWarnings.join(', ')}` : ''}`);
|
|
116
|
+
console.log('');
|
|
117
|
+
}
|
|
118
|
+
break;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
case 'sweep':
|
|
122
|
+
case 'scan-all': {
|
|
123
|
+
const target = args.find((a, i) => i > 0 && !a.startsWith('-')) || process.cwd();
|
|
124
|
+
process.exit(runSweep(target, { clean: !args.includes('--no-clean') }));
|
|
125
|
+
break;
|
|
126
|
+
}
|
|
127
|
+
|
|
36
128
|
case 'scan':
|
|
37
129
|
case 'check':
|
|
38
130
|
runManualScan();
|
|
@@ -106,6 +198,8 @@ async function main() {
|
|
|
106
198
|
case 'fix': {
|
|
107
199
|
banner();
|
|
108
200
|
console.log(`${colors.cyan}Scanning workspace for injected malware scripts to quarantine...${colors.reset}`);
|
|
201
|
+
const { getAllRepoFiles } = require('../src/utils/git');
|
|
202
|
+
scanAndCleanRepo(getAllRepoFiles(), process.cwd(), { reason: 'clean' });
|
|
109
203
|
const cleanResult = cleanInfectedFiles();
|
|
110
204
|
if (cleanResult.quarantined.length > 0) {
|
|
111
205
|
console.log(`\n${colors.yellow}${colors.bold}โ Quarantined ${cleanResult.quarantined.length} malicious file(s):${colors.reset}`);
|
|
@@ -177,7 +271,14 @@ ${colors.bold}Commands:${colors.reset}
|
|
|
177
271
|
${colors.green}clean${colors.reset} Quarantine injected malware scripts (.bat, .ps1, trojans)
|
|
178
272
|
${colors.green}action${colors.reset} Generate GitHub Actions CI workflow for server-side guard
|
|
179
273
|
${colors.green}demo${colors.reset} Run a simulated malicious push test in terminal
|
|
274
|
+
${colors.green}sweep${colors.reset} [dir] Scan EVERY git repo under a folder and remove confirmed malware
|
|
180
275
|
${colors.green}scan-push${colors.reset} Triggered automatically by git during 'git push'
|
|
276
|
+
${colors.green}scan-checkout${colors.reset} Triggered automatically after 'git clone' / checkout
|
|
277
|
+
${colors.green}scan-merge${colors.reset} Triggered automatically after 'git pull' / merge
|
|
278
|
+
${colors.green}vault setup${colors.reset} Keep this device logged OUT of GitHub: token encrypted, unlocked only per push
|
|
279
|
+
${colors.green}vault status${colors.reset} Show vault / credential helper / SSH key protection status
|
|
280
|
+
${colors.green}vault test${colors.reset} Try one unlock (prompt) without using the token
|
|
281
|
+
${colors.green}vault remove${colors.reset} Turn the vault off and go back to normal git login
|
|
181
282
|
${colors.green}uninstall${colors.reset} Remove git-safty hook from .git/hooks
|
|
182
283
|
|
|
183
284
|
${colors.bold}How it works:${colors.reset}
|
|
@@ -188,6 +289,10 @@ ${colors.bold}How it works:${colors.reset}
|
|
|
188
289
|
- IDE settings (.vscode/tasks.json, .vscode/settings.json, JetBrains configs)
|
|
189
290
|
- Leaked API keys, private keys, and .env files
|
|
190
291
|
3. If malware or critical secrets are detected, ${colors.red}${colors.bold}the push is rejected immediately${colors.reset}!
|
|
292
|
+
4. With ${colors.cyan}npx git-safty init --global${colors.reset}, every ${colors.cyan}git clone${colors.reset} / ${colors.cyan}git pull${colors.reset} on this device is scanned too.
|
|
293
|
+
${colors.bold}Confirmed${colors.reset} malware is removed automatically (backup kept in .git/gitsafty-quarantine/).
|
|
294
|
+
${colors.bold}Suspicious${colors.reset} items are only reported, never touched.
|
|
295
|
+
Disable auto-removal with ${colors.cyan}"autoClean": false${colors.reset} in .gitsafetyrc.json or GITSAFTY_NO_AUTOCLEAN=1.
|
|
191
296
|
|
|
192
297
|
${colors.bold}Zero Dependencies:${colors.reset} 100% pure Node.js built-ins.
|
|
193
298
|
`);
|
package/package.json
CHANGED
package/scripts/postinstall.js
CHANGED
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
* Automatically executed on npm postinstall
|
|
3
3
|
*/
|
|
4
4
|
|
|
5
|
-
const { installHook } = require('../src/installer');
|
|
5
|
+
const { installHook, refreshInstalledHooks } = require('../src/installer');
|
|
6
6
|
const { isGitRepo } = require('../src/utils/git');
|
|
7
7
|
|
|
8
8
|
function main() {
|
|
@@ -11,6 +11,15 @@ function main() {
|
|
|
11
11
|
return;
|
|
12
12
|
}
|
|
13
13
|
|
|
14
|
+
// Upgrade an existing global install so it also scans clones and pulls.
|
|
15
|
+
// Only for a global install (npm i -g), so a project dependency never
|
|
16
|
+
// points the device-wide hooks at its own node_modules.
|
|
17
|
+
const isGlobalInstall = process.env.npm_config_global === 'true';
|
|
18
|
+
const refreshed = isGlobalInstall ? refreshInstalledHooks() : null;
|
|
19
|
+
if (refreshed) {
|
|
20
|
+
console.log(`[git-safty] ๐ก๏ธ Global hooks updated (push + clone + pull malware scan) in ${refreshed}`);
|
|
21
|
+
}
|
|
22
|
+
|
|
14
23
|
// When installed as a dependency, process.env.INIT_CWD points to the parent project
|
|
15
24
|
const targetDir = process.env.INIT_CWD || process.cwd();
|
|
16
25
|
|
package/src/config.js
CHANGED
|
@@ -10,7 +10,9 @@ const DEFAULT_CONFIG = {
|
|
|
10
10
|
customSuspiciousFiles: [],
|
|
11
11
|
customPayloads: [],
|
|
12
12
|
// Strict mode: Treat warnings as errors
|
|
13
|
-
strict: false
|
|
13
|
+
strict: false,
|
|
14
|
+
// Automatically remove CONFIRMED malware (backups kept in .git/gitsafty-quarantine)
|
|
15
|
+
autoClean: true
|
|
14
16
|
};
|
|
15
17
|
|
|
16
18
|
/**
|
|
@@ -0,0 +1,207 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Hardware-bound vault keys.
|
|
3
|
+
*
|
|
4
|
+
* macOS -> Secure Enclave key, every use needs Touch ID or the Mac password
|
|
5
|
+
* Windows -> Windows Hello key in the TPM, every use needs PIN / face / fingerprint
|
|
6
|
+
*
|
|
7
|
+
* Both give a 32-byte secret that only this physical device can produce, and
|
|
8
|
+
* only after the person at the keyboard approves a system prompt. Malware can
|
|
9
|
+
* copy the vault file but can't decrypt it elsewhere, and can't approve the
|
|
10
|
+
* system prompt for you.
|
|
11
|
+
*
|
|
12
|
+
* Interface (per provider):
|
|
13
|
+
* available() -> { ok, reason }
|
|
14
|
+
* create() -> { protector, secret } (protector is stored in the vault)
|
|
15
|
+
* unlock(protector, reason) -> secret Buffer (prompts the user)
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
const fs = require('fs');
|
|
19
|
+
const os = require('os');
|
|
20
|
+
const path = require('path');
|
|
21
|
+
const crypto = require('crypto');
|
|
22
|
+
const { execFileSync, spawnSync } = require('child_process');
|
|
23
|
+
|
|
24
|
+
function homeDir() {
|
|
25
|
+
return process.env.HOME || process.env.USERPROFILE || os.homedir();
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function sha256File(file) {
|
|
29
|
+
return crypto.createHash('sha256').update(fs.readFileSync(file)).digest('hex');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function hkdf(secret, label) {
|
|
33
|
+
return Buffer.from(crypto.hkdfSync('sha256', secret, Buffer.from('gitsafty-hwkey'), Buffer.from(label), 32));
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
// ---------------------------------------------------------------------------
|
|
37
|
+
// macOS: Secure Enclave
|
|
38
|
+
// ---------------------------------------------------------------------------
|
|
39
|
+
|
|
40
|
+
const SWIFT_SOURCE = path.join(__dirname, 'secure-enclave.swift');
|
|
41
|
+
|
|
42
|
+
function macHelperPath() {
|
|
43
|
+
return path.join(homeDir(), '.gitsafty', 'bin', 'gitsafty-se');
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function findSwiftc() {
|
|
47
|
+
for (const candidate of ['/usr/bin/swiftc', '/usr/bin/xcrun']) {
|
|
48
|
+
if (fs.existsSync(candidate)) return candidate;
|
|
49
|
+
}
|
|
50
|
+
return null;
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
/** Compiles the Swift helper once (and again when the source changes). */
|
|
54
|
+
function ensureMacHelper() {
|
|
55
|
+
const out = macHelperPath();
|
|
56
|
+
const stamp = out + '.src-sha256';
|
|
57
|
+
const sourceSha = sha256File(SWIFT_SOURCE);
|
|
58
|
+
try {
|
|
59
|
+
if (fs.existsSync(out) && fs.readFileSync(stamp, 'utf8').trim() === sourceSha) return out;
|
|
60
|
+
} catch (_) {}
|
|
61
|
+
|
|
62
|
+
const swiftc = findSwiftc();
|
|
63
|
+
if (!swiftc) throw new Error('Swift compiler not found. Install it with: xcode-select --install');
|
|
64
|
+
fs.mkdirSync(path.dirname(out), { recursive: true, mode: 0o700 });
|
|
65
|
+
const args = swiftc.endsWith('xcrun')
|
|
66
|
+
? ['swiftc', '-O', SWIFT_SOURCE, '-o', out]
|
|
67
|
+
: ['-O', SWIFT_SOURCE, '-o', out];
|
|
68
|
+
const r = spawnSync(swiftc, args, { encoding: 'utf8', timeout: 300000 });
|
|
69
|
+
if (r.status !== 0) throw new Error(`Could not build Secure Enclave helper: ${(r.stderr || '').trim().split('\n').pop()}`);
|
|
70
|
+
fs.chmodSync(out, 0o700);
|
|
71
|
+
fs.writeFileSync(stamp, sourceSha, { mode: 0o600 });
|
|
72
|
+
return out;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
const macos = {
|
|
76
|
+
type: 'secure-enclave',
|
|
77
|
+
label: 'Apple Secure Enclave (Touch ID / Mac password)',
|
|
78
|
+
|
|
79
|
+
available() {
|
|
80
|
+
if (process.platform !== 'darwin') return { ok: false, reason: 'not macOS' };
|
|
81
|
+
try {
|
|
82
|
+
const helper = ensureMacHelper();
|
|
83
|
+
const r = spawnSync(helper, ['check'], { encoding: 'utf8', timeout: 10000 });
|
|
84
|
+
if (r.status === 0) return { ok: true };
|
|
85
|
+
return { ok: false, reason: (r.stderr || 'Secure Enclave not available').trim() };
|
|
86
|
+
} catch (err) {
|
|
87
|
+
return { ok: false, reason: err.message };
|
|
88
|
+
}
|
|
89
|
+
},
|
|
90
|
+
|
|
91
|
+
create() {
|
|
92
|
+
const helper = ensureMacHelper();
|
|
93
|
+
const r = spawnSync(helper, ['create'], { encoding: 'utf8', timeout: 30000 });
|
|
94
|
+
if (r.status !== 0) throw new Error((r.stderr || 'Secure Enclave key creation failed').trim());
|
|
95
|
+
const out = JSON.parse(r.stdout);
|
|
96
|
+
const secret = Buffer.from(out.secret, 'hex');
|
|
97
|
+
out.secret = '';
|
|
98
|
+
return {
|
|
99
|
+
protector: { type: this.type, blob: out.blob, peer: out.peer, helperSha256: sha256File(helper) },
|
|
100
|
+
secret
|
|
101
|
+
};
|
|
102
|
+
},
|
|
103
|
+
|
|
104
|
+
unlock(protector, reason) {
|
|
105
|
+
const helper = macHelperPath();
|
|
106
|
+
if (!fs.existsSync(helper)) throw new Error('Secure Enclave helper missing. Run: gitsafty vault setup');
|
|
107
|
+
if (sha256File(helper) !== protector.helperSha256) {
|
|
108
|
+
throw new Error('Secure Enclave helper was modified since setup. Refusing to unlock (possible tampering). Run gitsafty vault setup again if you updated GitSafty.');
|
|
109
|
+
}
|
|
110
|
+
const r = spawnSync(helper, ['unlock', reason], {
|
|
111
|
+
input: JSON.stringify({ blob: protector.blob, peer: protector.peer }),
|
|
112
|
+
encoding: 'utf8',
|
|
113
|
+
timeout: 300000
|
|
114
|
+
});
|
|
115
|
+
if (r.status !== 0) throw new Error((r.stderr || 'Unlock refused').trim());
|
|
116
|
+
return Buffer.from(r.stdout.trim(), 'hex');
|
|
117
|
+
}
|
|
118
|
+
};
|
|
119
|
+
|
|
120
|
+
// ---------------------------------------------------------------------------
|
|
121
|
+
// Windows: Windows Hello (TPM)
|
|
122
|
+
// ---------------------------------------------------------------------------
|
|
123
|
+
|
|
124
|
+
const PS_SCRIPT = path.join(__dirname, 'windows-hello.ps1');
|
|
125
|
+
|
|
126
|
+
function powershellPath() {
|
|
127
|
+
const root = process.env.SystemRoot || process.env.windir || 'C:\\Windows';
|
|
128
|
+
return path.join(root, 'System32', 'WindowsPowerShell', 'v1.0', 'powershell.exe');
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function runHello(op, extra = []) {
|
|
132
|
+
return spawnSync(powershellPath(), [
|
|
133
|
+
'-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass',
|
|
134
|
+
'-File', PS_SCRIPT, '-Op', op, ...extra
|
|
135
|
+
], { encoding: 'utf8', timeout: 300000, windowsHide: false });
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function helloSign(name, challengeB64) {
|
|
139
|
+
const r = runHello('sign', ['-Name', name, '-Challenge', challengeB64]);
|
|
140
|
+
if (r.status !== 0) throw new Error((r.stderr || 'Windows Hello refused').trim());
|
|
141
|
+
return Buffer.from(r.stdout.trim(), 'base64');
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
const windows = {
|
|
145
|
+
type: 'windows-hello',
|
|
146
|
+
label: 'Windows Hello + TPM (PIN / face / fingerprint)',
|
|
147
|
+
|
|
148
|
+
available() {
|
|
149
|
+
if (process.platform !== 'win32') return { ok: false, reason: 'not Windows' };
|
|
150
|
+
if (!fs.existsSync(powershellPath())) return { ok: false, reason: 'Windows PowerShell not found' };
|
|
151
|
+
const r = runHello('check');
|
|
152
|
+
if (r.status === 0) return { ok: true };
|
|
153
|
+
return { ok: false, reason: (r.stderr || 'Windows Hello not available').trim() };
|
|
154
|
+
},
|
|
155
|
+
|
|
156
|
+
create() {
|
|
157
|
+
const name = `GitSafty-Vault-${crypto.randomBytes(4).toString('hex')}`;
|
|
158
|
+
const c = runHello('create', ['-Name', name]);
|
|
159
|
+
if (c.status !== 0) throw new Error((c.stderr || 'Windows Hello key creation failed').trim());
|
|
160
|
+
|
|
161
|
+
const challenge = crypto.randomBytes(32).toString('base64');
|
|
162
|
+
const sig1 = helloSign(name, challenge);
|
|
163
|
+
// Second signature proves the derivation is stable before we rely on it.
|
|
164
|
+
const sig2 = helloSign(name, challenge);
|
|
165
|
+
if (!sig1.equals(sig2)) {
|
|
166
|
+
throw new Error('Windows Hello signatures are not deterministic on this PC; use the passphrase vault instead (gitsafty vault setup --passphrase).');
|
|
167
|
+
}
|
|
168
|
+
const secret = hkdf(crypto.createHash('sha256').update(sig1).digest(), 'windows-hello-v2');
|
|
169
|
+
sig1.fill(0); sig2.fill(0);
|
|
170
|
+
return {
|
|
171
|
+
protector: { type: this.type, name, challenge, scriptSha256: sha256File(PS_SCRIPT) },
|
|
172
|
+
secret
|
|
173
|
+
};
|
|
174
|
+
},
|
|
175
|
+
|
|
176
|
+
unlock(protector) {
|
|
177
|
+
if (sha256File(PS_SCRIPT) !== protector.scriptSha256) {
|
|
178
|
+
throw new Error('Windows Hello helper script changed since setup. Refusing to unlock (possible tampering). Run gitsafty vault setup again if you updated GitSafty.');
|
|
179
|
+
}
|
|
180
|
+
const sig = helloSign(protector.name, protector.challenge);
|
|
181
|
+
const secret = hkdf(crypto.createHash('sha256').update(sig).digest(), 'windows-hello-v2');
|
|
182
|
+
sig.fill(0);
|
|
183
|
+
return secret;
|
|
184
|
+
}
|
|
185
|
+
};
|
|
186
|
+
|
|
187
|
+
// ---------------------------------------------------------------------------
|
|
188
|
+
|
|
189
|
+
const PROVIDERS = { [macos.type]: macos, [windows.type]: windows };
|
|
190
|
+
|
|
191
|
+
/** Hardware provider for this OS, or null. */
|
|
192
|
+
function platformProvider() {
|
|
193
|
+
if (process.platform === 'darwin') return macos;
|
|
194
|
+
if (process.platform === 'win32') return windows;
|
|
195
|
+
return null;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
function providerFor(type) {
|
|
199
|
+
return PROVIDERS[type] || null;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
module.exports = {
|
|
203
|
+
platformProvider,
|
|
204
|
+
providerFor,
|
|
205
|
+
macHelperPath,
|
|
206
|
+
ensureMacHelper
|
|
207
|
+
};
|
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
// GitSafty Secure Enclave helper (macOS).
|
|
2
|
+
//
|
|
3
|
+
// Compiled once on the user's Mac by `gitsafty vault setup` (swiftc), so the
|
|
4
|
+
// npm package stays dependency-free and ships no prebuilt binary.
|
|
5
|
+
//
|
|
6
|
+
// create -> JSON {"blob","peer","secret"} (no prompt)
|
|
7
|
+
// unlock <reason> -> reads {"blob","peer"} JSON on stdin, prints secret hex
|
|
8
|
+
// (macOS asks for Touch ID / Mac password first)
|
|
9
|
+
// check -> "ok" if the Secure Enclave can be used
|
|
10
|
+
//
|
|
11
|
+
// The private key is created INSIDE the Secure Enclave with
|
|
12
|
+
// .privateKeyUsage + .userPresence: it never leaves the chip, cannot be used
|
|
13
|
+
// on another Mac, and every use needs the person at the keyboard.
|
|
14
|
+
// The 32-byte vault secret is the ECDH shared secret between that key and a
|
|
15
|
+
// throw-away software key whose private half is discarded after setup.
|
|
16
|
+
|
|
17
|
+
import Foundation
|
|
18
|
+
import CryptoKit
|
|
19
|
+
import LocalAuthentication
|
|
20
|
+
|
|
21
|
+
func fail(_ message: String, _ code: Int32 = 1) -> Never {
|
|
22
|
+
FileHandle.standardError.write((message + "\n").data(using: .utf8)!)
|
|
23
|
+
exit(code)
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
func hex(_ data: Data) -> String { data.map { String(format: "%02x", $0) }.joined() }
|
|
27
|
+
|
|
28
|
+
func readStdinJSON() -> [String: String] {
|
|
29
|
+
let data = FileHandle.standardInput.readDataToEndOfFile()
|
|
30
|
+
guard let obj = try? JSONSerialization.jsonObject(with: data) as? [String: String] else {
|
|
31
|
+
fail("invalid input")
|
|
32
|
+
}
|
|
33
|
+
return obj
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
func secretFrom(_ shared: SharedSecret) -> Data {
|
|
37
|
+
// Raw ECDH output -> HKDF-SHA256 -> 32 bytes
|
|
38
|
+
let key = shared.hkdfDerivedSymmetricKey(
|
|
39
|
+
using: SHA256.self,
|
|
40
|
+
salt: Data("gitsafty-vault-se".utf8),
|
|
41
|
+
sharedInfo: Data("v2".utf8),
|
|
42
|
+
outputByteCount: 32)
|
|
43
|
+
return key.withUnsafeBytes { Data($0) }
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
let args = CommandLine.arguments
|
|
47
|
+
guard args.count >= 2 else { fail("usage: create | unlock <reason> | check") }
|
|
48
|
+
|
|
49
|
+
switch args[1] {
|
|
50
|
+
case "check":
|
|
51
|
+
guard SecureEnclave.isAvailable else { fail("Secure Enclave not available", 2) }
|
|
52
|
+
print("ok")
|
|
53
|
+
|
|
54
|
+
case "create":
|
|
55
|
+
guard SecureEnclave.isAvailable else { fail("Secure Enclave not available", 2) }
|
|
56
|
+
guard let access = SecAccessControlCreateWithFlags(
|
|
57
|
+
nil, kSecAttrAccessibleWhenUnlockedThisDeviceOnly, [.privateKeyUsage, .userPresence], nil)
|
|
58
|
+
else { fail("could not create access control") }
|
|
59
|
+
do {
|
|
60
|
+
let seKey = try SecureEnclave.P256.KeyAgreement.PrivateKey(accessControl: access)
|
|
61
|
+
let peer = P256.KeyAgreement.PrivateKey()
|
|
62
|
+
let shared = try peer.sharedSecretFromKeyAgreement(with: seKey.publicKey)
|
|
63
|
+
let out: [String: String] = [
|
|
64
|
+
"blob": seKey.dataRepresentation.base64EncodedString(),
|
|
65
|
+
"peer": peer.publicKey.rawRepresentation.base64EncodedString(),
|
|
66
|
+
"secret": hex(secretFrom(shared))
|
|
67
|
+
]
|
|
68
|
+
let json = try JSONSerialization.data(withJSONObject: out)
|
|
69
|
+
FileHandle.standardOutput.write(json)
|
|
70
|
+
} catch {
|
|
71
|
+
fail("create failed: \(error.localizedDescription)")
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
case "unlock":
|
|
75
|
+
let reason = args.count >= 3 ? args[2] : "unlock your GitHub login for git"
|
|
76
|
+
let input = readStdinJSON()
|
|
77
|
+
guard let blobB64 = input["blob"], let blob = Data(base64Encoded: blobB64),
|
|
78
|
+
let peerB64 = input["peer"], let peerRaw = Data(base64Encoded: peerB64)
|
|
79
|
+
else { fail("missing blob/peer") }
|
|
80
|
+
let context = LAContext()
|
|
81
|
+
context.localizedReason = reason
|
|
82
|
+
do {
|
|
83
|
+
let seKey = try SecureEnclave.P256.KeyAgreement.PrivateKey(
|
|
84
|
+
dataRepresentation: blob, authenticationContext: context)
|
|
85
|
+
let peer = try P256.KeyAgreement.PublicKey(rawRepresentation: peerRaw)
|
|
86
|
+
let shared = try seKey.sharedSecretFromKeyAgreement(with: peer) // prompts here
|
|
87
|
+
print(hex(secretFrom(shared)))
|
|
88
|
+
} catch {
|
|
89
|
+
fail("unlock refused: \(error.localizedDescription)", 3)
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
default:
|
|
93
|
+
fail("unknown command")
|
|
94
|
+
}
|
|
@@ -0,0 +1,85 @@
|
|
|
1
|
+
# GitSafty Windows Hello helper.
|
|
2
|
+
#
|
|
3
|
+
# check -> "ok" if Windows Hello can be used
|
|
4
|
+
# create <name> -> creates a TPM-backed Hello key (prompts PIN/face/finger)
|
|
5
|
+
# sign <name> <challengeB64> -> prints base64 signature (prompts PIN/face/finger)
|
|
6
|
+
#
|
|
7
|
+
# The key is created by Windows Hello (KeyCredentialManager) and lives in the
|
|
8
|
+
# TPM: it can't be exported or copied to another PC, and every signature needs
|
|
9
|
+
# the person at the keyboard. GitSafty derives the vault secret from the
|
|
10
|
+
# signature of a fixed random challenge (RSA PKCS#1 v1.5 signatures are
|
|
11
|
+
# deterministic, so the same challenge always gives the same secret).
|
|
12
|
+
|
|
13
|
+
param(
|
|
14
|
+
[Parameter(Mandatory = $true)][string]$Op,
|
|
15
|
+
[string]$Name = 'GitSafty-Vault',
|
|
16
|
+
[string]$Challenge = ''
|
|
17
|
+
)
|
|
18
|
+
|
|
19
|
+
$ErrorActionPreference = 'Stop'
|
|
20
|
+
|
|
21
|
+
try {
|
|
22
|
+
Add-Type -AssemblyName System.Runtime.WindowsRuntime
|
|
23
|
+
$null = [Windows.Security.Credentials.KeyCredentialManager, Windows.Security.Credentials, ContentType = WindowsRuntime]
|
|
24
|
+
$null = [Windows.Storage.Streams.IBuffer, Windows.Storage.Streams, ContentType = WindowsRuntime]
|
|
25
|
+
} catch {
|
|
26
|
+
[Console]::Error.WriteLine('Windows Hello API not available on this system')
|
|
27
|
+
exit 2
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
$asTask = [System.WindowsRuntimeSystemExtensions].GetMethods() | Where-Object {
|
|
31
|
+
$_.Name -eq 'AsTask' -and $_.GetParameters().Count -eq 1 -and
|
|
32
|
+
$_.GetParameters()[0].ParameterType.Name -eq 'IAsyncOperation`1'
|
|
33
|
+
} | Select-Object -First 1
|
|
34
|
+
|
|
35
|
+
function Await($operation, [Type]$resultType) {
|
|
36
|
+
$task = $asTask.MakeGenericMethod($resultType).Invoke($null, @($operation))
|
|
37
|
+
$null = $task.Wait(-1)
|
|
38
|
+
return $task.Result
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
$KCM = [Windows.Security.Credentials.KeyCredentialManager]
|
|
42
|
+
$Status = [Windows.Security.Credentials.KeyCredentialStatus]
|
|
43
|
+
|
|
44
|
+
$supported = Await ($KCM::IsSupportedAsync()) ([bool])
|
|
45
|
+
if (-not $supported) {
|
|
46
|
+
[Console]::Error.WriteLine('Windows Hello is not set up. Settings > Accounts > Sign-in options > PIN (Windows Hello)')
|
|
47
|
+
exit 2
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
switch ($Op) {
|
|
51
|
+
'check' {
|
|
52
|
+
Write-Output 'ok'
|
|
53
|
+
exit 0
|
|
54
|
+
}
|
|
55
|
+
'create' {
|
|
56
|
+
$result = Await ($KCM::RequestCreateAsync($Name, [Windows.Security.Credentials.KeyCredentialCreationOption]::ReplaceExisting)) ([Windows.Security.Credentials.KeyCredentialRetrievalResult])
|
|
57
|
+
if ($result.Status -ne $Status::Success) {
|
|
58
|
+
[Console]::Error.WriteLine("Windows Hello refused: $($result.Status)")
|
|
59
|
+
exit 3
|
|
60
|
+
}
|
|
61
|
+
Write-Output 'ok'
|
|
62
|
+
exit 0
|
|
63
|
+
}
|
|
64
|
+
'sign' {
|
|
65
|
+
$opened = Await ($KCM::OpenAsync($Name)) ([Windows.Security.Credentials.KeyCredentialRetrievalResult])
|
|
66
|
+
if ($opened.Status -ne $Status::Success) {
|
|
67
|
+
[Console]::Error.WriteLine("Hello key not found: $($opened.Status)")
|
|
68
|
+
exit 4
|
|
69
|
+
}
|
|
70
|
+
$bytes = [Convert]::FromBase64String($Challenge)
|
|
71
|
+
$buffer = [System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeBufferExtensions]::AsBuffer($bytes)
|
|
72
|
+
$signed = Await ($opened.Credential.RequestSignAsync($buffer)) ([Windows.Security.Credentials.KeyCredentialOperationResult])
|
|
73
|
+
if ($signed.Status -ne $Status::Success) {
|
|
74
|
+
[Console]::Error.WriteLine("Windows Hello refused: $($signed.Status)")
|
|
75
|
+
exit 3
|
|
76
|
+
}
|
|
77
|
+
$sig = [System.Runtime.InteropServices.WindowsRuntime.WindowsRuntimeBufferExtensions]::ToArray($signed.Result)
|
|
78
|
+
Write-Output ([Convert]::ToBase64String($sig))
|
|
79
|
+
exit 0
|
|
80
|
+
}
|
|
81
|
+
default {
|
|
82
|
+
[Console]::Error.WriteLine("unknown op $Op")
|
|
83
|
+
exit 1
|
|
84
|
+
}
|
|
85
|
+
}
|