deployready 0.1.0

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 (115) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +136 -0
  3. package/bin/deployready.js +21 -0
  4. package/dist/agent/FileEditor.js +120 -0
  5. package/dist/agent/FileEditor.js.map +1 -0
  6. package/dist/agent/FixManager.js +47 -0
  7. package/dist/agent/FixManager.js.map +1 -0
  8. package/dist/agent/SessionManager.js +16 -0
  9. package/dist/agent/SessionManager.js.map +1 -0
  10. package/dist/agent/SystemPrompt.js +10 -0
  11. package/dist/agent/SystemPrompt.js.map +1 -0
  12. package/dist/agent/ToolDispatcher.js +14 -0
  13. package/dist/agent/ToolDispatcher.js.map +1 -0
  14. package/dist/ai/ClaudeHandler.js +73 -0
  15. package/dist/ai/ClaudeHandler.js.map +1 -0
  16. package/dist/ai/ContextChunker.js +29 -0
  17. package/dist/ai/ContextChunker.js.map +1 -0
  18. package/dist/ai/ModelRouter.js +86 -0
  19. package/dist/ai/ModelRouter.js.map +1 -0
  20. package/dist/ai/OllamaHandler.js +57 -0
  21. package/dist/ai/OllamaHandler.js.map +1 -0
  22. package/dist/ai/OpenAIHandler.js +51 -0
  23. package/dist/ai/OpenAIHandler.js.map +1 -0
  24. package/dist/ai/PromptBuilder.js +90 -0
  25. package/dist/ai/PromptBuilder.js.map +1 -0
  26. package/dist/ai/parseAiResponse.js +68 -0
  27. package/dist/ai/parseAiResponse.js.map +1 -0
  28. package/dist/ai/parseFix.js +29 -0
  29. package/dist/ai/parseFix.js.map +1 -0
  30. package/dist/analysis/IssueAggregator.js +37 -0
  31. package/dist/analysis/IssueAggregator.js.map +1 -0
  32. package/dist/analysis/ScoreCalculator.js +25 -0
  33. package/dist/analysis/ScoreCalculator.js.map +1 -0
  34. package/dist/analysis/SeverityScorer.js +17 -0
  35. package/dist/analysis/SeverityScorer.js.map +1 -0
  36. package/dist/analysis/VulnerabilityDetector.js +156 -0
  37. package/dist/analysis/VulnerabilityDetector.js.map +1 -0
  38. package/dist/analysis/rules.js +241 -0
  39. package/dist/analysis/rules.js.map +1 -0
  40. package/dist/cli/Commands.js +125 -0
  41. package/dist/cli/Commands.js.map +1 -0
  42. package/dist/cli/InteractiveShell.js +733 -0
  43. package/dist/cli/InteractiveShell.js.map +1 -0
  44. package/dist/cli/Onboarding.js +88 -0
  45. package/dist/cli/Onboarding.js.map +1 -0
  46. package/dist/config/ConfigManager.js +133 -0
  47. package/dist/config/ConfigManager.js.map +1 -0
  48. package/dist/core/CiGate.js +55 -0
  49. package/dist/core/CiGate.js.map +1 -0
  50. package/dist/core/Orchestrator.js +204 -0
  51. package/dist/core/Orchestrator.js.map +1 -0
  52. package/dist/core/Verifier.js +75 -0
  53. package/dist/core/Verifier.js.map +1 -0
  54. package/dist/dynamic/APIAnalyzer.js +66 -0
  55. package/dist/dynamic/APIAnalyzer.js.map +1 -0
  56. package/dist/dynamic/DynamicTester.js +36 -0
  57. package/dist/dynamic/DynamicTester.js.map +1 -0
  58. package/dist/dynamic/EndpointMapper.js +40 -0
  59. package/dist/dynamic/EndpointMapper.js.map +1 -0
  60. package/dist/dynamic/LocalhostDetector.js +95 -0
  61. package/dist/dynamic/LocalhostDetector.js.map +1 -0
  62. package/dist/dynamic/PerformanceTester.js +60 -0
  63. package/dist/dynamic/PerformanceTester.js.map +1 -0
  64. package/dist/dynamic/SecurityTester.js +165 -0
  65. package/dist/dynamic/SecurityTester.js.map +1 -0
  66. package/dist/dynamic/httpClient.js +45 -0
  67. package/dist/dynamic/httpClient.js.map +1 -0
  68. package/dist/index.js +45 -0
  69. package/dist/index.js.map +1 -0
  70. package/dist/parser/CodeParser.js +198 -0
  71. package/dist/parser/CodeParser.js.map +1 -0
  72. package/dist/parser/DependencyGraph.js +85 -0
  73. package/dist/parser/DependencyGraph.js.map +1 -0
  74. package/dist/parser/EntryPointDetector.js +77 -0
  75. package/dist/parser/EntryPointDetector.js.map +1 -0
  76. package/dist/parser/StackDetector.js +111 -0
  77. package/dist/parser/StackDetector.js.map +1 -0
  78. package/dist/parser/adapters/BabelAdapter.js +170 -0
  79. package/dist/parser/adapters/BabelAdapter.js.map +1 -0
  80. package/dist/parser/adapters/ParserAdapter.js +8 -0
  81. package/dist/parser/adapters/ParserAdapter.js.map +1 -0
  82. package/dist/parser/adapters/PythonAdapter.js +97 -0
  83. package/dist/parser/adapters/PythonAdapter.js.map +1 -0
  84. package/dist/tracker/ChecklistManager.js +40 -0
  85. package/dist/tracker/ChecklistManager.js.map +1 -0
  86. package/dist/tracker/ScoreTracker.js +15 -0
  87. package/dist/tracker/ScoreTracker.js.map +1 -0
  88. package/dist/tracker/StateManager.js +66 -0
  89. package/dist/tracker/StateManager.js.map +1 -0
  90. package/dist/types.js +7 -0
  91. package/dist/types.js.map +1 -0
  92. package/dist/ui/Banner.js +111 -0
  93. package/dist/ui/Banner.js.map +1 -0
  94. package/dist/ui/DeploymentGuide.js +42 -0
  95. package/dist/ui/DeploymentGuide.js.map +1 -0
  96. package/dist/ui/ExportManager.js +103 -0
  97. package/dist/ui/ExportManager.js.map +1 -0
  98. package/dist/ui/FixWalker.js +15 -0
  99. package/dist/ui/FixWalker.js.map +1 -0
  100. package/dist/ui/HtmlReporter.js +140 -0
  101. package/dist/ui/HtmlReporter.js.map +1 -0
  102. package/dist/ui/IssuePresenter.js +73 -0
  103. package/dist/ui/IssuePresenter.js.map +1 -0
  104. package/dist/utils/FileWalker.js +141 -0
  105. package/dist/utils/FileWalker.js.map +1 -0
  106. package/dist/utils/finding.js +47 -0
  107. package/dist/utils/finding.js.map +1 -0
  108. package/dist/utils/logger.js +47 -0
  109. package/dist/utils/logger.js.map +1 -0
  110. package/dist/utils/openBrowser.js +29 -0
  111. package/dist/utils/openBrowser.js.map +1 -0
  112. package/dist/utils/redact.js +83 -0
  113. package/dist/utils/redact.js.map +1 -0
  114. package/docs/sample-config.json +9 -0
  115. package/package.json +61 -0
@@ -0,0 +1,733 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ var __importDefault = (this && this.__importDefault) || function (mod) {
36
+ return (mod && mod.__esModule) ? mod : { "default": mod };
37
+ };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.InteractiveShell = void 0;
40
+ /**
41
+ * Interactive terminal session for DeployReady. Stays open and accepts one
42
+ * command per step (scan, parse, dynamic, ai, issues, fix, ...) until the user
43
+ * exits. Holds the scan state in memory and updates the score live as issues
44
+ * are fixed or ignored.
45
+ *
46
+ * All "ask before acting" gates live here: live probing, external AI sends, and
47
+ * writing any fix to disk all require an explicit confirmation.
48
+ */
49
+ const path = __importStar(require("path"));
50
+ const readline = __importStar(require("readline"));
51
+ const chalk_1 = __importDefault(require("chalk"));
52
+ const ora_1 = __importDefault(require("ora"));
53
+ const CodeParser_1 = require("../parser/CodeParser");
54
+ const VulnerabilityDetector_1 = require("../analysis/VulnerabilityDetector");
55
+ const IssueAggregator_1 = require("../analysis/IssueAggregator");
56
+ const LocalhostDetector_1 = require("../dynamic/LocalhostDetector");
57
+ const DynamicTester_1 = require("../dynamic/DynamicTester");
58
+ const ModelRouter_1 = require("../ai/ModelRouter");
59
+ const Verifier_1 = require("../core/Verifier");
60
+ const ConfigManager_1 = require("../config/ConfigManager");
61
+ const ExportManager_1 = require("../ui/ExportManager");
62
+ const Banner_1 = require("../ui/Banner");
63
+ const DeploymentGuide_1 = require("../ui/DeploymentGuide");
64
+ const ScoreTracker_1 = require("../tracker/ScoreTracker");
65
+ const ChecklistManager_1 = require("../tracker/ChecklistManager");
66
+ const FileEditor_1 = require("../agent/FileEditor");
67
+ const FixManager_1 = require("../agent/FixManager");
68
+ const openBrowser_1 = require("../utils/openBrowser");
69
+ const logger_1 = require("../utils/logger");
70
+ const VERSION = '0.1.0';
71
+ class InteractiveShell {
72
+ state;
73
+ config;
74
+ checklist = null;
75
+ ordered = [];
76
+ running = true;
77
+ rl;
78
+ // Buffered async line reader: lines are queued so none are dropped while a
79
+ // command is running, and the same primitive serves nested prompts (confirm).
80
+ lineBuffer = [];
81
+ lineWaiters = [];
82
+ closed = false;
83
+ muted = false;
84
+ out;
85
+ constructor(target, io) {
86
+ this.state = { target: path.resolve(target), graph: null, staticFindings: [], dynamic: null, aiFindings: [] };
87
+ this.out = io?.output ?? process.stdout;
88
+ this.rl = readline.createInterface({
89
+ input: io?.input ?? process.stdin,
90
+ output: this.out,
91
+ });
92
+ // Suppress echo while reading secrets (askHidden sets `muted`).
93
+ const rlAny = this.rl;
94
+ rlAny._writeToOutput = (s) => {
95
+ if (!this.muted)
96
+ this.out.write(s);
97
+ };
98
+ this.rl.on('line', (line) => {
99
+ const waiter = this.lineWaiters.shift();
100
+ if (waiter)
101
+ waiter(line);
102
+ else
103
+ this.lineBuffer.push(line);
104
+ });
105
+ // EOF (piped input ends) or Ctrl+C. Don't stop the loop here — let any
106
+ // buffered commands drain first; ask() returns null once they're consumed.
107
+ this.rl.on('close', () => {
108
+ this.closed = true;
109
+ while (this.lineWaiters.length)
110
+ this.lineWaiters.shift()(null);
111
+ });
112
+ }
113
+ async start() {
114
+ this.config = await ConfigManager_1.ConfigManager.load();
115
+ await Banner_1.Banner.play(VERSION);
116
+ await this.intro();
117
+ await this.menu(); // guided first action — no command knowledge required
118
+ while (this.running) {
119
+ const line = await this.ask(chalk_1.default.cyan('deployready › '));
120
+ if (line === null)
121
+ break; // stream closed
122
+ const trimmed = line.trim();
123
+ if (!trimmed)
124
+ continue;
125
+ const [cmd, ...args] = trimmed.split(/\s+/);
126
+ try {
127
+ await this.dispatch(cmd.toLowerCase(), args);
128
+ }
129
+ catch (err) {
130
+ logger_1.logger.error(err.message || 'Command failed.');
131
+ }
132
+ }
133
+ this.rl.close();
134
+ console.log(chalk_1.default.gray('\nBye — stay deploy ready. 👋\n'));
135
+ }
136
+ /** Write a prompt and read the next buffered line. Resolves null when closed. */
137
+ ask(prompt) {
138
+ this.out.write(prompt);
139
+ if (this.lineBuffer.length)
140
+ return Promise.resolve(this.lineBuffer.shift());
141
+ if (this.closed)
142
+ return Promise.resolve(null);
143
+ return new Promise((resolve) => this.lineWaiters.push(resolve));
144
+ }
145
+ /** Read a line without echoing it (for API keys). */
146
+ async askHidden(prompt) {
147
+ this.out.write(prompt);
148
+ this.muted = true;
149
+ const v = await this.ask('');
150
+ this.muted = false;
151
+ this.out.write('\n');
152
+ return v ?? '';
153
+ }
154
+ async dispatch(cmd, args) {
155
+ switch (cmd) {
156
+ case 'help':
157
+ case '?': return this.help();
158
+ case 'menu':
159
+ case 'm': return this.menu();
160
+ case 'scan': return this.scan();
161
+ case 'parse': return this.parse();
162
+ case 'dynamic':
163
+ case 'live': return this.dynamic();
164
+ case 'ai':
165
+ case 'analyze': return this.ai();
166
+ case 'issues':
167
+ case 'list':
168
+ case 'ls': return this.issues(args[0]);
169
+ case 'show': return this.show(args[0]);
170
+ case 'fix': return this.fix(args[0]);
171
+ case 'verify':
172
+ case 'v': return this.verify(args[0]);
173
+ case 'done':
174
+ case 'resolve': return this.mark(args[0], 'fixed');
175
+ case 'ignore': return this.mark(args[0], 'ignored');
176
+ case 'score': return this.printScore();
177
+ case 'status': return this.status();
178
+ case 'deploy': return this.deploy(args[0]);
179
+ case 'export': return this.export(args[0]);
180
+ case 'open': return this.open();
181
+ case 'config': return this.showConfig();
182
+ case 'clear':
183
+ case 'cls':
184
+ console.clear();
185
+ return;
186
+ case 'exit':
187
+ case 'quit':
188
+ case 'q':
189
+ this.running = false;
190
+ return;
191
+ default:
192
+ logger_1.logger.warn(`Unknown command "${cmd}". Type "help" for the list.`);
193
+ }
194
+ }
195
+ // ---------------------------------------------------------------- steps
196
+ async parse() {
197
+ const spinner = (0, ora_1.default)('Parsing codebase + static scan…').start();
198
+ this.state.graph = await CodeParser_1.CodeParser.analyze(this.state.target);
199
+ this.state.staticFindings = await VulnerabilityDetector_1.VulnerabilityDetector.scan(this.state.target);
200
+ this.recompute();
201
+ spinner.succeed(`Parsed ${this.state.graph.fileCount} files, ${this.state.graph.routes.length} routes — ${this.state.staticFindings.length} static findings.`);
202
+ this.printScore();
203
+ }
204
+ async dynamic() {
205
+ const detect = (0, ora_1.default)('Looking for a running app on localhost…').start();
206
+ const app = await LocalhostDetector_1.LocalhostDetector.find(this.config.defaultPorts);
207
+ if (!app) {
208
+ detect.info('No running app found on common ports. Start your app, then run `dynamic` again.');
209
+ return;
210
+ }
211
+ detect.succeed(`Found a running app at ${app.baseUrl}.`);
212
+ if (!(await this.confirm(`Run live security/performance tests against ${app.baseUrl}? (GET only)`, true))) {
213
+ logger_1.logger.info('Skipped live tests.');
214
+ return;
215
+ }
216
+ const aggressive = await this.confirm('Also run aggressive tests (small burst to probe rate limiting)?', false);
217
+ const spinner = (0, ora_1.default)('Running live tests…').start();
218
+ const routes = this.state.graph?.routes ?? [];
219
+ this.state.dynamic = await DynamicTester_1.DynamicTester.run(app.baseUrl, routes, { aggressive });
220
+ this.recompute();
221
+ spinner.succeed(`Live tests done — ${this.state.dynamic.findings.length} runtime findings.`);
222
+ this.printScore();
223
+ }
224
+ async ai() {
225
+ if (!this.hasFindings())
226
+ return logger_1.logger.warn('Nothing to analyze yet. Run `parse` or `scan` first.');
227
+ const router = new ModelRouter_1.ModelRouter(this.config);
228
+ if (!router.isConfigured()) {
229
+ return logger_1.logger.warn('No AI model configured. Run `deployready init` (or set an API key) first.');
230
+ }
231
+ if (router.sendsExternally && this.config.warnBeforeExternalSend) {
232
+ logger_1.logger.warn(`This sends a STRUCTURED findings report (no source code, secrets redacted) to the ${this.config.model} API.`);
233
+ if (!(await this.confirm('Continue with AI analysis?', true)))
234
+ return logger_1.logger.info('Skipped AI analysis.');
235
+ }
236
+ const spinner = (0, ora_1.default)(`Analyzing with ${this.config.model}…`).start();
237
+ try {
238
+ const analysis = await router.analyze(this.buildReport());
239
+ this.state.aiFindings = analysis.findings;
240
+ this.state.aiSummary = analysis.summary || undefined;
241
+ this.recompute();
242
+ spinner.succeed('AI analysis complete.');
243
+ if (this.state.aiSummary)
244
+ console.log('\n' + chalk_1.default.cyan('🤖 ') + this.state.aiSummary + '\n');
245
+ this.printScore();
246
+ }
247
+ catch (err) {
248
+ spinner.fail(`AI analysis failed: ${err.message}`);
249
+ }
250
+ }
251
+ async scan() {
252
+ await this.parse();
253
+ await this.dynamic();
254
+ if (new ModelRouter_1.ModelRouter(this.config).isConfigured() && (await this.confirm('Run AI analysis on the findings?', false))) {
255
+ await this.ai();
256
+ }
257
+ this.issues();
258
+ }
259
+ // ---------------------------------------------------------------- views
260
+ issues(filter) {
261
+ if (!this.hasFindings())
262
+ return logger_1.logger.warn('No findings yet. Run `scan` or `parse`.');
263
+ const sev = this.parseSeverity(filter);
264
+ let shown = 0;
265
+ this.ordered.forEach((f, i) => {
266
+ if (sev && f.severity !== sev)
267
+ return;
268
+ console.log(` ${chalk_1.default.gray(String(i + 1).padStart(2))}. ${this.statusMark(f)} ${this.sevBadge(f.severity)} ${f.title}${this.locText(f)}`);
269
+ shown++;
270
+ });
271
+ if (!shown)
272
+ logger_1.logger.info('No findings match that filter.');
273
+ else
274
+ console.log('');
275
+ this.printScore();
276
+ }
277
+ show(arg) {
278
+ const f = this.findingAt(arg);
279
+ if (!f)
280
+ return;
281
+ const refs = [f.owasp, f.cwe].filter(Boolean).join(' ');
282
+ console.log('\n' + chalk_1.default.bold(f.title));
283
+ console.log(` ${this.sevBadge(f.severity)} ${chalk_1.default.gray(`[${f.source}]`)} ${chalk_1.default.gray(refs)}`);
284
+ if (f.file || f.endpoint)
285
+ console.log(` ${chalk_1.default.gray('where:')} ${f.endpoint ?? `${f.file}:${f.line ?? '?'}`}`);
286
+ if (f.evidence)
287
+ console.log(` ${chalk_1.default.gray('evidence:')} ${f.evidence}`);
288
+ console.log(` ${chalk_1.default.gray('what:')} ${f.description}`);
289
+ console.log(` ${chalk_1.default.gray('fix:')} ${f.recommendation}\n`);
290
+ }
291
+ status() {
292
+ console.log('');
293
+ console.log(` target: ${this.state.target}`);
294
+ console.log(` parsed: ${this.state.graph ? `yes (${this.state.graph.stack.stack})` : chalk_1.default.gray('no')}`);
295
+ console.log(` dynamic: ${this.state.dynamic ? `yes (${this.state.dynamic.baseUrl})` : chalk_1.default.gray('no')}`);
296
+ console.log(` ai: ${this.state.aiFindings.length ? 'yes' : chalk_1.default.gray('no')}`);
297
+ console.log(` model: ${this.config.model}`);
298
+ console.log('');
299
+ this.printScore();
300
+ }
301
+ // ---------------------------------------------------------------- fix flow
302
+ async fix(arg) {
303
+ const f = this.findingAt(arg);
304
+ if (!f)
305
+ return;
306
+ this.show(arg);
307
+ const editor = new FileEditor_1.FileEditor(this.state.target);
308
+ // 1. Safe deterministic auto-fix.
309
+ if (FixManager_1.FixManager.autoFixable(f)) {
310
+ if (await this.confirm('Apply the automatic fix for this issue?', true)) {
311
+ const res = await FixManager_1.FixManager.autoFix(f, editor);
312
+ logger_1.logger.success(res.message);
313
+ if (res.backup)
314
+ logger_1.logger.info(`Backup: ${res.backup}`);
315
+ await this.verifyAndMark(f, true);
316
+ }
317
+ return;
318
+ }
319
+ // 2. AI-proposed fix (needs file+line and a configured model).
320
+ const router = new ModelRouter_1.ModelRouter(this.config);
321
+ if (FixManager_1.FixManager.aiFixable(f) && router.isConfigured()) {
322
+ if (!(await this.confirm('Ask the AI model to propose a code fix for this snippet?', true))) {
323
+ return this.offerManualMark(f);
324
+ }
325
+ if (router.sendsExternally) {
326
+ logger_1.logger.warn('To fix code, the relevant snippet (secrets redacted) is sent to the AI model.');
327
+ if (!(await this.confirm('Send the snippet and get a proposed fix?', true)))
328
+ return this.offerManualMark(f);
329
+ }
330
+ await this.aiFixFlow(f, editor, router);
331
+ return;
332
+ }
333
+ // 3. No automated path — show guidance and let the user mark it.
334
+ logger_1.logger.info('No automated fix available for this issue. Apply the recommendation above manually.');
335
+ await this.offerManualMark(f);
336
+ }
337
+ async aiFixFlow(f, editor, router) {
338
+ const spinner = (0, ora_1.default)('Asking the model for a fix…').start();
339
+ let snippet, suggestion;
340
+ try {
341
+ snippet = await FixManager_1.FixManager.snippetFor(f, editor);
342
+ suggestion = await FixManager_1.FixManager.aiSuggest(f, snippet, router);
343
+ spinner.succeed('Proposed fix:');
344
+ }
345
+ catch (err) {
346
+ spinner.fail(`Could not get a fix: ${err.message}`);
347
+ return this.offerManualMark(f);
348
+ }
349
+ this.printDiff(f.file, snippet.startLine, snippet.endLine, snippet.text, suggestion.newCode);
350
+ if (suggestion.explanation)
351
+ console.log(chalk_1.default.gray(` why: ${suggestion.explanation}\n`));
352
+ if (await this.confirm('Apply this fix to the file? (a backup is created first)', false)) {
353
+ const backup = await FixManager_1.FixManager.applySuggestion(f, snippet, suggestion.newCode, editor);
354
+ logger_1.logger.success(`Applied. Backup saved to ${backup}`);
355
+ await this.verifyAndMark(f, true);
356
+ }
357
+ else {
358
+ logger_1.logger.info('Fix not applied.');
359
+ }
360
+ }
361
+ /**
362
+ * Re-run the check for a finding. `appliedChange` = we just edited something,
363
+ * so an "unknown" result is treated as fixed-but-unverified; a standalone
364
+ * `verify` leaves an unknown/failed finding open.
365
+ */
366
+ async verifyAndMark(f, appliedChange) {
367
+ const spinner = (0, ora_1.default)('Verifying the fix…').start();
368
+ const ctx = {
369
+ target: this.state.target,
370
+ dynamic: this.state.dynamic
371
+ ? { baseUrl: this.state.dynamic.baseUrl, routes: this.state.graph?.routes ?? [] }
372
+ : undefined,
373
+ };
374
+ const res = await Verifier_1.Verifier.verify(f, ctx).catch((err) => ({ status: 'unknown', detail: err.message }));
375
+ if (res.status === 'fixed') {
376
+ spinner.succeed('Verified — the issue is gone. ✓');
377
+ this.markFinding(f, 'fixed');
378
+ }
379
+ else if (res.status === 'still-present') {
380
+ spinner.warn(`Not fixed yet — ${(res.detail ?? 'the check still fails').replace(/\.$/, '')}. Leaving it open.`);
381
+ if (appliedChange && f.source === 'dynamic') {
382
+ logger_1.logger.info('Tip: restart your running app so it picks up the code change, then `verify` again.');
383
+ }
384
+ }
385
+ else {
386
+ spinner.info(`Could not auto-verify — ${res.detail ?? 'no check available'}.`);
387
+ if (appliedChange) {
388
+ this.markFinding(f, 'fixed');
389
+ logger_1.logger.info('Marked fixed (change applied, but not automatically verified).');
390
+ }
391
+ }
392
+ this.printScore();
393
+ }
394
+ /** `verify <n>` — re-check a finding on demand without changing files. */
395
+ async verify(arg) {
396
+ const f = this.findingAt(arg);
397
+ if (!f)
398
+ return;
399
+ await this.verifyAndMark(f, false);
400
+ }
401
+ async offerManualMark(f) {
402
+ const ans = (await this.ask('Mark as [o]pen / [f]ixed / [i]gnored (default open): ')) ?? '';
403
+ const a = ans.trim().toLowerCase();
404
+ if (a === 'f' || a === 'fixed') {
405
+ this.markFinding(f, 'fixed');
406
+ this.printScore();
407
+ }
408
+ else if (a === 'i' || a === 'ignored') {
409
+ this.markFinding(f, 'ignored');
410
+ this.printScore();
411
+ }
412
+ }
413
+ printDiff(file, start, end, oldText, newText) {
414
+ console.log(chalk_1.default.gray(` ── ${file}:${start}-${end} ──`));
415
+ for (const l of oldText.split('\n'))
416
+ console.log(chalk_1.default.red(` - ${l}`));
417
+ for (const l of newText.split('\n'))
418
+ console.log(chalk_1.default.green(` + ${l}`));
419
+ console.log('');
420
+ }
421
+ // ---------------------------------------------------------------- marking
422
+ mark(arg, status) {
423
+ const f = this.findingAt(arg);
424
+ if (!f)
425
+ return;
426
+ this.markFinding(f, status);
427
+ logger_1.logger.success(`Marked "${f.title}" as ${status}.`);
428
+ this.printScore();
429
+ }
430
+ markFinding(f, status) {
431
+ this.checklist?.setStatus(f.id, status);
432
+ }
433
+ // ---------------------------------------------------------------- deploy/export/config
434
+ deploy(arg) {
435
+ if (!this.state.graph)
436
+ return logger_1.logger.warn('Run `parse` or `scan` first so I know your stack.');
437
+ const platform = arg === 'do' || arg === 'digitalocean' ? 'digitalocean' : 'aws';
438
+ const steps = DeploymentGuide_1.DeploymentGuide.generate(this.state.graph.stack.stack, platform);
439
+ console.log('\n' + chalk_1.default.bold(`📦 Deployment guide — ${platform.toUpperCase()} (stack: ${this.state.graph.stack.stack})`));
440
+ steps.forEach((s, i) => {
441
+ console.log(` ${i + 1}. ${s.title}`);
442
+ if (s.command)
443
+ console.log(chalk_1.default.gray(` $ ${s.command}`));
444
+ });
445
+ console.log('');
446
+ }
447
+ /** `export [md|html|all]` — defaults to a full report (both formats). */
448
+ async export(fmt) {
449
+ if (!this.hasFindings())
450
+ return logger_1.logger.warn('Nothing to export yet. Run `scan` first.');
451
+ const report = this.buildReport();
452
+ const f = (fmt ?? 'all').toLowerCase();
453
+ if (f === 'md' || f === 'markdown' || f === 'all') {
454
+ logger_1.logger.success(`Markdown report saved to ${await ExportManager_1.ExportManager.saveMarkdown(report, this.state.target)}`);
455
+ }
456
+ if (f === 'html' || f === 'dashboard' || f === 'all') {
457
+ logger_1.logger.success(`HTML dashboard saved to ${await ExportManager_1.ExportManager.saveHtml(report, this.state.target)}`);
458
+ }
459
+ }
460
+ /** `open` — write the HTML dashboard and launch it in the browser. */
461
+ async open() {
462
+ if (!this.hasFindings())
463
+ return logger_1.logger.warn('Nothing to open yet. Run `scan` first.');
464
+ const file = await ExportManager_1.ExportManager.saveHtml(this.buildReport(), this.state.target);
465
+ logger_1.logger.success(`HTML dashboard saved to ${file}`);
466
+ (0, openBrowser_1.openInBrowser)(file);
467
+ logger_1.logger.info('Opening the dashboard in your browser…');
468
+ }
469
+ showConfig() {
470
+ const c = this.config;
471
+ console.log(JSON.stringify({
472
+ model: c.model,
473
+ claudeApiKey: c.claudeApiKey ? '«set»' : null,
474
+ openaiApiKey: c.openaiApiKey ? '«set»' : null,
475
+ ollamaPort: c.ollamaPort,
476
+ ollamaModel: c.ollamaModel,
477
+ warnBeforeExternalSend: c.warnBeforeExternalSend,
478
+ defaultPorts: c.defaultPorts,
479
+ }, null, 2));
480
+ }
481
+ // ---------------------------------------------------------------- helpers
482
+ recompute() {
483
+ const prev = this.checklist?.toState();
484
+ const agg = IssueAggregator_1.IssueAggregator.process(this.state.staticFindings, this.state.dynamic?.findings ?? [], this.state.aiFindings);
485
+ this.ordered = agg.findings;
486
+ this.checklist = new ChecklistManager_1.ChecklistManager(agg.findings);
487
+ if (prev)
488
+ this.checklist.applyState(prev);
489
+ }
490
+ buildReport() {
491
+ const open = this.checklist?.openFindings() ?? this.ordered;
492
+ const agg = IssueAggregator_1.IssueAggregator.process(open);
493
+ const graph = this.state.graph ??
494
+ { root: this.state.target, stack: { stack: 'unknown', language: 'unknown', evidence: [] }, entryPoints: [], modules: [], routes: [], fileCount: 0 };
495
+ const now = new Date().toISOString();
496
+ return {
497
+ target: this.state.target,
498
+ startedAt: now,
499
+ finishedAt: now,
500
+ version: VERSION,
501
+ stack: graph.stack,
502
+ graph,
503
+ dynamic: this.state.dynamic ?? undefined,
504
+ findings: this.ordered,
505
+ score: agg.score,
506
+ summary: agg.summary,
507
+ aiSummary: this.state.aiSummary,
508
+ };
509
+ }
510
+ currentScore() {
511
+ return ScoreTracker_1.ScoreTracker.current(this.checklist?.openFindings() ?? this.ordered);
512
+ }
513
+ printScore() {
514
+ if (!this.hasFindings())
515
+ return;
516
+ const open = this.checklist?.openFindings() ?? this.ordered;
517
+ const crit = open.filter((f) => f.severity === 'critical').length;
518
+ const warn = open.filter((f) => f.severity === 'warning').length;
519
+ const info = open.filter((f) => f.severity === 'info').length;
520
+ const score = this.currentScore();
521
+ const colored = score >= 80 ? chalk_1.default.green : score >= 50 ? chalk_1.default.yellow : chalk_1.default.red;
522
+ console.log(` ${chalk_1.default.bold('Score')} ${colored.bold(`${score}/100`)} ${chalk_1.default.gray('· open:')} ${chalk_1.default.red(crit + ' crit')} ${chalk_1.default.yellow(warn + ' warn')} ${chalk_1.default.blue(info + ' info')}`);
523
+ }
524
+ hasFindings() {
525
+ return this.ordered.length > 0;
526
+ }
527
+ findingAt(arg) {
528
+ const n = Number(arg);
529
+ if (!arg || !Number.isInteger(n) || n < 1 || n > this.ordered.length) {
530
+ logger_1.logger.warn(`Give a finding number from the list (1–${this.ordered.length || 0}). Try "issues".`);
531
+ return null;
532
+ }
533
+ return this.ordered[n - 1];
534
+ }
535
+ parseSeverity(s) {
536
+ if (s === 'critical' || s === 'crit')
537
+ return 'critical';
538
+ if (s === 'warning' || s === 'warn')
539
+ return 'warning';
540
+ if (s === 'info')
541
+ return 'info';
542
+ return null;
543
+ }
544
+ statusMark(f) {
545
+ const st = this.checklist?.list().find((i) => i.finding.id === f.id)?.status ?? 'open';
546
+ if (st === 'fixed')
547
+ return chalk_1.default.green('✓');
548
+ if (st === 'ignored')
549
+ return chalk_1.default.gray('−');
550
+ return chalk_1.default.red('✗');
551
+ }
552
+ sevBadge(s) {
553
+ if (s === 'critical')
554
+ return chalk_1.default.red.bold('CRIT');
555
+ if (s === 'warning')
556
+ return chalk_1.default.yellow.bold('WARN');
557
+ return chalk_1.default.blue.bold('INFO');
558
+ }
559
+ locText(f) {
560
+ const loc = f.endpoint ?? (f.file ? `${f.file}${f.line ? `:${f.line}` : ''}` : '');
561
+ return loc ? chalk_1.default.gray(` — ${loc}`) : '';
562
+ }
563
+ async confirm(message, def) {
564
+ const ans = await this.ask(`${message} ${def ? '(Y/n)' : '(y/N)'} `);
565
+ if (ans === null)
566
+ return def;
567
+ const a = ans.trim().toLowerCase();
568
+ if (a === '')
569
+ return def;
570
+ return a === 'y' || a === 'yes';
571
+ }
572
+ help() {
573
+ const rows = [
574
+ ['menu', 'open the guided menu (great if you are not sure what to do)'],
575
+ ['scan', 'run the full pipeline (parse → live tests → optional AI)'],
576
+ ['parse', 'static parse + vulnerability scan'],
577
+ ['dynamic', 'live tests against your running localhost app'],
578
+ ['ai', 'send the findings report to your AI model for deeper analysis'],
579
+ ['issues [crit|warn|info]', 'list findings (optionally filter by severity)'],
580
+ ['show <n>', 'full detail of finding n'],
581
+ ['fix <n>', 'interactive fix: auto-fix, AI-proposed diff, or guidance (auto-verifies)'],
582
+ ['verify <n>', 're-run the check for a finding to confirm it is resolved'],
583
+ ['done <n> / ignore <n>', 'mark finding fixed / ignored (score updates live)'],
584
+ ['score / status', 'show the current score / session state'],
585
+ ['deploy [aws|do]', 'print a deployment guide for the detected stack'],
586
+ ['export [md|html|all]', 'save the report — markdown, HTML dashboard, or both'],
587
+ ['open', 'save the HTML dashboard and open it in your browser'],
588
+ ['config / clear / help', 'show config / clear screen / this help'],
589
+ ['exit', 'leave the session'],
590
+ ];
591
+ console.log('\n' + chalk_1.default.bold(' Commands'));
592
+ for (const [c, d] of rows)
593
+ console.log(` ${chalk_1.default.cyan(c.padEnd(24))} ${chalk_1.default.gray(d)}`);
594
+ console.log('');
595
+ }
596
+ // ---------------------------------------------------------------- guided onboarding
597
+ /** Friendly, plain-language intro shown after the banner. */
598
+ async intro() {
599
+ console.log(` ${chalk_1.default.bold('Welcome!')} I check your app for security, performance, and architecture issues`);
600
+ console.log(' before you ship it — then help you fix them, one at a time.');
601
+ console.log('');
602
+ console.log(` ${chalk_1.default.gray('Project:')} ${this.state.target}`);
603
+ const configured = await ConfigManager_1.ConfigManager.exists();
604
+ if (!configured && !process.env.ANTHROPIC_API_KEY && !process.env.OPENAI_API_KEY) {
605
+ console.log(` ${chalk_1.default.gray('AI:')} not set up yet ${chalk_1.default.gray('— that\'s fine, the scan works fully offline without it.')}`);
606
+ }
607
+ else {
608
+ console.log(` ${chalk_1.default.gray('AI:')} ${this.config.model} ${chalk_1.default.gray('(used only with your permission, for deeper analysis)')}`);
609
+ }
610
+ console.log('');
611
+ }
612
+ /** Numbered, guided menu so a new user never needs to know command names. */
613
+ async menu() {
614
+ console.log(chalk_1.default.bold(' What would you like to do?'));
615
+ console.log(` ${chalk_1.default.cyan('1')} Scan this project now ${chalk_1.default.gray('(recommended)')}`);
616
+ console.log(` ${chalk_1.default.cyan('2')} Set up or change the AI model`);
617
+ console.log(` ${chalk_1.default.cyan('3')} How does DeployReady work?`);
618
+ console.log(` ${chalk_1.default.cyan('4')} Go to the command prompt`);
619
+ console.log(` ${chalk_1.default.cyan('5')} Exit`);
620
+ console.log('');
621
+ const ans = await this.ask(chalk_1.default.cyan(' Pick 1–5 (or type a command) › '));
622
+ if (ans === null) {
623
+ this.running = false;
624
+ return;
625
+ }
626
+ const choice = ans.trim().toLowerCase();
627
+ switch (choice) {
628
+ case '1':
629
+ case 'scan': return this.guidedScan();
630
+ case '2':
631
+ case 'setup': return this.setupModel();
632
+ case '3':
633
+ case 'how':
634
+ case 'explain':
635
+ this.explain();
636
+ return this.menu();
637
+ case '4':
638
+ case 'prompt':
639
+ case '':
640
+ this.hints();
641
+ return;
642
+ case '5':
643
+ case 'exit':
644
+ case 'quit':
645
+ case 'q':
646
+ this.running = false;
647
+ return;
648
+ default:
649
+ // Power users can type any real command straight from the menu.
650
+ {
651
+ const [cmd, ...args] = choice.split(/\s+/);
652
+ return this.dispatch(cmd, args);
653
+ }
654
+ }
655
+ }
656
+ /** Run a scan with a short explanation of each phase, then suggest next steps. */
657
+ async guidedScan() {
658
+ console.log(chalk_1.default.gray('\n I will: (1) read your code, (2) test your running app if I find one, (3) score it.\n'));
659
+ await this.scan();
660
+ this.hints();
661
+ }
662
+ /** Context-aware next-step suggestions so the user always knows what to type. */
663
+ hints() {
664
+ console.log('');
665
+ if (this.hasFindings()) {
666
+ console.log(chalk_1.default.gray(' Next: ') + chalk_1.default.cyan('fix 1') + chalk_1.default.gray(' to fix the top issue · ') + chalk_1.default.cyan('show 1') + chalk_1.default.gray(' for details · ') + chalk_1.default.cyan('issues') + chalk_1.default.gray(' to list all'));
667
+ console.log(chalk_1.default.gray(' ') + chalk_1.default.cyan('menu') + chalk_1.default.gray(' for options · ') + chalk_1.default.cyan('open') + chalk_1.default.gray(' for the HTML dashboard · ') + chalk_1.default.cyan('exit') + chalk_1.default.gray(' to quit'));
668
+ }
669
+ else {
670
+ console.log(chalk_1.default.gray(' Next: ') + chalk_1.default.cyan('scan') + chalk_1.default.gray(' to analyze this project · ') + chalk_1.default.cyan('menu') + chalk_1.default.gray(' for options · ') + chalk_1.default.cyan('help') + chalk_1.default.gray(' for all commands'));
671
+ }
672
+ console.log('');
673
+ }
674
+ /** Short, friendly explainer of the flow + privacy model. */
675
+ explain() {
676
+ console.log('');
677
+ console.log(chalk_1.default.bold(' How it works'));
678
+ console.log(` ${chalk_1.default.cyan('1.')} I parse your code and run security/performance checks locally.`);
679
+ console.log(` ${chalk_1.default.cyan('2.')} If your app is running on localhost, I safely probe it (GET requests only, with your OK).`);
680
+ console.log(` ${chalk_1.default.cyan('3.')} You get a 0–100 readiness score and a ranked list of issues (OWASP / CWE tagged).`);
681
+ console.log(` ${chalk_1.default.cyan('4.')} ${chalk_1.default.cyan('fix <n>')} walks you through fixing each one — auto-fix, an AI-proposed diff you approve, or guidance.`);
682
+ console.log('');
683
+ console.log(chalk_1.default.bold(' Your privacy'));
684
+ console.log(' The scan is local. Nothing is sent to an AI unless you choose to, and even then only a');
685
+ console.log(' redacted findings summary — never your raw code (the one exception is a single snippet');
686
+ console.log(' during ' + chalk_1.default.cyan('fix') + ', shown and confirmed first). Use Ollama to stay 100% offline.');
687
+ console.log('');
688
+ }
689
+ /** In-session AI model setup (no need to leave for `init`). */
690
+ async setupModel() {
691
+ console.log('');
692
+ console.log(chalk_1.default.bold(' Choose an AI model') + chalk_1.default.gray(' (optional — scan works without one)'));
693
+ console.log(` ${chalk_1.default.cyan('1')} Claude (Anthropic)`);
694
+ console.log(` ${chalk_1.default.cyan('2')} OpenAI`);
695
+ console.log(` ${chalk_1.default.cyan('3')} Ollama (local, fully offline)`);
696
+ console.log(` ${chalk_1.default.cyan('4')} Skip for now`);
697
+ const pick = (await this.ask(chalk_1.default.cyan(' Pick 1–4 › ')))?.trim();
698
+ if (pick === '1' || pick === '2') {
699
+ const isClaude = pick === '1';
700
+ this.config.model = isClaude ? 'claude' : 'openai';
701
+ const envName = isClaude ? 'ANTHROPIC_API_KEY' : 'OPENAI_API_KEY';
702
+ if (process.env[envName]) {
703
+ logger_1.logger.success(`Using ${this.config.model} via ${envName} from your environment (key not stored on disk).`);
704
+ }
705
+ else {
706
+ const key = await this.askHidden(` Paste your ${isClaude ? 'Anthropic' : 'OpenAI'} API key (hidden), or press Enter to skip: `);
707
+ if (key.trim().length > 10) {
708
+ if (isClaude)
709
+ this.config.claudeApiKey = key.trim();
710
+ else
711
+ this.config.openaiApiKey = key.trim();
712
+ logger_1.logger.success('Key saved (config file is owner-only, 0600).');
713
+ }
714
+ else {
715
+ logger_1.logger.info(`No key entered. You can set ${envName} as an environment variable instead.`);
716
+ }
717
+ }
718
+ await ConfigManager_1.ConfigManager.save(this.config);
719
+ }
720
+ else if (pick === '3') {
721
+ this.config.model = 'ollama';
722
+ await ConfigManager_1.ConfigManager.save(this.config);
723
+ logger_1.logger.success(`Set to Ollama (local). Make sure it's running: \`ollama serve\` on port ${this.config.ollamaPort}.`);
724
+ }
725
+ else {
726
+ logger_1.logger.info('Skipped AI setup.');
727
+ }
728
+ console.log('');
729
+ return this.menu();
730
+ }
731
+ }
732
+ exports.InteractiveShell = InteractiveShell;
733
+ //# sourceMappingURL=InteractiveShell.js.map