Repository navigation
Expand file tree
/
Copy pathutils.js
More file actions
400 lines (352 loc) · 9.95 KB
/
Copy pathutils.js
File metadata and controls
400 lines (352 loc) · 9.95 KB
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
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
import { URL } from 'url';
/**
* Validate a target URL or IP address
* @param {string} target - Target to validate
* @returns {Object} Validation result with valid boolean and error message
*/
export function validateTarget(target) {
if (!target || typeof target !== 'string') {
return {
valid: false,
error: 'Target must be a non-empty string'
};
}
target = target.trim();
// Check if it's an IP address
if (isValidIP(target)) {
return {
valid: true,
type: 'ip',
target: target
};
}
// Check if it's a URL
if (isValidUrl(target)) {
return {
valid: true,
type: 'url',
target: target
};
}
// If it already has a protocol but isn't HTTP/HTTPS, reject it
if (target.includes('://') && !target.startsWith('http://') && !target.startsWith('https://')) {
return {
valid: false,
error: 'Only HTTP and HTTPS protocols are supported'
};
}
// Try to add protocol and validate
const withProtocol = target.startsWith('http') ? target : `http://${target}`;
if (isValidUrl(withProtocol)) {
return {
valid: true,
type: 'url',
target: withProtocol
};
}
// Check if it looks like a domain name (has at least one dot and valid format)
if (target.includes('.') && !target.includes(' ') && target.length > 3) {
// Basic domain validation - should have valid characters and structure
const domainRegex = /^[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?(\.[a-zA-Z0-9]([a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/;
if (domainRegex.test(target)) {
const withHttp = `http://${target}`;
if (isValidUrl(withHttp)) {
return {
valid: true,
type: 'url',
target: withHttp
};
}
}
}
return {
valid: false,
error: 'Target must be a valid URL or IP address'
};
}
/**
* Check if a string is a valid URL
* @param {string} urlString - URL string to validate
* @returns {boolean} True if valid URL
*/
export function isValidUrl(urlString) {
try {
const url = new URL(urlString);
return (url.protocol === 'http:' || url.protocol === 'https:') && url.hostname.length > 0;
} catch (error) {
return false;
}
}
/**
* Check if a string is a valid IP address (IPv4 or IPv6)
* @param {string} ip - IP address string to validate
* @returns {boolean} True if valid IP address
*/
export function isValidIP(ip) {
// IPv4 regex
const ipv4Regex = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
// IPv6 regex (simplified)
const ipv6Regex = /^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$|^::1$|^::$/;
return ipv4Regex.test(ip) || ipv6Regex.test(ip);
}
/**
* Parse a URL and extract components
* @param {string} urlString - URL string to parse
* @returns {Object} Parsed URL components
*/
export function parseUrl(urlString) {
try {
const url = new URL(urlString);
return {
protocol: url.protocol,
hostname: url.hostname,
port: url.port || (url.protocol === 'https:' ? '443' : '80'),
pathname: url.pathname,
search: url.search,
hash: url.hash,
origin: url.origin,
href: url.href
};
} catch (error) {
return null;
}
}
/**
* Sanitize a string for use in file names
* @param {string} str - String to sanitize
* @returns {string} Sanitized string
*/
export function sanitizeFilename(str) {
return str
.replace(/[^a-z0-9]/gi, '_')
.replace(/_+/g, '_')
.replace(/^_|_$/g, '')
.toLowerCase();
}
/**
* Format duration in seconds to human readable format
* @param {number} seconds - Duration in seconds
* @returns {string} Formatted duration
*/
export function formatDuration(seconds) {
if (seconds < 60) {
return `${seconds}s`;
}
const minutes = Math.floor(seconds / 60);
const remainingSeconds = seconds % 60;
if (minutes < 60) {
return remainingSeconds > 0 ? `${minutes}m ${remainingSeconds}s` : `${minutes}m`;
}
const hours = Math.floor(minutes / 60);
const remainingMinutes = minutes % 60;
let result = `${hours}h`;
if (remainingMinutes > 0) {
result += ` ${remainingMinutes}m`;
}
if (remainingSeconds > 0) {
result += ` ${remainingSeconds}s`;
}
return result;
}
/**
* Format file size in bytes to human readable format
* @param {number} bytes - Size in bytes
* @returns {string} Formatted size
*/
export function formatFileSize(bytes) {
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
let size = bytes;
let unitIndex = 0;
while (size >= 1024 && unitIndex < units.length - 1) {
size /= 1024;
unitIndex++;
}
return `${size.toFixed(unitIndex === 0 ? 0 : 1)}${units[unitIndex]}`;
}
/**
* Get severity color for console output
* @param {string} severity - Severity level
* @returns {string} ANSI color code
*/
export function getSeverityColor(severity) {
const colors = {
critical: '\x1b[41m\x1b[37m', // Red background, white text
high: '\x1b[31m', // Red text
medium: '\x1b[33m', // Yellow text
low: '\x1b[36m', // Cyan text
info: '\x1b[37m', // White text
reset: '\x1b[0m' // Reset
};
return colors[severity?.toLowerCase()] || colors.info;
}
/**
* Get severity emoji
* @param {string} severity - Severity level
* @returns {string} Emoji representing severity
*/
export function getSeverityEmoji(severity) {
const emojis = {
critical: '🔴',
high: '🟠',
medium: '🟡',
low: '🔵',
info: '⚪'
};
return emojis[severity?.toLowerCase()] || emojis.info;
}
/**
* Create a progress bar string
* @param {number} current - Current progress
* @param {number} total - Total items
* @param {number} width - Width of progress bar
* @returns {string} Progress bar string
*/
export function createProgressBar(current, total, width = 20) {
const percentage = Math.min(current / total, 1);
const filled = Math.floor(percentage * width);
const empty = width - filled;
const bar = '█'.repeat(filled) + '░'.repeat(empty);
const percent = Math.floor(percentage * 100);
return `[${bar}] ${percent}% (${current}/${total})`;
}
/**
* Debounce function to limit function calls
* @param {Function} func - Function to debounce
* @param {number} wait - Wait time in milliseconds
* @returns {Function} Debounced function
*/
export function debounce(func, wait) {
let timeout;
return function executedFunction(...args) {
const later = () => {
clearTimeout(timeout);
func(...args);
};
clearTimeout(timeout);
timeout = setTimeout(later, wait);
};
}
/**
* Deep merge two objects
* @param {Object} target - Target object
* @param {Object} source - Source object
* @returns {Object} Merged object
*/
export function deepMerge(target, source) {
const result = { ...target };
for (const key in source) {
if (source.hasOwnProperty(key)) {
if (typeof source[key] === 'object' && source[key] !== null && !Array.isArray(source[key])) {
result[key] = deepMerge(result[key] || {}, source[key]);
} else {
result[key] = source[key];
}
}
}
return result;
}
/**
* Generate a unique scan ID
* @returns {string} Unique scan ID
*/
export function generateScanId() {
const timestamp = Date.now();
const random = Math.random().toString(36).substr(2, 9);
return `scan-${timestamp}-${random}`;
}
/**
* Check if a port is commonly used for web services
* @param {number|string} port - Port number
* @returns {boolean} True if it's a common web port
*/
export function isWebPort(port) {
const webPorts = [80, 443, 8080, 8443, 3000, 5000, 8000, 8888, 9000];
return webPorts.includes(parseInt(port));
}
/**
* Extract domain from URL or hostname
* @param {string} input - URL or hostname
* @returns {string} Domain name
*/
export function extractDomain(input) {
try {
if (input.includes('://')) {
const url = new URL(input);
return url.hostname;
} else {
// Assume it's already a hostname
return input.split(':')[0]; // Remove port if present
}
} catch (error) {
return input;
}
}
/**
* Check if running with sufficient privileges for certain scans
* @returns {boolean} True if running as root/admin
*/
export function hasElevatedPrivileges() {
return process.getuid && process.getuid() === 0;
}
/**
* Escape shell arguments to prevent injection
* @param {string} arg - Argument to escape
* @returns {string} Escaped argument
*/
export function escapeShellArg(arg) {
return `'${arg.replace(/'/g, "'\"'\"'")}'`;
}
/**
* Parse command line style arguments from a string
* @param {string} str - String containing arguments
* @returns {Array} Array of parsed arguments
*/
export function parseArgs(str) {
const args = [];
let current = '';
let inQuotes = false;
let quoteChar = '';
for (let i = 0; i < str.length; i++) {
const char = str[i];
if ((char === '"' || char === "'") && !inQuotes) {
inQuotes = true;
quoteChar = char;
} else if (char === quoteChar && inQuotes) {
inQuotes = false;
quoteChar = '';
} else if (char === ' ' && !inQuotes) {
if (current) {
args.push(current);
current = '';
}
} else {
current += char;
}
}
if (current) {
args.push(current);
}
return args;
}
/**
* Retry a function with exponential backoff
* @param {Function} fn - Function to retry
* @param {number} maxRetries - Maximum number of retries
* @param {number} baseDelay - Base delay in milliseconds
* @returns {Promise} Promise that resolves with function result
*/
export async function retryWithBackoff(fn, maxRetries = 3, baseDelay = 1000) {
let lastError;
for (let attempt = 0; attempt <= maxRetries; attempt++) {
try {
return await fn();
} catch (error) {
lastError = error;
if (attempt === maxRetries) {
throw lastError;
}
const delay = baseDelay * Math.pow(2, attempt);
await new Promise(resolve => setTimeout(resolve, delay));
}
}
}