perfai-cloud-mcp 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 (99) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +243 -0
  3. package/dist/auth/oauthFlow.d.ts +23 -0
  4. package/dist/auth/oauthFlow.d.ts.map +1 -0
  5. package/dist/auth/oauthFlow.js +174 -0
  6. package/dist/auth/pkce.d.ts +11 -0
  7. package/dist/auth/pkce.d.ts.map +1 -0
  8. package/dist/auth/pkce.js +17 -0
  9. package/dist/auth/tokenValidator.d.ts +40 -0
  10. package/dist/auth/tokenValidator.d.ts.map +1 -0
  11. package/dist/auth/tokenValidator.js +117 -0
  12. package/dist/cli.d.ts +3 -0
  13. package/dist/cli.d.ts.map +1 -0
  14. package/dist/cli.js +387 -0
  15. package/dist/client/apiClient.d.ts +27 -0
  16. package/dist/client/apiClient.d.ts.map +1 -0
  17. package/dist/client/apiClient.js +81 -0
  18. package/dist/client/authManager.d.ts +42 -0
  19. package/dist/client/authManager.d.ts.map +1 -0
  20. package/dist/client/authManager.js +136 -0
  21. package/dist/client/errors.d.ts +10 -0
  22. package/dist/client/errors.d.ts.map +1 -0
  23. package/dist/client/errors.js +29 -0
  24. package/dist/client/types.d.ts +54 -0
  25. package/dist/client/types.d.ts.map +1 -0
  26. package/dist/client/types.js +1 -0
  27. package/dist/config.d.ts +23 -0
  28. package/dist/config.d.ts.map +1 -0
  29. package/dist/config.js +50 -0
  30. package/dist/env.d.ts +2 -0
  31. package/dist/env.d.ts.map +1 -0
  32. package/dist/env.js +8 -0
  33. package/dist/log-guard.d.ts +2 -0
  34. package/dist/log-guard.d.ts.map +1 -0
  35. package/dist/log-guard.js +17 -0
  36. package/dist/server.d.ts +4 -0
  37. package/dist/server.d.ts.map +1 -0
  38. package/dist/server.js +370 -0
  39. package/dist/tools/index.d.ts +352 -0
  40. package/dist/tools/index.d.ts.map +1 -0
  41. package/dist/tools/index.js +39 -0
  42. package/dist/tools/protected/autoFix.d.ts +22 -0
  43. package/dist/tools/protected/autoFix.d.ts.map +1 -0
  44. package/dist/tools/protected/autoFix.js +64 -0
  45. package/dist/tools/protected/autoFixAll.d.ts +26 -0
  46. package/dist/tools/protected/autoFixAll.d.ts.map +1 -0
  47. package/dist/tools/protected/autoFixAll.js +79 -0
  48. package/dist/tools/protected/checkAppStatus.d.ts +21 -0
  49. package/dist/tools/protected/checkAppStatus.d.ts.map +1 -0
  50. package/dist/tools/protected/checkAppStatus.js +57 -0
  51. package/dist/tools/protected/checkTaskStatus.d.ts +21 -0
  52. package/dist/tools/protected/checkTaskStatus.d.ts.map +1 -0
  53. package/dist/tools/protected/checkTaskStatus.js +53 -0
  54. package/dist/tools/protected/getFixSummary.d.ts +17 -0
  55. package/dist/tools/protected/getFixSummary.d.ts.map +1 -0
  56. package/dist/tools/protected/getFixSummary.js +90 -0
  57. package/dist/tools/protected/getVulnerabilities.d.ts +29 -0
  58. package/dist/tools/protected/getVulnerabilities.d.ts.map +1 -0
  59. package/dist/tools/protected/getVulnerabilities.js +41 -0
  60. package/dist/tools/protected/listApps.d.ts +25 -0
  61. package/dist/tools/protected/listApps.d.ts.map +1 -0
  62. package/dist/tools/protected/listApps.js +32 -0
  63. package/dist/tools/protected/logout.d.ts +12 -0
  64. package/dist/tools/protected/logout.d.ts.map +1 -0
  65. package/dist/tools/protected/logout.js +9 -0
  66. package/dist/tools/protected/registerApp.d.ts +33 -0
  67. package/dist/tools/protected/registerApp.d.ts.map +1 -0
  68. package/dist/tools/protected/registerApp.js +96 -0
  69. package/dist/tools/protected/runSecurityTest.d.ts +17 -0
  70. package/dist/tools/protected/runSecurityTest.d.ts.map +1 -0
  71. package/dist/tools/protected/runSecurityTest.js +48 -0
  72. package/dist/tools/protected/selectApp.d.ts +18 -0
  73. package/dist/tools/protected/selectApp.d.ts.map +1 -0
  74. package/dist/tools/protected/selectApp.js +29 -0
  75. package/dist/tools/protected/submitAppCredentials.d.ts +22 -0
  76. package/dist/tools/protected/submitAppCredentials.d.ts.map +1 -0
  77. package/dist/tools/protected/submitAppCredentials.js +43 -0
  78. package/dist/tools/protected/suggestFix.d.ts +22 -0
  79. package/dist/tools/protected/suggestFix.d.ts.map +1 -0
  80. package/dist/tools/protected/suggestFix.js +37 -0
  81. package/dist/tools/protected/vulnerabilityActions.d.ts +62 -0
  82. package/dist/tools/protected/vulnerabilityActions.d.ts.map +1 -0
  83. package/dist/tools/protected/vulnerabilityActions.js +69 -0
  84. package/dist/tools/public/authStatus.d.ts +12 -0
  85. package/dist/tools/public/authStatus.d.ts.map +1 -0
  86. package/dist/tools/public/authStatus.js +13 -0
  87. package/dist/tools/public/login.d.ts +21 -0
  88. package/dist/tools/public/login.d.ts.map +1 -0
  89. package/dist/tools/public/login.js +305 -0
  90. package/dist/utils/formatters.d.ts +7 -0
  91. package/dist/utils/formatters.d.ts.map +1 -0
  92. package/dist/utils/formatters.js +47 -0
  93. package/dist/utils/poll.d.ts +19 -0
  94. package/dist/utils/poll.d.ts.map +1 -0
  95. package/dist/utils/poll.js +32 -0
  96. package/dist/utils/promptBuilder.d.ts +20 -0
  97. package/dist/utils/promptBuilder.d.ts.map +1 -0
  98. package/dist/utils/promptBuilder.js +131 -0
  99. package/package.json +55 -0
package/dist/cli.js ADDED
@@ -0,0 +1,387 @@
1
+ #!/usr/bin/env node
2
+ import "./env.js";
3
+ import { createServer } from "node:http";
4
+ import { exec } from "node:child_process";
5
+ import { platform } from "node:os";
6
+ import { createInterface } from "node:readline";
7
+ import { AuthManager } from "./client/authManager.js";
8
+ import { registerApp, getApp, runSecurityAgent, getTask, getVulnerabilities, } from "./client/apiClient.js";
9
+ import { pollWithBudget } from "./utils/poll.js";
10
+ import { POLL_START_MS, POLL_MAX_INTERVAL_MS, POLL_TASK_TIMEOUT_MS, POLL_REGISTRATION_TIMEOUT_MS, APP_TERMINAL_STATES, TASK_TERMINAL_STATES, SERVER_INFO, } from "./config.js";
11
+ /* ------------------------------------------------------------------ */
12
+ /* Terminal output helpers */
13
+ /* ------------------------------------------------------------------ */
14
+ const BOLD = "\x1b[1m";
15
+ const DIM = "\x1b[2m";
16
+ const RESET = "\x1b[0m";
17
+ const RED = "\x1b[31m";
18
+ const GREEN = "\x1b[32m";
19
+ const YELLOW = "\x1b[33m";
20
+ const CYAN = "\x1b[36m";
21
+ const MAGENTA = "\x1b[35m";
22
+ const SEVERITY_COLOR = {
23
+ critical: RED,
24
+ high: MAGENTA,
25
+ medium: YELLOW,
26
+ low: GREEN,
27
+ };
28
+ function log(msg) { process.stdout.write(msg + "\n"); }
29
+ function info(msg) { log(`${CYAN}ℹ${RESET} ${msg}`); }
30
+ function ok(msg) { log(`${GREEN}✔${RESET} ${msg}`); }
31
+ function fail(msg) { log(`${RED}✖${RESET} ${msg}`); }
32
+ function step(n, total, msg) {
33
+ log(`\n${DIM}[${n}/${total}]${RESET} ${BOLD}${msg}${RESET}`);
34
+ }
35
+ function spinner(msg) {
36
+ const frames = ["⠋", "⠙", "⠹", "⠸", "⠼", "⠴", "⠦", "⠧", "⠇", "⠏"];
37
+ let i = 0;
38
+ const id = setInterval(() => {
39
+ process.stdout.write(`\r${CYAN}${frames[i++ % frames.length]}${RESET} ${msg}`);
40
+ }, 80);
41
+ return {
42
+ stop(final) {
43
+ clearInterval(id);
44
+ process.stdout.write(`\r${final}\x1b[K\n`);
45
+ },
46
+ };
47
+ }
48
+ /* ------------------------------------------------------------------ */
49
+ /* Browser login (reused from login tool, standalone version) */
50
+ /* ------------------------------------------------------------------ */
51
+ function openBrowser(url) {
52
+ const cmd = platform() === "win32" ? `start "" "${url}"`
53
+ : platform() === "darwin" ? `open "${url}"`
54
+ : `xdg-open "${url}"`;
55
+ exec(cmd, () => { });
56
+ }
57
+ const LOGIN_HTML = `<!DOCTYPE html><html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
58
+ <title>PerfAI Login</title><style>
59
+ *{margin:0;padding:0;box-sizing:border-box}body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;background:#f5f5f5;display:flex;align-items:center;justify-content:center;min-height:100vh}
60
+ .c{background:#fff;border-radius:12px;padding:40px;box-shadow:0 4px 24px rgba(0,0,0,.1);width:100%;max-width:400px}
61
+ .logo{text-align:center;margin-bottom:24px}.logo h1{font-size:24px;color:#111}.logo p{color:#666;font-size:14px;margin-top:4px}
62
+ label{display:block;font-size:14px;font-weight:500;color:#333;margin-bottom:6px}
63
+ input{width:100%;padding:10px 12px;border:1px solid #ddd;border-radius:8px;font-size:14px;margin-bottom:16px;outline:none}input:focus{border-color:#111}
64
+ button{width:100%;padding:12px;background:#111;color:#fff;border:none;border-radius:8px;font-size:15px;font-weight:600;cursor:pointer}button:hover{background:#333}button:disabled{background:#999}
65
+ .err{color:#e53e3e;font-size:13px;margin-bottom:12px;display:none}.ok{text-align:center;color:#38a169;font-size:16px;font-weight:600;display:none;margin-top:16px}
66
+ </style></head><body><div class="c"><div class="logo"><h1>PerfAI</h1><p>Sign in with your cloud.perfai.ai account</p></div>
67
+ <form id="f"><label for="e">Email</label><input type="email" id="e" placeholder="you@example.com" required autofocus>
68
+ <label for="p">Password</label><input type="password" id="p" placeholder="Your password" required>
69
+ <div class="err" id="x"></div><button type="submit" id="b">Sign in</button></form>
70
+ <div class="ok" id="s">Authenticated! You can close this tab.</div></div>
71
+ <script>document.getElementById('f').addEventListener('submit',async e=>{e.preventDefault();const b=document.getElementById('b'),x=document.getElementById('x');
72
+ b.disabled=true;b.textContent='Signing in...';x.style.display='none';try{const r=await fetch('/auth',{method:'POST',headers:{'Content-Type':'application/json'},
73
+ body:JSON.stringify({email:document.getElementById('e').value,password:document.getElementById('p').value})});const d=await r.json();
74
+ if(d.ok){document.getElementById('f').style.display='none';document.getElementById('s').style.display='block'}
75
+ else{x.textContent=d.message||'Login failed';x.style.display='block';b.disabled=false;b.textContent='Sign in'}}
76
+ catch{x.textContent='Connection error';x.style.display='block';b.disabled=false;b.textContent='Sign in'}});</script></body></html>`;
77
+ function browserLogin(auth) {
78
+ return new Promise((resolve, reject) => {
79
+ const server = createServer((req, res) => {
80
+ if (req.method === "GET") {
81
+ res.writeHead(200, { "Content-Type": "text/html" });
82
+ res.end(LOGIN_HTML);
83
+ return;
84
+ }
85
+ if (req.method === "POST" && req.url === "/auth") {
86
+ let body = "";
87
+ req.on("data", (c) => { body += c; });
88
+ req.on("end", async () => {
89
+ try {
90
+ const { email, password } = JSON.parse(body);
91
+ await auth.login(email, password);
92
+ res.writeHead(200, { "Content-Type": "application/json" });
93
+ res.end(JSON.stringify({ ok: true }));
94
+ setTimeout(() => server.close(), 1000);
95
+ resolve();
96
+ }
97
+ catch (err) {
98
+ res.writeHead(401, { "Content-Type": "application/json" });
99
+ res.end(JSON.stringify({ ok: false, message: err instanceof Error ? err.message : "Login failed" }));
100
+ }
101
+ });
102
+ return;
103
+ }
104
+ res.writeHead(404);
105
+ res.end();
106
+ });
107
+ const timeout = setTimeout(() => {
108
+ server.close();
109
+ reject(new Error("Login timed out (5 min). Try again."));
110
+ }, 5 * 60 * 1000);
111
+ server.listen(0, "127.0.0.1", () => {
112
+ const addr = server.address();
113
+ if (!addr || typeof addr === "string")
114
+ return;
115
+ const url = `http://127.0.0.1:${addr.port}`;
116
+ info(`Browser login opened at ${DIM}${url}${RESET}`);
117
+ openBrowser(url);
118
+ });
119
+ server.on("close", () => clearTimeout(timeout));
120
+ });
121
+ }
122
+ /* ------------------------------------------------------------------ */
123
+ /* Prompt for credentials (fallback if browser can't open) */
124
+ /* ------------------------------------------------------------------ */
125
+ function promptCredentials() {
126
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
127
+ return new Promise((resolve) => {
128
+ rl.question(` ${BOLD}Email:${RESET} `, (email) => {
129
+ process.stdout.write(` ${BOLD}Password:${RESET} `);
130
+ // Hide password input
131
+ if (process.stdin.isTTY)
132
+ process.stdin.setRawMode?.(true);
133
+ let password = "";
134
+ const onData = (ch) => {
135
+ const c = ch.toString();
136
+ if (c === "\n" || c === "\r") {
137
+ if (process.stdin.isTTY)
138
+ process.stdin.setRawMode?.(false);
139
+ process.stdin.removeListener("data", onData);
140
+ process.stdout.write("\n");
141
+ rl.close();
142
+ resolve({ email: email.trim(), password });
143
+ }
144
+ else if (c === "\u007f" || c === "\b") {
145
+ password = password.slice(0, -1);
146
+ }
147
+ else if (c.charCodeAt(0) >= 32) {
148
+ password += c;
149
+ }
150
+ };
151
+ process.stdin.on("data", onData);
152
+ });
153
+ });
154
+ }
155
+ /* ------------------------------------------------------------------ */
156
+ /* Vulnerability table formatter for terminal */
157
+ /* ------------------------------------------------------------------ */
158
+ function printVulnTable(vulns) {
159
+ if (vulns.length === 0) {
160
+ ok("No vulnerabilities found!");
161
+ return;
162
+ }
163
+ const bySeverity = {};
164
+ for (const v of vulns) {
165
+ const s = (v.severity ?? "unknown").toLowerCase();
166
+ (bySeverity[s] ??= []).push(v);
167
+ }
168
+ const order = ["critical", "high", "medium", "low"];
169
+ let seq = 1;
170
+ for (const severity of order) {
171
+ const list = bySeverity[severity];
172
+ if (!list || list.length === 0)
173
+ continue;
174
+ const color = SEVERITY_COLOR[severity] ?? "";
175
+ log(`\n ${color}${BOLD}${severity.toUpperCase()} (${list.length})${RESET}`);
176
+ for (const v of list) {
177
+ const title = v.title ?? v.label ?? v.category ?? "Untitled";
178
+ const endpoint = v.method && v.path
179
+ ? `${DIM}${String(v.method).toUpperCase()} ${v.path}${RESET}`
180
+ : v.path ? `${DIM}${v.path}${RESET}` : "";
181
+ log(` ${DIM}${String(seq).padStart(3)}.${RESET} ${color}●${RESET} ${title}${endpoint ? " " + endpoint : ""}`);
182
+ seq++;
183
+ }
184
+ }
185
+ // Summary line
186
+ const counts = order
187
+ .filter(s => bySeverity[s]?.length)
188
+ .map(s => `${SEVERITY_COLOR[s]}${bySeverity[s].length} ${s}${RESET}`)
189
+ .join(", ");
190
+ log(`\n ${BOLD}Total: ${vulns.length} vulnerabilities${RESET} (${counts})`);
191
+ }
192
+ /* ------------------------------------------------------------------ */
193
+ /* Main scan flow */
194
+ /* ------------------------------------------------------------------ */
195
+ async function scan(url) {
196
+ const TOTAL_STEPS = 5;
197
+ const auth = new AuthManager();
198
+ // ── Step 1: Authenticate ──────────────────────────────────────────
199
+ step(1, TOTAL_STEPS, "Authenticate with PerfAI");
200
+ if (auth.hasCredentials()) {
201
+ const sp = spinner("Logging in with environment credentials...");
202
+ await auth.login();
203
+ sp.stop(`${GREEN}✔${RESET} Logged in as ${BOLD}${auth.getAuthenticatedEmail()}${RESET}`);
204
+ }
205
+ else {
206
+ info("No credentials found in environment.");
207
+ if (process.stdin.isTTY) {
208
+ info("Opening browser for login...");
209
+ try {
210
+ await browserLogin(auth);
211
+ ok(`Logged in as ${BOLD}${auth.getAuthenticatedEmail()}${RESET}`);
212
+ }
213
+ catch {
214
+ info("Browser login failed. Enter credentials manually:");
215
+ const creds = await promptCredentials();
216
+ const sp = spinner("Authenticating...");
217
+ await auth.login(creds.email, creds.password);
218
+ sp.stop(`${GREEN}✔${RESET} Logged in as ${BOLD}${auth.getAuthenticatedEmail()}${RESET}`);
219
+ }
220
+ }
221
+ else {
222
+ fail("No credentials. Set PERFAI_EMAIL and PERFAI_PASSWORD environment variables.");
223
+ process.exit(1);
224
+ }
225
+ }
226
+ // ── Step 2: Register app ──────────────────────────────────────────
227
+ step(2, TOTAL_STEPS, `Register app: ${CYAN}${url}${RESET}`);
228
+ let appId;
229
+ let appAlreadyReady = false;
230
+ try {
231
+ const app = await registerApp(auth, { appUrl: url });
232
+ appId = app.appId;
233
+ if (app.registrationStatus === "COMPLETED") {
234
+ ok(`App already registered and ready (${DIM}${appId}${RESET})`);
235
+ appAlreadyReady = true;
236
+ }
237
+ else {
238
+ ok(`App registered (${DIM}${appId}${RESET})`);
239
+ }
240
+ }
241
+ catch (err) {
242
+ if (err?.statusCode === 409 || err?.message?.includes("409")) {
243
+ info("App already registered — looking it up...");
244
+ const apps = await (await import("./client/apiClient.js")).listApps(auth, { search: url });
245
+ const match = apps.data.find((a) => a.appUrl === url);
246
+ if (!match) {
247
+ fail(`Could not find existing app for ${url}`);
248
+ process.exit(1);
249
+ }
250
+ appId = match.appId;
251
+ if (match.registrationStatus === "COMPLETED") {
252
+ ok(`Found existing app, ready (${DIM}${appId}${RESET})`);
253
+ appAlreadyReady = true;
254
+ }
255
+ else {
256
+ ok(`Found existing app (${DIM}${appId}${RESET})`);
257
+ }
258
+ }
259
+ else {
260
+ throw err;
261
+ }
262
+ }
263
+ // ── Step 3: Wait for registration ─────────────────────────────────
264
+ if (!appAlreadyReady) {
265
+ step(3, TOTAL_STEPS, "Waiting for app registration to complete");
266
+ const sp = spinner("Registering...");
267
+ const { value: finalApp, terminal } = await pollWithBudget({
268
+ fetch: () => getApp(auth, appId),
269
+ isTerminal: (a) => APP_TERMINAL_STATES.has(a.registrationStatus ?? ""),
270
+ budgetMs: POLL_REGISTRATION_TIMEOUT_MS,
271
+ startIntervalMs: POLL_START_MS,
272
+ maxIntervalMs: POLL_MAX_INTERVAL_MS,
273
+ });
274
+ if (!terminal || finalApp.registrationStatus === "FAILED") {
275
+ sp.stop(`${RED}✖${RESET} Registration ${finalApp.registrationStatus ?? "timed out"}`);
276
+ process.exit(1);
277
+ }
278
+ sp.stop(`${GREEN}✔${RESET} Registration complete`);
279
+ }
280
+ else {
281
+ step(3, TOTAL_STEPS, "Registration already complete — skipping");
282
+ }
283
+ // ── Step 4: Run security test ─────────────────────────────────────
284
+ step(4, TOTAL_STEPS, "Running security test");
285
+ const sp2 = spinner("Starting scan...");
286
+ let task;
287
+ try {
288
+ task = await runSecurityAgent(auth, appId);
289
+ }
290
+ catch (err) {
291
+ sp2.stop(`${RED}✖${RESET} Failed to start scan: ${err.message ?? err}`);
292
+ process.exit(1);
293
+ }
294
+ sp2.stop(`${GREEN}✔${RESET} Scan started (task: ${DIM}${task.taskId}${RESET})`);
295
+ const sp3 = spinner("Scanning — this may take several minutes...");
296
+ const { value: finalTask, terminal: taskDone } = await pollWithBudget({
297
+ fetch: () => getTask(auth, task.taskId),
298
+ isTerminal: (t) => TASK_TERMINAL_STATES.has(t.state ?? ""),
299
+ budgetMs: POLL_TASK_TIMEOUT_MS,
300
+ startIntervalMs: POLL_START_MS,
301
+ maxIntervalMs: POLL_MAX_INTERVAL_MS,
302
+ });
303
+ if (!taskDone || finalTask.state === "FAILED") {
304
+ sp3.stop(`${RED}✖${RESET} Scan ${finalTask.state ?? "timed out"}`);
305
+ process.exit(1);
306
+ }
307
+ sp3.stop(`${GREEN}✔${RESET} Scan complete`);
308
+ // ── Step 5: Fetch and display results ─────────────────────────────
309
+ step(5, TOTAL_STEPS, "Fetching results");
310
+ let allVulns = [];
311
+ let page = 1;
312
+ while (true) {
313
+ const result = await getVulnerabilities(auth, appId, { page, pageSize: 100 });
314
+ allVulns = allVulns.concat(result.data);
315
+ if (allVulns.length >= result.total)
316
+ break;
317
+ page++;
318
+ }
319
+ log(`\n${"─".repeat(60)}`);
320
+ log(`${BOLD} Security Report: ${CYAN}${url}${RESET}`);
321
+ log(`${"─".repeat(60)}`);
322
+ printVulnTable(allVulns);
323
+ log(`\n${"─".repeat(60)}`);
324
+ if (allVulns.length > 0) {
325
+ log(`\n${BOLD}Next steps:${RESET}`);
326
+ log(` • Use the MCP server in ChatGPT/Cursor to get AI-powered fixes`);
327
+ log(` • Run ${DIM}npx perfai scan ${url}${RESET} again after fixing to verify`);
328
+ }
329
+ log("");
330
+ }
331
+ /* ------------------------------------------------------------------ */
332
+ /* CLI argument parsing */
333
+ /* ------------------------------------------------------------------ */
334
+ function printHelp() {
335
+ log(`
336
+ ${BOLD}perfai${RESET} — PerfAI Security Scanner CLI v${SERVER_INFO.version}
337
+
338
+ ${BOLD}USAGE${RESET}
339
+ npx perfai scan <url> Scan an app for security vulnerabilities
340
+ npx perfai scan --help Show this help
341
+
342
+ ${BOLD}EXAMPLES${RESET}
343
+ npx perfai scan https://api.myapp.com
344
+ npx perfai scan https://staging.example.com
345
+
346
+ ${BOLD}AUTHENTICATION${RESET}
347
+ Set environment variables for non-interactive login:
348
+ PERFAI_EMAIL=you@example.com
349
+ PERFAI_PASSWORD=your-password
350
+
351
+ Or omit them — a browser window will open for you to sign in.
352
+
353
+ ${BOLD}MORE INFO${RESET}
354
+ https://cloud.perfai.ai
355
+ https://mcp-server.perfai.ai
356
+ `);
357
+ }
358
+ async function main() {
359
+ const args = process.argv.slice(2);
360
+ if (args.length === 0 || args[0] === "--help" || args[0] === "-h") {
361
+ printHelp();
362
+ process.exit(0);
363
+ }
364
+ if (args[0] !== "scan") {
365
+ fail(`Unknown command: ${args[0]}`);
366
+ log(` Run ${DIM}npx perfai --help${RESET} for usage.`);
367
+ process.exit(1);
368
+ }
369
+ const url = args[1];
370
+ if (!url) {
371
+ fail("Missing URL. Usage: npx perfai scan <url>");
372
+ process.exit(1);
373
+ }
374
+ if (!url.startsWith("http://") && !url.startsWith("https://")) {
375
+ fail("URL must start with http:// or https://");
376
+ process.exit(1);
377
+ }
378
+ log(`\n${BOLD}PerfAI Security Scanner${RESET} v${SERVER_INFO.version}\n`);
379
+ try {
380
+ await scan(url);
381
+ }
382
+ catch (error) {
383
+ fail(error instanceof Error ? error.message : String(error));
384
+ process.exit(1);
385
+ }
386
+ }
387
+ main();
@@ -0,0 +1,27 @@
1
+ import { AuthManager } from "./authManager.js";
2
+ import type { AppListResponse, AppRecord, TaskRecord, VulnerabilityListResponse } from "./types.js";
3
+ export interface RegisterAppInput {
4
+ appUrl: string;
5
+ tenantOneCredentials?: Record<string, unknown>;
6
+ createTestAccounts?: boolean;
7
+ skipEndpoints?: string[];
8
+ }
9
+ export declare function registerApp(auth: AuthManager, input: RegisterAppInput): Promise<AppRecord>;
10
+ export declare function getApp(auth: AuthManager, appId: string): Promise<AppRecord>;
11
+ export declare function listApps(auth: AuthManager, params: {
12
+ page?: number;
13
+ pageSize?: number;
14
+ search?: string;
15
+ }): Promise<AppListResponse>;
16
+ export declare function submitAccountSetup(auth: AuthManager, appId: string, credentials: Record<string, unknown>): Promise<TaskRecord>;
17
+ export declare function runSecurityAgent(auth: AuthManager, appId: string): Promise<TaskRecord>;
18
+ export declare function getTask(auth: AuthManager, taskId: string): Promise<TaskRecord>;
19
+ export declare function getVulnerabilities(auth: AuthManager, appId: string, params: {
20
+ page?: number;
21
+ pageSize?: number;
22
+ search?: string;
23
+ }): Promise<VulnerabilityListResponse>;
24
+ export declare function dismissVulnerability(auth: AuthManager, id: string): Promise<unknown>;
25
+ export declare function reopenVulnerability(auth: AuthManager, id: string): Promise<unknown>;
26
+ export declare function fixVulnerability(auth: AuthManager, id: string): Promise<unknown>;
27
+ //# sourceMappingURL=apiClient.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"apiClient.d.ts","sourceRoot":"","sources":["../../src/client/apiClient.ts"],"names":[],"mappings":"AAEA,OAAO,EAAE,WAAW,EAAE,MAAM,kBAAkB,CAAC;AAE/C,OAAO,KAAK,EACV,eAAe,EACf,SAAS,EACT,UAAU,EACV,yBAAyB,EAC1B,MAAM,YAAY,CAAC;AAiDpB,MAAM,WAAW,gBAAgB;IAC/B,MAAM,EAAE,MAAM,CAAC;IACf,oBAAoB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC/C,kBAAkB,CAAC,EAAE,OAAO,CAAC;IAC7B,aAAa,CAAC,EAAE,MAAM,EAAE,CAAC;CAC1B;AAED,wBAAgB,WAAW,CAAC,IAAI,EAAE,WAAW,EAAE,KAAK,EAAE,gBAAgB,GAAG,OAAO,CAAC,SAAS,CAAC,CAE1F;AAED,wBAAgB,MAAM,CAAC,IAAI,EAAE,WAAW,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,SAAS,CAAC,CAE3E;AAED,wBAAgB,QAAQ,CACtB,IAAI,EAAE,WAAW,EACjB,MAAM,EAAE;IAAE,IAAI,CAAC,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE,GAC5D,OAAO,CAAC,eAAe,CAAC,CAE1B;AAED,wBAAgB,kBAAkB,CAChC,IAAI,EAAE,WAAW,EACjB,KAAK,EAAE,MAAM,EACb,WAAW,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GACnC,OAAO,CAAC,UAAU,CAAC,CAMrB;AAED,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,WAAW,EAAE,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC,CAKtF;AAED,wBAAgB,OAAO,CAAC,IAAI,EAAE,WAAW,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,UAAU,CAAC,CAE9E;AAED,wBAAgB,kBAAkB,CAChC,IAAI,EAAE,WAAW,EACjB,KAAK,EAAE,MAAM,EACb,MAAM,EAAE;IAAE,IAAI,CAAC,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,EAAE,MAAM,CAAC;IAAC,MAAM,CAAC,EAAE,MAAM,CAAA;CAAE,GAC5D,OAAO,CAAC,yBAAyB,CAAC,CAMpC;AAED,wBAAgB,oBAAoB,CAAC,IAAI,EAAE,WAAW,EAAE,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAEpF;AAED,wBAAgB,mBAAmB,CAAC,IAAI,EAAE,WAAW,EAAE,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAEnF;AAED,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,WAAW,EAAE,EAAE,EAAE,MAAM,GAAG,OAAO,CAAC,OAAO,CAAC,CAEhF"}
@@ -0,0 +1,81 @@
1
+ import axios from "axios";
2
+ import { API_BASE_URL } from "../config.js";
3
+ import { ApiError, formatApiError } from "./errors.js";
4
+ async function request(auth, config, allowReauth = true) {
5
+ if (!auth.isAuthenticated()) {
6
+ if (auth.hasCredentials()) {
7
+ await auth.login();
8
+ }
9
+ else {
10
+ throw new Error("Not authenticated. Run the `login` tool first (or set PERFAI_EMAIL / PERFAI_PASSWORD).");
11
+ }
12
+ }
13
+ try {
14
+ const response = await axios.request({
15
+ ...config,
16
+ baseURL: API_BASE_URL,
17
+ timeout: 30_000,
18
+ headers: {
19
+ ...config.headers,
20
+ Authorization: `Bearer ${auth.getToken()}`,
21
+ "Content-Type": "application/json",
22
+ },
23
+ });
24
+ return response.data;
25
+ }
26
+ catch (error) {
27
+ if (axios.isAxiosError(error)) {
28
+ const status = error.response?.status;
29
+ // Tokens are short-lived (per docs) — transparently re-auth once on 401.
30
+ if (status === 401 && allowReauth && auth.hasCredentials()) {
31
+ console.error("Access token rejected (401) — re-authenticating and retrying once.");
32
+ await auth.login();
33
+ return request(auth, config, false);
34
+ }
35
+ console.error(`API request failed: ${config.method?.toUpperCase()} ${config.url}`, status, error.response?.data);
36
+ throw new ApiError(formatApiError(error), status, error.response?.data);
37
+ }
38
+ throw error;
39
+ }
40
+ }
41
+ export function registerApp(auth, input) {
42
+ return request(auth, { method: "POST", url: "/apps", data: input });
43
+ }
44
+ export function getApp(auth, appId) {
45
+ return request(auth, { method: "GET", url: `/apps/${encodeURIComponent(appId)}` });
46
+ }
47
+ export function listApps(auth, params) {
48
+ return request(auth, { method: "GET", url: "/apps", params });
49
+ }
50
+ export function submitAccountSetup(auth, appId, credentials) {
51
+ return request(auth, {
52
+ method: "POST",
53
+ url: `/apps/${encodeURIComponent(appId)}/account-setup`,
54
+ data: credentials,
55
+ });
56
+ }
57
+ export function runSecurityAgent(auth, appId) {
58
+ return request(auth, {
59
+ method: "POST",
60
+ url: `/apps/${encodeURIComponent(appId)}/security-agent`,
61
+ });
62
+ }
63
+ export function getTask(auth, taskId) {
64
+ return request(auth, { method: "GET", url: `/tasks/${encodeURIComponent(taskId)}` });
65
+ }
66
+ export function getVulnerabilities(auth, appId, params) {
67
+ return request(auth, {
68
+ method: "GET",
69
+ url: `/apps/${encodeURIComponent(appId)}/vulnerabilities`,
70
+ params,
71
+ });
72
+ }
73
+ export function dismissVulnerability(auth, id) {
74
+ return request(auth, { method: "POST", url: `/vulnerabilities/${encodeURIComponent(id)}/dismiss` });
75
+ }
76
+ export function reopenVulnerability(auth, id) {
77
+ return request(auth, { method: "POST", url: `/vulnerabilities/${encodeURIComponent(id)}/reopen` });
78
+ }
79
+ export function fixVulnerability(auth, id) {
80
+ return request(auth, { method: "POST", url: `/vulnerabilities/${encodeURIComponent(id)}/fix` });
81
+ }
@@ -0,0 +1,42 @@
1
+ import type { VulnerabilityRecord } from "./types.js";
2
+ export type AuthMethod = "credentials" | "token" | "oauth" | "none";
3
+ /**
4
+ * Holds the auth token plus the small amount of "current selection" state
5
+ * (app / task / cached vulnerability sequence numbers) that lets tools refer
6
+ * to things by short-lived sequence numbers instead of raw IDs, matching the
7
+ * UX of listing something then acting on "#3".
8
+ */
9
+ export declare class AuthManager {
10
+ private email?;
11
+ private password?;
12
+ private idToken?;
13
+ private authenticatedEmail?;
14
+ private authMethod;
15
+ currentAppId?: string;
16
+ currentAppUrl?: string;
17
+ currentTaskId?: string;
18
+ private vulnCache;
19
+ private vulnCacheAppId?;
20
+ constructor();
21
+ hasCredentials(): boolean;
22
+ setCredentials(email: string, password: string): void;
23
+ /**
24
+ * Accept a pre-existing id_token directly — no email/password exchange.
25
+ * Used by: PERFAI_TOKEN env var, OAuth PKCE browser flow, HTTP bearer auth.
26
+ */
27
+ setToken(token: string, email?: string, method?: AuthMethod): void;
28
+ isAuthenticated(): boolean;
29
+ getToken(): string | undefined;
30
+ getAuthenticatedEmail(): string | undefined;
31
+ getAuthMethod(): AuthMethod;
32
+ login(email?: string, password?: string): Promise<string>;
33
+ logout(): void;
34
+ setCurrentApp(appId: string, appUrl?: string): void;
35
+ /** Caches a vulnerability page (keyed by 1-based sequence number) so tools can refer to "#3". */
36
+ cacheVulnerabilities(appId: string, vulnerabilities: VulnerabilityRecord[]): void;
37
+ /** Looks up a cached vulnerability by sequence number ("3") or raw ID, if it was seen in the last listing. */
38
+ getCachedVulnerability(appId: string, idOrSequence: string): VulnerabilityRecord | undefined;
39
+ /** Resolves a raw vulnerability ID or a cached sequence number ("3") to an ID. */
40
+ resolveVulnerabilityId(appId: string, idOrSequence: string): string;
41
+ }
42
+ //# sourceMappingURL=authManager.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"authManager.d.ts","sourceRoot":"","sources":["../../src/client/authManager.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAEtD,MAAM,MAAM,UAAU,GAAG,aAAa,GAAG,OAAO,GAAG,OAAO,GAAG,MAAM,CAAC;AAEpE;;;;;GAKG;AACH,qBAAa,WAAW;IACtB,OAAO,CAAC,KAAK,CAAC,CAAwB;IACtC,OAAO,CAAC,QAAQ,CAAC,CAA2B;IAC5C,OAAO,CAAC,OAAO,CAAC,CAAS;IACzB,OAAO,CAAC,kBAAkB,CAAC,CAAS;IACpC,OAAO,CAAC,UAAU,CAAsB;IAExC,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,aAAa,CAAC,EAAE,MAAM,CAAC;IAEvB,OAAO,CAAC,SAAS,CAA0C;IAC3D,OAAO,CAAC,cAAc,CAAC,CAAS;;IAWhC,cAAc,IAAI,OAAO;IAIzB,cAAc,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,MAAM,GAAG,IAAI;IAKrD;;;OAGG;IACH,QAAQ,CAAC,KAAK,EAAE,MAAM,EAAE,KAAK,CAAC,EAAE,MAAM,EAAE,MAAM,GAAE,UAAoB,GAAG,IAAI;IAgB3E,eAAe,IAAI,OAAO;IAI1B,QAAQ,IAAI,MAAM,GAAG,SAAS;IAI9B,qBAAqB,IAAI,MAAM,GAAG,SAAS;IAI3C,aAAa,IAAI,UAAU;IAIrB,KAAK,CAAC,KAAK,CAAC,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;IAyC/D,MAAM,IAAI,IAAI;IAWd,aAAa,CAAC,KAAK,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI;IAKnD,iGAAiG;IACjG,oBAAoB,CAAC,KAAK,EAAE,MAAM,EAAE,eAAe,EAAE,mBAAmB,EAAE,GAAG,IAAI;IAMjF,8GAA8G;IAC9G,sBAAsB,CAAC,KAAK,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,GAAG,mBAAmB,GAAG,SAAS;IAa5F,kFAAkF;IAClF,sBAAsB,CAAC,KAAK,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,GAAG,MAAM;CAKpE"}