perfai-cloud-mcp 0.5.3 → 0.7.5
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.
- package/README.md +14 -10
- package/dist/auth/bearerAuth.js +103 -19
- package/dist/auth/tokenValidator.js +3 -2
- package/dist/client/apiClient.js +45 -11
- package/dist/client/authManager.js +46 -10
- package/dist/client/errors.js +11 -0
- package/dist/client/relay.js +63 -0
- package/dist/config.js +23 -4
- package/dist/http.js +125 -0
- package/dist/mcpServer.js +132 -0
- package/dist/server.js +18 -207
- package/dist/tools/protected/autoFix.js +13 -10
- package/dist/tools/protected/autoFixAll.js +16 -8
- package/dist/tools/protected/getFixSummary.js +2 -2
- package/dist/tools/protected/getVulnerabilities.js +59 -12
- package/dist/tools/protected/listApps.js +1 -1
- package/dist/tools/protected/registerApp.js +7 -3
- package/dist/tools/protected/runSecurityTest.js +67 -13
- package/dist/tools/protected/suggestFix.js +5 -4
- package/dist/tools/protected/vulnerabilityActions.js +104 -33
- package/dist/utils/appResolver.js +8 -0
- package/dist/utils/clientInfo.js +8 -0
- package/dist/utils/dismissReason.js +73 -0
- package/dist/utils/formatters.js +18 -25
- package/dist/utils/promptBuilder.js +63 -6
- package/dist/utils/runState.js +3 -6
- package/dist/utils/testInfo.js +93 -0
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -55,11 +55,11 @@ logout # clear session
|
|
|
55
55
|
| Tool | Description |
|
|
56
56
|
| --- | --- |
|
|
57
57
|
| `get_vulnerabilities` | List findings from the latest security test. Accepts `app` (name) or `appId`, and `status`: `open` (default), `fixed` (confirmed fixes) or `dismissed` (Perfai staff only — other accounts are told dismissed findings are not listable). The open list ends with how many dismissed findings it leaves out. |
|
|
58
|
-
| `suggest_fix` | Get a conversational fix prompt for a
|
|
58
|
+
| `suggest_fix` | Get a conversational fix prompt for a listed item (every route grouped on it). |
|
|
59
59
|
| `auto_fix` | Get structured, step-by-step fix instructions for one vulnerability. Accepts `app` (name). |
|
|
60
|
-
| `auto_fix_all` | The one-line fix. Takes `app` (name), optional `severity` / `max_fixes`; returns a prioritized plan the agent runs autonomously, 15 findings per batch. |
|
|
60
|
+
| `auto_fix_all` | The one-line fix. Takes `app` (name), optional `severity` / `max_fixes`; returns a prioritized plan the agent runs autonomously, 15 findings per batch. Free-plan findings hidden beyond the top 5 are left out and counted. |
|
|
61
61
|
| `get_fix_summary` | Fix progress: fixed, skipped as not applicable (dismissed), still open — by severity. Accepts `app` (name). Every account gets the skipped total (the API's `dismissedCount`); only Perfai staff get it by severity. If the API cannot count dismissals, Skipped reads `?`, never 0. |
|
|
62
|
-
| `dismiss_vulnerability` | Dismiss a finding
|
|
62
|
+
| `dismiss_vulnerability` | Dismiss a finding as a false positive, an accepted risk (until a date, 90 days by default), won't fix or a duplicate. With no reason given, it asks once. The reason and your words are stored on the finding. The reply names the finding and gives its ID for undoing it. |
|
|
63
63
|
| `reopen_vulnerability` | Reopen a dismissed finding (or undo a fix claim), by the ID from the dismiss reply. |
|
|
64
64
|
| `mark_vulnerability_fixed` | Claim a finding as fixed after applying the code change; the next scan confirms it. |
|
|
65
65
|
|
|
@@ -69,10 +69,10 @@ logout # clear session
|
|
|
69
69
|
|
|
70
70
|
| Say | Does |
|
|
71
71
|
| --- | --- |
|
|
72
|
-
| `perfai test <url>` | A new URL is registered and onboarded; onboarding runs the first security test itself. Replies "
|
|
73
|
-
| `perfai test` (onboarded app) | Starts a new security test. |
|
|
72
|
+
| `perfai test <url>` | A new URL (`https://` optional; a bare domain gets it added) is registered and onboarded; onboarding runs the first security test itself. Replies "Perfai is setting up <App> and will run its first test automatically. This takes up to 20 minutes.", then where the completion email goes (when the session knows the email) and 'Say "perfai status" to check.' |
|
|
73
|
+
| `perfai test` (onboarded app) | Starts a new security test. Replies "Test started — ID <id>.", the last test's open issue count, and "Perfai emails the app's owner when it finishes." |
|
|
74
74
|
| `perfai status` / `check status` | Reads the status once: "<App> is still onboarding. Check again later." or "<App> onboarding is complete." |
|
|
75
|
-
| `perfai issues` |
|
|
75
|
+
| `perfai issues` | "Last test: <YYYY-MM-DD HH:mm UTC> · Open: N (c critical, h high, m medium, l low)", on the free plan "+N more open issues are hidden on the free plan. Upgrade: …", then the findings (same name and severity grouped as one item with its routes and a "Fix:" hint) and 'Next: say "perfai fix" … then "perfai test" to check again.' Or "No completed test yet.". While a test runs: "A test is running now: <stage>, about N min left.", the last completed test with its counts (or "none") and "Perfai emails the app's owner when it finishes." While the app is still onboarding, it says so. |
|
|
76
76
|
| `perfai fix` / `<App_name> fix all` | Fixes the findings (see below). |
|
|
77
77
|
|
|
78
78
|
Onboarding and security tests run in the background on Perfai. The agent never waits or polls for them — every reply ends the turn, and status is checked only when you ask.
|
|
@@ -195,6 +195,8 @@ $env:MCP_TRANSPORT="http"; node dist/server.js
|
|
|
195
195
|
| `OAUTH_SCOPES` | No | `openid profile email offline_access` | Scopes requested during OAuth login |
|
|
196
196
|
| `LOGIN_WAIT_SECONDS` | No | `90` | How long `login` waits for the browser sign-in before asking the agent to call it again. Keep it under your client's tool-call timeout |
|
|
197
197
|
| `MCP_API_KEY` | No | — | Legacy shared key. Opens an HTTP session with no PerfAI identity — the caller must still `login`. Use per-user API keys instead. |
|
|
198
|
+
| `MCP_RESOURCE_URL` | No | — | HTTP only. This server's public MCP URL (`https://mcp.perfai.ai/mcp` on prod, `https://mcp-server.perfai.ai/mcp` on dev). Turns on OAuth sign-in for MCP clients such as Lovable: the protected-resource metadata, the `WWW-Authenticate` challenge, and access tokens whose audience is this URL. Unset: OAuth sign-in is off |
|
|
199
|
+
| `WEBUI_CLIENT_IDS` | No | — | HTTP only. Comma-separated audience(s) of the Perfai web app's id_tokens (WebApp-API's `AUTH0_AUDIENCE`). Only these JWTs, besides MCP access tokens, are accepted as a bearer. Unset: web-app id_tokens are refused |
|
|
198
200
|
|
|
199
201
|
### Deploy with Docker
|
|
200
202
|
|
|
@@ -210,6 +212,7 @@ docker run -p 3000:3000 -e MCP_TRANSPORT=http perfai-mcp
|
|
|
210
212
|
| `POST` | `/mcp` | MCP JSON-RPC requests |
|
|
211
213
|
| `GET` | `/mcp` | SSE stream (server-initiated messages) |
|
|
212
214
|
| `DELETE` | `/mcp` | Session termination |
|
|
215
|
+
| `GET` | `/.well-known/oauth-protected-resource` (also `…/mcp`) | OAuth protected-resource metadata (RFC 9728): where MCP clients sign in. No auth. Only when `MCP_RESOURCE_URL` is set |
|
|
213
216
|
| `GET` | `/health` | Health check — `{"status":"ok"}` only |
|
|
214
217
|
| `GET` | `/` | `{"status":"ok"}` only. The running version is in the MCP `initialize` reply (`serverInfo.version`). |
|
|
215
218
|
|
|
@@ -243,7 +246,7 @@ Every tool maps directly to a Perfai cloud API endpoint:
|
|
|
243
246
|
| `auto_fix` | Local prompt builder (no API call) |
|
|
244
247
|
| `auto_fix_all` | `GET /v1/apps/{appId}/vulnerabilities` + local prompt builder |
|
|
245
248
|
| `get_fix_summary` | `GET /v1/apps/{appId}/vulnerabilities` — default (with `dismissedCount`), `isFixed=true` and `isDismissed=true` — merged locally |
|
|
246
|
-
| `dismiss_vulnerability` | `POST /v1/vulnerabilities/{id}/dismiss` (`reason`
|
|
249
|
+
| `dismiss_vulnerability` | `POST /v1/vulnerabilities/{id}/dismiss` (`disposition`, `reason`, `comment`, `expiresAt`, `duplicateOf`) |
|
|
247
250
|
| `reopen_vulnerability` | `POST /v1/vulnerabilities/{id}/reopen` |
|
|
248
251
|
| `mark_vulnerability_fixed` | `POST /v1/vulnerabilities/{id}/fix` |
|
|
249
252
|
| `app` name on any tool | `GET /v1/apps?search=` in the session org; on a miss, `GET /api/v1/org-users/get_users_orgs` then the same search per org with `X-Org-ID` |
|
|
@@ -273,9 +276,10 @@ Every tool maps directly to a Perfai cloud API endpoint:
|
|
|
273
276
|
## Security
|
|
274
277
|
|
|
275
278
|
- Access tokens are transmitted over **HTTPS** only
|
|
276
|
-
-
|
|
277
|
-
- Validated tokens are cached server-side for 30 minutes
|
|
278
|
-
- Each MCP session gets its own isolated authentication state
|
|
279
|
+
- Every HTTP request is checked: a `pfk_` API key is forwarded to the Perfai API, which validates it; a JWT must be signed by Perfai's Auth0 tenant (RS256), unexpired, from issuer `https://auth.perfai.ai/`, and meant for this server (an MCP access token with the `tests:run` and `issues:read` scopes) or for the Perfai web app. Any other token is refused
|
|
280
|
+
- Validated tokens are cached server-side for up to 30 minutes, never past their expiry
|
|
281
|
+
- Each MCP session gets its own isolated authentication state, bound to its user (OAuth) or its API key. An OAuth session keeps working when the client refreshes its token
|
|
282
|
+
- Without `issues:write`, an OAuth session cannot mark, dismiss or reopen findings
|
|
279
283
|
- No credentials are stored on disk by the MCP server
|
|
280
284
|
|
|
281
285
|
---
|
package/dist/auth/bearerAuth.js
CHANGED
|
@@ -1,21 +1,82 @@
|
|
|
1
1
|
import { createHash, timingSafeEqual } from "node:crypto";
|
|
2
2
|
import { apiKeyId, isPerfaiApiKey } from "../client/authManager.js";
|
|
3
|
-
import {
|
|
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
|
|
11
|
-
|
|
12
|
+
export function resourceMetadataUrl(resourceUrl) {
|
|
13
|
+
return `${new URL(resourceUrl).origin}/.well-known/oauth-protected-resource`;
|
|
12
14
|
}
|
|
13
|
-
export function
|
|
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
|
-
|
|
18
|
-
"
|
|
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
|
|
34
|
-
if (
|
|
35
|
-
|
|
36
|
-
|
|
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
|
-
|
|
40
|
-
|
|
41
|
-
|
|
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
|
-
|
|
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
|
|
51
|
-
|
|
52
|
-
|
|
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
|
}
|
|
@@ -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/client/apiClient.js
CHANGED
|
@@ -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,42 @@ async function request(auth, config, allowReauth = true) {
|
|
|
39
41
|
throw error;
|
|
40
42
|
}
|
|
41
43
|
}
|
|
42
|
-
|
|
43
|
-
|
|
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 = result.plan ?? records.find((app) => app?.plan)?.plan;
|
|
58
|
+
if (plan)
|
|
59
|
+
auth.notePlan(plan);
|
|
60
|
+
return result;
|
|
61
|
+
}
|
|
62
|
+
export async function registerApp(auth, input) {
|
|
63
|
+
return notingPlan(auth, await request(auth, { method: "POST", url: "/apps", data: input }));
|
|
44
64
|
}
|
|
45
|
-
export function getApp(auth, appId) {
|
|
46
|
-
return request(auth, { method: "GET", url: `/apps/${encodeURIComponent(appId)}` });
|
|
65
|
+
export async function getApp(auth, appId) {
|
|
66
|
+
return notingPlan(auth, await request(auth, { method: "GET", url: `/apps/${encodeURIComponent(appId)}` }));
|
|
47
67
|
}
|
|
48
|
-
export function listApps(auth, params) {
|
|
49
|
-
return request(auth, { method: "GET", url: "/apps", params });
|
|
68
|
+
export async function listApps(auth, params) {
|
|
69
|
+
return notingPlan(auth, await request(auth, { method: "GET", url: "/apps", params }));
|
|
70
|
+
}
|
|
71
|
+
export async function learnPlan(auth) {
|
|
72
|
+
if (!auth.isAuthenticated() || auth.getPlan() !== undefined || !auth.claimPlanLookup())
|
|
73
|
+
return;
|
|
74
|
+
try {
|
|
75
|
+
await listApps(auth, { pageSize: 1 });
|
|
76
|
+
}
|
|
77
|
+
catch (error) {
|
|
78
|
+
console.error("Plan lookup failed:", error instanceof Error ? error.message : String(error));
|
|
79
|
+
}
|
|
50
80
|
}
|
|
51
81
|
export function submitAccountSetup(auth, appId, credentials) {
|
|
52
82
|
return request(auth, {
|
|
@@ -64,18 +94,21 @@ export function runSecurityAgent(auth, appId) {
|
|
|
64
94
|
export function getTask(auth, taskId) {
|
|
65
95
|
return request(auth, { method: "GET", url: `/tasks/${encodeURIComponent(taskId)}` });
|
|
66
96
|
}
|
|
67
|
-
export function getVulnerabilities(auth, appId, params) {
|
|
68
|
-
|
|
97
|
+
export async function getVulnerabilities(auth, appId, params) {
|
|
98
|
+
const result = await request(auth, {
|
|
69
99
|
method: "GET",
|
|
70
100
|
url: `/apps/${encodeURIComponent(appId)}/vulnerabilities`,
|
|
71
101
|
params,
|
|
72
102
|
});
|
|
103
|
+
return { ...result, data: result.data ?? [], total: result.total ?? 0 };
|
|
73
104
|
}
|
|
74
105
|
export async function listAllVulnerabilities(auth, appId, filters = {}) {
|
|
75
106
|
const all = [];
|
|
76
107
|
let dismissedCount = null;
|
|
77
108
|
for (let page = 1;; page++) {
|
|
78
109
|
const result = await getVulnerabilities(auth, appId, { ...filters, page, pageSize: 100 });
|
|
110
|
+
if (result.status === "RUN_IN_PROGRESS")
|
|
111
|
+
throw new TestRunningError();
|
|
79
112
|
if (page === 1 && typeof result.dismissedCount === "number")
|
|
80
113
|
dismissedCount = result.dismissedCount;
|
|
81
114
|
all.push(...result.data);
|
|
@@ -90,11 +123,11 @@ function actionBody(comment) {
|
|
|
90
123
|
const trimmed = comment?.trim();
|
|
91
124
|
return trimmed ? { comment: trimmed.slice(0, 1000) } : undefined;
|
|
92
125
|
}
|
|
93
|
-
export function dismissVulnerability(auth, id,
|
|
126
|
+
export function dismissVulnerability(auth, id, body) {
|
|
94
127
|
return request(auth, {
|
|
95
128
|
method: "POST",
|
|
96
129
|
url: `/vulnerabilities/${encodeURIComponent(id)}/dismiss`,
|
|
97
|
-
data:
|
|
130
|
+
data: body,
|
|
98
131
|
});
|
|
99
132
|
}
|
|
100
133
|
export function reopenVulnerability(auth, id) {
|
|
@@ -120,6 +153,7 @@ export async function getUserOrganizations(auth) {
|
|
|
120
153
|
}
|
|
121
154
|
catch (error) {
|
|
122
155
|
if (axios.isAxiosError(error)) {
|
|
156
|
+
relayIfFixedReply(auth, error.response?.status, error.response?.data);
|
|
123
157
|
console.error(`Organization list request failed: ${describeFailedRequest("GET", ORGANIZATIONS_URL, error)}`);
|
|
124
158
|
throw new ApiError(formatApiError(error), error.response?.status, error.response?.data);
|
|
125
159
|
}
|
|
@@ -14,14 +14,18 @@ export class AuthManager {
|
|
|
14
14
|
idToken;
|
|
15
15
|
authenticatedEmail;
|
|
16
16
|
authMethod = "none";
|
|
17
|
+
scopes = [];
|
|
17
18
|
currentAppId;
|
|
18
19
|
currentAppUrl;
|
|
19
20
|
currentTaskId;
|
|
20
21
|
currentTaskAppId;
|
|
21
22
|
vulnCache = new Map();
|
|
22
23
|
vulnCacheAppId;
|
|
24
|
+
planLookupOrg;
|
|
23
25
|
organizations = [];
|
|
24
26
|
selectedOrgId;
|
|
27
|
+
plan;
|
|
28
|
+
lastTests = new Map();
|
|
25
29
|
constructor({ useEnv = true } = {}) {
|
|
26
30
|
if (!useEnv)
|
|
27
31
|
return;
|
|
@@ -59,6 +63,12 @@ export class AuthManager {
|
|
|
59
63
|
catch { }
|
|
60
64
|
}
|
|
61
65
|
}
|
|
66
|
+
setScopes(scopes) {
|
|
67
|
+
this.scopes = scopes ? [...scopes] : [];
|
|
68
|
+
}
|
|
69
|
+
hasScope(scope) {
|
|
70
|
+
return this.scopes.includes(scope);
|
|
71
|
+
}
|
|
62
72
|
describeIdentity() {
|
|
63
73
|
if (this.authenticatedEmail)
|
|
64
74
|
return this.authenticatedEmail;
|
|
@@ -121,6 +131,29 @@ export class AuthManager {
|
|
|
121
131
|
this.vulnCacheAppId = undefined;
|
|
122
132
|
this.organizations = [];
|
|
123
133
|
this.selectedOrgId = undefined;
|
|
134
|
+
this.plan = undefined;
|
|
135
|
+
this.planLookupOrg = undefined;
|
|
136
|
+
this.lastTests.clear();
|
|
137
|
+
}
|
|
138
|
+
notePlan(plan) {
|
|
139
|
+
if (plan === "free" || plan === "paid")
|
|
140
|
+
this.plan = plan;
|
|
141
|
+
}
|
|
142
|
+
getPlan() {
|
|
143
|
+
return this.plan;
|
|
144
|
+
}
|
|
145
|
+
claimPlanLookup() {
|
|
146
|
+
const org = this.selectedOrgId ?? "";
|
|
147
|
+
if (this.planLookupOrg === org)
|
|
148
|
+
return false;
|
|
149
|
+
this.planLookupOrg = org;
|
|
150
|
+
return true;
|
|
151
|
+
}
|
|
152
|
+
rememberLastTest(appId, completedAt) {
|
|
153
|
+
this.lastTests.set(appId, completedAt);
|
|
154
|
+
}
|
|
155
|
+
lastTestOf(appId) {
|
|
156
|
+
return this.lastTests.get(appId);
|
|
124
157
|
}
|
|
125
158
|
getOrganizations() {
|
|
126
159
|
return this.organizations;
|
|
@@ -129,11 +162,15 @@ export class AuthManager {
|
|
|
129
162
|
return this.selectedOrgId;
|
|
130
163
|
}
|
|
131
164
|
setSelectedOrgId(orgId) {
|
|
165
|
+
if (orgId !== this.selectedOrgId)
|
|
166
|
+
this.plan = undefined;
|
|
132
167
|
this.selectedOrgId = orgId;
|
|
133
168
|
}
|
|
134
169
|
setOrganizations(organizations, currentOrgId) {
|
|
135
170
|
this.organizations = organizations;
|
|
136
171
|
if (currentOrgId) {
|
|
172
|
+
if (currentOrgId !== this.selectedOrgId)
|
|
173
|
+
this.plan = undefined;
|
|
137
174
|
this.selectedOrgId = currentOrgId;
|
|
138
175
|
}
|
|
139
176
|
else if (!this.selectedOrgId && organizations.length > 0) {
|
|
@@ -149,26 +186,25 @@ export class AuthManager {
|
|
|
149
186
|
this.currentTaskAppId = appId;
|
|
150
187
|
}
|
|
151
188
|
cacheVulnerabilities(appId, vulnerabilities) {
|
|
189
|
+
this.cacheVulnerabilityGroups(appId, vulnerabilities.map((v) => [v]));
|
|
190
|
+
}
|
|
191
|
+
cacheVulnerabilityGroups(appId, groups) {
|
|
152
192
|
this.vulnCache.clear();
|
|
153
193
|
this.vulnCacheAppId = appId;
|
|
154
|
-
|
|
194
|
+
groups.forEach((group, i) => this.vulnCache.set(i + 1, group));
|
|
155
195
|
}
|
|
156
|
-
|
|
196
|
+
getCachedGroup(appId, idOrSequence) {
|
|
157
197
|
if (this.vulnCacheAppId !== appId)
|
|
158
198
|
return undefined;
|
|
159
199
|
const asNumber = Number(idOrSequence);
|
|
160
200
|
if (Number.isInteger(asNumber) && asNumber > 0 && this.vulnCache.has(asNumber)) {
|
|
161
201
|
return this.vulnCache.get(asNumber);
|
|
162
202
|
}
|
|
163
|
-
for (const
|
|
164
|
-
|
|
165
|
-
|
|
203
|
+
for (const group of this.vulnCache.values()) {
|
|
204
|
+
const match = group.find((v) => String(v.id ?? v._id) === idOrSequence);
|
|
205
|
+
if (match)
|
|
206
|
+
return [match];
|
|
166
207
|
}
|
|
167
208
|
return undefined;
|
|
168
209
|
}
|
|
169
|
-
resolveVulnerabilityId(appId, idOrSequence) {
|
|
170
|
-
const cached = this.getCachedVulnerability(appId, idOrSequence);
|
|
171
|
-
const id = cached?.id ?? cached?._id;
|
|
172
|
-
return id ? String(id) : idOrSequence;
|
|
173
|
-
}
|
|
174
210
|
}
|
package/dist/client/errors.js
CHANGED
|
@@ -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,63 @@
|
|
|
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, learnPlan = async () => { }) {
|
|
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
|
+
if (!store.paywall && store.relay === undefined)
|
|
44
|
+
await toolCall.exit(learnPlan);
|
|
45
|
+
return store.paywall || isFreePlan() ? withFooter(result) : result;
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
export function withFooter(result) {
|
|
49
|
+
const content = [...(result?.content ?? [])];
|
|
50
|
+
const last = content.length - 1;
|
|
51
|
+
if (last >= 0 && content[last].type === "text" && typeof content[last].text === "string") {
|
|
52
|
+
if (content[last].text.endsWith(FREE_PLAN_FOOTER))
|
|
53
|
+
return result;
|
|
54
|
+
content[last] = { ...content[last], text: `${content[last].text}\n\n${FREE_PLAN_FOOTER}` };
|
|
55
|
+
}
|
|
56
|
+
else {
|
|
57
|
+
content.push({ type: "text", text: FREE_PLAN_FOOTER });
|
|
58
|
+
}
|
|
59
|
+
return { ...result, content };
|
|
60
|
+
}
|
|
61
|
+
function relayResult(text) {
|
|
62
|
+
return { isError: true, content: [{ type: "text", text }] };
|
|
63
|
+
}
|
package/dist/config.js
CHANGED
|
@@ -1,13 +1,14 @@
|
|
|
1
1
|
export const SERVER_INFO = {
|
|
2
2
|
name: "perfai-cloud-mcp",
|
|
3
|
-
version: "0.5
|
|
3
|
+
version: "0.7.5",
|
|
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 ' +
|
|
7
7
|
'onboarding runs the first security test itself); "Perfai issues" → get_vulnerabilities; ' +
|
|
8
8
|
'"Perfai status" / "check status" → check_app_status; ' +
|
|
9
9
|
'"Perfai dismiss <n>" → dismiss_vulnerability (also when the user asks to skip, ignore or accept the risk of ' +
|
|
10
|
-
"a finding, or calls it a false positive, not applicable or won't fix
|
|
10
|
+
"a finding, or calls it a false positive, not applicable or won't fix; with no reason given, the reply is a " +
|
|
11
|
+
"question to ask the user once); " +
|
|
11
12
|
'"Perfai reopen <n>" → reopen_vulnerability (undo a dismissal, using the ID from the dismiss reply). ' +
|
|
12
13
|
"Dismiss and reopen are available whenever the user asks, not only during a fix run; never tell the user to " +
|
|
13
14
|
'use the web app for them. "Perfai issues dismissed" → get_vulnerabilities with status: "dismissed" ' +
|
|
@@ -25,8 +26,8 @@ export const SERVER_INSTRUCTIONS = "Perfai security testing and auto-fix. Each u
|
|
|
25
26
|
"Then execute the returned plan " +
|
|
26
27
|
"autonomously, by editing code only — never run shell, network or install commands while executing it " +
|
|
27
28
|
"unless the user asks: fix each finding and call mark_vulnerability_fixed. Inside an auto_fix_all run only: " +
|
|
28
|
-
"if a finding does not apply to the code, call dismiss_vulnerability
|
|
29
|
-
"mentioning it in chat. Finish with get_fix_summary and a one-line count. " +
|
|
29
|
+
"if a finding does not apply to the code, call dismiss_vulnerability (false_positive / other, comment " +
|
|
30
|
+
"\"AI agent: <specific reason>\") without mentioning it in chat. Finish with get_fix_summary and a one-line count. " +
|
|
30
31
|
'Always write the product name as "Perfai", never "PerfAI", and relay each returned message as-is, without rewording it.';
|
|
31
32
|
const API_HOST = process.env.PERFAI_API_HOST || "api.perfai.ai";
|
|
32
33
|
export const AUTH_TOKEN_URL = `https://${API_HOST}/api/v1/auth/token`;
|
|
@@ -40,6 +41,24 @@ export const AUTH0_CLIENT_ID = process.env.AUTH0_CLIENT_ID ?? "OxipoJS8EIdpN3Kzh
|
|
|
40
41
|
export const AUTH0_AUDIENCE = process.env.AUTH0_AUDIENCE ?? "";
|
|
41
42
|
export const OAUTH_CALLBACK_PORT = parseInt(process.env.OAUTH_CALLBACK_PORT ?? "5173", 10);
|
|
42
43
|
export const OAUTH_SCOPES = process.env.OAUTH_SCOPES ?? "openid profile email offline_access";
|
|
44
|
+
export const MCP_RESOURCE_URL = process.env.MCP_RESOURCE_URL?.trim() || undefined;
|
|
45
|
+
export const WEBUI_CLIENT_IDS = (process.env.WEBUI_CLIENT_IDS ?? "")
|
|
46
|
+
.split(",")
|
|
47
|
+
.map((id) => id.trim())
|
|
48
|
+
.filter(Boolean);
|
|
49
|
+
export const OAUTH_ISSUER = "https://auth.perfai.ai/";
|
|
50
|
+
export const MCP_OAUTH_SCOPES = [
|
|
51
|
+
"openid",
|
|
52
|
+
"profile",
|
|
53
|
+
"email",
|
|
54
|
+
"offline_access",
|
|
55
|
+
"tests:run",
|
|
56
|
+
"issues:read",
|
|
57
|
+
"issues:write",
|
|
58
|
+
];
|
|
59
|
+
export const MCP_OAUTH_REQUIRED_SCOPES = ["tests:run", "issues:read"];
|
|
60
|
+
export const MCP_OAUTH_DOCS_URL = "https://docs.perfai.ai/docs/mcp/lovable";
|
|
61
|
+
export const MCP_CLAIM_NS = "https://perfai.com/";
|
|
43
62
|
export const LOGIN_WAIT_MS = parseInt(process.env.LOGIN_WAIT_SECONDS ?? "90", 10) * 1000;
|
|
44
63
|
export const POLL_START_MS = 5_000;
|
|
45
64
|
export const POLL_MAX_INTERVAL_MS = 60_000;
|