-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconfig_manager.js
More file actions
556 lines (477 loc) · 17.5 KB
/
config_manager.js
File metadata and controls
556 lines (477 loc) · 17.5 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
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
/**
* Iran Internet Access Analysis Tool
* Configuration management system
* For maintaining internet freedom in restricted environments
*/
const fs = require('fs');
const path = require('path');
const DEFAULT_CONFIG = {
// Network settings
network: {
timeout: 5, // seconds for each test
maxConcurrent: 50, // maximum concurrent tests
retryAttempts: 3, // retry failed connections
retryDelay: 1000, // ms between retries
pingTimeout: 3, // seconds for ping timeout
tcpTimeout: 5, // seconds for TCP connection timeout
dnsTimeout: 3, // seconds for DNS resolution timeout
packetSize: 56, // bytes for ping packet size
maxPacketLoss: 50, // percentage threshold for packet loss
},
// Test configuration
testing: {
sampleSize: 5, // number of IPs to test per CIDR range
testAllPorts: true, // test all common ports
testPing: true, // include ping tests
testTcp: true, // include TCP connection tests
testDns: true, // include DNS resolution tests
testTraceroute: false, // include traceroute (slower)
saveRawData: false, // save raw test data
enableLogging: true, // enable detailed logging
logLevel: 'info', // debug, info, warn, error
},
// Provider settings
providers: {
// Enable/disable specific provider categories
enableCloudProviders: true, // AWS, Google Cloud, Azure
enableCDNProviders: true, // Cloudflare, Akamai, Fastly
enableDNSProviders: true, // Google DNS, Cloudflare DNS, etc.
enableRegionalProviders: true, // Iranian, Turkish, UAE, etc.
enableCustomProviders: true, // User-defined providers
// Priority order for testing
priorityOrder: [
'iranian_data_centers',
'turkish_data_centers',
'emirati_data_centers',
'qatari_data_centers',
'russian_data_centers',
'chinese_data_centers',
'hetzner_falkenstein_cx22',
'ovh_gravelines_starter',
'scaleway_paris_dev1s',
'vultr_fremont_regular',
'digitalocean_fra1_basic',
'cloudflare',
'aws',
'google_cloud',
'azure',
'akamai',
'fastly'
]
},
// Custom IP ranges
customIps: {
enabled: false,
ranges: [],
description: 'Custom IP ranges for testing'
},
// Output settings
output: {
format: 'json', // json, csv, txt, html
filename: 'iran_analysis',
includeTimestamp: true,
includeSummary: true,
includeDetails: true,
includeRecommendations: true,
compressOutput: false, // gzip compression
maxFileSize: 100, // MB
},
// Security settings
security: {
enableEncryption: false, // encrypt sensitive data
encryptionKey: '', // encryption key (auto-generated if empty)
hashAlgorithm: 'sha256', // hashing algorithm for data integrity
enableIntegrityCheck: true, // verify data integrity
},
// Performance settings
performance: {
memoryLimit: 512, // MB memory limit
cpuLimit: 80, // percentage CPU limit
maxTestDuration: 3600, // seconds (1 hour)
enableRateLimiting: true, // prevent overwhelming targets
rateLimit: {
maxRequests: 100, // requests per minute per IP
windowMs: 60000, // 1 minute window
delayMs: 1000 // delay between requests
}
},
// Alert settings
alerts: {
enabled: false,
email: {
enabled: false,
smtp: {
host: '',
port: 587,
secure: true,
user: '',
password: ''
},
recipients: [],
subject: 'Iran Connectivity Analysis Report',
onComplete: true,
onFailure: true
},
webhook: {
enabled: false,
url: '',
method: 'POST',
headers: {},
onComplete: true,
onFailure: true
}
},
// Advanced settings
advanced: {
enableIPv6: false, // test IPv6 addresses
enableProxy: false, // use proxy for testing
proxy: {
host: '',
port: 8080,
protocol: 'http', // http, https, socks5
auth: {
username: '',
password: ''
}
},
userAgent: 'IranCheck/1.0', // user agent for HTTP requests
enableDebugging: false, // enable debug mode
debugPort: 9229, // Node.js debug port
enableProfiling: false // enable performance profiling
}
};
class ConfigManager {
constructor(configPath = null) {
this.configPath = configPath || this.getDefaultConfigPath();
this.config = this.loadConfig();
this.isDirty = false;
}
getDefaultConfigPath() {
// Try to find config in multiple locations
const possiblePaths = [
path.join(process.cwd(), 'irancheck.config.json'),
path.join(process.cwd(), 'config.json'),
path.join(require('os').homedir(), '.irancheck', 'config.json'),
'/etc/irancheck/config.json'
];
for (const configPath of possiblePaths) {
if (fs.existsSync(configPath)) {
return configPath;
}
}
// Return default path in current directory
return path.join(process.cwd(), 'irancheck.config.json');
}
loadConfig() {
try {
if (fs.existsSync(this.configPath)) {
const fileConfig = JSON.parse(fs.readFileSync(this.configPath, 'utf8'));
// Merge with default config to ensure all properties exist
return this.deepMerge(DEFAULT_CONFIG, fileConfig);
}
} catch (error) {
console.warn(`Warning: Could not load config from ${this.configPath}: ${error.message}`);
}
// Return default config if file doesn't exist or is invalid
return JSON.parse(JSON.stringify(DEFAULT_CONFIG));
}
saveConfig() {
if (!this.isDirty) {
return;
}
try {
// Ensure directory exists
const dir = path.dirname(this.configPath);
if (!fs.existsSync(dir)) {
fs.mkdirSync(dir, { recursive: true });
}
// Backup existing config
if (fs.existsSync(this.configPath)) {
const backupPath = `${this.configPath}.backup.${Date.now()}`;
fs.copyFileSync(this.configPath, backupPath);
}
// Save new config
fs.writeFileSync(this.configPath, JSON.stringify(this.config, null, 2));
this.isDirty = false;
console.log(`Configuration saved to: ${this.configPath}`);
} catch (error) {
throw new Error(`Failed to save configuration: ${error.message}`);
}
}
get(path) {
return this.getNestedValue(this.config, path);
}
set(path, value) {
this.setNestedValue(this.config, path, value);
this.isDirty = true;
}
getNestedValue(obj, path) {
const keys = this.parsePath(path);
if (keys.length === 0) {
return undefined;
}
return keys.reduce((current, key) => {
return current && current[key] !== undefined ? current[key] : undefined;
}, obj);
}
setNestedValue(obj, path, value) {
const keys = this.parsePath(path);
if (keys.length === 0) {
throw new Error('Invalid configuration path');
}
const lastKey = keys.pop();
const target = keys.reduce((current, key) => {
if (!current[key] || typeof current[key] !== 'object') {
current[key] = {};
}
return current[key];
}, obj);
target[lastKey] = value;
}
deepMerge(target, source) {
const result = JSON.parse(JSON.stringify(target));
for (const key in source) {
if (Object.prototype.hasOwnProperty.call(source, key) && !this.isUnsafeKey(key)) {
if (this.isPlainObject(source[key])) {
result[key] = this.deepMerge(result[key] || {}, source[key]);
} else {
result[key] = source[key];
}
}
}
return result;
}
parsePath(pathValue) {
if (typeof pathValue !== 'string') {
throw new Error('Configuration path must be a string');
}
const keys = pathValue.split('.').map(k => k.trim()).filter(Boolean);
if (keys.some(key => this.isUnsafeKey(key))) {
throw new Error('Unsafe configuration path');
}
return keys;
}
isUnsafeKey(key) {
return key === '__proto__' || key === 'constructor' || key === 'prototype';
}
isPlainObject(value) {
return Boolean(value) && typeof value === 'object' && !Array.isArray(value);
}
validateConfig() {
const errors = [];
const warnings = [];
// Validate network settings
if (this.config.network.timeout < 1 || this.config.network.timeout > 30) {
errors.push('Network timeout must be between 1 and 30 seconds');
}
if (this.config.network.maxConcurrent < 1 || this.config.network.maxConcurrent > 1000) {
errors.push('Max concurrent tests must be between 1 and 1000');
}
// Validate testing settings
if (this.config.testing.sampleSize < 1 || this.config.testing.sampleSize > 100) {
errors.push('Sample size must be between 1 and 100');
}
// Validate output settings
const validFormats = ['json', 'csv', 'txt', 'html'];
if (!validFormats.includes(this.config.output.format)) {
errors.push(`Output format must be one of: ${validFormats.join(', ')}`);
}
// Validate security settings
if (this.config.security.enableEncryption && !this.config.security.encryptionKey) {
warnings.push('Encryption enabled but no encryption key provided (will be auto-generated)');
}
// Validate alert settings
if (this.config.alerts.enabled) {
if (this.config.alerts.email.enabled && !this.config.alerts.email.smtp.host) {
warnings.push('Email alerts enabled but no SMTP server configured');
}
if (this.config.alerts.webhook.enabled && !this.config.alerts.webhook.url) {
warnings.push('Webhook alerts enabled but no webhook URL configured');
}
}
// Validate proxy settings
if (this.config.advanced.enableProxy && !this.config.advanced.proxy.host) {
errors.push('Proxy enabled but no proxy host configured');
}
return { errors, warnings };
}
resetToDefaults() {
this.config = JSON.parse(JSON.stringify(DEFAULT_CONFIG));
this.isDirty = true;
}
getAllProviders() {
return this.config.providers.priorityOrder;
}
enableProvider(providerKey) {
if (!this.config.providers.priorityOrder.includes(providerKey)) {
this.config.providers.priorityOrder.push(providerKey);
this.isDirty = true;
}
}
disableProvider(providerKey) {
const index = this.config.providers.priorityOrder.indexOf(providerKey);
if (index > -1) {
this.config.providers.priorityOrder.splice(index, 1);
this.isDirty = true;
}
}
addCustomIpRange(range, description = '') {
if (!this.config.customIps.ranges.find(r => r.range === range)) {
this.config.customIps.ranges.push({
range: range,
description: description,
enabled: true
});
this.config.customIps.enabled = true;
this.isDirty = true;
}
}
removeCustomIpRange(range) {
const index = this.config.customIps.ranges.findIndex(r => r.range === range);
if (index > -1) {
this.config.customIps.ranges.splice(index, 1);
this.isDirty = true;
}
}
getCustomIpRanges() {
return this.config.customIps.enabled ? this.config.customIps.ranges : [];
}
generateEncryptionKey() {
const crypto = require('crypto');
return crypto.randomBytes(32).toString('hex');
}
createSampleConfig() {
const sampleConfig = JSON.parse(JSON.stringify(DEFAULT_CONFIG));
// Add some sample custom IP ranges
sampleConfig.customIps.enabled = true;
sampleConfig.customIps.ranges = [
{
range: '192.168.1.0/24',
description: 'Sample local network',
enabled: true
},
{
range: '10.0.0.0/8',
description: 'Sample private network',
enabled: false
}
];
// Enable some advanced features for demo
sampleConfig.advanced.enableDebugging = true;
sampleConfig.testing.logLevel = 'debug';
return sampleConfig;
}
toString() {
return JSON.stringify(this.config, null, 2);
}
}
// CLI interface for configuration management
class ConfigCLI {
constructor() {
this.configManager = new ConfigManager();
}
async runCommand(command, args = {}) {
try {
switch (command) {
case 'show':
return this.showConfig();
case 'get':
return this.getValue(args.path);
case 'set':
return this.setValue(args.path, args.value);
case 'validate':
return this.validateConfig();
case 'reset':
return this.resetConfig();
case 'create-sample':
return this.createSampleConfig();
case 'add-ip':
return this.addCustomIp(args.range, args.description);
case 'remove-ip':
return this.removeCustomIp(args.range);
case 'list-ips':
return this.listCustomIps();
default:
throw new Error(`Unknown command: ${command}`);
}
} catch (error) {
throw new Error(`Configuration error: ${error.message}`);
}
}
showConfig() {
return this.configManager.toString();
}
getValue(path) {
const value = this.configManager.get(path);
return value !== undefined ? JSON.stringify(value, null, 2) : 'undefined';
}
setValue(path, value) {
// Try to parse as JSON first, otherwise treat as string
let parsedValue;
try {
parsedValue = JSON.parse(value);
} catch {
parsedValue = value;
}
this.configManager.set(path, parsedValue);
this.configManager.saveConfig();
return `Value set successfully: ${path} = ${JSON.stringify(parsedValue)}`;
}
validateConfig() {
const { errors, warnings } = this.configManager.validateConfig();
let result = '';
if (errors.length > 0) {
result += '❌ Errors:\n';
errors.forEach(error => {
result += ` - ${error}\n`;
});
}
if (warnings.length > 0) {
result += '⚠️ Warnings:\n';
warnings.forEach(warning => {
result += ` - ${warning}\n`;
});
}
if (errors.length === 0 && warnings.length === 0) {
result = '✅ Configuration is valid!';
}
return result;
}
resetConfig() {
this.configManager.resetToDefaults();
this.configManager.saveConfig();
return 'Configuration reset to defaults successfully';
}
createSampleConfig() {
const sampleConfig = this.configManager.createSampleConfig();
const samplePath = 'irancheck.config.sample.json';
fs.writeFileSync(samplePath, JSON.stringify(sampleConfig, null, 2));
return `Sample configuration created at: ${samplePath}`;
}
addCustomIp(range, description = '') {
this.configManager.addCustomIpRange(range, description);
this.configManager.saveConfig();
return `Custom IP range added: ${range}`;
}
removeCustomIp(range) {
this.configManager.removeCustomIpRange(range);
this.configManager.saveConfig();
return `Custom IP range removed: ${range}`;
}
listCustomIps() {
const ranges = this.configManager.getCustomIpRanges();
if (ranges.length === 0) {
return 'No custom IP ranges configured';
}
let result = 'Custom IP ranges:\n';
ranges.forEach(range => {
result += ` ${range.range} - ${range.description} ${range.enabled ? '(enabled)' : '(disabled)'}\n`;
});
return result;
}
}
module.exports = {
ConfigManager,
ConfigCLI,
DEFAULT_CONFIG
};