@arifbiswas/git-pre-push 1.0.4 โ†’ 1.0.5

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 CHANGED
@@ -128,13 +128,41 @@ This configures `git config --global core.hooksPath`, ensuring every repository
128
128
  |---|---|
129
129
  | `npx @arifbiswas/git-pre-push init` | Installs the pre-push security hook into `.git/hooks/pre-push` |
130
130
  | `npx @arifbiswas/git-pre-push init --global` | Protects **all** Git repositories across the entire PC |
131
- | `npx @arifbiswas/git-pre-push scan` | Manually audits workspace files, untracked scripts & staged diffs |
131
+ | `npx @arifbiswas/git-pre-push scan` | Manually audits local workspace files, untracked scripts & staged diffs |
132
+ | `npx @arifbiswas/git-pre-push scan-remote` | **Zero-Clone Audit:** Scans any remote GitHub repo without cloning or downloading |
132
133
  | `npx @arifbiswas/git-pre-push clean` | Unstages and quarantines injected malware files to `.git/git-safty-quarantine/` |
134
+ | `npx @arifbiswas/git-pre-push demo` | Simulates a blocked push in terminal |
133
135
  | `npx @arifbiswas/git-pre-push action` | Generates a `.github/workflows/git-safty.yml` CI workflow |
134
136
  | `npx @arifbiswas/git-pre-push uninstall` | Cleanly removes the hook from `.git/hooks` |
135
137
 
136
138
  ---
137
139
 
140
+ ## ๐ŸŒ Zero-Clone Remote Repository Scanner (`scan-remote`)
141
+
142
+ Scan any GitHub repository **without cloning or downloading code to your hard drive**:
143
+
144
+ ```bash
145
+ npx @arifbiswas/git-pre-push scan-remote
146
+ ```
147
+
148
+ The CLI will prompt you for the GitHub URL:
149
+ ```text
150
+ ? Enter GitHub Repository URL: https://github.com/sparktechagency/gantle-backend
151
+ ```
152
+
153
+ Or pass the URL directly:
154
+ ```bash
155
+ npx @arifbiswas/git-pre-push scan-remote https://github.com/sparktechagency/gantle-backend
156
+ ```
157
+
158
+ **How it works:**
159
+ 1. Fetches the repository's recursive Git tree metadata via GitHub REST API in **1 single HTTP request**.
160
+ 2. Performs instant in-memory path matching against all trojan filenames and blacklisted extensions.
161
+ 3. Only if a suspicious file is discovered, fetches the specific blob directly into RAM for static payload/secret analysis.
162
+ 4. **0 MB downloaded to disk** โ€” fast, lightweight, and completely bandwidth-friendly.
163
+
164
+ ---
165
+
138
166
  ## ๐Ÿงน Quarantine & Remediation (`clean`)
139
167
 
140
168
  If malware has already generated files in your project, clean them up instantly:
package/bin/cli.js CHANGED
@@ -20,6 +20,51 @@ async function main() {
20
20
  runManualScan();
21
21
  break;
22
22
 
23
+ case 'scan-remote':
24
+ case 'scan-url':
25
+ case 'remote': {
26
+ banner();
27
+ let repoUrl = args[1];
28
+
29
+ if (!repoUrl) {
30
+ const readline = require('readline');
31
+ const rl = readline.createInterface({
32
+ input: process.stdin,
33
+ output: process.stdout
34
+ });
35
+ repoUrl = await new Promise((resolve) => {
36
+ rl.question(`${colors.bold}${colors.cyan}? Enter GitHub Repository URL (e.g. https://github.com/owner/repo): ${colors.reset}`, (answer) => {
37
+ rl.close();
38
+ resolve(answer.trim());
39
+ });
40
+ });
41
+ }
42
+
43
+ if (!repoUrl) {
44
+ console.error(`\n${colors.red}Error: No repository URL provided.${colors.reset}\n`);
45
+ process.exit(1);
46
+ }
47
+
48
+ const { scanRemoteRepositoryZeroClone, printRemoteScanReport } = require('../src/remoteScanner');
49
+
50
+ console.log(`\n${colors.cyan}Starting Zero-Clone In-Memory Security Audit...${colors.reset}`);
51
+ try {
52
+ const result = await scanRemoteRepositoryZeroClone(repoUrl, null, (msg) => {
53
+ console.log(` ${colors.dim}โ„น ${msg}${colors.reset}`);
54
+ });
55
+
56
+ printRemoteScanReport(result);
57
+
58
+ if (result.hasCritical) {
59
+ process.exit(1);
60
+ }
61
+ } catch (err) {
62
+ console.error(`\n${colors.red}${colors.bold}โœ– Scan Failed:${colors.reset} ${err.message}\n`);
63
+ process.exit(1);
64
+ }
65
+ break;
66
+ }
67
+
23
68
  case 'demo':
24
69
  case 'test-run': {
25
70
  banner();
@@ -108,10 +153,14 @@ ${colors.bold}Usage:${colors.reset}
108
153
  npx git-safty <command>
109
154
 
110
155
  ${colors.bold}Commands:${colors.reset}
111
- ${colors.green}init${colors.reset} Install the pre-push guard hook into .git/hooks/pre-push
112
- ${colors.green}scan${colors.reset} Scan current repository, staged files & working tree
113
- ${colors.green}scan-push${colors.reset} Triggered automatically by git during 'git push'
114
- ${colors.green}uninstall${colors.reset} Remove git-safty hook from .git/hooks
156
+ ${colors.green}init${colors.reset} Install the pre-push guard hook into .git/hooks/pre-push
157
+ ${colors.green}scan${colors.reset} Scan current local repository, staged files & working tree
158
+ ${colors.green}scan-remote${colors.reset} Scan remote GitHub repository without downloading or cloning
159
+ ${colors.green}clean${colors.reset} Quarantine injected malware scripts (.bat, .ps1, trojans)
160
+ ${colors.green}action${colors.reset} Generate GitHub Actions CI workflow for server-side guard
161
+ ${colors.green}demo${colors.reset} Run a simulated malicious push test in terminal
162
+ ${colors.green}scan-push${colors.reset} Triggered automatically by git during 'git push'
163
+ ${colors.green}uninstall${colors.reset} Remove git-safty hook from .git/hooks
115
164
 
116
165
  ${colors.bold}How it works:${colors.reset}
117
166
  1. Run ${colors.cyan}npx git-safty init${colors.reset} in any git repository.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@arifbiswas/git-pre-push",
3
- "version": "1.0.4",
3
+ "version": "1.0.5",
4
4
  "description": "Zero-dependency pre-push security guard that stops malware, injected scripts, and leaked secrets from reaching GitHub.",
5
5
  "main": "src/index.js",
6
6
  "bin": {
@@ -0,0 +1,279 @@
1
+ const { checkFilename } = require('./rules/filenames');
2
+ const { scanPayloads } = require('./rules/payloads');
3
+ const { scanSecrets } = require('./rules/secrets');
4
+ const { inspectIdeConfig } = require('./rules/ideConfig');
5
+ const { colors, symbols } = require('./reporter');
6
+ const { execSync } = require('child_process');
7
+
8
+ /**
9
+ * Parses GitHub repo URL or string into { owner, repo, branch }
10
+ * @param {string} inputUrl
11
+ * @returns {{ owner: string, repo: string, branch?: string } | null}
12
+ */
13
+ function parseGitHubUrl(inputUrl) {
14
+ if (!inputUrl) return null;
15
+ let clean = inputUrl.trim().replace(/\.git$/, '');
16
+
17
+ // Handle git@github.com:owner/repo
18
+ if (clean.startsWith('git@github.com:')) {
19
+ clean = clean.replace('git@github.com:', '');
20
+ } else {
21
+ clean = clean.replace(/^https?:\/\/github\.com\//, '');
22
+ }
23
+
24
+ const parts = clean.split('/').filter(Boolean);
25
+ if (parts.length < 2) return null;
26
+
27
+ const owner = parts[0];
28
+ const repo = parts[1];
29
+ let branch;
30
+
31
+ if (parts[2] === 'tree' && parts[3]) {
32
+ branch = parts.slice(3).join('/');
33
+ }
34
+
35
+ return { owner, repo, branch };
36
+ }
37
+
38
+ /**
39
+ * Tries to get GitHub token from env or GitHub CLI
40
+ * @returns {string | null}
41
+ */
42
+ function resolveGitHubToken() {
43
+ if (process.env.GITHUB_TOKEN) return process.env.GITHUB_TOKEN;
44
+ if (process.env.GH_TOKEN) return process.env.GH_TOKEN;
45
+
46
+ // Try gh auth token
47
+ try {
48
+ const ghToken = execSync('gh auth token', {
49
+ encoding: 'utf8',
50
+ stdio: ['pipe', 'pipe', 'pipe']
51
+ }).trim();
52
+ if (ghToken) return ghToken;
53
+ } catch (_) {}
54
+
55
+ return null;
56
+ }
57
+
58
+ /**
59
+ * Makes GitHub API request with proper headers
60
+ * @param {string} endpoint
61
+ * @param {string | null} [token]
62
+ */
63
+ async function fetchGitHubApi(endpoint, token = null) {
64
+ const url = endpoint.startsWith('http') ? endpoint : `https://api.github.com${endpoint}`;
65
+ const headers = {
66
+ 'Accept': 'application/vnd.github+json',
67
+ 'User-Agent': 'git-pre-push-remote-scanner/1.0',
68
+ 'X-GitHub-Api-Version': '2022-11-28',
69
+ ...(token ? { 'Authorization': `Bearer ${token}` } : {})
70
+ };
71
+
72
+ const res = await fetch(url, { headers });
73
+ if (!res.ok) {
74
+ const errText = await res.text();
75
+ if (res.status === 404) {
76
+ throw new Error(`Repository not found or private. If private, please provide a GitHub token.`);
77
+ }
78
+ if (res.status === 403 && res.headers.get('x-ratelimit-remaining') === '0') {
79
+ throw new Error(`GitHub API rate limit exceeded. Please provide a GitHub token to scan.`);
80
+ }
81
+ throw new Error(`GitHub API Error [${res.status}]: ${errText}`);
82
+ }
83
+
84
+ return res.json();
85
+ }
86
+
87
+ /**
88
+ * Scans a remote GitHub repository in memory without cloning or downloading
89
+ * @param {string} repoInput
90
+ * @param {string | null} [customToken]
91
+ * @param {(msg: string) => void} [onProgress]
92
+ */
93
+ async function scanRemoteRepositoryZeroClone(repoInput, customToken = null, onProgress = () => {}) {
94
+ const startTime = Date.now();
95
+ const parsed = parseGitHubUrl(repoInput);
96
+
97
+ if (!parsed) {
98
+ throw new Error(`Invalid GitHub repository URL: "${repoInput}". Format: https://github.com/owner/repo or owner/repo`);
99
+ }
100
+
101
+ const { owner, repo } = parsed;
102
+ const token = customToken || resolveGitHubToken();
103
+
104
+ onProgress(`Connecting to GitHub API for ${owner}/${repo}...`);
105
+
106
+ // 1. Get repository info to resolve default branch
107
+ let branch = parsed.branch;
108
+ if (!branch) {
109
+ const repoInfo = await fetchGitHubApi(`/repos/${owner}/${repo}`, token);
110
+ branch = repoInfo.default_branch || 'main';
111
+ }
112
+
113
+ onProgress(`Fetching recursive file tree for branch "${branch}" (Zero-Clone)...`);
114
+
115
+ // 2. Fetch full tree metadata in 1 single HTTP call
116
+ const treeData = await fetchGitHubApi(`/repos/${owner}/${repo}/git/trees/${branch}?recursive=1`, token);
117
+ const items = (treeData.tree || []).filter(item => item.type === 'blob');
118
+
119
+ onProgress(`Indexed ${items.length} files. Running Stage 1 Path & Filename Audit...`);
120
+
121
+ const threats = [];
122
+ const inspectContentQueue = [];
123
+
124
+ // Stage 1: Path & Filename Match (Instant in-memory check)
125
+ for (const item of items) {
126
+ const filePath = item.path;
127
+ const fileRule = checkFilename(filePath);
128
+
129
+ if (fileRule) {
130
+ threats.push({
131
+ name: fileRule.rule,
132
+ severity: fileRule.severity,
133
+ description: 'Unauthorized, dangerous or suspicious file detected in remote repository.',
134
+ filePath,
135
+ sha: item.sha
136
+ });
137
+ }
138
+
139
+ // Flag files needing Stage 2 deep blob inspection
140
+ const lower = filePath.toLowerCase();
141
+ const needsBlobCheck =
142
+ lower.includes('.vscode/tasks.json') ||
143
+ lower.includes('.vscode/settings.json') ||
144
+ lower.includes('.idea/') ||
145
+ lower.endsWith('.env') ||
146
+ lower.endsWith('.bat') ||
147
+ lower.endsWith('.ps1') ||
148
+ lower.endsWith('.vbs') ||
149
+ lower.endsWith('.sh');
150
+
151
+ if (needsBlobCheck) {
152
+ inspectContentQueue.push(item);
153
+ }
154
+ }
155
+
156
+ // Stage 2: On-Demand In-Memory Blob Inspection (Only for suspicious candidates)
157
+ if (inspectContentQueue.length > 0) {
158
+ onProgress(`Inspecting ${inspectContentQueue.length} suspicious file blobs in RAM...`);
159
+
160
+ for (const item of inspectContentQueue) {
161
+ try {
162
+ const blobData = await fetchGitHubApi(`/repos/${owner}/${repo}/git/blobs/${item.sha}`, token);
163
+ let content = '';
164
+ if (blobData.encoding === 'base64') {
165
+ content = Buffer.from(blobData.content, 'base64').toString('utf8');
166
+ } else {
167
+ content = blobData.content || '';
168
+ }
169
+
170
+ const filePath = item.path;
171
+
172
+ // IDE tasks & settings
173
+ if (filePath.includes('.vscode/') || filePath.includes('.idea/')) {
174
+ const ideThreats = inspectIdeConfig(filePath, content);
175
+ for (const it of ideThreats) {
176
+ threats.push({
177
+ name: it.name,
178
+ severity: it.severity,
179
+ description: it.description,
180
+ filePath,
181
+ line: it.line,
182
+ sha: item.sha
183
+ });
184
+ }
185
+ }
186
+
187
+ // Payload signatures
188
+ const payloadThreats = scanPayloads(content, filePath);
189
+ for (const pt of payloadThreats) {
190
+ threats.push({
191
+ name: pt.name,
192
+ severity: pt.severity,
193
+ description: pt.description,
194
+ filePath,
195
+ line: pt.line,
196
+ sha: item.sha
197
+ });
198
+ }
199
+
200
+ // Secret checks
201
+ const secretThreats = scanSecrets(content, filePath);
202
+ for (const st of secretThreats) {
203
+ threats.push({
204
+ name: st.name,
205
+ severity: st.severity,
206
+ description: st.description,
207
+ filePath,
208
+ sha: item.sha
209
+ });
210
+ }
211
+ } catch (_) {}
212
+ }
213
+ }
214
+
215
+ const durationMs = Date.now() - startTime;
216
+ const hasCritical = threats.some(t => t.severity === 'CRITICAL');
217
+ const hasWarning = threats.some(t => t.severity === 'WARNING');
218
+
219
+ return {
220
+ owner,
221
+ repo,
222
+ branch,
223
+ totalFiles: items.length,
224
+ threats,
225
+ durationMs,
226
+ hasCritical,
227
+ hasWarning
228
+ };
229
+ }
230
+
231
+ /**
232
+ * Prints formatted visual report for remote scan
233
+ * @param {ReturnType<typeof scanRemoteRepositoryZeroClone> extends Promise<infer T> ? T : any} result
234
+ */
235
+ function printRemoteScanReport(result) {
236
+ const { owner, repo, branch, totalFiles, threats, durationMs } = result;
237
+
238
+ console.log(`\n${colors.cyan}${colors.bold}================================================================${colors.reset}`);
239
+ console.log(`${colors.cyan}${colors.bold} REMOTE REPOSITORY AUDIT REPORT (ZERO-CLONE) ${colors.reset}`);
240
+ console.log(`${colors.cyan}${colors.bold}================================================================${colors.reset}`);
241
+
242
+ console.log(`\n${colors.bold}Target:${colors.reset} ${colors.cyan}https://github.com/${owner}/${repo}${colors.reset}`);
243
+ console.log(`${colors.bold}Branch:${colors.reset} ${branch}`);
244
+ console.log(`${colors.bold}Files:${colors.reset} ${totalFiles} files indexed`);
245
+ console.log(`${colors.bold}Storage:${colors.reset} ${colors.green}0 MB downloaded (100% in-memory)${colors.reset}`);
246
+ console.log(`${colors.bold}Time:${colors.reset} ${durationMs}ms`);
247
+
248
+ if (threats.length === 0) {
249
+ console.log(`\n${colors.bgGreen}${colors.bold} PASSED ${colors.reset} ${colors.green}${colors.bold}Repository is CLEAN. No malware, Trojan scripts, or secrets found.${colors.reset}\n`);
250
+ return;
251
+ }
252
+
253
+ const criticals = threats.filter(t => t.severity === 'CRITICAL');
254
+ const warnings = threats.filter(t => t.severity === 'WARNING');
255
+
256
+ console.log(`\n${colors.bgRed}${colors.bold} THREATS DETECTED IN REMOTE REPOSITORY ${colors.reset}\n`);
257
+
258
+ for (const t of threats) {
259
+ const isCrit = t.severity === 'CRITICAL';
260
+ const tag = isCrit
261
+ ? `${colors.bgRed}${colors.white}${colors.bold} CRITICAL ${colors.reset}`
262
+ : `${colors.bgYellow}${colors.white}${colors.bold} WARNING ${colors.reset}`;
263
+
264
+ console.log(`${tag} ${colors.bold}${t.name}${colors.reset}`);
265
+ console.log(` ${colors.dim}File:${colors.reset} ${colors.yellow}${t.filePath}${colors.reset}`);
266
+ if (t.description) console.log(` ${colors.dim}Reason:${colors.reset} ${t.description}`);
267
+ if (t.line) console.log(` ${colors.dim}Line:${colors.reset} ${colors.red}${t.line}${colors.reset}`);
268
+ console.log('');
269
+ }
270
+
271
+ console.log(`${colors.bold}Audit Summary:${colors.reset} ${colors.red}${criticals.length} Critical${colors.reset}, ${colors.yellow}${warnings.length} Warnings\n`);
272
+ }
273
+
274
+ module.exports = {
275
+ parseGitHubUrl,
276
+ scanRemoteRepositoryZeroClone,
277
+ printRemoteScanReport,
278
+ resolveGitHubToken
279
+ };