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
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
|
/**
* Main Application Entry Point
*
* This is the main entry point for the CLI application.
* It integrates all the deobfuscated components and provides
* the primary interface for the shell command processing system.
*/
const { ShellParser } = require("./core/shell-parser");
const { HttpClient } = require("./network/http-client");
const { performanceMonitor } = require("./instrumentation/performance-monitor");
const { moduleLoader } = require("./module-system/module-loader");
const { getGlobalObject } = require("./platform/global-object");
const { detectRuntime } = require("./platform/environment-detection");
const { TimingUtils } = require("./platform/compatibility");
const { generateUuid4 } = require("./utils/uuid");
const pathUtils = require("./utils/path-utils");
const stringUtils = require("./utils/string-utils");
/**
* Main CLI Application class
*/
class CLIApplication {
constructor(options = {}) {
this.options = {
debug: options.debug || false,
timeout: options.timeout || 30000,
maxConcurrency: options.maxConcurrency || 10,
...options,
};
this.shellParser = new ShellParser();
this.httpClient = new HttpClient();
this.timingUtils = new TimingUtils();
this.activeCommands = new Map();
this.commandHistory = [];
this.environment = detectRuntime();
this.init();
}
/**
* Initialize the application
*/
init() {
this.setupGlobalErrorHandlers();
this.setupPerformanceMonitoring();
this.logStartupInfo();
}
/**
* Setup global error handlers
*/
setupGlobalErrorHandlers() {
const global = getGlobalObject();
if (typeof global.addEventListener === "function") {
global.addEventListener("error", (event) => {
this.handleError(event.error, "global-error");
});
global.addEventListener("unhandledrejection", (event) => {
this.handleError(event.reason, "unhandled-rejection");
});
}
}
/**
* Setup performance monitoring
*/
setupPerformanceMonitoring() {
if (this.options.debug) {
performanceMonitor.startTiming("application-lifecycle");
}
}
/**
* Log startup information
*/
logStartupInfo() {
if (this.options.debug) {
console.log("CLI Application Starting...");
console.log("Runtime:", this.environment.name, this.environment.version);
console.log("Platform:", this.environment.platform);
console.log("Features:", this.environment.features);
}
}
/**
* Execute a shell command
* @param {string} command - Command to execute
* @param {Object} context - Execution context
* @returns {Promise<Object>} Execution result
*/
async executeCommand(command, context = {}) {
const commandId = generateUuid4();
const timerId = performanceMonitor.startTiming(`command-${commandId}`);
try {
// Parse the command
const parsed = this.shellParser.parseShellCommand(command, context.env);
// Validate command
if (!parsed.command) {
throw new Error("Invalid command: empty or malformed");
}
// Track active command
this.activeCommands.set(commandId, {
command: parsed.command,
args: parsed.args,
startTime: Date.now(),
timerId,
});
// Execute based on command type
let result;
if (this.isBuiltinCommand(parsed.command)) {
result = await this.executeBuiltinCommand(parsed, context);
} else {
result = await this.executeExternalCommand(parsed, context);
}
// Add to history
this.addToHistory(command, result);
return result;
} catch (error) {
this.handleError(error, "command-execution", { command, commandId });
throw error;
} finally {
// Cleanup
this.activeCommands.delete(commandId);
performanceMonitor.endTiming(timerId);
}
}
/**
* Check if command is a builtin
* @param {string} command - Command name
* @returns {boolean} True if builtin
*/
isBuiltinCommand(command) {
const builtins = [
"cd",
"pwd",
"echo",
"export",
"set",
"unset",
"alias",
"unalias",
"history",
"jobs",
"help",
"version",
"exit",
"quit",
];
return builtins.includes(command);
}
/**
* Execute builtin command
* @param {Object} parsed - Parsed command
* @param {Object} context - Execution context
* @returns {Promise<Object>} Result
*/
async executeBuiltinCommand(parsed, context) {
const { command, args } = parsed;
switch (command) {
case "echo":
return this.executeEcho(args);
case "pwd":
return this.executePwd();
case "cd":
return this.executeCd(args[0]);
case "export":
return this.executeExport(args, context);
case "set":
return this.executeSet(args, context);
case "history":
return this.executeHistory(args);
case "help":
return this.executeHelp(args);
case "version":
return this.executeVersion();
case "exit":
case "quit":
return this.executeExit(args);
default:
throw new Error(`Unknown builtin command: ${command}`);
}
}
/**
* Execute external command
* @param {Object} parsed - Parsed command
* @param {Object} context - Execution context
* @returns {Promise<Object>} Result
*/
async executeExternalCommand(parsed, context) {
// In a real implementation, this would spawn a child process
// For this deobfuscated version, we'll simulate command execution
const { command, args } = parsed;
// Simulate some common commands
if (command === "ls" || command === "dir") {
return this.simulateListDirectory(args);
} else if (command === "cat" || command === "type") {
return this.simulateReadFile(args);
} else if (command === "curl" || command === "wget") {
return this.simulateHttpRequest(args);
}
// Default simulation
return {
exitCode: 0,
stdout: `Simulated execution of: ${command} ${args.join(" ")}`,
stderr: "",
duration: Math.random() * 1000 + 100,
};
}
/**
* Execute echo command
* @param {Array<string>} args - Command arguments
* @returns {Object} Result
*/
executeEcho(args) {
const output = args.join(" ");
return {
exitCode: 0,
stdout: output,
stderr: "",
};
}
/**
* Execute pwd command
* @returns {Object} Result
*/
executePwd() {
const cwd = process.cwd ? process.cwd() : "/";
return {
exitCode: 0,
stdout: cwd,
stderr: "",
};
}
/**
* Execute cd command
* @param {string} path - Target path
* @returns {Object} Result
*/
executeCd(path) {
if (!path) path = "~";
try {
const resolvedPath = pathUtils.resolve(path);
// In a real implementation, this would change the working directory
return {
exitCode: 0,
stdout: "",
stderr: "",
cwd: resolvedPath,
};
} catch (error) {
return {
exitCode: 1,
stdout: "",
stderr: `cd: ${error.message}`,
};
}
}
/**
* Execute export command
* @param {Array<string>} args - Command arguments
* @param {Object} context - Execution context
* @returns {Object} Result
*/
executeExport(args, context) {
if (args.length === 0) {
// Show all exported variables
const vars = Object.entries(context.env || {})
.map(([key, value]) => `${key}=${value}`)
.join("\n");
return {
exitCode: 0,
stdout: vars,
stderr: "",
};
}
// Set environment variables
for (const arg of args) {
const [key, value] = arg.split("=", 2);
if (key && value !== undefined) {
context.env = context.env || {};
context.env[key] = value;
}
}
return {
exitCode: 0,
stdout: "",
stderr: "",
};
}
/**
* Execute set command
* @param {Array<string>} args - Command arguments
* @param {Object} context - Execution context
* @returns {Object} Result
*/
executeSet(args, context) {
// Similar to export but for shell variables
return this.executeExport(args, context);
}
/**
* Execute history command
* @param {Array<string>} args - Command arguments
* @returns {Object} Result
*/
executeHistory(args) {
const count = args[0] ? parseInt(args[0], 10) : this.commandHistory.length;
const history = this.commandHistory
.slice(-count)
.map((entry, index) => `${index + 1} ${entry.command}`)
.join("\n");
return {
exitCode: 0,
stdout: history,
stderr: "",
};
}
/**
* Execute help command
* @param {Array<string>} args - Command arguments
* @returns {Object} Result
*/
executeHelp(args) {
const helpText = `
CLI Application Help
Builtin Commands:
cd [path] Change directory
pwd Print working directory
echo [args] Print arguments
export [var] Set environment variable
set [var] Set shell variable
history [n] Show command history
help [cmd] Show help information
version Show version information
exit/quit Exit the application
External Commands:
Commands are executed in the system shell when not builtin.
Examples:
cd /home/user
echo "Hello World"
export PATH=/usr/bin:$PATH
ls -la
curl https://example.com
`.trim();
return {
exitCode: 0,
stdout: helpText,
stderr: "",
};
}
/**
* Execute version command
* @returns {Object} Result
*/
executeVersion() {
const version = `CLI Application v1.0.0
Runtime: ${this.environment.name} ${this.environment.version}
Platform: ${this.environment.platform}
Node.js: ${process.version || "N/A"}`;
return {
exitCode: 0,
stdout: version,
stderr: "",
};
}
/**
* Execute exit command
* @param {Array<string>} args - Command arguments
* @returns {Object} Result
*/
executeExit(args) {
const exitCode = args[0] ? parseInt(args[0], 10) : 0;
// Cleanup
this.cleanup();
return {
exitCode,
stdout: "Goodbye!",
stderr: "",
shouldExit: true,
};
}
/**
* Simulate directory listing
* @param {Array<string>} args - Command arguments
* @returns {Object} Result
*/
simulateListDirectory(args) {
const files = [
"file1.txt",
"file2.js",
"directory1/",
"README.md",
".hidden",
];
return {
exitCode: 0,
stdout: files.join("\n"),
stderr: "",
};
}
/**
* Simulate file reading
* @param {Array<string>} args - Command arguments
* @returns {Object} Result
*/
simulateReadFile(args) {
if (args.length === 0) {
return {
exitCode: 1,
stdout: "",
stderr: "cat: missing file operand",
};
}
const filename = args[0];
return {
exitCode: 0,
stdout: `Contents of ${filename}:\nThis is simulated file content.`,
stderr: "",
};
}
/**
* Simulate HTTP request
* @param {Array<string>} args - Command arguments
* @returns {Promise<Object>} Result
*/
async simulateHttpRequest(args) {
if (args.length === 0) {
return {
exitCode: 1,
stdout: "",
stderr: "curl: missing URL",
};
}
const url = args[0];
try {
const response = await this.httpClient.get(url);
return {
exitCode: 0,
stdout: JSON.stringify(response.data, null, 2),
stderr: "",
};
} catch (error) {
return {
exitCode: 1,
stdout: "",
stderr: `curl: ${error.message}`,
};
}
}
/**
* Add command to history
* @param {string} command - Command string
* @param {Object} result - Execution result
*/
addToHistory(command, result) {
this.commandHistory.push({
command,
timestamp: Date.now(),
exitCode: result.exitCode,
duration: result.duration,
});
// Keep history limited
if (this.commandHistory.length > 1000) {
this.commandHistory = this.commandHistory.slice(-500);
}
}
/**
* Handle errors
* @param {Error} error - Error object
* @param {string} context - Error context
* @param {Object} metadata - Additional metadata
*/
handleError(error, context, metadata = {}) {
const errorInfo = {
message: error.message,
stack: error.stack,
context,
timestamp: Date.now(),
...metadata,
};
if (this.options.debug) {
console.error("CLI Error:", errorInfo);
}
// In a real implementation, this might send to a logging service
}
/**
* Get application statistics
* @returns {Object} Statistics
*/
getStats() {
return {
commandsExecuted: this.commandHistory.length,
activeCommands: this.activeCommands.size,
uptime: Date.now() - (this.startTime || Date.now()),
environment: this.environment,
memoryUsage: this.getMemoryUsage(),
};
}
/**
* Get memory usage
* @returns {Object} Memory usage info
*/
getMemoryUsage() {
if (typeof process !== "undefined" && process.memoryUsage) {
return process.memoryUsage();
}
if (typeof performance !== "undefined" && performance.memory) {
return {
rss: performance.memory.usedJSHeapSize,
heapTotal: performance.memory.totalJSHeapSize,
heapUsed: performance.memory.usedJSHeapSize,
external: 0,
};
}
return null;
}
/**
* Cleanup resources
*/
cleanup() {
if (this.options.debug) {
const duration = performanceMonitor.endTiming("application-lifecycle");
console.log(`Application ran for ${duration}ms`);
}
// Clear active commands
this.activeCommands.clear();
// Cleanup performance monitoring
performanceMonitor.clearAllMeasurements();
}
}
/**
* Create and run CLI application
* @param {Object} options - Application options
* @returns {CLIApplication} Application instance
*/
function createCLI(options = {}) {
return new CLIApplication(options);
}
/**
* Main entry point when run directly
*/
function main() {
const app = createCLI({ debug: true });
// Example usage
if (
typeof process !== "undefined" &&
process.argv &&
process.argv.length > 2
) {
const command = process.argv.slice(2).join(" ");
app
.executeCommand(command)
.then((result) => {
console.log(result.stdout);
if (result.stderr) console.error(result.stderr);
if (result.shouldExit) process.exit(result.exitCode);
})
.catch((error) => {
console.error("Command failed:", error.message);
process.exit(1);
});
} else {
console.log(
"CLI Application initialized. Use createCLI() to create an instance.",
);
}
}
module.exports = {
CLIApplication,
createCLI,
main,
};
// Run main if this is the entry point
if (typeof require !== "undefined" && require.main === module) {
main();
}
|