-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathURL_Extractor.cjs
274 lines (229 loc) · 9.7 KB
/
URL_Extractor.cjs
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
const { Worker, isMainThread, parentPort, workerData } = require('worker_threads');
const fs = require('fs');
const path = require('path');
const readline = require('readline');
const stringSimilarity = require('string-similarity');
const { chromium } = require('playwright');
const url = require('url');
const dangerousSinks = [
'eval', 'innerHTML', 'document.write', 'setTimeout', 'setInterval', 'location.href', 'location.assign',
'location.replace', 'Function', 'setAttribute', 'onclick', 'insertAdjacentHTML', 'window.open',
'XMLHttpRequest', 'fetch', 'document.domain', 'window.name', 'history.pushState', 'history.replaceState',
'localStorage.setItem', 'sessionStorage.setItem', 'indexedDB.open', 'WebSocket.send', 'document.cookie',
'document.open', 'document.close', 'document.implementation.createHTMLDocument', 'document.implementation.createDocument',
'document.implementation.createDocumentFragment', 'document.implementation.createNodeIterator', 'document.implementation.createTreeWalker'
];
const cleanOutputFolder = (folderPath) => {
if (fs.existsSync(folderPath)) {
fs.readdirSync(folderPath).forEach((file) => {
const curPath = path.join(folderPath, file);
if (fs.lstatSync(curPath).isDirectory()) {
cleanOutputFolder(curPath);
} else {
fs.unlinkSync(curPath);
}
});
console.log(`Cleaned output folder: ${folderPath}`);
}
};
// Function to read hostnames from file
const readHostnamesFromFile = (filename) => {
const filePath = path.resolve(__dirname, filename);
return fs.readFileSync(filePath, 'utf8').split('\n').map(line => line.trim()).filter(Boolean);
};
if (isMainThread) {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout
});
let worker;
const outputDir = path.resolve(__dirname, 'output');
cleanOutputFolder(outputDir);
// Define chunkSize
const chunkSize = 8192;
// Prompt for the file containing hostnames
rl.question('Please enter the filename containing the hostnames: ', async (filename) => {
const hostnames = readHostnamesFromFile(filename);
await processHostnames(hostnames);
rl.close();
});
const processHostnames = async (hostnames) => {
for (const hostname of hostnames) {
await new Promise((resolve) => {
worker = new Worker(__filename, { workerData: { hostname, outputDir } });
worker.on('message', (message) => {
if (message.type === 'save') {
saveLogsToFile(hostname, message.urlLog, outputDir);
resolve();
}
});
worker.on('exit', () => {
console.log(`Finished processing ${hostname}`);
resolve();
});
});
}
console.log('All hostnames have been processed.');
};
let hostCounter = 1; // Global counter for host numbering
const saveLogsToFile = (hostname, urlLog, outputDir) => {
// Save URLs log
const groupedUrls = groupUrls(urlLog);
const finalUrls = calculateSimilarity(groupedUrls);
// Filter out hosts that only have a root path ("/")
const filteredUrls = finalUrls.filter(urlObj => urlObj.url !== '/');
// Detect and retain the shortest URL from similar patterns
const shortestUrls = retainShortestUrls(filteredUrls);
if (shortestUrls.length > 0) {
let currentContent = `Host-${hostCounter}: ${hostname}\n\n`;
shortestUrls.forEach((urlObj) => {
const transformedUrl = urlObj.url.replace(new RegExp(`^https?://${hostname}`, 'i'), '');
urlObj.transformedUrl = transformedUrl;
currentContent += `${transformedUrl}\n`;
});
// Add space after each host's URLs
currentContent += `\n\n`;
// Append to the file instead of overwriting
fs.appendFileSync(path.join(outputDir, 'urls.txt'), currentContent.trim() + '\n\n', 'utf8');
console.log(`URLs for ${hostname} have been appended to "urls.txt" in the "output" directory.`);
// Increment the host counter
hostCounter++;
} else {
console.log(`No valid URLs found for ${hostname}.`);
}
};
// Function to retain the shortest URL from similar patterns
const retainShortestUrls = (urls) => {
const uniqueUrls = [];
urls.forEach((urlObj) => {
let isUnique = true;
for (let i = 0; i < uniqueUrls.length; i++) {
if (stringSimilarity.compareTwoStrings(urlObj.url, uniqueUrls[i].url) > 0.85) {
// Retain the shortest URL
if (urlObj.url.length < uniqueUrls[i].url.length) {
uniqueUrls[i] = urlObj;
}
isUnique = false;
break;
}
}
if (isUnique) {
uniqueUrls.push(urlObj);
}
});
return uniqueUrls;
};
const groupUrls = (urls) => {
const groups = {};
urls.forEach((urlObj) => {
const baseUrl = urlObj.url.split('?')[0];
const key = baseUrl.split('/').slice(0, -1).join('/') + ':' + baseUrl.length;
if (!groups[key]) {
groups[key] = [];
}
groups[key].push(urlObj);
});
return Object.values(groups).map(group => group[group.length - 1]);
};
const calculateSimilarity = (urls) => {
const uniqueUrls = [];
urls.forEach((urlObj) => {
let isUnique = true;
for (let i = 0; i < uniqueUrls.length; i++) {
if (stringSimilarity.compareTwoStrings(urlObj.url, uniqueUrls[i].url) > 0.85) {
isUnique = false;
break;
}
}
if (isUnique) {
uniqueUrls.push(urlObj);
}
});
return uniqueUrls;
};
} else {
const { hostname, outputDir } = workerData;
let urlLog = [];
let requests = [];
const urlToRequestIndexMap = {};
const removeProtocolAndHost = (url) => {
try {
const urlObj = new URL(url);
return urlObj.pathname + urlObj.search;
} catch (e) {
return url;
}
};
const createPacketString = (requestPacket, hostname) => {
const headersObject = JSON.parse(JSON.stringify(requestPacket.headers));
const headersString = Object.entries(headersObject).map(([name, value]) => `${name}: ${value}`).join('\r\n');
const requestLine = `${requestPacket.method} ${requestPacket.url} HTTP/1.1`;
const body = requestPacket.postData || '';
const hostHeader = `Host: ${hostname}`;
return `${requestLine}\r\n${hostHeader}\r\n${headersString}\r\n\r\n${body}`;
};
const startPlaywright = async (hostname, outputDir) => {
const chromePath = path.resolve(__dirname, 'C:\\Program Files\\Google\\Chrome\\Application', 'chrome.exe');
const startupAddress = `https://${hostname}`;
if (!fs.existsSync(outputDir)) {
fs.mkdirSync(outputDir);
}
const browser = await chromium.launch({
executablePath: chromePath,
headless: true,
bypassCSP: true,
ignoreHTTPSErrors: true,
javaScriptEnabled: true,
acceptDownloads: true,
permissions: ['geolocation', 'notifications'],
userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.124 Safari/537.36',
viewport: { width: 1280, height: 720 },
recordHar: { path: 'network_logs.har', mode: 'full' },
offline: false,
extraHTTPHeaders: {
'Cache-Control': 'no-cache'
}
});
const page = await browser.newPage();
page.on('request', request => {
const url = request.url();
if (url.includes(hostname)) {
const strippedUrl = removeProtocolAndHost(url);
console.log(`Request: ${strippedUrl}`);
const packetString = createPacketString({
url: strippedUrl,
headers: request.headers(),
method: request.method(),
postData: request.postData(),
}, hostname);
requests.push({
url: strippedUrl,
headers: request.headers(),
method: request.method(),
postData: request.postData(),
packetString,
});
urlLog.push({ url: strippedUrl, packetString });
urlToRequestIndexMap[strippedUrl] = requests.length - 1;
}
});
page.on('response', async response => {
const url = response.url();
if (url.includes(hostname)) {
const strippedUrl = removeProtocolAndHost(url);
console.log(`Response: ${strippedUrl}`);
}
});
try {
await page.goto(startupAddress);
console.log('Page loaded successfully');
} catch (error) {
console.error('Playwright navigation error:', error);
}
console.log('Browser is open. Interact with the page and close the browser when done.');
await browser.close();
console.log('Browser closed.');
parentPort.postMessage({ type: 'save', urlLog });
};
startPlaywright(hostname, outputDir);
}