perfai-cloud-mcp 0.3.0 → 0.5.3

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 (104) hide show
  1. package/README.md +45 -24
  2. package/dist/auth/bearerAuth.js +53 -0
  3. package/dist/auth/oauthFlow.js +1 -19
  4. package/dist/auth/pkce.js +0 -8
  5. package/dist/auth/tokenValidator.js +77 -67
  6. package/dist/cli.js +85 -52
  7. package/dist/client/apiClient.js +18 -25
  8. package/dist/client/authManager.js +42 -51
  9. package/dist/client/errors.js +42 -14
  10. package/dist/config.js +35 -38
  11. package/dist/env.js +0 -6
  12. package/dist/log-guard.js +0 -9
  13. package/dist/prompts.js +2 -8
  14. package/dist/server.js +45 -176
  15. package/dist/tools/protected/autoFix.js +0 -1
  16. package/dist/tools/protected/autoFixAll.js +4 -7
  17. package/dist/tools/protected/checkAppStatus.js +34 -32
  18. package/dist/tools/protected/checkTaskStatus.js +29 -28
  19. package/dist/tools/protected/getFixSummary.js +41 -11
  20. package/dist/tools/protected/getVulnerabilities.js +58 -8
  21. package/dist/tools/protected/manageOrganizations.js +4 -5
  22. package/dist/tools/protected/registerApp.js +17 -33
  23. package/dist/tools/protected/runSecurityTest.js +82 -26
  24. package/dist/tools/protected/submitAppCredentials.js +4 -3
  25. package/dist/tools/protected/vulnerabilityActions.js +32 -8
  26. package/dist/tools/public/authStatus.js +2 -2
  27. package/dist/tools/public/login.js +3 -27
  28. package/dist/utils/appResolver.js +25 -85
  29. package/dist/utils/formatters.js +9 -9
  30. package/dist/utils/poll.js +0 -7
  31. package/dist/utils/promptBuilder.js +93 -94
  32. package/dist/utils/registrationState.js +28 -0
  33. package/dist/utils/runState.js +129 -0
  34. package/package.json +6 -2
  35. package/dist/auth/oauthFlow.d.ts +0 -23
  36. package/dist/auth/oauthFlow.d.ts.map +0 -1
  37. package/dist/auth/pkce.d.ts +0 -11
  38. package/dist/auth/pkce.d.ts.map +0 -1
  39. package/dist/auth/tokenValidator.d.ts +0 -40
  40. package/dist/auth/tokenValidator.d.ts.map +0 -1
  41. package/dist/cli.d.ts +0 -3
  42. package/dist/cli.d.ts.map +0 -1
  43. package/dist/client/apiClient.d.ts +0 -36
  44. package/dist/client/apiClient.d.ts.map +0 -1
  45. package/dist/client/authManager.d.ts +0 -61
  46. package/dist/client/authManager.d.ts.map +0 -1
  47. package/dist/client/errors.d.ts +0 -10
  48. package/dist/client/errors.d.ts.map +0 -1
  49. package/dist/client/types.d.ts +0 -72
  50. package/dist/client/types.d.ts.map +0 -1
  51. package/dist/config.d.ts +0 -27
  52. package/dist/config.d.ts.map +0 -1
  53. package/dist/env.d.ts +0 -2
  54. package/dist/env.d.ts.map +0 -1
  55. package/dist/log-guard.d.ts +0 -2
  56. package/dist/log-guard.d.ts.map +0 -1
  57. package/dist/prompts.d.ts +0 -31
  58. package/dist/prompts.d.ts.map +0 -1
  59. package/dist/server.d.ts +0 -4
  60. package/dist/server.d.ts.map +0 -1
  61. package/dist/tools/index.d.ts +0 -404
  62. package/dist/tools/index.d.ts.map +0 -1
  63. package/dist/tools/protected/autoFix.d.ts +0 -26
  64. package/dist/tools/protected/autoFix.d.ts.map +0 -1
  65. package/dist/tools/protected/autoFixAll.d.ts +0 -30
  66. package/dist/tools/protected/autoFixAll.d.ts.map +0 -1
  67. package/dist/tools/protected/checkAppStatus.d.ts +0 -21
  68. package/dist/tools/protected/checkAppStatus.d.ts.map +0 -1
  69. package/dist/tools/protected/checkTaskStatus.d.ts +0 -21
  70. package/dist/tools/protected/checkTaskStatus.d.ts.map +0 -1
  71. package/dist/tools/protected/getFixSummary.d.ts +0 -21
  72. package/dist/tools/protected/getFixSummary.d.ts.map +0 -1
  73. package/dist/tools/protected/getVulnerabilities.d.ts +0 -33
  74. package/dist/tools/protected/getVulnerabilities.d.ts.map +0 -1
  75. package/dist/tools/protected/listApps.d.ts +0 -25
  76. package/dist/tools/protected/listApps.d.ts.map +0 -1
  77. package/dist/tools/protected/logout.d.ts +0 -12
  78. package/dist/tools/protected/logout.d.ts.map +0 -1
  79. package/dist/tools/protected/manageOrganizations.d.ts +0 -26
  80. package/dist/tools/protected/manageOrganizations.d.ts.map +0 -1
  81. package/dist/tools/protected/registerApp.d.ts +0 -33
  82. package/dist/tools/protected/registerApp.d.ts.map +0 -1
  83. package/dist/tools/protected/runSecurityTest.d.ts +0 -21
  84. package/dist/tools/protected/runSecurityTest.d.ts.map +0 -1
  85. package/dist/tools/protected/selectApp.d.ts +0 -18
  86. package/dist/tools/protected/selectApp.d.ts.map +0 -1
  87. package/dist/tools/protected/submitAppCredentials.d.ts +0 -22
  88. package/dist/tools/protected/submitAppCredentials.d.ts.map +0 -1
  89. package/dist/tools/protected/suggestFix.d.ts +0 -22
  90. package/dist/tools/protected/suggestFix.d.ts.map +0 -1
  91. package/dist/tools/protected/vulnerabilityActions.d.ts +0 -70
  92. package/dist/tools/protected/vulnerabilityActions.d.ts.map +0 -1
  93. package/dist/tools/public/authStatus.d.ts +0 -12
  94. package/dist/tools/public/authStatus.d.ts.map +0 -1
  95. package/dist/tools/public/login.d.ts +0 -31
  96. package/dist/tools/public/login.d.ts.map +0 -1
  97. package/dist/utils/appResolver.d.ts +0 -24
  98. package/dist/utils/appResolver.d.ts.map +0 -1
  99. package/dist/utils/formatters.d.ts +0 -8
  100. package/dist/utils/formatters.d.ts.map +0 -1
  101. package/dist/utils/poll.d.ts +0 -19
  102. package/dist/utils/poll.d.ts.map +0 -1
  103. package/dist/utils/promptBuilder.d.ts +0 -26
  104. package/dist/utils/promptBuilder.d.ts.map +0 -1
package/dist/cli.js CHANGED
@@ -5,12 +5,14 @@ import { exec } from "node:child_process";
5
5
  import { platform } from "node:os";
6
6
  import { createInterface } from "node:readline";
7
7
  import { AuthManager } from "./client/authManager.js";
8
- import { registerApp, getApp, runSecurityAgent, getTask, getVulnerabilities, } from "./client/apiClient.js";
8
+ import { registerApp, runSecurityAgent, getTask, getVulnerabilities, } from "./client/apiClient.js";
9
+ import { isAppNotRegisteredError } from "./client/errors.js";
9
10
  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
- /* ------------------------------------------------------------------ */
11
+ import { getRegistrationSnapshot } from "./utils/registrationState.js";
12
+ import { describeStatus, isTerminalTaskStatus } from "./utils/runState.js";
13
+ import { POLL_START_MS, POLL_MAX_INTERVAL_MS, POLL_TASK_TIMEOUT_MS, POLL_REGISTRATION_TIMEOUT_MS, SERVER_INFO, } from "./config.js";
14
+ const EXIT_NEEDS_INPUT = 2;
15
+ const EXIT_INTERRUPTED = 3;
14
16
  const BOLD = "\x1b[1m";
15
17
  const DIM = "\x1b[2m";
16
18
  const RESET = "\x1b[0m";
@@ -29,6 +31,17 @@ function log(msg) { process.stdout.write(msg + "\n"); }
29
31
  function info(msg) { log(`${CYAN}ℹ${RESET} ${msg}`); }
30
32
  function ok(msg) { log(`${GREEN}✔${RESET} ${msg}`); }
31
33
  function fail(msg) { log(`${RED}✖${RESET} ${msg}`); }
34
+ function outcomeLine(view) {
35
+ const mark = view.outcome === "interrupted" || view.outcome === "cancelled" ? `${CYAN}ℹ${RESET}` : `${YELLOW}●${RESET}`;
36
+ return `${mark} ${view.label} — ${view.message}`;
37
+ }
38
+ function exitOnOutcome(view) {
39
+ if (view.outcome === "needs_input") {
40
+ log(` Supply what it needs in the Perfai console (or with the MCP submit_app_credentials tool), then run this again.`);
41
+ process.exit(EXIT_NEEDS_INPUT);
42
+ }
43
+ process.exit(EXIT_INTERRUPTED);
44
+ }
32
45
  function step(n, total, msg) {
33
46
  log(`\n${DIM}[${n}/${total}]${RESET} ${BOLD}${msg}${RESET}`);
34
47
  }
@@ -45,9 +58,6 @@ function spinner(msg) {
45
58
  },
46
59
  };
47
60
  }
48
- /* ------------------------------------------------------------------ */
49
- /* Browser login (reused from login tool, standalone version) */
50
- /* ------------------------------------------------------------------ */
51
61
  function openBrowser(url) {
52
62
  const cmd = platform() === "win32" ? `start "" "${url}"`
53
63
  : platform() === "darwin" ? `open "${url}"`
@@ -119,15 +129,11 @@ function browserLogin(auth) {
119
129
  server.on("close", () => clearTimeout(timeout));
120
130
  });
121
131
  }
122
- /* ------------------------------------------------------------------ */
123
- /* Prompt for credentials (fallback if browser can't open) */
124
- /* ------------------------------------------------------------------ */
125
132
  function promptCredentials() {
126
133
  const rl = createInterface({ input: process.stdin, output: process.stdout });
127
134
  return new Promise((resolve) => {
128
135
  rl.question(` ${BOLD}Email:${RESET} `, (email) => {
129
136
  process.stdout.write(` ${BOLD}Password:${RESET} `);
130
- // Hide password input
131
137
  if (process.stdin.isTTY)
132
138
  process.stdin.setRawMode?.(true);
133
139
  let password = "";
@@ -152,9 +158,6 @@ function promptCredentials() {
152
158
  });
153
159
  });
154
160
  }
155
- /* ------------------------------------------------------------------ */
156
- /* Vulnerability table formatter for terminal */
157
- /* ------------------------------------------------------------------ */
158
161
  function printVulnTable(vulns) {
159
162
  if (vulns.length === 0) {
160
163
  ok("No vulnerabilities found!");
@@ -174,7 +177,7 @@ function printVulnTable(vulns) {
174
177
  const color = SEVERITY_COLOR[severity] ?? "";
175
178
  log(`\n ${color}${BOLD}${severity.toUpperCase()} (${list.length})${RESET}`);
176
179
  for (const v of list) {
177
- const title = v.title ?? v.label ?? v.category ?? "Untitled";
180
+ const title = v.title ?? v.label ?? "Untitled";
178
181
  const endpoint = v.method && v.path
179
182
  ? `${DIM}${String(v.method).toUpperCase()} ${v.path}${RESET}`
180
183
  : v.path ? `${DIM}${v.path}${RESET}` : "";
@@ -182,20 +185,15 @@ function printVulnTable(vulns) {
182
185
  seq++;
183
186
  }
184
187
  }
185
- // Summary line
186
188
  const counts = order
187
189
  .filter(s => bySeverity[s]?.length)
188
190
  .map(s => `${SEVERITY_COLOR[s]}${bySeverity[s].length} ${s}${RESET}`)
189
191
  .join(", ");
190
192
  log(`\n ${BOLD}Total: ${vulns.length} vulnerabilities${RESET} (${counts})`);
191
193
  }
192
- /* ------------------------------------------------------------------ */
193
- /* Main scan flow */
194
- /* ------------------------------------------------------------------ */
195
194
  async function scan(url) {
196
195
  const TOTAL_STEPS = 5;
197
196
  const auth = new AuthManager();
198
- // ── Step 1: Authenticate ──────────────────────────────────────────
199
197
  step(1, TOTAL_STEPS, "Authenticate with Perfai");
200
198
  if (auth.hasCredentials()) {
201
199
  const sp = spinner("Logging in with environment credentials...");
@@ -223,14 +221,13 @@ async function scan(url) {
223
221
  process.exit(1);
224
222
  }
225
223
  }
226
- // ── Step 2: Register app ──────────────────────────────────────────
227
224
  step(2, TOTAL_STEPS, `Register app: ${CYAN}${url}${RESET}`);
228
225
  let appId;
229
226
  let appAlreadyReady = false;
230
227
  try {
231
228
  const app = await registerApp(auth, { appUrl: url });
232
229
  appId = app.appId;
233
- if (app.registrationStatus === "COMPLETED") {
230
+ if (describeStatus(app.registrationStatus, app).outcome === "ready") {
234
231
  ok(`App already registered and ready (${DIM}${appId}${RESET})`);
235
232
  appAlreadyReady = true;
236
233
  }
@@ -248,7 +245,7 @@ async function scan(url) {
248
245
  process.exit(1);
249
246
  }
250
247
  appId = match.appId;
251
- if (match.registrationStatus === "COMPLETED") {
248
+ if (describeStatus(match.registrationStatus, match).outcome === "ready") {
252
249
  ok(`Found existing app, ready (${DIM}${appId}${RESET})`);
253
250
  appAlreadyReady = true;
254
251
  }
@@ -260,52 +257,81 @@ async function scan(url) {
260
257
  throw err;
261
258
  }
262
259
  }
263
- // ── Step 3: Wait for registration ─────────────────────────────────
260
+ let partialCoverage = false;
264
261
  if (!appAlreadyReady) {
265
262
  step(3, TOTAL_STEPS, "Waiting for app registration to complete");
266
263
  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 ?? ""),
264
+ const { value: registration, terminal } = await pollWithBudget({
265
+ fetch: () => getRegistrationSnapshot(auth, appId),
266
+ isTerminal: (s) => s.view.outcome !== "pending",
270
267
  budgetMs: POLL_REGISTRATION_TIMEOUT_MS,
271
268
  startIntervalMs: POLL_START_MS,
272
269
  maxIntervalMs: POLL_MAX_INTERVAL_MS,
273
270
  });
274
- if (!terminal || finalApp.registrationStatus === "FAILED") {
275
- sp.stop(`${RED}✖${RESET} Registration ${finalApp.registrationStatus ?? "timed out"}`);
271
+ const view = registration.view;
272
+ if (!terminal) {
273
+ sp.stop(`${YELLOW}●${RESET} Registration still ${view.label} after ${POLL_REGISTRATION_TIMEOUT_MS / 60_000} min — run this again later to pick it up`);
276
274
  process.exit(1);
277
275
  }
278
- sp.stop(`${GREEN}✔${RESET} Registration complete`);
276
+ if (view.outcome === "ready") {
277
+ sp.stop(`${GREEN}✔${RESET} Registration complete`);
278
+ }
279
+ else if (view.outcome === "partial") {
280
+ sp.stop(outcomeLine(view));
281
+ }
282
+ else {
283
+ sp.stop(outcomeLine(view));
284
+ exitOnOutcome(view);
285
+ }
279
286
  }
280
287
  else {
281
288
  step(3, TOTAL_STEPS, "Registration already complete — skipping");
282
289
  }
283
- // ── Step 4: Run security test ─────────────────────────────────────
284
290
  step(4, TOTAL_STEPS, "Running security test");
285
- const sp2 = spinner("Starting scan...");
291
+ const sp2 = spinner("Starting security test...");
286
292
  let task;
287
293
  try {
288
294
  task = await runSecurityAgent(auth, appId);
289
295
  }
290
296
  catch (err) {
291
- sp2.stop(`${RED}✖${RESET} Failed to start scan: ${err.message ?? err}`);
292
- process.exit(1);
297
+ if (isAppNotRegisteredError(err)) {
298
+ const refused = describeStatus(err.data?.registrationStatus);
299
+ sp2.stop(`${YELLOW}●${RESET} Security test not started — onboarding isn't finished (${refused.label})`);
300
+ partialCoverage = true;
301
+ }
302
+ else {
303
+ sp2.stop(`${RED}✖${RESET} Could not start the security test: ${err.message ?? err}`);
304
+ process.exit(1);
305
+ }
293
306
  }
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);
307
+ if (task) {
308
+ sp2.stop(`${GREEN}✔${RESET} Security test started (task: ${DIM}${task.taskId}${RESET})`);
309
+ const sp3 = spinner("Security test running — this may take several minutes...");
310
+ const taskId = task.taskId;
311
+ const { value: finalTask, terminal: taskDone } = await pollWithBudget({
312
+ fetch: () => getTask(auth, taskId),
313
+ isTerminal: (t) => isTerminalTaskStatus(t.state),
314
+ budgetMs: POLL_TASK_TIMEOUT_MS,
315
+ startIntervalMs: POLL_START_MS,
316
+ maxIntervalMs: POLL_MAX_INTERVAL_MS,
317
+ });
318
+ const view = describeStatus(finalTask.state, finalTask, finalTask.result?.intervention);
319
+ if (!taskDone) {
320
+ sp3.stop(`${YELLOW}●${RESET} Security test still ${view.label} after ${POLL_TASK_TIMEOUT_MS / 60_000} min — results will appear in the Perfai console`);
321
+ process.exit(1);
322
+ }
323
+ if (view.outcome === "ready") {
324
+ sp3.stop(`${GREEN}✔${RESET} Security test complete`);
325
+ }
326
+ else if (view.outcome === "partial") {
327
+ sp3.stop(outcomeLine(view));
328
+ partialCoverage = true;
329
+ }
330
+ else {
331
+ sp3.stop(outcomeLine(view));
332
+ exitOnOutcome(view);
333
+ }
306
334
  }
307
- sp3.stop(`${GREEN}✔${RESET} Scan complete`);
308
- // ── Step 5: Fetch and display results ─────────────────────────────
309
335
  step(5, TOTAL_STEPS, "Fetching results");
310
336
  let allVulns = [];
311
337
  let page = 1;
@@ -318,6 +344,10 @@ async function scan(url) {
318
344
  }
319
345
  log(`\n${"─".repeat(60)}`);
320
346
  log(`${BOLD} Security Report: ${CYAN}${url}${RESET}`);
347
+ if (partialCoverage) {
348
+ log(` ${YELLOW}Partial coverage:${RESET} some checks didn't run, so these findings are incomplete —`);
349
+ log(` an area with no finding was not necessarily tested.`);
350
+ }
321
351
  log(`${"─".repeat(60)}`);
322
352
  printVulnTable(allVulns);
323
353
  log(`\n${"─".repeat(60)}`);
@@ -328,9 +358,6 @@ async function scan(url) {
328
358
  }
329
359
  log("");
330
360
  }
331
- /* ------------------------------------------------------------------ */
332
- /* CLI argument parsing */
333
- /* ------------------------------------------------------------------ */
334
361
  function printHelp() {
335
362
  log(`
336
363
  ${BOLD}perfai${RESET} — Perfai Security Scanner CLI v${SERVER_INFO.version}
@@ -350,6 +377,12 @@ ${BOLD}AUTHENTICATION${RESET}
350
377
 
351
378
  Or omit them — a browser window will open for you to sign in.
352
379
 
380
+ ${BOLD}EXIT CODES${RESET}
381
+ 0 Completed (including partial coverage)
382
+ 1 Error, or still running when the CLI stopped waiting
383
+ ${EXIT_NEEDS_INPUT} Waiting on your input (e.g. a login for the app)
384
+ ${EXIT_INTERRUPTED} Interrupted or cancelled
385
+
353
386
  ${BOLD}MORE INFO${RESET}
354
387
  https://cloud.perfai.ai
355
388
  https://mcp-server.perfai.ai
@@ -1,13 +1,8 @@
1
1
  import axios from "axios";
2
2
  import { API_BASE_URL, ORGANIZATIONS_URL } from "../config.js";
3
- import { ApiError, formatApiError } from "./errors.js";
4
- /**
5
- * `orgId` overrides the X-Org-ID header for this one request without changing
6
- * the session's selected org — used to search other orgs for an app by name.
7
- */
3
+ import { ApiError, describeFailedRequest, formatApiError } from "./errors.js";
8
4
  async function request(auth, config, allowReauth = true) {
9
- const { orgId: orgOverride, ...axiosConfig } = config;
10
- const orgId = orgOverride ?? auth.getSelectedOrgId();
5
+ const orgId = auth.getSelectedOrgId();
11
6
  if (!auth.isAuthenticated()) {
12
7
  if (auth.hasCredentials()) {
13
8
  await auth.login();
@@ -18,11 +13,11 @@ async function request(auth, config, allowReauth = true) {
18
13
  }
19
14
  try {
20
15
  const response = await axios.request({
21
- ...axiosConfig,
16
+ ...config,
22
17
  baseURL: API_BASE_URL,
23
18
  timeout: 30_000,
24
19
  headers: {
25
- ...axiosConfig.headers,
20
+ ...config.headers,
26
21
  Authorization: `Bearer ${auth.getToken()}`,
27
22
  ...(orgId ? { "X-Org-ID": orgId } : {}),
28
23
  "Content-Type": "application/json",
@@ -33,13 +28,12 @@ async function request(auth, config, allowReauth = true) {
33
28
  catch (error) {
34
29
  if (axios.isAxiosError(error)) {
35
30
  const status = error.response?.status;
36
- // Tokens are short-lived (per docs) — transparently re-auth once on 401.
37
- if (status === 401 && allowReauth && auth.hasCredentials()) {
31
+ if (status === 401 && allowReauth && auth.canReauthenticate()) {
38
32
  console.error("Access token rejected (401) — re-authenticating and retrying once.");
39
33
  await auth.login();
40
34
  return request(auth, config, false);
41
35
  }
42
- console.error(`API request failed: ${config.method?.toUpperCase()} ${config.url}`, status, error.response?.data);
36
+ console.error(`API request failed: ${describeFailedRequest(config.method, config.url, error)}`);
43
37
  throw new ApiError(formatApiError(error), status, error.response?.data);
44
38
  }
45
39
  throw error;
@@ -51,8 +45,8 @@ export function registerApp(auth, input) {
51
45
  export function getApp(auth, appId) {
52
46
  return request(auth, { method: "GET", url: `/apps/${encodeURIComponent(appId)}` });
53
47
  }
54
- export function listApps(auth, params, orgId) {
55
- return request(auth, { method: "GET", url: "/apps", params, orgId });
48
+ export function listApps(auth, params) {
49
+ return request(auth, { method: "GET", url: "/apps", params });
56
50
  }
57
51
  export function submitAccountSetup(auth, appId, credentials) {
58
52
  return request(auth, {
@@ -77,17 +71,21 @@ export function getVulnerabilities(auth, appId, params) {
77
71
  params,
78
72
  });
79
73
  }
80
- /** Pages through every finding for an app (the API caps pageSize at 100). */
81
- export async function getAllVulnerabilities(auth, appId) {
74
+ export async function listAllVulnerabilities(auth, appId, filters = {}) {
82
75
  const all = [];
76
+ let dismissedCount = null;
83
77
  for (let page = 1;; page++) {
84
- const result = await getVulnerabilities(auth, appId, { page, pageSize: 100 });
78
+ const result = await getVulnerabilities(auth, appId, { ...filters, page, pageSize: 100 });
79
+ if (page === 1 && typeof result.dismissedCount === "number")
80
+ dismissedCount = result.dismissedCount;
85
81
  all.push(...result.data);
86
82
  if (result.data.length === 0 || all.length >= result.total)
87
- return all;
83
+ return { data: all, dismissedCount };
88
84
  }
89
85
  }
90
- /** The dismiss / fix endpoints accept an optional comment (max 1000 chars) stored on the finding. */
86
+ export async function getAllVulnerabilities(auth, appId, filters = {}) {
87
+ return (await listAllVulnerabilities(auth, appId, filters)).data;
88
+ }
91
89
  function actionBody(comment) {
92
90
  const trimmed = comment?.trim();
93
91
  return trimmed ? { comment: trimmed.slice(0, 1000) } : undefined;
@@ -109,12 +107,6 @@ export function fixVulnerability(auth, id, comment) {
109
107
  data: actionBody(comment),
110
108
  });
111
109
  }
112
- /**
113
- * Lists the organizations (tenants) this account belongs to, plus whichever
114
- * one the account was last using. Separate base URL from the rest of the
115
- * API (lives under /api/v1, not /v1), so this bypasses the shared request()
116
- * helper rather than fighting its baseURL binding.
117
- */
118
110
  export async function getUserOrganizations(auth) {
119
111
  if (!auth.isAuthenticated()) {
120
112
  throw new Error("Not authenticated. Run the `login` tool first.");
@@ -128,6 +120,7 @@ export async function getUserOrganizations(auth) {
128
120
  }
129
121
  catch (error) {
130
122
  if (axios.isAxiosError(error)) {
123
+ console.error(`Organization list request failed: ${describeFailedRequest("GET", ORGANIZATIONS_URL, error)}`);
131
124
  throw new ApiError(formatApiError(error), error.response?.status, error.response?.data);
132
125
  }
133
126
  throw error;
@@ -1,62 +1,72 @@
1
1
  import axios from "axios";
2
2
  import { AUTH_TOKEN_URL, PERFAI_EMAIL, PERFAI_PASSWORD, PERFAI_TOKEN } from "../config.js";
3
- import { formatApiError } from "./errors.js";
4
- /**
5
- * Holds the auth token plus the small amount of "current selection" state
6
- * (app / task / cached vulnerability sequence numbers) that lets tools refer
7
- * to things by short-lived sequence numbers instead of raw IDs, matching the
8
- * UX of listing something then acting on "#3".
9
- */
3
+ import { describeFailedRequest, formatApiError } from "./errors.js";
4
+ const API_KEY_PATTERN = /^pfk_([A-Za-z0-9]{12})_[A-Za-z0-9]{40,}$/;
5
+ export function isPerfaiApiKey(token) {
6
+ return API_KEY_PATTERN.test(token);
7
+ }
8
+ export function apiKeyId(token) {
9
+ return API_KEY_PATTERN.exec(token)?.[1];
10
+ }
10
11
  export class AuthManager {
11
- email = PERFAI_EMAIL;
12
- password = PERFAI_PASSWORD;
12
+ email;
13
+ password;
13
14
  idToken;
14
15
  authenticatedEmail;
15
16
  authMethod = "none";
16
17
  currentAppId;
17
18
  currentAppUrl;
18
19
  currentTaskId;
20
+ currentTaskAppId;
19
21
  vulnCache = new Map();
20
22
  vulnCacheAppId;
21
23
  organizations = [];
22
24
  selectedOrgId;
23
- defaultOrgId;
24
- /** appId → org it lives in, for apps surfaced by a cross-org name lookup. */
25
- appOrgHints = new Map();
26
- constructor() {
27
- // Auto-load PERFAI_TOKEN if set (headless fallback for Replit/Lovable/Bolt).
28
- // This takes priority over email/password since it's an existing, validated token.
25
+ constructor({ useEnv = true } = {}) {
26
+ if (!useEnv)
27
+ return;
28
+ this.email = PERFAI_EMAIL;
29
+ this.password = PERFAI_PASSWORD;
29
30
  if (PERFAI_TOKEN) {
30
31
  this.setToken(PERFAI_TOKEN);
31
- console.error("Loaded PERFAI_TOKEN from environment (headless token auth).");
32
+ console.error(`Loaded PERFAI_TOKEN from environment (${this.authMethod} auth).`);
32
33
  }
33
34
  }
34
35
  hasCredentials() {
35
36
  return Boolean(this.email && this.password);
36
37
  }
38
+ canReauthenticate() {
39
+ return this.authMethod !== "api_key" && this.hasCredentials();
40
+ }
37
41
  setCredentials(email, password) {
38
42
  this.email = email;
39
43
  this.password = password;
40
44
  }
41
- /**
42
- * Accept a pre-existing id_token directly — no email/password exchange.
43
- * Used by: PERFAI_TOKEN env var, OAuth PKCE browser flow, HTTP bearer auth.
44
- */
45
- setToken(token, email, method = "token") {
45
+ setToken(token, email, method) {
46
46
  this.idToken = token;
47
- this.authMethod = method;
47
+ this.authMethod = method ?? (isPerfaiApiKey(token) ? "api_key" : "token");
48
48
  if (email) {
49
49
  this.authenticatedEmail = email;
50
50
  }
51
+ else if (isPerfaiApiKey(token)) {
52
+ this.authenticatedEmail = undefined;
53
+ }
51
54
  else {
52
- // Try to extract email from JWT payload
53
55
  try {
54
56
  const payload = JSON.parse(Buffer.from(token.split(".")[1], "base64url").toString());
55
57
  this.authenticatedEmail = payload.email ?? payload.sub;
56
58
  }
57
- catch { /* non-JWT or malformed — that's fine */ }
59
+ catch { }
58
60
  }
59
61
  }
62
+ describeIdentity() {
63
+ if (this.authenticatedEmail)
64
+ return this.authenticatedEmail;
65
+ const keyId = this.idToken ? apiKeyId(this.idToken) : undefined;
66
+ if (keyId)
67
+ return `API key pfk_${keyId}_…`;
68
+ return `unknown (${this.authMethod}-based session)`;
69
+ }
60
70
  isAuthenticated() {
61
71
  return Boolean(this.idToken);
62
72
  }
@@ -80,7 +90,8 @@ export class AuthManager {
80
90
  const response = await axios.post(AUTH_TOKEN_URL, { username: useEmail, password: usePassword }, { headers: { "Content-Type": "application/json" }, timeout: 30_000 });
81
91
  const idToken = response.data?.id_token;
82
92
  if (!idToken) {
83
- throw new Error(`Login response did not include an id_token. Response: ${JSON.stringify(response.data)}`);
93
+ console.error(`Login for ${useEmail}: ${response.status} response without an id_token`);
94
+ throw new Error("Login response did not include an id_token");
84
95
  }
85
96
  this.idToken = idToken;
86
97
  this.email = useEmail;
@@ -92,7 +103,7 @@ export class AuthManager {
92
103
  }
93
104
  catch (error) {
94
105
  if (axios.isAxiosError(error)) {
95
- console.error(`Login failed for ${useEmail}:`, error.response?.status, error.response?.data);
106
+ console.error(`Login failed for ${useEmail}: ${describeFailedRequest("POST", AUTH_TOKEN_URL, error)}`);
96
107
  throw new Error(formatApiError(error));
97
108
  }
98
109
  throw error;
@@ -105,29 +116,23 @@ export class AuthManager {
105
116
  this.currentAppId = undefined;
106
117
  this.currentAppUrl = undefined;
107
118
  this.currentTaskId = undefined;
119
+ this.currentTaskAppId = undefined;
108
120
  this.vulnCache.clear();
109
121
  this.vulnCacheAppId = undefined;
110
122
  this.organizations = [];
111
123
  this.selectedOrgId = undefined;
112
- this.defaultOrgId = undefined;
113
- this.appOrgHints.clear();
114
124
  }
115
- /** Returns the cached org list (empty until manage_organizations fetches it). */
116
125
  getOrganizations() {
117
126
  return this.organizations;
118
127
  }
119
128
  getSelectedOrgId() {
120
129
  return this.selectedOrgId;
121
130
  }
122
- /** Selects an org by ID; subsequent API calls send it as X-Org-ID. */
123
131
  setSelectedOrgId(orgId) {
124
132
  this.selectedOrgId = orgId;
125
133
  }
126
- /** Caches the org list from get_users_orgs; auto-selects currentOrgId, or
127
- * the first org if nothing is selected yet (mirrors login-time default). */
128
134
  setOrganizations(organizations, currentOrgId) {
129
135
  this.organizations = organizations;
130
- this.defaultOrgId = currentOrgId;
131
136
  if (currentOrgId) {
132
137
  this.selectedOrgId = currentOrgId;
133
138
  }
@@ -135,32 +140,19 @@ export class AuthManager {
135
140
  this.selectedOrgId = organizations[0].org_id;
136
141
  }
137
142
  }
138
- /** The org the API falls back to when no X-Org-ID is sent (currentOrg from get_users_orgs). */
139
- getDefaultOrgId() {
140
- return this.defaultOrgId;
141
- }
142
- /** Caches the org list for app-name resolution WITHOUT changing the selected org. */
143
- cacheOrganizationList(organizations, defaultOrgId) {
144
- this.organizations = organizations;
145
- this.defaultOrgId = defaultOrgId;
146
- }
147
- rememberAppOrg(appId, orgId) {
148
- this.appOrgHints.set(appId, orgId);
149
- }
150
- getAppOrg(appId) {
151
- return this.appOrgHints.get(appId);
152
- }
153
143
  setCurrentApp(appId, appUrl) {
154
144
  this.currentAppId = appId;
155
145
  this.currentAppUrl = appUrl;
156
146
  }
157
- /** Caches a vulnerability page (keyed by 1-based sequence number) so tools can refer to "#3". */
147
+ setCurrentTask(taskId, appId) {
148
+ this.currentTaskId = taskId;
149
+ this.currentTaskAppId = appId;
150
+ }
158
151
  cacheVulnerabilities(appId, vulnerabilities) {
159
152
  this.vulnCache.clear();
160
153
  this.vulnCacheAppId = appId;
161
154
  vulnerabilities.forEach((v, i) => this.vulnCache.set(i + 1, v));
162
155
  }
163
- /** Looks up a cached vulnerability by sequence number ("3") or raw ID, if it was seen in the last listing. */
164
156
  getCachedVulnerability(appId, idOrSequence) {
165
157
  if (this.vulnCacheAppId !== appId)
166
158
  return undefined;
@@ -174,7 +166,6 @@ export class AuthManager {
174
166
  }
175
167
  return undefined;
176
168
  }
177
- /** Resolves a raw vulnerability ID or a cached sequence number ("3") to an ID. */
178
169
  resolveVulnerabilityId(appId, idOrSequence) {
179
170
  const cached = this.getCachedVulnerability(appId, idOrSequence);
180
171
  const id = cached?.id ?? cached?._id;
@@ -1,29 +1,57 @@
1
- /** An API failure that preserves the status + RFC 9457 Problem Details body, so callers can react to specific fields (e.g. an existing appId on a 409). */
1
+ import axios from "axios";
2
2
  export class ApiError extends Error {
3
3
  status;
4
- data;
5
4
  constructor(message, status, data) {
6
5
  super(message);
7
6
  this.status = status;
8
- this.data = data;
9
7
  this.name = "ApiError";
8
+ Object.defineProperty(this, "data", { value: data, enumerable: false });
10
9
  }
11
10
  }
12
- /** Formats an axios error whose body follows RFC 9457 Problem Details into a readable message. */
11
+ export function isAppNotRegisteredError(error) {
12
+ return (error instanceof ApiError &&
13
+ error.status === 400 &&
14
+ typeof error.data?.type === "string" &&
15
+ error.data.type.endsWith("/app-not-registered"));
16
+ }
17
+ export function isForbiddenError(error) {
18
+ return error instanceof ApiError && error.status === 403;
19
+ }
20
+ function oneLine(value, max) {
21
+ if (typeof value !== "string")
22
+ return "";
23
+ const text = value.replace(/\s+/g, " ").trim();
24
+ return text.length > max ? `${text.slice(0, max)}…` : text;
25
+ }
26
+ function networkCode(error) {
27
+ return typeof error.code === "string" && /^[A-Z0-9_]{2,40}$/.test(error.code) ? error.code : "";
28
+ }
13
29
  export function formatApiError(error) {
14
30
  const status = error.response?.status;
15
31
  const data = error.response?.data;
32
+ const problem = data && typeof data === "object" ? data : undefined;
33
+ const title = oneLine(problem?.title, 120);
34
+ if (!error.response) {
35
+ const code = networkCode(error);
36
+ return `Could not reach the Perfai API${code ? ` (${code})` : ""}. Try again shortly.`;
37
+ }
16
38
  if (status === 429) {
17
- const retryAfter = error.response?.headers?.["retry-after"];
18
- return `Rate limited (429)${retryAfter ? ` — retry after ${retryAfter}s` : ""}: ${data?.title ?? "Too many requests"}`;
39
+ const retryAfter = oneLine(error.response.headers?.["retry-after"], 20);
40
+ return `Rate limited (429)${retryAfter ? ` — retry after ${retryAfter}s` : ""}: ${title || "Too many requests"}`;
19
41
  }
20
- if (data && typeof data === "object" && ("title" in data || "type" in data)) {
21
- const title = data.title ?? "Request failed";
22
- const extra = Object.entries(data)
23
- .filter(([k]) => !["type", "title", "status"].includes(k))
24
- .map(([k, v]) => `${k}: ${typeof v === "string" ? v : JSON.stringify(v)}`)
25
- .join(", ");
26
- return `[${status ?? "?"}] ${title}${extra ? ` (${extra})` : ""}`;
42
+ const detail = oneLine(problem?.detail, 300);
43
+ return `[${status}] ${title || "Request failed"}${detail ? ` (${detail})` : ""}`;
44
+ }
45
+ export function describeFailedRequest(method, url, error) {
46
+ const target = `${(method ?? "GET").toUpperCase()} ${url ?? "?"}`;
47
+ if (!error.response) {
48
+ const code = networkCode(error);
49
+ return `${target} → no response${code ? ` (${code})` : ""}`;
27
50
  }
28
- return `[${status ?? "?"}] ${error.message}`;
51
+ const data = error.response.data;
52
+ const title = data && typeof data === "object" ? oneLine(data.title, 120) : "";
53
+ return `${target} → ${error.response.status}${title ? ` ${title}` : ""}`;
54
+ }
55
+ export function loggable(error) {
56
+ return axios.isAxiosError(error) ? describeFailedRequest(error.config?.method, error.config?.url, error) : error;
29
57
  }