@arifbiswas/git-pre-push 0.0.0-stage → 1.0.1
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/LICENSE +22 -0
- package/README.md +237 -2
- package/bin/cli.js +135 -0
- package/package.json +38 -4
- package/scripts/postinstall.js +26 -0
- package/src/action.js +63 -0
- package/src/cleaner.js +57 -0
- package/src/config.js +50 -0
- package/src/index.js +114 -0
- package/src/installer.js +202 -0
- package/src/reporter.js +90 -0
- package/src/rules/filenames.js +85 -0
- package/src/rules/ideConfig.js +81 -0
- package/src/rules/index.js +12 -0
- package/src/rules/payloads.js +163 -0
- package/src/rules/secrets.js +122 -0
- package/src/scanner.js +129 -0
- package/src/utils/git.js +173 -0
- package/src/utils/tty.js +52 -0
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Malicious payload signatures for outgoing commit diff and content inspection
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
const PAYLOAD_SIGNATURES = [
|
|
6
|
+
// 1. PowerShell execution & download cradles
|
|
7
|
+
{
|
|
8
|
+
name: 'PowerShell Obfuscated/Encoded Execution',
|
|
9
|
+
regex: /powershell(\.exe)?\s+(-[a-z]*e[a-z]*|-enc|-encodedcommand)\s+[A-Za-z0-9+/=]{10,}/i,
|
|
10
|
+
severity: 'CRITICAL',
|
|
11
|
+
description: 'Encoded PowerShell command execution commonly used by droppers.'
|
|
12
|
+
},
|
|
13
|
+
{
|
|
14
|
+
name: 'PowerShell Web Download Cradle',
|
|
15
|
+
regex: /(invoke-webrequest|invoke-restmethod|downloadstring|downloadfile)\s*\(?['"][^'"]*https?:\/\//i,
|
|
16
|
+
severity: 'CRITICAL',
|
|
17
|
+
description: 'PowerShell downloading remote scripts or binaries.'
|
|
18
|
+
},
|
|
19
|
+
{
|
|
20
|
+
name: 'PowerShell IEX Execution Cradle',
|
|
21
|
+
regex: /iex\s*\(?(new-object\s+net\.webclient|invoke-webrequest|irm|curl)/i,
|
|
22
|
+
severity: 'CRITICAL',
|
|
23
|
+
description: 'PowerShell IEX download-and-execute cradle.'
|
|
24
|
+
},
|
|
25
|
+
|
|
26
|
+
// 2. Shell download & pipe to bash / sh
|
|
27
|
+
{
|
|
28
|
+
name: 'Remote Pipe to Shell',
|
|
29
|
+
regex: /(curl|wget)\s+[^|\n]+(\|\s*(ba)?sh|\|\s*python|\|\s*perl)/i,
|
|
30
|
+
severity: 'CRITICAL',
|
|
31
|
+
description: 'Piping remote web content directly into shell interpreter.'
|
|
32
|
+
},
|
|
33
|
+
|
|
34
|
+
// 3. Obfuscated evaluation & decoding
|
|
35
|
+
{
|
|
36
|
+
name: 'Obfuscated Base64 Eval',
|
|
37
|
+
regex: /eval\s*\(\s*(base64_decode|atob|Buffer\.from\([^)]*base64)/i,
|
|
38
|
+
severity: 'CRITICAL',
|
|
39
|
+
description: 'Dynamic execution of base64 decoded string.'
|
|
40
|
+
},
|
|
41
|
+
{
|
|
42
|
+
name: 'PowerShell Base64 Decode',
|
|
43
|
+
regex: /\[System\.Convert\]::FromBase64String/i,
|
|
44
|
+
severity: 'WARNING',
|
|
45
|
+
description: 'Base64 decoding in PowerShell script.'
|
|
46
|
+
},
|
|
47
|
+
|
|
48
|
+
// 4. Windows Lolbins / Dropper tools
|
|
49
|
+
{
|
|
50
|
+
name: 'Certutil Remote Cache Download',
|
|
51
|
+
regex: /certutil(\.exe)?\s+(-urlcache|-f|-split)/i,
|
|
52
|
+
severity: 'CRITICAL',
|
|
53
|
+
description: 'Certutil abuse to download external payloads.'
|
|
54
|
+
},
|
|
55
|
+
{
|
|
56
|
+
name: 'Bitsadmin Download Transfer',
|
|
57
|
+
regex: /bitsadmin(\.exe)?\s+\/transfer/i,
|
|
58
|
+
severity: 'CRITICAL',
|
|
59
|
+
description: 'Bitsadmin background transfer abuse.'
|
|
60
|
+
},
|
|
61
|
+
{
|
|
62
|
+
name: 'MSHTA Remote Script Execution',
|
|
63
|
+
regex: /mshta(\.exe)?\s+(http|vbscript|javascript):/i,
|
|
64
|
+
severity: 'CRITICAL',
|
|
65
|
+
description: 'MSHTA executing remote scripts.'
|
|
66
|
+
},
|
|
67
|
+
{
|
|
68
|
+
name: 'Rundll32 Remote DLL Execution',
|
|
69
|
+
regex: /rundll32(\.exe)?\s+javascript:/i,
|
|
70
|
+
severity: 'CRITICAL',
|
|
71
|
+
description: 'Rundll32 abuse executing script protocols.'
|
|
72
|
+
},
|
|
73
|
+
|
|
74
|
+
// 5. Reverse shells
|
|
75
|
+
{
|
|
76
|
+
name: 'TCP Reverse Shell Pattern',
|
|
77
|
+
regex: /((\/bin\/sh|\/bin\/bash)\s+-i\s+>&?\s*\/dev\/tcp\/|0<&196;exec\s+196<>\/dev\/tcp\/|nc(\.traditional)?\s+-[a-z0-9]*e\s+(\/bin\/sh|\/bin\/bash|cmd\.exe))/i,
|
|
78
|
+
severity: 'CRITICAL',
|
|
79
|
+
description: 'Direct interactive reverse shell socket invocation.'
|
|
80
|
+
},
|
|
81
|
+
{
|
|
82
|
+
name: 'Python/Perl One-Liner Reverse Shell',
|
|
83
|
+
regex: /(python[23]?\s+-c\s+['"].*import\s+(socket|subprocess).*connect\(|perl\s+-e\s+['"].*use\s+Socket.*connect\()/i,
|
|
84
|
+
severity: 'CRITICAL',
|
|
85
|
+
description: 'One-liner Python/Perl interactive reverse shell payload.'
|
|
86
|
+
},
|
|
87
|
+
|
|
88
|
+
// 6. Suspicious Exfiltration Endpoints in scripts
|
|
89
|
+
{
|
|
90
|
+
name: 'Discord Webhook Exfiltration Candidate',
|
|
91
|
+
regex: /https:\/\/discord(app)?\.com\/api\/webhooks\/[0-9]{15,22}\/[A-Za-z0-9_-]{50,80}/i,
|
|
92
|
+
severity: 'CRITICAL',
|
|
93
|
+
description: 'Discord webhook URL commonly used by infostealers to dump credentials.'
|
|
94
|
+
},
|
|
95
|
+
{
|
|
96
|
+
name: 'Telegram Bot Token in Outgoing Diff',
|
|
97
|
+
regex: /https:\/\/api\.telegram\.org\/bot[0-9]{8,12}:[A-Za-z0-9_-]{35}/i,
|
|
98
|
+
severity: 'CRITICAL',
|
|
99
|
+
description: 'Telegram Bot Token used to transmit stolen logs.'
|
|
100
|
+
},
|
|
101
|
+
{
|
|
102
|
+
name: 'Public Exfiltration Service Hook',
|
|
103
|
+
regex: /https?:\/\/(webhook\.site|requestbin\.(com|net)|pipedream\.net|filebin\.net)\/[a-z0-9-]+/i,
|
|
104
|
+
severity: 'WARNING',
|
|
105
|
+
description: 'Temporary upload or webhook logging service detected.'
|
|
106
|
+
},
|
|
107
|
+
|
|
108
|
+
// 7. Malicious package lifecycle hooks
|
|
109
|
+
{
|
|
110
|
+
name: 'Suspicious Network Call in npm Script',
|
|
111
|
+
regex: /(preinstall|postinstall)\s*:\s*['"][^'"]*(curl|wget|powershell|certutil)\s+/i,
|
|
112
|
+
severity: 'CRITICAL',
|
|
113
|
+
description: 'npm lifecycle hook executing remote network downloads upon installation.'
|
|
114
|
+
}
|
|
115
|
+
];
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Scans content (diff or file text) for payload signatures
|
|
119
|
+
* @param {string} content
|
|
120
|
+
* @param {string} [filePath]
|
|
121
|
+
* @returns {Array<{ name: string, severity: 'CRITICAL' | 'WARNING', description: string, line: string, lineNumber?: number }>}
|
|
122
|
+
*/
|
|
123
|
+
function scanPayloads(content, filePath = '') {
|
|
124
|
+
const findings = [];
|
|
125
|
+
if (!content) return findings;
|
|
126
|
+
|
|
127
|
+
const lines = content.split('\n');
|
|
128
|
+
|
|
129
|
+
for (let i = 0; i < lines.length; i++) {
|
|
130
|
+
const line = lines[i];
|
|
131
|
+
|
|
132
|
+
// In a unified git diff, only check added lines (+) or entire file if scanning full content
|
|
133
|
+
if (content.startsWith('diff --git') && !line.startsWith('+')) {
|
|
134
|
+
continue;
|
|
135
|
+
}
|
|
136
|
+
// Ignore the +++ file headers in git diff
|
|
137
|
+
if (line.startsWith('+++')) continue;
|
|
138
|
+
|
|
139
|
+
const cleanLine = line.startsWith('+') ? line.slice(1).trim() : line.trim();
|
|
140
|
+
if (!cleanLine) continue;
|
|
141
|
+
|
|
142
|
+
for (const signature of PAYLOAD_SIGNATURES) {
|
|
143
|
+
if (signature.regex.test(cleanLine)) {
|
|
144
|
+
findings.push({
|
|
145
|
+
name: signature.name,
|
|
146
|
+
severity: signature.severity,
|
|
147
|
+
description: signature.description,
|
|
148
|
+
line: cleanLine.slice(0, 160),
|
|
149
|
+
lineNumber: i + 1,
|
|
150
|
+
filePath
|
|
151
|
+
});
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
return findings;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
module.exports = {
|
|
160
|
+
PAYLOAD_SIGNATURES,
|
|
161
|
+
scanPayloads
|
|
162
|
+
};
|
|
163
|
+
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Secret & Credential Leakage Rules
|
|
3
|
+
*/
|
|
4
|
+
|
|
5
|
+
const SECRET_PATTERNS = [
|
|
6
|
+
{
|
|
7
|
+
name: 'Private Key',
|
|
8
|
+
regex: /-----BEGIN\s+(RSA|OPENSSH|DSA|EC|PGP)?\s*PRIVATE KEY-----/,
|
|
9
|
+
severity: 'CRITICAL',
|
|
10
|
+
description: 'Cryptographic private key detected.'
|
|
11
|
+
},
|
|
12
|
+
{
|
|
13
|
+
name: 'GitHub Personal Access Token',
|
|
14
|
+
regex: /(ghp_[0-9a-zA-Z]{36}|github_pat_[0-9a-zA-Z_]{82})/,
|
|
15
|
+
severity: 'CRITICAL',
|
|
16
|
+
description: 'GitHub Personal Access Token detected.'
|
|
17
|
+
},
|
|
18
|
+
{
|
|
19
|
+
name: 'AWS Access Key ID',
|
|
20
|
+
regex: /\b(AKIA[0-9A-Z]{16})\b/,
|
|
21
|
+
severity: 'CRITICAL',
|
|
22
|
+
description: 'AWS Access Key ID detected.'
|
|
23
|
+
},
|
|
24
|
+
{
|
|
25
|
+
name: 'Slack Token',
|
|
26
|
+
regex: /\b(xox[baprs]-[0-9a-zA-Z]{10,48})\b/,
|
|
27
|
+
severity: 'CRITICAL',
|
|
28
|
+
description: 'Slack API token detected.'
|
|
29
|
+
},
|
|
30
|
+
{
|
|
31
|
+
name: 'Google API Key',
|
|
32
|
+
regex: /\b(AIza[0-9A-Za-z\\-_]{35})\b/,
|
|
33
|
+
severity: 'WARNING',
|
|
34
|
+
description: 'Google Cloud / Firebase API key detected.'
|
|
35
|
+
},
|
|
36
|
+
{
|
|
37
|
+
name: 'Generic High Entropy Secret / Token Assignment',
|
|
38
|
+
regex: /(api_key|apikey|secret_key|client_secret|auth_token)\s*[:=]\s*['"][A-Za-z0-9_\-]{24,}['"]/i,
|
|
39
|
+
severity: 'WARNING',
|
|
40
|
+
description: 'Hardcoded secret or API credential assignment.'
|
|
41
|
+
}
|
|
42
|
+
];
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* Checks if a file path is a committed .env file with secrets
|
|
46
|
+
* @param {string} filePath
|
|
47
|
+
* @returns {boolean}
|
|
48
|
+
*/
|
|
49
|
+
function isCommittedEnvFile(filePath) {
|
|
50
|
+
const normalized = filePath.replace(/\\/g, '/').toLowerCase();
|
|
51
|
+
const basename = normalized.split('/').pop() || '';
|
|
52
|
+
|
|
53
|
+
// Allow examples, templates and test mocks
|
|
54
|
+
if (basename.includes('.example') || basename.includes('.sample') || basename.includes('.template')) {
|
|
55
|
+
return false;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
return basename === '.env' || basename.startsWith('.env.local') || basename.startsWith('.env.production');
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Scans content for leaked secrets
|
|
63
|
+
* @param {string} content
|
|
64
|
+
* @param {string} filePath
|
|
65
|
+
* @returns {Array<{ name: string, severity: 'CRITICAL' | 'WARNING', description: string, line: string, lineNumber?: number }>}
|
|
66
|
+
*/
|
|
67
|
+
function scanSecrets(content = '', filePath = '') {
|
|
68
|
+
const findings = [];
|
|
69
|
+
|
|
70
|
+
// Check if .env file itself is being committed
|
|
71
|
+
if (filePath && isCommittedEnvFile(filePath)) {
|
|
72
|
+
findings.push({
|
|
73
|
+
name: 'Committed Environment File (.env)',
|
|
74
|
+
severity: 'CRITICAL',
|
|
75
|
+
description: 'Production or local .env file should never be committed into git.',
|
|
76
|
+
line: `File: ${filePath}`,
|
|
77
|
+
filePath
|
|
78
|
+
});
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
if (!content) return findings;
|
|
82
|
+
|
|
83
|
+
const lines = content.split('\n');
|
|
84
|
+
|
|
85
|
+
for (let i = 0; i < lines.length; i++) {
|
|
86
|
+
const line = lines[i];
|
|
87
|
+
|
|
88
|
+
if (content.startsWith('diff --git') && !line.startsWith('+')) {
|
|
89
|
+
continue;
|
|
90
|
+
}
|
|
91
|
+
if (line.startsWith('+++')) continue;
|
|
92
|
+
|
|
93
|
+
const cleanLine = line.startsWith('+') ? line.slice(1).trim() : line.trim();
|
|
94
|
+
if (!cleanLine) continue;
|
|
95
|
+
|
|
96
|
+
// Skip example or dummy placeholder values
|
|
97
|
+
if (/your[-_]api[-_]key|example|dummy|placeholder|<your-|test_token/i.test(cleanLine)) {
|
|
98
|
+
continue;
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
for (const pattern of SECRET_PATTERNS) {
|
|
102
|
+
if (pattern.regex.test(cleanLine)) {
|
|
103
|
+
findings.push({
|
|
104
|
+
name: pattern.name,
|
|
105
|
+
severity: pattern.severity,
|
|
106
|
+
description: pattern.description,
|
|
107
|
+
line: cleanLine.slice(0, 80) + '...',
|
|
108
|
+
lineNumber: i + 1,
|
|
109
|
+
filePath
|
|
110
|
+
});
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
return findings;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
module.exports = {
|
|
119
|
+
SECRET_PATTERNS,
|
|
120
|
+
isCommittedEnvFile,
|
|
121
|
+
scanSecrets
|
|
122
|
+
};
|
package/src/scanner.js
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
const fs = require('fs');
|
|
2
|
+
const path = require('path');
|
|
3
|
+
const { checkFilename } = require('./rules/filenames');
|
|
4
|
+
const { scanPayloads } = require('./rules/payloads');
|
|
5
|
+
const { scanSecrets } = require('./rules/secrets');
|
|
6
|
+
const { inspectIdeConfig } = require('./rules/ideConfig');
|
|
7
|
+
const { loadConfig } = require('./config');
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Scans a list of files and diff content
|
|
11
|
+
* @param {string[]} files
|
|
12
|
+
* @param {string} diffContent
|
|
13
|
+
* @param {string} [cwd]
|
|
14
|
+
* @returns {{ totalFiles: number, threats: Array<any>, durationMs: number, hasCritical: boolean, hasWarning: boolean }}
|
|
15
|
+
*/
|
|
16
|
+
function scanFilesAndDiff(files, diffContent = '', cwd = process.cwd()) {
|
|
17
|
+
const startTime = Date.now();
|
|
18
|
+
const config = loadConfig(cwd);
|
|
19
|
+
const rawThreats = [];
|
|
20
|
+
const uniqueFiles = Array.from(new Set(files.filter(Boolean)));
|
|
21
|
+
|
|
22
|
+
// Filter out ignored files based on config
|
|
23
|
+
const filesToScan = uniqueFiles.filter(file => {
|
|
24
|
+
const normalized = file.replace(/\\/g, '/');
|
|
25
|
+
return !config.ignoreFiles.some(ignored => {
|
|
26
|
+
if (ignored.startsWith('*')) {
|
|
27
|
+
return normalized.endsWith(ignored.slice(1));
|
|
28
|
+
}
|
|
29
|
+
return normalized === ignored || normalized.endsWith('/' + ignored);
|
|
30
|
+
});
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
// 1. Check all filenames
|
|
34
|
+
for (const file of filesToScan) {
|
|
35
|
+
const fileRule = checkFilename(file);
|
|
36
|
+
if (fileRule) {
|
|
37
|
+
rawThreats.push({
|
|
38
|
+
name: fileRule.rule,
|
|
39
|
+
severity: fileRule.severity,
|
|
40
|
+
description: 'Unauthorized, dangerous or suspicious file detected.',
|
|
41
|
+
filePath: file
|
|
42
|
+
});
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// Check custom suspicious files from config
|
|
46
|
+
for (const customPattern of config.customSuspiciousFiles) {
|
|
47
|
+
if (new RegExp(customPattern, 'i').test(file)) {
|
|
48
|
+
rawThreats.push({
|
|
49
|
+
name: `Custom Suspicious File Pattern: "${file}"`,
|
|
50
|
+
severity: 'CRITICAL',
|
|
51
|
+
description: 'Matches user-configured suspicious file blacklist.',
|
|
52
|
+
filePath: file
|
|
53
|
+
});
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
// 2. Inspect IDE configuration files if present
|
|
58
|
+
const normalized = file.replace(/\\/g, '/');
|
|
59
|
+
if (
|
|
60
|
+
normalized.includes('.vscode/tasks.json') ||
|
|
61
|
+
normalized.includes('.vscode/settings.json') ||
|
|
62
|
+
normalized.includes('.idea/')
|
|
63
|
+
) {
|
|
64
|
+
try {
|
|
65
|
+
const fullPath = path.resolve(cwd, file);
|
|
66
|
+
if (fs.existsSync(fullPath)) {
|
|
67
|
+
const content = fs.readFileSync(fullPath, 'utf8');
|
|
68
|
+
const ideThreats = inspectIdeConfig(file, content);
|
|
69
|
+
rawThreats.push(...ideThreats);
|
|
70
|
+
}
|
|
71
|
+
} catch (_) {}
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// 3. Check for .env secret committing
|
|
75
|
+
if (normalized.endsWith('.env') || normalized.includes('.env.local') || normalized.includes('.env.production')) {
|
|
76
|
+
const envThreats = scanSecrets('', file);
|
|
77
|
+
rawThreats.push(...envThreats);
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
// 4. Scan commit diff content for payloads
|
|
82
|
+
if (diffContent) {
|
|
83
|
+
const payloadThreats = scanPayloads(diffContent);
|
|
84
|
+
rawThreats.push(...payloadThreats);
|
|
85
|
+
|
|
86
|
+
const secretThreats = scanSecrets(diffContent);
|
|
87
|
+
rawThreats.push(...secretThreats);
|
|
88
|
+
|
|
89
|
+
// Custom payloads from config
|
|
90
|
+
for (const customPayload of config.customPayloads) {
|
|
91
|
+
const regex = new RegExp(customPayload, 'i');
|
|
92
|
+
if (regex.test(diffContent)) {
|
|
93
|
+
rawThreats.push({
|
|
94
|
+
name: `Custom Blacklisted Payload Pattern`,
|
|
95
|
+
severity: 'CRITICAL',
|
|
96
|
+
description: `Matches user-defined payload pattern: ${customPayload}`,
|
|
97
|
+
line: customPayload
|
|
98
|
+
});
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
// Filter out any ignored rules
|
|
104
|
+
const threats = rawThreats.filter(t => {
|
|
105
|
+
return !config.ignoreRules.includes(t.name);
|
|
106
|
+
}).map(t => {
|
|
107
|
+
if (config.strict && t.severity === 'WARNING') {
|
|
108
|
+
return { ...t, severity: 'CRITICAL' };
|
|
109
|
+
}
|
|
110
|
+
return t;
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
const durationMs = Date.now() - startTime;
|
|
114
|
+
const hasCritical = threats.some(t => t.severity === 'CRITICAL');
|
|
115
|
+
const hasWarning = threats.some(t => t.severity === 'WARNING');
|
|
116
|
+
|
|
117
|
+
return {
|
|
118
|
+
totalFiles: filesToScan.length,
|
|
119
|
+
threats,
|
|
120
|
+
durationMs,
|
|
121
|
+
hasCritical,
|
|
122
|
+
hasWarning
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
module.exports = {
|
|
127
|
+
scanFilesAndDiff
|
|
128
|
+
};
|
|
129
|
+
|
package/src/utils/git.js
ADDED
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
const { execSync } = require('child_process');
|
|
2
|
+
const path = require('path');
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Runs a git command and returns stdout as trimmed string
|
|
7
|
+
* @param {string} command
|
|
8
|
+
* @param {string} [cwd]
|
|
9
|
+
* @returns {string}
|
|
10
|
+
*/
|
|
11
|
+
function runGit(command, cwd = process.cwd()) {
|
|
12
|
+
try {
|
|
13
|
+
return execSync(`git ${command}`, {
|
|
14
|
+
cwd,
|
|
15
|
+
encoding: 'utf8',
|
|
16
|
+
stdio: ['pipe', 'pipe', 'pipe'],
|
|
17
|
+
maxBuffer: 50 * 1024 * 1024 // 50MB
|
|
18
|
+
}).trim();
|
|
19
|
+
} catch (err) {
|
|
20
|
+
return '';
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Checks if directory is a git repository
|
|
26
|
+
* @param {string} [cwd]
|
|
27
|
+
* @returns {boolean}
|
|
28
|
+
*/
|
|
29
|
+
function isGitRepo(cwd = process.cwd()) {
|
|
30
|
+
const result = runGit('rev-parse --is-inside-work-tree', cwd);
|
|
31
|
+
return result === 'true';
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Gets path to git hooks directory
|
|
36
|
+
* @param {string} [cwd]
|
|
37
|
+
* @returns {string | null}
|
|
38
|
+
*/
|
|
39
|
+
function getHooksDir(cwd = process.cwd()) {
|
|
40
|
+
if (!isGitRepo(cwd)) return null;
|
|
41
|
+
|
|
42
|
+
// Check git core.hooksPath if configured
|
|
43
|
+
const customHooksPath = runGit('config core.hooksPath', cwd);
|
|
44
|
+
if (customHooksPath) {
|
|
45
|
+
return path.resolve(cwd, customHooksPath);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
const gitDir = runGit('rev-parse --git-dir', cwd);
|
|
49
|
+
if (!gitDir) return null;
|
|
50
|
+
|
|
51
|
+
return path.resolve(cwd, gitDir, 'hooks');
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Parses pre-push stdin lines (local_ref local_oid remote_ref remote_oid)
|
|
56
|
+
* @param {string} stdinText
|
|
57
|
+
* @returns {Array<{ localRef: string, localOid: string, remoteRef: string, remoteOid: string, diffRange: string }>}
|
|
58
|
+
*/
|
|
59
|
+
function parsePrePushInput(stdinText) {
|
|
60
|
+
const ZERO_OID = '0000000000000000000000000000000000000000';
|
|
61
|
+
const pushes = [];
|
|
62
|
+
|
|
63
|
+
const lines = stdinText.split('\n');
|
|
64
|
+
for (const rawLine of lines) {
|
|
65
|
+
const line = rawLine.trim();
|
|
66
|
+
if (!line) continue;
|
|
67
|
+
|
|
68
|
+
const parts = line.split(/\s+/);
|
|
69
|
+
if (parts.length < 4) continue;
|
|
70
|
+
|
|
71
|
+
const [localRef, localOid, remoteRef, remoteOid] = parts;
|
|
72
|
+
|
|
73
|
+
// Branch/tag deletion: nothing to scan
|
|
74
|
+
if (localOid === ZERO_OID) continue;
|
|
75
|
+
|
|
76
|
+
let diffRange;
|
|
77
|
+
if (remoteOid === ZERO_OID) {
|
|
78
|
+
// New remote branch: check commit or commits not in origin/main / HEAD
|
|
79
|
+
diffRange = localOid;
|
|
80
|
+
} else {
|
|
81
|
+
diffRange = `${remoteOid}..${localOid}`;
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
pushes.push({
|
|
85
|
+
localRef,
|
|
86
|
+
localOid,
|
|
87
|
+
remoteRef,
|
|
88
|
+
remoteOid,
|
|
89
|
+
diffRange
|
|
90
|
+
});
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
return pushes;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Gets files changed in diff range
|
|
98
|
+
* @param {string} diffRange
|
|
99
|
+
* @param {string} [cwd]
|
|
100
|
+
* @returns {string[]}
|
|
101
|
+
*/
|
|
102
|
+
function getChangedFiles(diffRange, cwd = process.cwd()) {
|
|
103
|
+
// Use git diff-tree or git log to extract changed filenames
|
|
104
|
+
const output = runGit(`diff-tree --no-commit-id --name-only -r ${diffRange}`, cwd);
|
|
105
|
+
if (!output) {
|
|
106
|
+
// Fallback to git log
|
|
107
|
+
const logOutput = runGit(`log ${diffRange} --name-only --oneline`, cwd);
|
|
108
|
+
if (!logOutput) return [];
|
|
109
|
+
const files = new Set();
|
|
110
|
+
for (const line of logOutput.split('\n')) {
|
|
111
|
+
const trimmed = line.trim();
|
|
112
|
+
if (!trimmed || /^[0-9a-f]{7,}/i.test(trimmed)) continue;
|
|
113
|
+
files.add(trimmed);
|
|
114
|
+
}
|
|
115
|
+
return Array.from(files);
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
return output.split('\n').map(f => f.trim()).filter(Boolean);
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
/**
|
|
122
|
+
* Gets git diff for commit range
|
|
123
|
+
* @param {string} diffRange
|
|
124
|
+
* @param {string} [cwd]
|
|
125
|
+
* @returns {string}
|
|
126
|
+
*/
|
|
127
|
+
function getDiffContent(diffRange, cwd = process.cwd()) {
|
|
128
|
+
return runGit(`diff ${diffRange}`, cwd);
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Gets staged files (for pre-commit or manual scan)
|
|
133
|
+
* @param {string} [cwd]
|
|
134
|
+
* @returns {string[]}
|
|
135
|
+
*/
|
|
136
|
+
function getStagedFiles(cwd = process.cwd()) {
|
|
137
|
+
const output = runGit('diff --cached --name-only', cwd);
|
|
138
|
+
if (!output) return [];
|
|
139
|
+
return output.split('\n').map(f => f.trim()).filter(Boolean);
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Gets staged diff
|
|
144
|
+
* @param {string} [cwd]
|
|
145
|
+
* @returns {string}
|
|
146
|
+
*/
|
|
147
|
+
function getStagedDiff(cwd = process.cwd()) {
|
|
148
|
+
return runGit('diff --cached', cwd);
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/**
|
|
152
|
+
* Gets all files in repository
|
|
153
|
+
* @param {string} [cwd]
|
|
154
|
+
* @returns {string[]}
|
|
155
|
+
*/
|
|
156
|
+
function getAllRepoFiles(cwd = process.cwd()) {
|
|
157
|
+
const output = runGit('ls-files --cached --others --exclude-standard', cwd);
|
|
158
|
+
if (!output) return [];
|
|
159
|
+
return output.split('\n').map(f => f.trim()).filter(Boolean);
|
|
160
|
+
}
|
|
161
|
+
|
|
162
|
+
module.exports = {
|
|
163
|
+
runGit,
|
|
164
|
+
isGitRepo,
|
|
165
|
+
getHooksDir,
|
|
166
|
+
parsePrePushInput,
|
|
167
|
+
getChangedFiles,
|
|
168
|
+
getDiffContent,
|
|
169
|
+
getStagedFiles,
|
|
170
|
+
getStagedDiff,
|
|
171
|
+
getAllRepoFiles
|
|
172
|
+
};
|
|
173
|
+
|
package/src/utils/tty.js
ADDED
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
const fs = require('fs');
|
|
2
|
+
const readline = require('readline');
|
|
3
|
+
|
|
4
|
+
/**
|
|
5
|
+
* Asks the user an interactive confirmation prompt, even when process.stdin was redirected
|
|
6
|
+
* @param {string} questionText
|
|
7
|
+
* @returns {Promise<boolean>}
|
|
8
|
+
*/
|
|
9
|
+
async function promptUser(questionText) {
|
|
10
|
+
// If non-interactive environment (CI/CD), skip prompt
|
|
11
|
+
if (process.env.CI || process.env.CONTINUOUS_INTEGRATION || !process.stdout.isTTY) {
|
|
12
|
+
return true;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
let inputHandle;
|
|
16
|
+
try {
|
|
17
|
+
const ttyDevice = process.platform === 'win32' ? 'CONIN$' : '/dev/tty';
|
|
18
|
+
inputHandle = fs.openSync(ttyDevice, 'r');
|
|
19
|
+
} catch (err) {
|
|
20
|
+
// If /dev/tty or CONIN$ fails, fallback to process.stdin if it is TTY
|
|
21
|
+
if (process.stdin.isTTY) {
|
|
22
|
+
inputHandle = process.stdin;
|
|
23
|
+
} else {
|
|
24
|
+
return true;
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
const inputStream = typeof inputHandle === 'number' ? new fs.ReadStream('', { fd: inputHandle }) : inputHandle;
|
|
29
|
+
|
|
30
|
+
const rl = readline.createInterface({
|
|
31
|
+
input: inputStream,
|
|
32
|
+
output: process.stdout
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
return new Promise((resolve) => {
|
|
36
|
+
rl.question(questionText, (answer) => {
|
|
37
|
+
rl.close();
|
|
38
|
+
if (typeof inputHandle === 'number') {
|
|
39
|
+
try {
|
|
40
|
+
fs.closeSync(inputHandle);
|
|
41
|
+
} catch (_) {}
|
|
42
|
+
}
|
|
43
|
+
const trimmed = answer.trim().toLowerCase();
|
|
44
|
+
resolve(trimmed === 'y' || trimmed === 'yes');
|
|
45
|
+
});
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
module.exports = {
|
|
50
|
+
promptUser
|
|
51
|
+
};
|
|
52
|
+
|