perfai-cloud-mcp 0.5.2 → 0.7.2

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.
@@ -1,21 +1,82 @@
1
1
  import { createHash, timingSafeEqual } from "node:crypto";
2
2
  import { apiKeyId, isPerfaiApiKey } from "../client/authManager.js";
3
- import { isJWT, validateBearerToken } from "./tokenValidator.js";
3
+ import { MCP_CLAIM_NS, MCP_OAUTH_REQUIRED_SCOPES, MCP_OAUTH_SCOPES, OAUTH_ISSUER, } from "../config.js";
4
+ import { decodeJWTPayload, isJWT, validateBearerToken } from "./tokenValidator.js";
5
+ const SCOPE_LIST = MCP_OAUTH_SCOPES.join(" ");
4
6
  export function hashCredential(value) {
5
7
  return createHash("sha256").update(value).digest("hex");
6
8
  }
7
9
  export function constantTimeEquals(a, b) {
8
10
  return timingSafeEqual(createHash("sha256").update(a).digest(), createHash("sha256").update(b).digest());
9
11
  }
10
- function reject(res, status, message) {
11
- res.status(status).json({ jsonrpc: "2.0", error: { code: -32001, message }, id: null });
12
+ export function resourceMetadataUrl(resourceUrl) {
13
+ return `${new URL(resourceUrl).origin}/.well-known/oauth-protected-resource`;
12
14
  }
13
- export function createBearerAuth({ mcpApiKey, validateToken = validateBearerToken, }) {
15
+ export function protectedResourceMetadata(resourceUrl, docsUrl) {
16
+ return {
17
+ resource: resourceUrl,
18
+ authorization_servers: [OAUTH_ISSUER],
19
+ scopes_supported: MCP_OAUTH_SCOPES,
20
+ bearer_methods_supported: ["header"],
21
+ resource_name: "Perfai",
22
+ resource_documentation: docsUrl,
23
+ };
24
+ }
25
+ function audiences(payload) {
26
+ const aud = payload?.aud;
27
+ if (typeof aud === "string")
28
+ return [aud];
29
+ return Array.isArray(aud) ? aud.filter((a) => typeof a === "string") : [];
30
+ }
31
+ function scopesOf(payload) {
32
+ return typeof payload.scope === "string" ? payload.scope.split(/\s+/).filter(Boolean) : [];
33
+ }
34
+ function stringClaim(payload, key) {
35
+ const value = payload[key];
36
+ return typeof value === "string" && value ? value : undefined;
37
+ }
38
+ function body(message) {
39
+ return { jsonrpc: "2.0", error: { code: -32001, message }, id: null };
40
+ }
41
+ export function createBearerAuth({ mcpApiKey, resourceUrl, webuiClientIds = [], validateToken = validateBearerToken, }) {
42
+ const metadataUrl = resourceUrl ? resourceMetadataUrl(resourceUrl) : undefined;
43
+ function unauthorized(res, message, tokenPresented) {
44
+ if (metadataUrl) {
45
+ res.setHeader("WWW-Authenticate", `Bearer resource_metadata="${metadataUrl}", scope="${SCOPE_LIST}"` +
46
+ (tokenPresented ? ', error="invalid_token"' : ""));
47
+ }
48
+ res.status(401).json(body(message));
49
+ }
50
+ function insufficientScope(res, message) {
51
+ if (metadataUrl) {
52
+ res.setHeader("WWW-Authenticate", `Bearer error="insufficient_scope", scope="${SCOPE_LIST}", resource_metadata="${metadataUrl}"`);
53
+ }
54
+ res.status(403).json(body(message));
55
+ }
56
+ async function verified(token, res) {
57
+ const result = await validateToken(token);
58
+ if (!result.valid || !result.payload) {
59
+ console.error(`Token rejected at gate: ${result.error ?? "invalid token"}`);
60
+ unauthorized(res, `Token validation failed: ${result.error ?? "invalid token"}.`, true);
61
+ return undefined;
62
+ }
63
+ if (result.payload.iss !== OAUTH_ISSUER) {
64
+ console.error("Token rejected at gate: wrong issuer");
65
+ unauthorized(res, "Token validation failed: wrong issuer.", true);
66
+ return undefined;
67
+ }
68
+ if (!stringClaim(result.payload, "sub")) {
69
+ console.error("Token rejected at gate: no subject");
70
+ unauthorized(res, "Token validation failed: no subject.", true);
71
+ return undefined;
72
+ }
73
+ return result.payload;
74
+ }
14
75
  return async (req, res, next) => {
15
76
  const match = /^Bearer\s+(\S+)\s*$/i.exec(req.headers.authorization ?? "");
16
77
  if (!match) {
17
- reject(res, 401, "Unauthorized: Bearer token required. " +
18
- "Use a PerfAI API key (pfk_…) or your Perfai id_token as the bearer value.");
78
+ unauthorized(res, "Unauthorized: Bearer token required. " +
79
+ "Sign in with OAuth, or use a PerfAI API key (pfk_…) as the bearer value.", false);
19
80
  return;
20
81
  }
21
82
  const token = match[1];
@@ -30,24 +91,47 @@ export function createBearerAuth({ mcpApiKey, validateToken = validateBearerToke
30
91
  return next();
31
92
  }
32
93
  if (isJWT(token)) {
33
- const result = await validateToken(token);
34
- if (result.valid) {
35
- req.perfaiAuth = { method: "jwt", credentialHash, token, email: result.email };
36
- console.error(`Authenticated (token): ${result.email ?? "unknown"}`);
94
+ const aud = audiences(decodeJWTPayload(token));
95
+ if (resourceUrl && aud.includes(resourceUrl)) {
96
+ const payload = await verified(token, res);
97
+ if (!payload)
98
+ return;
99
+ const scopes = scopesOf(payload);
100
+ if (!MCP_OAUTH_REQUIRED_SCOPES.every((scope) => scopes.includes(scope))) {
101
+ console.error("Token rejected at gate: insufficient scope");
102
+ insufficientScope(res, `Insufficient scope: ${MCP_OAUTH_REQUIRED_SCOPES.join(" and ")} are required.`);
103
+ return;
104
+ }
105
+ const email = stringClaim(payload, `${MCP_CLAIM_NS}email`);
106
+ const sub = stringClaim(payload, "sub");
107
+ req.perfaiAuth = { method: "mcp_oauth", credentialHash, token, email, sub, scopes };
108
+ console.error(`Authenticated (mcp_oauth): ${email ?? sub}`);
37
109
  return next();
38
110
  }
39
- console.error(`Token rejected at gate: ${result.error ?? "invalid token"}`);
40
- reject(res, 401, `Token validation failed: ${result.error ?? "invalid token"}. ` +
41
- "Use a PerfAI API key (pfk_…), or get a fresh token via OAuth login at https://cloud.perfai.ai.");
111
+ if (webuiClientIds.some((id) => aud.includes(id))) {
112
+ const payload = await verified(token, res);
113
+ if (!payload)
114
+ return;
115
+ const sub = stringClaim(payload, "sub");
116
+ const email = stringClaim(payload, "email") ?? sub;
117
+ req.perfaiAuth = { method: "jwt", credentialHash, token, email, sub };
118
+ console.error(`Authenticated (token): ${email}`);
119
+ return next();
120
+ }
121
+ console.error("Token rejected at gate: audience is not this server");
122
+ unauthorized(res, "Token validation failed: this token is not for the Perfai MCP server.", true);
42
123
  return;
43
124
  }
44
125
  console.error("Unrecognized bearer rejected at gate (not an API key or JWT)");
45
- reject(res, 401, "Unrecognized token format. Provide either: " +
46
- "(1) a PerfAI API key (pfk_…), or " +
47
- "(2) a Perfai id_token from OAuth login.");
126
+ unauthorized(res, "Unrecognized token format. Sign in with OAuth, or use a PerfAI API key (pfk_…).", true);
48
127
  };
49
128
  }
50
- export function sameCaller(req, sessionCredentialHash) {
51
- const presented = req.perfaiAuth?.credentialHash;
52
- return Boolean(presented) && constantTimeEquals(presented, sessionCredentialHash);
129
+ export function sessionKey(gate) {
130
+ return gate.sub && (gate.method === "jwt" || gate.method === "mcp_oauth")
131
+ ? `sub:${gate.sub}`
132
+ : gate.credentialHash;
133
+ }
134
+ export function sameCaller(req, sessionKeyValue) {
135
+ const gate = req.perfaiAuth;
136
+ return Boolean(gate) && constantTimeEquals(sessionKey(gate), sessionKeyValue);
53
137
  }
@@ -33,17 +33,17 @@ export function startOAuthBrowserFlow() {
33
33
  callbackServer = null;
34
34
  }
35
35
  };
36
- const SUCCESS_HTML = `<!DOCTYPE html><html><head><meta charset="UTF-8">
37
- <title>Perfai — Authenticated</title>
38
- <style>*{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}
39
- .c{background:#fff;border-radius:12px;padding:40px;box-shadow:0 4px 24px rgba(0,0,0,.1);max-width:420px;text-align:center}
40
- h1{color:#38a169;font-size:24px;margin-bottom:12px}p{color:#666;font-size:14px;line-height:1.5}</style></head>
36
+ const SUCCESS_HTML = `<!DOCTYPE html><html><head><meta charset="UTF-8">
37
+ <title>Perfai — Authenticated</title>
38
+ <style>*{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}
39
+ .c{background:#fff;border-radius:12px;padding:40px;box-shadow:0 4px 24px rgba(0,0,0,.1);max-width:420px;text-align:center}
40
+ h1{color:#38a169;font-size:24px;margin-bottom:12px}p{color:#666;font-size:14px;line-height:1.5}</style></head>
41
41
  <body><div class="c"><h1>Authenticated!</h1><p>You can close this tab and return to your AI assistant.</p></div></body></html>`;
42
- const ERROR_HTML = (msg) => `<!DOCTYPE html><html><head><meta charset="UTF-8">
43
- <title>Perfai — Error</title>
44
- <style>*{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}
45
- .c{background:#fff;border-radius:12px;padding:40px;box-shadow:0 4px 24px rgba(0,0,0,.1);max-width:420px;text-align:center}
46
- h1{color:#e53e3e;font-size:24px;margin-bottom:12px}p{color:#666;font-size:14px;line-height:1.5}</style></head>
42
+ const ERROR_HTML = (msg) => `<!DOCTYPE html><html><head><meta charset="UTF-8">
43
+ <title>Perfai — Error</title>
44
+ <style>*{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}
45
+ .c{background:#fff;border-radius:12px;padding:40px;box-shadow:0 4px 24px rgba(0,0,0,.1);max-width:420px;text-align:center}
46
+ h1{color:#e53e3e;font-size:24px;margin-bottom:12px}p{color:#666;font-size:14px;line-height:1.5}</style></head>
47
47
  <body><div class="c"><h1>Login Failed</h1><p>${msg}</p></div></body></html>`;
48
48
  callbackServer = createServer(async (req, res) => {
49
49
  const url = new URL(req.url ?? "/", `http://localhost:${OAUTH_CALLBACK_PORT}`);
@@ -90,14 +90,15 @@ async function verifyJWT(token) {
90
90
  const email = payload.email ?? payload.sub;
91
91
  validatedTokens.set(tokenHash(token), {
92
92
  email,
93
+ payload,
93
94
  expiresAt: Math.min(Date.now() + CACHE_TTL_MS, payload.exp * 1000),
94
95
  });
95
- return { valid: true, email };
96
+ return { valid: true, email, payload };
96
97
  }
97
98
  export async function validateBearerToken(token) {
98
99
  const cached = validatedTokens.get(tokenHash(token));
99
100
  if (cached && Date.now() < cached.expiresAt) {
100
- return { valid: true, email: cached.email };
101
+ return { valid: true, email: cached.email, payload: cached.payload };
101
102
  }
102
103
  if (isJWT(token))
103
104
  return verifyJWT(token);
package/dist/cli.js CHANGED
@@ -64,25 +64,25 @@ function openBrowser(url) {
64
64
  : `xdg-open "${url}"`;
65
65
  exec(cmd, () => { });
66
66
  }
67
- const LOGIN_HTML = `<!DOCTYPE html><html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
68
- <title>Perfai Login</title><style>
69
- *{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}
70
- .c{background:#fff;border-radius:12px;padding:40px;box-shadow:0 4px 24px rgba(0,0,0,.1);width:100%;max-width:400px}
71
- .logo{text-align:center;margin-bottom:24px}.logo h1{font-size:24px;color:#111}.logo p{color:#666;font-size:14px;margin-top:4px}
72
- label{display:block;font-size:14px;font-weight:500;color:#333;margin-bottom:6px}
73
- 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}
74
- 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}
75
- .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}
76
- </style></head><body><div class="c"><div class="logo"><h1>Perfai</h1><p>Sign in with your cloud.perfai.ai account</p></div>
77
- <form id="f"><label for="e">Email</label><input type="email" id="e" placeholder="you@example.com" required autofocus>
78
- <label for="p">Password</label><input type="password" id="p" placeholder="Your password" required>
79
- <div class="err" id="x"></div><button type="submit" id="b">Sign in</button></form>
80
- <div class="ok" id="s">Authenticated! You can close this tab.</div></div>
81
- <script>document.getElementById('f').addEventListener('submit',async e=>{e.preventDefault();const b=document.getElementById('b'),x=document.getElementById('x');
82
- b.disabled=true;b.textContent='Signing in...';x.style.display='none';try{const r=await fetch('/auth',{method:'POST',headers:{'Content-Type':'application/json'},
83
- body:JSON.stringify({email:document.getElementById('e').value,password:document.getElementById('p').value})});const d=await r.json();
84
- if(d.ok){document.getElementById('f').style.display='none';document.getElementById('s').style.display='block'}
85
- else{x.textContent=d.message||'Login failed';x.style.display='block';b.disabled=false;b.textContent='Sign in'}}
67
+ const LOGIN_HTML = `<!DOCTYPE html><html><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1">
68
+ <title>Perfai Login</title><style>
69
+ *{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}
70
+ .c{background:#fff;border-radius:12px;padding:40px;box-shadow:0 4px 24px rgba(0,0,0,.1);width:100%;max-width:400px}
71
+ .logo{text-align:center;margin-bottom:24px}.logo h1{font-size:24px;color:#111}.logo p{color:#666;font-size:14px;margin-top:4px}
72
+ label{display:block;font-size:14px;font-weight:500;color:#333;margin-bottom:6px}
73
+ 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}
74
+ 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}
75
+ .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}
76
+ </style></head><body><div class="c"><div class="logo"><h1>Perfai</h1><p>Sign in with your cloud.perfai.ai account</p></div>
77
+ <form id="f"><label for="e">Email</label><input type="email" id="e" placeholder="you@example.com" required autofocus>
78
+ <label for="p">Password</label><input type="password" id="p" placeholder="Your password" required>
79
+ <div class="err" id="x"></div><button type="submit" id="b">Sign in</button></form>
80
+ <div class="ok" id="s">Authenticated! You can close this tab.</div></div>
81
+ <script>document.getElementById('f').addEventListener('submit',async e=>{e.preventDefault();const b=document.getElementById('b'),x=document.getElementById('x');
82
+ b.disabled=true;b.textContent='Signing in...';x.style.display='none';try{const r=await fetch('/auth',{method:'POST',headers:{'Content-Type':'application/json'},
83
+ body:JSON.stringify({email:document.getElementById('e').value,password:document.getElementById('p').value})});const d=await r.json();
84
+ if(d.ok){document.getElementById('f').style.display='none';document.getElementById('s').style.display='block'}
85
+ else{x.textContent=d.message||'Login failed';x.style.display='block';b.disabled=false;b.textContent='Sign in'}}
86
86
  catch{x.textContent='Connection error';x.style.display='block';b.disabled=false;b.textContent='Sign in'}});</script></body></html>`;
87
87
  function browserLogin(auth) {
88
88
  return new Promise((resolve, reject) => {
@@ -359,33 +359,33 @@ async function scan(url) {
359
359
  log("");
360
360
  }
361
361
  function printHelp() {
362
- log(`
363
- ${BOLD}perfai${RESET} — Perfai Security Scanner CLI v${SERVER_INFO.version}
364
-
365
- ${BOLD}USAGE${RESET}
366
- npx perfai scan <url> Scan an app for security vulnerabilities
367
- npx perfai scan --help Show this help
368
-
369
- ${BOLD}EXAMPLES${RESET}
370
- npx perfai scan https://api.myapp.com
371
- npx perfai scan https://staging.example.com
372
-
373
- ${BOLD}AUTHENTICATION${RESET}
374
- Set environment variables for non-interactive login:
375
- PERFAI_EMAIL=you@example.com
376
- PERFAI_PASSWORD=your-password
377
-
378
- Or omit them — a browser window will open for you to sign in.
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
-
386
- ${BOLD}MORE INFO${RESET}
387
- https://cloud.perfai.ai
388
- https://mcp-server.perfai.ai
362
+ log(`
363
+ ${BOLD}perfai${RESET} — Perfai Security Scanner CLI v${SERVER_INFO.version}
364
+
365
+ ${BOLD}USAGE${RESET}
366
+ npx perfai scan <url> Scan an app for security vulnerabilities
367
+ npx perfai scan --help Show this help
368
+
369
+ ${BOLD}EXAMPLES${RESET}
370
+ npx perfai scan https://api.myapp.com
371
+ npx perfai scan https://staging.example.com
372
+
373
+ ${BOLD}AUTHENTICATION${RESET}
374
+ Set environment variables for non-interactive login:
375
+ PERFAI_EMAIL=you@example.com
376
+ PERFAI_PASSWORD=your-password
377
+
378
+ Or omit them — a browser window will open for you to sign in.
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
+
386
+ ${BOLD}MORE INFO${RESET}
387
+ https://cloud.perfai.ai
388
+ https://mcp-server.perfai.ai
389
389
  `);
390
390
  }
391
391
  async function main() {
@@ -1,6 +1,7 @@
1
1
  import axios from "axios";
2
2
  import { API_BASE_URL, ORGANIZATIONS_URL } from "../config.js";
3
- import { ApiError, describeFailedRequest, formatApiError } from "./errors.js";
3
+ import { ApiError, describeFailedRequest, formatApiError, TestRunningError } from "./errors.js";
4
+ import { isPaywallReply, markPaywall, relayedForbiddenText, relayToUser, SIGN_IN_EXPIRED_TEXT } from "./relay.js";
4
5
  async function request(auth, config, allowReauth = true) {
5
6
  const orgId = auth.getSelectedOrgId();
6
7
  if (!auth.isAuthenticated()) {
@@ -28,6 +29,7 @@ async function request(auth, config, allowReauth = true) {
28
29
  catch (error) {
29
30
  if (axios.isAxiosError(error)) {
30
31
  const status = error.response?.status;
32
+ relayIfFixedReply(auth, error.response?.status, error.response?.data);
31
33
  if (status === 401 && allowReauth && auth.canReauthenticate()) {
32
34
  console.error("Access token rejected (401) — re-authenticating and retrying once.");
33
35
  await auth.login();
@@ -39,14 +41,32 @@ async function request(auth, config, allowReauth = true) {
39
41
  throw error;
40
42
  }
41
43
  }
42
- export function registerApp(auth, input) {
43
- return request(auth, { method: "POST", url: "/apps", data: input });
44
+ function relayIfFixedReply(auth, status, data) {
45
+ if (isPaywallReply(status, data))
46
+ markPaywall();
47
+ if (status === 401 && auth.getAuthMethod() === "mcp_oauth")
48
+ relayToUser(SIGN_IN_EXPIRED_TEXT);
49
+ if (status === 403) {
50
+ const text = relayedForbiddenText(data);
51
+ if (text)
52
+ relayToUser(text);
53
+ }
54
+ }
55
+ function notingPlan(auth, result) {
56
+ const records = "data" in result && Array.isArray(result.data) ? result.data : [result];
57
+ const plan = records.find((app) => app?.plan)?.plan;
58
+ if (plan)
59
+ auth.notePlan(plan);
60
+ return result;
44
61
  }
45
- export function getApp(auth, appId) {
46
- return request(auth, { method: "GET", url: `/apps/${encodeURIComponent(appId)}` });
62
+ export async function registerApp(auth, input) {
63
+ return notingPlan(auth, await request(auth, { method: "POST", url: "/apps", data: input }));
47
64
  }
48
- export function listApps(auth, params) {
49
- return request(auth, { method: "GET", url: "/apps", params });
65
+ export async function getApp(auth, appId) {
66
+ return notingPlan(auth, await request(auth, { method: "GET", url: `/apps/${encodeURIComponent(appId)}` }));
67
+ }
68
+ export async function listApps(auth, params) {
69
+ return notingPlan(auth, await request(auth, { method: "GET", url: "/apps", params }));
50
70
  }
51
71
  export function submitAccountSetup(auth, appId, credentials) {
52
72
  return request(auth, {
@@ -64,18 +84,21 @@ export function runSecurityAgent(auth, appId) {
64
84
  export function getTask(auth, taskId) {
65
85
  return request(auth, { method: "GET", url: `/tasks/${encodeURIComponent(taskId)}` });
66
86
  }
67
- export function getVulnerabilities(auth, appId, params) {
68
- return request(auth, {
87
+ export async function getVulnerabilities(auth, appId, params) {
88
+ const result = await request(auth, {
69
89
  method: "GET",
70
90
  url: `/apps/${encodeURIComponent(appId)}/vulnerabilities`,
71
91
  params,
72
92
  });
93
+ return { ...result, data: result.data ?? [], total: result.total ?? 0 };
73
94
  }
74
95
  export async function listAllVulnerabilities(auth, appId, filters = {}) {
75
96
  const all = [];
76
97
  let dismissedCount = null;
77
98
  for (let page = 1;; page++) {
78
99
  const result = await getVulnerabilities(auth, appId, { ...filters, page, pageSize: 100 });
100
+ if (result.status === "RUN_IN_PROGRESS")
101
+ throw new TestRunningError();
79
102
  if (page === 1 && typeof result.dismissedCount === "number")
80
103
  dismissedCount = result.dismissedCount;
81
104
  all.push(...result.data);
@@ -120,6 +143,7 @@ export async function getUserOrganizations(auth) {
120
143
  }
121
144
  catch (error) {
122
145
  if (axios.isAxiosError(error)) {
146
+ relayIfFixedReply(auth, error.response?.status, error.response?.data);
123
147
  console.error(`Organization list request failed: ${describeFailedRequest("GET", ORGANIZATIONS_URL, error)}`);
124
148
  throw new ApiError(formatApiError(error), error.response?.status, error.response?.data);
125
149
  }
@@ -14,6 +14,7 @@ export class AuthManager {
14
14
  idToken;
15
15
  authenticatedEmail;
16
16
  authMethod = "none";
17
+ scopes = [];
17
18
  currentAppId;
18
19
  currentAppUrl;
19
20
  currentTaskId;
@@ -22,6 +23,8 @@ export class AuthManager {
22
23
  vulnCacheAppId;
23
24
  organizations = [];
24
25
  selectedOrgId;
26
+ plan;
27
+ lastTests = new Map();
25
28
  constructor({ useEnv = true } = {}) {
26
29
  if (!useEnv)
27
30
  return;
@@ -59,6 +62,12 @@ export class AuthManager {
59
62
  catch { }
60
63
  }
61
64
  }
65
+ setScopes(scopes) {
66
+ this.scopes = scopes ? [...scopes] : [];
67
+ }
68
+ hasScope(scope) {
69
+ return this.scopes.includes(scope);
70
+ }
62
71
  describeIdentity() {
63
72
  if (this.authenticatedEmail)
64
73
  return this.authenticatedEmail;
@@ -121,6 +130,21 @@ export class AuthManager {
121
130
  this.vulnCacheAppId = undefined;
122
131
  this.organizations = [];
123
132
  this.selectedOrgId = undefined;
133
+ this.plan = undefined;
134
+ this.lastTests.clear();
135
+ }
136
+ notePlan(plan) {
137
+ if (plan === "free" || plan === "paid")
138
+ this.plan = plan;
139
+ }
140
+ getPlan() {
141
+ return this.plan;
142
+ }
143
+ rememberLastTest(appId, completedAt) {
144
+ this.lastTests.set(appId, completedAt);
145
+ }
146
+ lastTestOf(appId) {
147
+ return this.lastTests.get(appId);
124
148
  }
125
149
  getOrganizations() {
126
150
  return this.organizations;
@@ -129,11 +153,15 @@ export class AuthManager {
129
153
  return this.selectedOrgId;
130
154
  }
131
155
  setSelectedOrgId(orgId) {
156
+ if (orgId !== this.selectedOrgId)
157
+ this.plan = undefined;
132
158
  this.selectedOrgId = orgId;
133
159
  }
134
160
  setOrganizations(organizations, currentOrgId) {
135
161
  this.organizations = organizations;
136
162
  if (currentOrgId) {
163
+ if (currentOrgId !== this.selectedOrgId)
164
+ this.plan = undefined;
137
165
  this.selectedOrgId = currentOrgId;
138
166
  }
139
167
  else if (!this.selectedOrgId && organizations.length > 0) {
@@ -17,6 +17,17 @@ export function isAppNotRegisteredError(error) {
17
17
  export function isForbiddenError(error) {
18
18
  return error instanceof ApiError && error.status === 403;
19
19
  }
20
+ export class TestRunningError extends Error {
21
+ constructor() {
22
+ super("⏳ A security test is running on this app. Its findings are available when it finishes, so try again then.");
23
+ this.name = "TestRunningError";
24
+ }
25
+ }
26
+ export function findingsFailureText(error) {
27
+ if (error instanceof TestRunningError)
28
+ return error.message;
29
+ return `❌ Failed to fetch vulnerabilities: ${error instanceof Error ? error.message : String(error)}`;
30
+ }
20
31
  function oneLine(value, max) {
21
32
  if (typeof value !== "string")
22
33
  return "";
@@ -0,0 +1,61 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+ const toolCall = new AsyncLocalStorage();
3
+ export const SIGN_IN_EXPIRED_TEXT = "Your Perfai sign-in expired. Reconnect Perfai in your AI tool.";
4
+ export const RELAYED_FORBIDDEN_CODES = new Set(["signup_not_allowed", "email_not_verified"]);
5
+ export function relayToUser(text) {
6
+ const store = toolCall.getStore();
7
+ if (store && store.relay === undefined)
8
+ store.relay = text;
9
+ }
10
+ export const FREE_PLAN_FOOTER = "—\nFree plan: top 5 issues shown, 500 credits/month, no scheduled tests. Upgrade to Pro: https://cloud.perfai.ai/usage";
11
+ export function isPaywallReply(status, data) {
12
+ if (status === 402)
13
+ return true;
14
+ const type = data && typeof data === "object" ? data.type : undefined;
15
+ return status === 409 && typeof type === "string" && type.endsWith("/app-limit-reached");
16
+ }
17
+ export function markPaywall() {
18
+ const store = toolCall.getStore();
19
+ if (store)
20
+ store.paywall = true;
21
+ }
22
+ export function relayedForbiddenText(data) {
23
+ if (!data || typeof data !== "object")
24
+ return undefined;
25
+ const { code, message } = data;
26
+ return typeof code === "string" && RELAYED_FORBIDDEN_CODES.has(code) && typeof message === "string" && message
27
+ ? message
28
+ : undefined;
29
+ }
30
+ export async function runTool(fn, isFreePlan = () => false) {
31
+ const store = {};
32
+ return toolCall.run(store, async () => {
33
+ let result;
34
+ try {
35
+ const value = await fn();
36
+ result = store.relay !== undefined ? relayResult(store.relay) : value;
37
+ }
38
+ catch (error) {
39
+ if (store.relay === undefined)
40
+ throw error;
41
+ result = relayResult(store.relay);
42
+ }
43
+ return store.paywall || isFreePlan() ? withFooter(result) : result;
44
+ });
45
+ }
46
+ export function withFooter(result) {
47
+ const content = [...(result?.content ?? [])];
48
+ const last = content.length - 1;
49
+ if (last >= 0 && content[last].type === "text" && typeof content[last].text === "string") {
50
+ if (content[last].text.endsWith(FREE_PLAN_FOOTER))
51
+ return result;
52
+ content[last] = { ...content[last], text: `${content[last].text}\n\n${FREE_PLAN_FOOTER}` };
53
+ }
54
+ else {
55
+ content.push({ type: "text", text: FREE_PLAN_FOOTER });
56
+ }
57
+ return { ...result, content };
58
+ }
59
+ function relayResult(text) {
60
+ return { isError: true, content: [{ type: "text", text }] };
61
+ }
package/dist/config.js CHANGED
@@ -1,6 +1,6 @@
1
1
  export const SERVER_INFO = {
2
2
  name: "perfai-cloud-mcp",
3
- version: "0.5.2",
3
+ version: "0.7.2",
4
4
  };
5
5
  export const SERVER_INSTRUCTIONS = "Perfai security testing and auto-fix. Each user command is ONE tool call: " +
6
6
  '"Perfai test <url or app>" → run_security_test (a URL that is not registered yet is onboarded, and ' +
@@ -40,6 +40,24 @@ export const AUTH0_CLIENT_ID = process.env.AUTH0_CLIENT_ID ?? "OxipoJS8EIdpN3Kzh
40
40
  export const AUTH0_AUDIENCE = process.env.AUTH0_AUDIENCE ?? "";
41
41
  export const OAUTH_CALLBACK_PORT = parseInt(process.env.OAUTH_CALLBACK_PORT ?? "5173", 10);
42
42
  export const OAUTH_SCOPES = process.env.OAUTH_SCOPES ?? "openid profile email offline_access";
43
+ export const MCP_RESOURCE_URL = process.env.MCP_RESOURCE_URL?.trim() || undefined;
44
+ export const WEBUI_CLIENT_IDS = (process.env.WEBUI_CLIENT_IDS ?? "")
45
+ .split(",")
46
+ .map((id) => id.trim())
47
+ .filter(Boolean);
48
+ export const OAUTH_ISSUER = "https://auth.perfai.ai/";
49
+ export const MCP_OAUTH_SCOPES = [
50
+ "openid",
51
+ "profile",
52
+ "email",
53
+ "offline_access",
54
+ "tests:run",
55
+ "issues:read",
56
+ "issues:write",
57
+ ];
58
+ export const MCP_OAUTH_REQUIRED_SCOPES = ["tests:run", "issues:read"];
59
+ export const MCP_OAUTH_DOCS_URL = "https://docs.perfai.ai/docs/mcp/lovable";
60
+ export const MCP_CLAIM_NS = "https://perfai.com/";
43
61
  export const LOGIN_WAIT_MS = parseInt(process.env.LOGIN_WAIT_SECONDS ?? "90", 10) * 1000;
44
62
  export const POLL_START_MS = 5_000;
45
63
  export const POLL_MAX_INTERVAL_MS = 60_000;