@feardread/fear 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/FEAR.js +459 -0
  2. package/FEARServer.js +280 -0
  3. package/controllers/agent.js +438 -0
  4. package/controllers/auth/index.js +345 -0
  5. package/controllers/auth/token.js +50 -0
  6. package/controllers/blog.js +105 -0
  7. package/controllers/brand.js +10 -0
  8. package/controllers/cart.js +425 -0
  9. package/controllers/category.js +9 -0
  10. package/controllers/coupon.js +63 -0
  11. package/controllers/crud/crud.js +508 -0
  12. package/controllers/crud/index.js +36 -0
  13. package/controllers/email.js +34 -0
  14. package/controllers/enquiry.js +65 -0
  15. package/controllers/events.js +9 -0
  16. package/controllers/order.js +125 -0
  17. package/controllers/payment.js +31 -0
  18. package/controllers/product.js +147 -0
  19. package/controllers/review.js +247 -0
  20. package/controllers/tag.js +10 -0
  21. package/controllers/task.js +10 -0
  22. package/controllers/upload.js +41 -0
  23. package/controllers/user.js +401 -0
  24. package/index.js +7 -0
  25. package/libs/agent/index.js +561 -0
  26. package/libs/agent/modules/ai/ai.js +285 -0
  27. package/libs/agent/modules/ai/chat.js +518 -0
  28. package/libs/agent/modules/ai/config.js +688 -0
  29. package/libs/agent/modules/ai/operations.js +787 -0
  30. package/libs/agent/modules/analyze/api.js +546 -0
  31. package/libs/agent/modules/analyze/dorks.js +395 -0
  32. package/libs/agent/modules/ccard/README.md +454 -0
  33. package/libs/agent/modules/ccard/audit.js +479 -0
  34. package/libs/agent/modules/ccard/checker.js +674 -0
  35. package/libs/agent/modules/ccard/payment-processors.json +16 -0
  36. package/libs/agent/modules/ccard/validator.js +629 -0
  37. package/libs/agent/modules/code/analyzer.js +303 -0
  38. package/libs/agent/modules/code/jquery.js +1093 -0
  39. package/libs/agent/modules/code/react.js +1536 -0
  40. package/libs/agent/modules/code/refactor.js +499 -0
  41. package/libs/agent/modules/crypto/exchange.js +564 -0
  42. package/libs/agent/modules/net/proxy.js +409 -0
  43. package/libs/agent/modules/security/cve.js +442 -0
  44. package/libs/agent/modules/security/monitor.js +360 -0
  45. package/libs/agent/modules/security/scanner.js +300 -0
  46. package/libs/agent/modules/security/vulnerability.js +506 -0
  47. package/libs/agent/modules/security/web.js +465 -0
  48. package/libs/agent/modules/utils/browser.js +492 -0
  49. package/libs/agent/modules/utils/colorizer.js +285 -0
  50. package/libs/agent/modules/utils/manager.js +478 -0
  51. package/libs/cloud/index.js +228 -0
  52. package/libs/config/db.js +21 -0
  53. package/libs/config/validator.js +82 -0
  54. package/libs/db/index.js +318 -0
  55. package/libs/emailer/imap.js +126 -0
  56. package/libs/emailer/info.js +41 -0
  57. package/libs/emailer/smtp.js +77 -0
  58. package/libs/handler/async.js +3 -0
  59. package/libs/handler/error.js +66 -0
  60. package/libs/handler/index.js +161 -0
  61. package/libs/logger/index.js +49 -0
  62. package/libs/logger/morgan.js +24 -0
  63. package/libs/passport/passport.js +109 -0
  64. package/libs/search/api.js +384 -0
  65. package/libs/search/features.js +219 -0
  66. package/libs/search/service.js +64 -0
  67. package/libs/swagger/config.js +18 -0
  68. package/libs/swagger/index.js +35 -0
  69. package/libs/validator/index.js +254 -0
  70. package/models/blog.js +31 -0
  71. package/models/brand.js +12 -0
  72. package/models/cart.js +14 -0
  73. package/models/category.js +11 -0
  74. package/models/coupon.js +9 -0
  75. package/models/customer.js +0 -0
  76. package/models/enquiry.js +29 -0
  77. package/models/events.js +13 -0
  78. package/models/order.js +94 -0
  79. package/models/product.js +32 -0
  80. package/models/review.js +14 -0
  81. package/models/tag.js +10 -0
  82. package/models/task.js +11 -0
  83. package/models/user.js +68 -0
  84. package/package.json +12 -0
  85. package/routes/agent.js +615 -0
  86. package/routes/auth.js +13 -0
  87. package/routes/blog.js +19 -0
  88. package/routes/brand.js +15 -0
  89. package/routes/cart.js +105 -0
  90. package/routes/category.js +16 -0
  91. package/routes/coupon.js +15 -0
  92. package/routes/enquiry.js +14 -0
  93. package/routes/events.js +16 -0
  94. package/routes/mail.js +170 -0
  95. package/routes/order.js +19 -0
  96. package/routes/product.js +22 -0
  97. package/routes/review.js +11 -0
  98. package/routes/task.js +12 -0
  99. package/routes/user.js +17 -0
@@ -0,0 +1,787 @@
1
+ // modules/ai/operations.js - Enhanced AI Operations & Security Analysis
2
+ const fs = require('fs').promises;
3
+ const path = require('path');
4
+ const colorizer = require('../utils/colorizer');
5
+ const readline = require('readline');
6
+
7
+ const AIOperations = function (config) {
8
+ this.config = config;
9
+ this.conversationHistory = [];
10
+ this.maxHistoryLength = 20;
11
+
12
+ this.systemPrompt = `You are an advanced AI assistant specializing in:
13
+ - Security analysis and vulnerability assessment
14
+ - Cybersecurity best practices and threat modeling
15
+ - Node.js development and architecture
16
+ - Code review and optimization
17
+ - Web application security (OWASP Top 10)
18
+ - Penetration testing concepts and methodologies
19
+
20
+ Your communication style:
21
+ - Clear, concise, and actionable responses
22
+ - Technical depth appropriate to the question
23
+ - Security-focused perspective
24
+ - Practical examples and code snippets when helpful
25
+ - Emphasis on ethical practices and responsible disclosure
26
+
27
+ Always provide comprehensive, accurate, and helpful information.`;
28
+ };
29
+
30
+ AIOperations.prototype = {
31
+
32
+ analyzeCode(args) {
33
+ if (!this.config.isConfigured()) {
34
+ console.log(colorizer.error('AI not configured. Use "ai-setup <provider> <key>" first.\n'));
35
+ return Promise.resolve();
36
+ }
37
+
38
+ const filePath = args[0];
39
+ if (!filePath) {
40
+ console.log(colorizer.error('Usage: ai-analyze <file-path>'));
41
+ console.log(colorizer.info('Example: ai-analyze ./src/auth.js\n'));
42
+ return Promise.resolve();
43
+ }
44
+
45
+ return fs.readFile(filePath, 'utf8')
46
+ .then(code => {
47
+ console.log(colorizer.header('AI Security Analysis'));
48
+ console.log(colorizer.separator());
49
+ console.log(colorizer.cyan('File: ') + colorizer.bright(filePath));
50
+ console.log(colorizer.cyan('Provider: ') + colorizer.bright(this.config.getProviderName()));
51
+ console.log(colorizer.cyan('Model: ') + colorizer.dim(this.config.getModel()));
52
+ console.log(colorizer.cyan('Analyzing...\n'));
53
+
54
+ const prompt = `You are a senior security engineer conducting a comprehensive code security audit.
55
+
56
+ File: ${filePath}
57
+
58
+ \`\`\`
59
+ ${code}
60
+ \`\`\`
61
+
62
+ Provide a detailed security analysis with:
63
+
64
+ 1. **CRITICAL VULNERABILITIES** - Immediate security risks
65
+ 2. **HIGH PRIORITY ISSUES** - Serious concerns requiring attention
66
+ 3. **MEDIUM PRIORITY ISSUES** - Important best practice violations
67
+ 4. **LOW PRIORITY ISSUES** - Minor improvements
68
+
69
+ For each issue include:
70
+ - Severity level and CWE reference if applicable
71
+ - Specific line numbers or code sections
72
+ - Clear explanation of the vulnerability
73
+ - Concrete code examples showing the fix
74
+ - Potential impact if exploited
75
+
76
+ 5. **SECURITY RECOMMENDATIONS**
77
+ - General security improvements
78
+ - Best practices to implement
79
+ - Tools or libraries to consider
80
+
81
+ Be thorough, specific, and actionable. Focus on real security concerns.`;
82
+
83
+ return this.config.call(prompt, 6000);
84
+ })
85
+ .then(response => {
86
+ console.log(response);
87
+ console.log('\n' + colorizer.separator());
88
+ console.log(colorizer.info('💡 Tip: Use "ai-chat" to ask follow-up questions\n'));
89
+ })
90
+ .catch(err => {
91
+ console.log(colorizer.error('AI analysis failed: ' + err.message + '\n'));
92
+ });
93
+ },
94
+
95
+ threatAssessment(args) {
96
+ if (!this.config.isConfigured()) {
97
+ console.log(colorizer.error('AI not configured. Use "ai-setup <provider> <key>" first.\n'));
98
+ return Promise.resolve();
99
+ }
100
+
101
+ const description = args.join(' ');
102
+ if (!description) {
103
+ console.log(colorizer.error('Usage: ai-threat <threat description>'));
104
+ console.log(colorizer.info('Examples:'));
105
+ console.log(colorizer.dim(' ai-threat SQL injection in user login form'));
106
+ console.log(colorizer.dim(' ai-threat XSS vulnerability in comment section\n'));
107
+ return Promise.resolve();
108
+ }
109
+
110
+ console.log(colorizer.header('AI Threat Assessment'));
111
+ console.log(colorizer.separator());
112
+ console.log(colorizer.cyan('Query: ') + colorizer.bright(description));
113
+ console.log(colorizer.cyan('Provider: ') + colorizer.bright(this.config.getProviderName()));
114
+ console.log(colorizer.cyan('Analyzing threat...\n'));
115
+
116
+ const prompt = `You are a cybersecurity expert conducting a threat assessment.
117
+
118
+ Threat/Vulnerability: "${description}"
119
+
120
+ Provide a comprehensive analysis:
121
+
122
+ 1. **THREAT OVERVIEW**
123
+ - What is this vulnerability/threat?
124
+ - Technical explanation of the attack mechanism
125
+
126
+ 2. **SEVERITY ASSESSMENT**
127
+ - Severity Level: CRITICAL/HIGH/MEDIUM/LOW
128
+ - CVSS Score (if applicable)
129
+ - Justification for severity rating
130
+
131
+ 3. **ATTACK VECTORS**
132
+ - How can this be exploited?
133
+ - Prerequisites for exploitation
134
+ - Common attack scenarios
135
+
136
+ 4. **POTENTIAL IMPACT**
137
+ - Confidentiality impact
138
+ - Integrity impact
139
+ - Availability impact
140
+ - Business consequences
141
+
142
+ 5. **MITIGATION STRATEGIES**
143
+ - Immediate countermeasures
144
+ - Long-term preventive measures
145
+ - Code examples of secure implementation
146
+
147
+ 6. **DETECTION & MONITORING**
148
+ - How to identify if you're vulnerable
149
+ - Indicators of compromise (IOCs)
150
+ - Monitoring strategies
151
+
152
+ 7. **REAL-WORLD CONTEXT**
153
+ - Known exploits or CVEs
154
+ - Recent incidents if relevant
155
+ - Industry best practices
156
+
157
+ Be practical, specific, and security-focused.`;
158
+
159
+ return this.config.call(prompt, 5000)
160
+ .then(response => {
161
+ console.log(response);
162
+ console.log('\n' + colorizer.separator() + '\n');
163
+ })
164
+ .catch(err => {
165
+ console.log(colorizer.error('Threat assessment failed: ' + err.message + '\n'));
166
+ });
167
+ },
168
+
169
+ explainVulnerability(args) {
170
+ if (!this.config.isConfigured()) {
171
+ console.log(colorizer.error('AI not configured. Use "ai-setup <provider> <key>" first.\n'));
172
+ return Promise.resolve();
173
+ }
174
+
175
+ const vulnerability = args.join(' ');
176
+ if (!vulnerability) {
177
+ console.log(colorizer.error('Usage: ai-explain <vulnerability or CWE>'));
178
+ console.log(colorizer.info('Examples:'));
179
+ console.log(colorizer.dim(' ai-explain CWE-79'));
180
+ console.log(colorizer.dim(' ai-explain XSS vulnerability'));
181
+ console.log(colorizer.dim(' ai-explain buffer overflow\n'));
182
+ return Promise.resolve();
183
+ }
184
+
185
+ console.log(colorizer.header('AI Vulnerability Explanation'));
186
+ console.log(colorizer.separator());
187
+ console.log(colorizer.cyan('Topic: ') + colorizer.bright(vulnerability));
188
+ console.log(colorizer.cyan('Provider: ') + colorizer.bright(this.config.getProviderName()));
189
+ console.log(colorizer.cyan('Generating explanation...\n'));
190
+
191
+ const prompt = `Provide a comprehensive educational explanation of this security concept:
192
+
193
+ Topic: "${vulnerability}"
194
+
195
+ Structure your response:
196
+
197
+ 1. **DEFINITION**
198
+ - What is it in simple terms?
199
+ - Technical definition
200
+
201
+ 2. **HOW IT WORKS**
202
+ - Technical mechanism explained step-by-step
203
+ - Attack flow or exploitation process
204
+
205
+ 3. **WHY IT'S DANGEROUS**
206
+ - Potential consequences and impact
207
+ - Real-world risk scenarios
208
+
209
+ 4. **COMMON SCENARIOS**
210
+ - Where this vulnerability typically appears
211
+ - Programming languages/frameworks most affected
212
+ - Common coding mistakes that cause it
213
+
214
+ 5. **PREVENTION**
215
+ - Best practices to avoid it
216
+ - Secure coding guidelines
217
+ - Security controls and defenses
218
+
219
+ 6. **CODE EXAMPLES**
220
+ - Vulnerable code example
221
+ - Secure/fixed code example
222
+ - Explanation of the differences
223
+
224
+ 7. **DETECTION**
225
+ - How to identify this vulnerability
226
+ - Tools that can detect it
227
+ - Testing approaches
228
+
229
+ Keep it educational, clear, and practical.`;
230
+
231
+ return this.config.call(prompt, 5000)
232
+ .then(response => {
233
+ console.log(response);
234
+ console.log('\n' + colorizer.separator() + '\n');
235
+ })
236
+ .catch(err => {
237
+ console.log(colorizer.error('Explanation failed: ' + err.message + '\n'));
238
+ });
239
+ },
240
+
241
+ generateNodeCode(args) {
242
+ if (!this.config.isConfigured()) {
243
+ console.log(colorizer.error('AI not configured. Use "ai-setup <provider> <key>" first.\n'));
244
+ return Promise.resolve();
245
+ }
246
+
247
+ const taskDescription = args.join(' ');
248
+ if (!taskDescription) {
249
+ console.log(colorizer.error('Usage: ai-generate <task description>'));
250
+ console.log(colorizer.info('Examples:'));
251
+ console.log(colorizer.dim(' ai-generate Express API with JWT authentication'));
252
+ console.log(colorizer.dim(' ai-generate Rate limiter middleware for Express\n'));
253
+ return Promise.resolve();
254
+ }
255
+
256
+ console.log(colorizer.header('AI Code Generation'));
257
+ console.log(colorizer.separator());
258
+ console.log(colorizer.cyan('Task: ') + colorizer.bright(taskDescription));
259
+ console.log(colorizer.cyan('Provider: ') + colorizer.bright(this.config.getProviderName()));
260
+ console.log(colorizer.cyan('Generating code...\n'));
261
+
262
+ const prompt = `You are an expert Node.js developer. Generate production-ready, secure Node.js code.
263
+
264
+ Task: ${taskDescription}
265
+
266
+ Requirements:
267
+ 1. Include all necessary imports and dependencies
268
+ 2. Implement comprehensive error handling
269
+ 3. Follow Node.js and JavaScript best practices
270
+ 4. Add security measures (input validation, sanitization, etc.)
271
+ 5. Include clear comments explaining key sections
272
+ 6. Make code efficient and performant
273
+ 7. Follow OWASP security guidelines
274
+ 8. Include usage examples if applicable
275
+
276
+ Provide complete, working code that can be used immediately. If the code needs a specific npm package, mention it.`;
277
+
278
+ return this.config.call(prompt, 6000)
279
+ .then(response => {
280
+ console.log(response);
281
+ console.log('\n' + colorizer.separator() + '\n');
282
+ })
283
+ .catch(err => {
284
+ console.log(colorizer.error('Code generation failed: ' + err.message + '\n'));
285
+ });
286
+ },
287
+
288
+ analyzeTrafficPattern(trafficData) {
289
+ if (!this.config.isConfigured()) {
290
+ return Promise.resolve(null);
291
+ }
292
+
293
+ const prompt = `Analyze this network traffic pattern for security concerns:
294
+
295
+ ${JSON.stringify(trafficData, null, 2)}
296
+
297
+ Identify:
298
+ 1. **Suspicious Patterns** - Anomalies in the traffic
299
+ 2. **Potential Attacks** - DDoS, port scanning, brute force, etc.
300
+ 3. **Risk Assessment** - Severity and likelihood
301
+ 4. **Recommendations** - Immediate actions to take
302
+
303
+ Be concise and actionable. Focus on security-critical findings.`;
304
+
305
+ return this.config.call(prompt, 3000)
306
+ .catch(err => {
307
+ console.error(colorizer.error('AI traffic analysis failed: ' + err.message));
308
+ return null;
309
+ });
310
+ },
311
+
312
+ compareCodeVersions(args) {
313
+ if (!this.config.isConfigured()) {
314
+ console.log(colorizer.error('AI not configured. Use "ai-setup <provider> <key>" first.\n'));
315
+ return Promise.resolve();
316
+ }
317
+
318
+ const file1Path = args[0];
319
+ const file2Path = args[1];
320
+
321
+ if (!file1Path || !file2Path) {
322
+ console.log(colorizer.error('Usage: ai-compare <original-file> <modified-file>'));
323
+ console.log(colorizer.info('Example: ai-compare ./old/auth.js ./new/auth.js\n'));
324
+ return Promise.resolve();
325
+ }
326
+
327
+ return Promise.all([
328
+ fs.readFile(file1Path, 'utf8'),
329
+ fs.readFile(file2Path, 'utf8')
330
+ ])
331
+ .then(([code1, code2]) => {
332
+ console.log(colorizer.header('AI Code Security Comparison'));
333
+ console.log(colorizer.separator());
334
+ console.log(colorizer.cyan('Original: ') + colorizer.bright(file1Path));
335
+ console.log(colorizer.cyan('Modified: ') + colorizer.bright(file2Path));
336
+ console.log(colorizer.cyan('Provider: ') + colorizer.bright(this.config.getProviderName()));
337
+ console.log(colorizer.cyan('Analyzing security implications...\n'));
338
+
339
+ const prompt = `Compare these two code versions from a security perspective:
340
+
341
+ **Original Version** (${file1Path}):
342
+ \`\`\`
343
+ ${code1}
344
+ \`\`\`
345
+
346
+ **Modified Version** (${file2Path}):
347
+ \`\`\`
348
+ ${code2}
349
+ \`\`\`
350
+
351
+ Provide a detailed security comparison:
352
+
353
+ 1. **NEW VULNERABILITIES INTRODUCED**
354
+ - Security issues that didn't exist in original
355
+ - Severity and impact of each
356
+ - Specific code changes that introduced them
357
+
358
+ 2. **SECURITY IMPROVEMENTS MADE**
359
+ - Vulnerabilities fixed or mitigated
360
+ - Better security practices implemented
361
+ - Defense mechanisms added
362
+
363
+ 3. **SECURITY REGRESSIONS**
364
+ - Previously secure code made less secure
365
+ - Removed security controls
366
+ - Weakened defenses
367
+
368
+ 4. **FUNCTIONALITY VS SECURITY TRADEOFFS**
369
+ - New features that affect security posture
370
+ - Performance changes with security implications
371
+
372
+ 5. **OVERALL SECURITY IMPACT**
373
+ - Net security improvement or degradation
374
+ - Risk assessment: Better/Worse/Neutral
375
+ - Recommendations for next steps
376
+
377
+ Focus only on security-relevant changes. Be specific and actionable.`;
378
+
379
+ return this.config.call(prompt, 5000);
380
+ })
381
+ .then(response => {
382
+ console.log(response);
383
+ console.log('\n' + colorizer.separator() + '\n');
384
+ })
385
+ .catch(err => {
386
+ console.log(colorizer.error('Comparison failed: ' + err.message + '\n'));
387
+ });
388
+ },
389
+
390
+ suggestImprovements(args) {
391
+ if (!this.config.isConfigured()) {
392
+ console.log(colorizer.error('AI not configured. Use "ai-setup <provider> <key>" first.\n'));
393
+ return Promise.resolve();
394
+ }
395
+
396
+ const projectPath = args[0] || '.';
397
+ const pkgPath = path.join(projectPath, 'package.json');
398
+
399
+ return fs.readFile(pkgPath, 'utf8')
400
+ .catch(() => '')
401
+ .then(pkg => {
402
+ const projectInfo = pkg ? `Package.json:\n\`\`\`json\n${pkg}\n\`\`\`\n` : 'No package.json found.\n';
403
+
404
+ console.log(colorizer.header('AI Security Recommendations'));
405
+ console.log(colorizer.separator());
406
+ console.log(colorizer.cyan('Project: ') + colorizer.bright(projectPath));
407
+ console.log(colorizer.cyan('Provider: ') + colorizer.bright(this.config.getProviderName()));
408
+ console.log(colorizer.cyan('Generating improvement plan...\n'));
409
+
410
+ const prompt = `As a senior security consultant, provide a comprehensive security improvement plan for this Node.js project:
411
+
412
+ ${projectInfo}
413
+
414
+ Provide actionable recommendations:
415
+
416
+ 1. **QUICK WINS** (Implement Today)
417
+ - Easy security improvements with high impact
418
+ - Configuration changes
419
+ - Simple code updates
420
+
421
+ 2. **CRITICAL PRIORITIES** (This Week)
422
+ - Must-fix security issues
423
+ - High-risk vulnerabilities
424
+ - Essential security controls
425
+
426
+ 3. **DEPENDENCY SECURITY**
427
+ - Vulnerable packages to update
428
+ - Unnecessary dependencies to remove
429
+ - Suggested secure alternatives
430
+
431
+ 4. **SECURITY BEST PRACTICES** (This Month)
432
+ - Security measures to implement
433
+ - Code patterns to adopt
434
+ - Architecture improvements
435
+
436
+ 5. **TOOLS & INTEGRATION** (Ongoing)
437
+ - Security scanning tools (SAST, DAST, SCA)
438
+ - Monitoring and logging solutions
439
+ - CI/CD security pipeline additions
440
+
441
+ 6. **DEVELOPMENT WORKFLOW**
442
+ - Security review processes
443
+ - Secure coding guidelines
444
+ - Training and awareness
445
+
446
+ 7. **LONG-TERM STRATEGY** (Quarterly)
447
+ - Security architecture evolution
448
+ - Compliance considerations (OWASP, SOC 2, etc.)
449
+ - Incident response planning
450
+
451
+ Be practical, prioritized, and specific. Include concrete examples where applicable.`;
452
+
453
+ return this.config.call(prompt, 5000);
454
+ })
455
+ .then(response => {
456
+ console.log(response);
457
+ console.log('\n' + colorizer.separator() + '\n');
458
+ })
459
+ .catch(err => {
460
+ console.log(colorizer.error('Recommendations failed: ' + err.message + '\n'));
461
+ });
462
+ },
463
+
464
+ chat(args) {
465
+ if (!this.config.isConfigured()) {
466
+ console.log(colorizer.error('AI not configured. Use "ai-setup <provider> <key>" first.\n'));
467
+ return Promise.resolve();
468
+ }
469
+
470
+ const query = args.join(' ');
471
+
472
+ // If no query provided, enter interactive mode
473
+ if (!query) {
474
+ return this.startInteractiveChat();
475
+ }
476
+
477
+ // Single query mode
478
+ console.log(colorizer.header('AI Assistant'));
479
+ console.log(colorizer.separator());
480
+ console.log(colorizer.cyan('Query: ') + colorizer.bright(query));
481
+ console.log(colorizer.cyan('Provider: ') + colorizer.bright(this.config.getProviderName()));
482
+ console.log(colorizer.cyan('Thinking...\n'));
483
+
484
+ const prompt = this.buildPromptWithHistory(query);
485
+
486
+ return this.config.call(prompt, 4096)
487
+ .then(response => {
488
+ // Add to conversation history
489
+ this.addToHistory('user', query);
490
+ this.addToHistory('assistant', response);
491
+
492
+ console.log(response);
493
+ console.log('\n' + colorizer.separator());
494
+ console.log(colorizer.info('💡 Tip: Run "ai-chat" without arguments for interactive mode\n'));
495
+ })
496
+ .catch(err => {
497
+ console.log(colorizer.error('Chat failed: ' + err.message + '\n'));
498
+ });
499
+ },
500
+
501
+ startInteractiveChat() {
502
+ console.log(colorizer.header('AI Interactive Chat'));
503
+ console.log(colorizer.separator());
504
+ console.log(colorizer.cyan('Provider: ') + colorizer.bright(this.config.getProviderName()));
505
+ console.log(colorizer.cyan('Model: ') + colorizer.dim(this.config.getModel()));
506
+ console.log();
507
+ console.log(colorizer.info('Commands:'));
508
+ console.log(colorizer.dim(' /exit or /quit - Exit chat'));
509
+ console.log(colorizer.dim(' /clear - Clear conversation history'));
510
+ console.log(colorizer.dim(' /history - Show conversation history'));
511
+ console.log(colorizer.dim(' /save <filename> - Save conversation to file'));
512
+ console.log(colorizer.dim(' /stream - Toggle streaming mode (Google Gemini only)'));
513
+ console.log();
514
+ console.log(colorizer.success('Chat started! Ask me anything...\n'));
515
+
516
+ const rl = readline.createInterface({
517
+ input: process.stdin,
518
+ output: process.stdout,
519
+ prompt: colorizer.cyan('You: ')
520
+ });
521
+
522
+ let streamMode = false;
523
+
524
+ const handleInput = (input) => {
525
+ const trimmedInput = input.trim();
526
+
527
+ // Handle empty input
528
+ if (!trimmedInput) {
529
+ rl.prompt();
530
+ return;
531
+ }
532
+
533
+ // Handle commands
534
+ if (trimmedInput.startsWith('/')) {
535
+ return this.handleChatCommand(trimmedInput, rl, () => handleInput, streamMode)
536
+ .then(result => {
537
+ if (result && result.exit) {
538
+ rl.close();
539
+ return;
540
+ }
541
+ if (result && result.streamMode !== undefined) {
542
+ streamMode = result.streamMode;
543
+ }
544
+ rl.prompt();
545
+ });
546
+ }
547
+
548
+ // Add user message to history
549
+ this.addToHistory('user', trimmedInput);
550
+
551
+ // Build prompt with context
552
+ const prompt = this.buildPromptWithHistory(trimmedInput);
553
+
554
+ console.log(colorizer.dim('\nAI: '));
555
+
556
+ // Use streaming if enabled and provider supports it
557
+ if (streamMode && this.config.provider === 'google') {
558
+ let response = '';
559
+ this.config.callStream(prompt, 4096, (chunk) => {
560
+ process.stdout.write(chunk);
561
+ response += chunk;
562
+ })
563
+ .then(() => {
564
+ console.log('\n');
565
+ this.addToHistory('assistant', response);
566
+ rl.prompt();
567
+ })
568
+ .catch(err => {
569
+ console.log(colorizer.error('\n\nError: ' + err.message + '\n'));
570
+ rl.prompt();
571
+ });
572
+ } else {
573
+ // Regular non-streaming response
574
+ this.config.call(prompt, 4096)
575
+ .then(response => {
576
+ console.log(response + '\n');
577
+ this.addToHistory('assistant', response);
578
+ rl.prompt();
579
+ })
580
+ .catch(err => {
581
+ console.log(colorizer.error('\nError: ' + err.message + '\n'));
582
+ rl.prompt();
583
+ });
584
+ }
585
+ };
586
+
587
+ rl.prompt();
588
+ rl.on('line', handleInput);
589
+
590
+ return new Promise((resolve) => {
591
+ rl.on('close', () => {
592
+ console.log(colorizer.info('\nChat ended. Goodbye!\n'));
593
+ resolve();
594
+ });
595
+ });
596
+ },
597
+
598
+ handleChatCommand(command, rl, handleInput, streamMode) {
599
+ const parts = command.split(' ');
600
+ const cmd = parts[0].toLowerCase();
601
+
602
+ switch (cmd) {
603
+ case '/exit':
604
+ case '/quit':
605
+ return Promise.resolve({ exit: true });
606
+
607
+ case '/clear':
608
+ this.conversationHistory = [];
609
+ console.log(colorizer.success('Conversation history cleared.\n'));
610
+ return Promise.resolve();
611
+
612
+ case '/history':
613
+ return this.showHistory();
614
+
615
+ case '/save':
616
+ const filename = parts[1] || `chat_${Date.now()}.txt`;
617
+ return this.saveConversation(filename);
618
+
619
+ case '/stream':
620
+ if (this.config.provider === 'google') {
621
+ streamMode = !streamMode;
622
+ console.log(colorizer.success(`Streaming mode ${streamMode ? 'enabled' : 'disabled'}.\n`));
623
+ return Promise.resolve({ streamMode });
624
+ } else {
625
+ console.log(colorizer.warning('Streaming only available with Google Gemini.\n'));
626
+ return Promise.resolve();
627
+ }
628
+
629
+ case '/help':
630
+ console.log(colorizer.info('Available commands:'));
631
+ console.log(colorizer.dim(' /exit, /quit - Exit chat'));
632
+ console.log(colorizer.dim(' /clear - Clear conversation history'));
633
+ console.log(colorizer.dim(' /history - Show conversation history'));
634
+ console.log(colorizer.dim(' /save <filename> - Save conversation'));
635
+ console.log(colorizer.dim(' /stream - Toggle streaming (Gemini only)'));
636
+ console.log(colorizer.dim(' /help - Show this help\n'));
637
+ return Promise.resolve();
638
+
639
+ default:
640
+ console.log(colorizer.warning('Unknown command. Type /help for available commands.\n'));
641
+ return Promise.resolve();
642
+ }
643
+ },
644
+
645
+ buildPromptWithHistory(currentQuery) {
646
+ let prompt = this.systemPrompt + '\n\n';
647
+
648
+ // Add conversation history if available
649
+ if (this.conversationHistory.length > 0) {
650
+ prompt += 'Previous conversation:\n';
651
+ this.conversationHistory.forEach(msg => {
652
+ prompt += `${msg.role === 'user' ? 'User' : 'Assistant'}: ${msg.content}\n`;
653
+ });
654
+ prompt += '\n';
655
+ }
656
+
657
+ prompt += `Current user question: ${currentQuery}\n\n`;
658
+ prompt += 'Provide a comprehensive, helpful response that addresses the user\'s question with practical, actionable information. If this is a follow-up question, consider the previous conversation context.';
659
+
660
+ return prompt;
661
+ },
662
+
663
+ addToHistory(role, content) {
664
+ this.conversationHistory.push({ role, content, timestamp: Date.now() });
665
+
666
+ // Trim history if it gets too long
667
+ if (this.conversationHistory.length > this.maxHistoryLength) {
668
+ this.conversationHistory = this.conversationHistory.slice(-this.maxHistoryLength);
669
+ }
670
+ },
671
+
672
+ showHistory() {
673
+ if (this.conversationHistory.length === 0) {
674
+ console.log(colorizer.info('No conversation history yet.\n'));
675
+ return Promise.resolve();
676
+ }
677
+
678
+ console.log(colorizer.header('Conversation History'));
679
+ console.log(colorizer.separator());
680
+
681
+ this.conversationHistory.forEach((msg, index) => {
682
+ const role = msg.role === 'user' ? colorizer.cyan('You') : colorizer.green('AI');
683
+ const preview = msg.content.substring(0, 100) + (msg.content.length > 100 ? '...' : '');
684
+ console.log(`${index + 1}. ${role}: ${preview}`);
685
+ });
686
+
687
+ console.log();
688
+ return Promise.resolve();
689
+ },
690
+
691
+ saveConversation(filename) {
692
+ if (this.conversationHistory.length === 0) {
693
+ console.log(colorizer.warning('No conversation to save.\n'));
694
+ return Promise.resolve();
695
+ }
696
+
697
+ let content = '# AI Chat Conversation\n\n';
698
+ content += `Date: ${new Date().toISOString()}\n`;
699
+ content += `Provider: ${this.config.getProviderName()}\n`;
700
+ content += `Model: ${this.config.getModel()}\n\n`;
701
+ content += '---\n\n';
702
+
703
+ this.conversationHistory.forEach((msg, index) => {
704
+ content += `## ${msg.role === 'user' ? 'User' : 'AI Assistant'} (Message ${index + 1})\n\n`;
705
+ content += msg.content + '\n\n';
706
+ content += '---\n\n';
707
+ });
708
+
709
+ return fs.writeFile(filename, content)
710
+ .then(() => {
711
+ console.log(colorizer.success(`Conversation saved to ${filename}\n`));
712
+ })
713
+ .catch(err => {
714
+ console.log(colorizer.error(`Failed to save conversation: ${err.message}\n`));
715
+ });
716
+ },
717
+
718
+ clearHistory() {
719
+ this.conversationHistory = [];
720
+ },
721
+
722
+ // Batch analyze multiple files
723
+ analyzeBatch(args) {
724
+ if (!this.config.isConfigured()) {
725
+ console.log(colorizer.error('AI not configured. Use "ai-setup <provider> <key>" first.\n'));
726
+ return Promise.resolve();
727
+ }
728
+
729
+ const directory = args[0] || '.';
730
+ const extension = args[1] || '.js';
731
+
732
+ console.log(colorizer.header('AI Batch Security Analysis'));
733
+ console.log(colorizer.separator());
734
+ console.log(colorizer.cyan('Directory: ') + colorizer.bright(directory));
735
+ console.log(colorizer.cyan('Extension: ') + colorizer.bright(extension));
736
+ console.log(colorizer.cyan('Scanning for files...\n'));
737
+
738
+ return this.findFiles(directory, extension)
739
+ .then(files => {
740
+ if (files.length === 0) {
741
+ console.log(colorizer.warning('No files found.\n'));
742
+ return;
743
+ }
744
+
745
+ console.log(colorizer.info(`Found ${files.length} file(s)\n`));
746
+
747
+ // Analyze each file
748
+ return files.reduce((promise, file) => {
749
+ return promise.then(() => {
750
+ console.log(colorizer.cyan('\nAnalyzing: ') + file);
751
+ return this.analyzeCode([file])
752
+ .catch(err => {
753
+ console.log(colorizer.warning(`Skipped ${file}: ${err.message}`));
754
+ });
755
+ });
756
+ }, Promise.resolve());
757
+ })
758
+ .then(() => {
759
+ console.log(colorizer.success('\nBatch analysis complete!\n'));
760
+ })
761
+ .catch(err => {
762
+ console.log(colorizer.error('Batch analysis failed: ' + err.message + '\n'));
763
+ });
764
+ },
765
+
766
+ findFiles(dir, extension) {
767
+ return fs.readdir(dir, { withFileTypes: true })
768
+ .then(items => {
769
+ const promises = items.map(item => {
770
+ const fullPath = path.join(dir, item.name);
771
+
772
+ if (item.isDirectory() && !['node_modules', '.git', 'dist'].includes(item.name)) {
773
+ return this.findFiles(fullPath, extension);
774
+ } else if (item.isFile() && fullPath.endsWith(extension)) {
775
+ return [fullPath];
776
+ }
777
+ return [];
778
+ });
779
+
780
+ return Promise.all(promises);
781
+ })
782
+ .then(results => results.flat())
783
+ .catch(() => []);
784
+ }
785
+ };
786
+
787
+ module.exports = AIOperations;