-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathindex.js
338 lines (289 loc) · 11.8 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
#!/usr/bin/env node
// Import required modules
const axios = require('axios');
const { ArgumentParser } = require('argparse');
const colors = {
GREEN: '\x1b[32m',
YELLOW: '\x1b[33m',
NC: '\x1b[0m',
CYAN: '\x1b[36m',
}
// Constants
const API_URL = 'https://api.github.com';
const HEADER = {
Accept: 'application/vnd.github.v3+json',
'User-Agent':
'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/81.0.4044.141 Safari/537.36',
};
let found = []
let DELAY = 3000; // Delay of one second between requests
// Factory function to create Repository objects
const Repository = (name, isFork) => ({
name,
isFork,
});
// Function to update HTTP headers
const updateHeader = (updateObj) => {
Object.assign(HEADER, updateObj);
};
// Function to retrieve user's repositories
const getRepositories = async (username) => {
const repositoriesSeen = new Set();
const repositories = [];
let pageCounter = 1;
while (true) {
let continueLoop = true;
// Construct the URL for fetching repositories
const url = `${API_URL}/users/${username}/repos?per_page=100&page=${pageCounter}`;
const result = await apiCall(url);
if ('message' in result) {
if (result.message.includes('API rate limit exceeded for ')) {
console.warn('API rate limit exceeded - not all repos were fetched');
break;
}
if (result.message === 'Not Found') {
console.warn(`There is no user with the username "${username}"`);
break;
}
}
// Process each repository in the result
for (const repository of result) {
const repoName = repository.name;
if (repositoriesSeen.has(repoName)) {
continueLoop = false;
break;
} else {
repositories.push(Repository(repoName, repository.fork));
repositoriesSeen.add(repoName);
}
}
if (continueLoop && result.length === 100) {
pageCounter += 1;
} else {
break;
}
}
return repositories;
};
// Function to retrieve email addresses from a repository's commits
const getEmails = async (username, repoName) => {
const emailsToName = new Map();
const seenCommits = new Set();
let pageCounter = 1;
let commitCounter = 1;
while (true) {
let continueLoop = true;
const url = `${API_URL}/repos/${username}/${repoName}/commits?per_page=100&page=${pageCounter}`;
const result = await apiCall(url);
if ('message' in result) {
if (result.message === 'Git Repository is empty.') {
console.info('Git repository is empty');
continue;
}
if (result.message.includes('API rate limit exceeded for ')) {
console.warn('API rate limit exceeded');
return emailsToName;
}
if (result.message === 'Not Found') {
console.warn(`Repository Not Found: "${repoName}"`);
return emailsToName;
}
}
// Process each commit in the result
for (const commit of result) {
const sha = commit.sha;
if (seenCommits.has(sha)) {
continueLoop = false;
break;
}
seenCommits.add(sha);
// console.info(`Scanning commit -> ${commitCounter}`);
commitCounter += 1;
if (!commit.author) {
continue;
}
const user = commit.author.login;
if (user.toLowerCase() === username.toLowerCase()) {
const { author, committer } = commit.commit;
const authorName = author.name;
const authorEmail = author.email;
const committerName = committer.name;
const committerEmail = committer.email;
if (authorEmail) {
if (!emailsToName.has(authorEmail)) {
emailsToName.set(authorEmail, new Set());
}
emailsToName.get(authorEmail).add(authorName);
}
if (committerEmail) {
if (!emailsToName.has(committerEmail)) {
emailsToName.set(committerEmail, new Set());
}
emailsToName.get(committerEmail).add(committerName);
}
}
}
if (continueLoop && result.length === 100) {
pageCounter += 1;
} else {
break;
}
}
return emailsToName;
};
const findUserNameByEmail = async (email) => {
// url https://api.github.com/search/[email protected]
const url = `${API_URL}/search/users?q=${email}`;
const result = await apiCall(url);
return result
}
// Function to make API calls with a delay
const apiCall = async (url) => {
await new Promise((resolve) => setTimeout(resolve, DELAY));
const response = await axios.get(url, { headers: HEADER, timeout: 10000 });
return response.data;
};
const emailRegex = (email) => {
const re = /\S+@\S+\.\S+/;
return re.test(email)
}
// Main function
const main = async () => {
console.log(`${colors.CYAN}
██████╗ ██╗████████╗██████╗ ███████╗ ██████╗ ██████╗ ███╗ ██╗
██╔════╝ ██║╚══██╔══╝██╔══██╗██╔════╝██╔════╝██╔═══██╗████╗ ██║
██║ ███╗██║ ██║ ██████╔╝█████╗ ██║ ██║ ██║██╔██╗ ██║
██║ ██║██║ ██║ ██╔══██╗██╔══╝ ██║ ██║ ██║██║╚██╗██║
╚██████╔╝██║ ██║ ██║ ██║███████╗╚██████╗╚██████╔╝██║ ╚████║
╚═════╝ ╚═╝ ╚═╝ ╚═╝ ╚═╝╚══════╝ ╚═════╝ ╚═════╝ ╚═╝ ╚═══╝
https://github.com/atiilla
`);
// Create an argument parser
const parser = new ArgumentParser({
add_help: true, // Use add_help instead of addHelp
description:
'A tool to scan GitHub repositories for exposed email addresses and names',
});
// Define command line arguments
parser.add_argument('-u', '--user', {
help: 'name of the user whose repositories should be scanned',
type: String,
required: false,
});
parser.add_argument('-e', '--email', {
help: 'email address to search for github username',
type: String,
required: false,
});
parser.add_argument('-r', '--repository', {
help: 'name of the repository which should be scanned',
type: String,
});
parser.add_argument('-t', '--token', {
help: 'GitHub API token (optional) to increase the rate limit',
type: String,
});
parser.add_argument('-n', '--no-forks', {
help: 'do not scan forked repositories',
action: 'store_true',
});
// Parse command line arguments
const args = parser.parse_args();
// one of the required arguments is missing
if (!args.user && !args.email) {
console.warn('No username and email specified [!]\n');
parser.print_help();
return;
}
if (args.token) {
updateHeader({ Authorization: `token ${args.token}` });
}
// if email is provided
if (args.email) {
// if email is not valid
if (!emailRegex(args.email)) {
console.warn('Invalid email address [!]\n');
parser.print_help();
return;
}
const result = await findUserNameByEmail(args.email)
// {
// "login": "tomtom0",
// "id": 5770687,
// "node_id": "MDQ6VXNlcjU3NzA2ODc=",
// "avatar_url": "https://avatars.githubusercontent.com/u/5770687?v=4",
// "gravatar_id": "",
// "url": "https://api.github.com/users/tomtom0",
// "html_url": "https://github.com/tomtom0",
// "followers_url": "https://api.github.com/users/tomtom0/followers",
// "following_url": "https://api.github.com/users/tomtom0/following{/other_user}",
// "gists_url": "https://api.github.com/users/tomtom0/gists{/gist_id}",
// "starred_url": "https://api.github.com/users/tomtom0/starred{/owner}{/repo}",
// "subscriptions_url": "https://api.github.com/users/tomtom0/subscriptions",
// "organizations_url": "https://api.github.com/users/tomtom0/orgs",
// "repos_url": "https://api.github.com/users/tomtom0/repos",
// "events_url": "https://api.github.com/users/tomtom0/events{/privacy}",
// "received_events_url": "https://api.github.com/users/tomtom0/received_events",
// "type": "User",
// "site_admin": false,
// "score": 1.0
// }
if(result.total_count > 0){
console.log(`${colors.CYAN} Found username ${colors.YELLOW}${result.items[0].login}${colors.CYAN} for email ${colors.YELLOW}${args.email}${colors.CYAN}`);
}else{
console.log(`${colors.CYAN} No username found for email ${colors.YELLOW}${args.email}${colors.CYAN}`);
}
}
if (args.user) {
let reposToScan = [];
if (args.repository) {
reposToScan = [args.repository];
} else {
console.info(`Scan all public repositories of ${args.user}`);
const reposToScanSorted = (
await getRepositories(args.user)
).sort((a, b) => (a.isFork ? 1 : -1));
reposToScan = reposToScanSorted
.filter(
(repo) =>
!args.no_forks || !repo.isFork
)
.map((repo) => repo.name);
console.info(`Found ${reposToScan.length} public repositories`);
}
const emailsToName = new Map();
try {
for (const repo of reposToScan) {
console.info(`${colors.GREEN}Scanning repository "${colors.YELLOW}${repo}${colors.YELLOW}${colors.GREEN}"`);
const emailsToNameNew = await getEmails(args.user, repo);
for (const [email, names] of emailsToNameNew.entries()) {
if (!emailsToName.has(email)) {
emailsToName.set(email, new Set());
}
names.forEach((name) => emailsToName.get(email).add(name));
}
}
} catch (error) {
console.warn('An error occurred:', error.message);
}
if (emailsToName.size > 0) {
const maxEmailWidth = Math.max(...Array.from(emailsToName.keys(), (email) => email.length));
console.info(`${colors.YELLOW}Found the following emails:`);
for (const [email, names] of emailsToName.entries()) {
const namesString = Array.from(names).join('; ');
const obj = {
email: email.padEnd(maxEmailWidth, ' '),
authors: namesString
}
found.push(obj)
}
// \x1b[0m
console.log(`\x1b[0m`)
console.table(found)
} else {
console.info('No emails found');
}
}
};
// Run the main function and handle errors
main().catch((error) => console.error(error));