perfai-cloud-mcp 0.5.3 → 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.
- package/README.md +11 -7
- package/dist/auth/bearerAuth.js +103 -19
- package/dist/auth/tokenValidator.js +3 -2
- package/dist/client/apiClient.js +33 -9
- package/dist/client/authManager.js +28 -0
- package/dist/client/errors.js +11 -0
- package/dist/client/relay.js +61 -0
- package/dist/config.js +19 -1
- package/dist/http.js +125 -0
- package/dist/mcpServer.js +129 -0
- package/dist/server.js +18 -207
- package/dist/tools/protected/autoFix.js +4 -3
- package/dist/tools/protected/autoFixAll.js +15 -7
- package/dist/tools/protected/getFixSummary.js +2 -2
- package/dist/tools/protected/getVulnerabilities.js +51 -11
- package/dist/tools/protected/registerApp.js +3 -1
- package/dist/tools/protected/runSecurityTest.js +51 -6
- package/dist/utils/clientInfo.js +8 -0
- package/dist/utils/promptBuilder.js +6 -0
- package/dist/utils/testInfo.js +63 -0
- package/package.json +3 -3
package/README.md
CHANGED
|
@@ -57,7 +57,7 @@ logout # clear session
|
|
|
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
58
|
| `suggest_fix` | Get a conversational fix prompt for a specific vulnerability. |
|
|
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
62
|
| `dismiss_vulnerability` | Dismiss a finding (false positive, accepted risk, etc.) with an optional `reason`, 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. |
|
|
@@ -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 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` | Lists the findings
|
|
75
|
+
| `perfai issues` | Lists the findings under "Last test: <YYYY-MM-DD HH:mm UTC> · Open: N (c critical, h high, m medium, l low)", or "No completed test yet.". While a test runs: "A test is running now. Last completed test: <date>." (the findings show when it finishes). During onboarding: "A test is running now. Last completed test: none." once the first test has started, else that the app is still onboarding. On the free plan only the top 5 are listed in full, followed by "+N more open issues are hidden on the free plan." |
|
|
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
|
|
|
@@ -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,32 @@ 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 = records.find((app) => app?.plan)?.plan;
|
|
58
|
+
if (plan)
|
|
59
|
+
auth.notePlan(plan);
|
|
60
|
+
return result;
|
|
44
61
|
}
|
|
45
|
-
export function
|
|
46
|
-
return request(auth, { method: "
|
|
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
|
|
49
|
-
return request(auth, { method: "GET", url:
|
|
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
|
-
|
|
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) {
|
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,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.
|
|
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;
|
package/dist/http.js
ADDED
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
import { randomUUID } from "node:crypto";
|
|
2
|
+
import express from "express";
|
|
3
|
+
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
4
|
+
import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js";
|
|
5
|
+
import { createBearerAuth, protectedResourceMetadata, sameCaller, sessionKey, } from "./auth/bearerAuth.js";
|
|
6
|
+
import { AuthManager } from "./client/authManager.js";
|
|
7
|
+
import { MCP_OAUTH_DOCS_URL } from "./config.js";
|
|
8
|
+
import { createMcpServer } from "./mcpServer.js";
|
|
9
|
+
const AUTH_METHOD = {
|
|
10
|
+
api_key: "api_key",
|
|
11
|
+
jwt: "oauth",
|
|
12
|
+
mcp_oauth: "mcp_oauth",
|
|
13
|
+
};
|
|
14
|
+
function applyGate(auth, gate) {
|
|
15
|
+
if (gate.method === "mcp_api_key" || !gate.token)
|
|
16
|
+
return;
|
|
17
|
+
auth.setToken(gate.token, gate.email, AUTH_METHOD[gate.method]);
|
|
18
|
+
auth.setScopes(gate.method === "mcp_oauth" ? gate.scopes : undefined);
|
|
19
|
+
}
|
|
20
|
+
function jsonRpcError(res, status, code, message) {
|
|
21
|
+
res.status(status).json({ jsonrpc: "2.0", error: { code, message }, id: null });
|
|
22
|
+
}
|
|
23
|
+
export function createHttpApp(options) {
|
|
24
|
+
const app = express();
|
|
25
|
+
app.use(express.json());
|
|
26
|
+
if (options.resourceUrl) {
|
|
27
|
+
const metadata = protectedResourceMetadata(options.resourceUrl, MCP_OAUTH_DOCS_URL);
|
|
28
|
+
const serveMetadata = (_req, res) => {
|
|
29
|
+
res.setHeader("Cache-Control", "public, max-age=3600");
|
|
30
|
+
res.json(metadata);
|
|
31
|
+
};
|
|
32
|
+
app.get("/.well-known/oauth-protected-resource", serveMetadata);
|
|
33
|
+
app.get("/.well-known/oauth-protected-resource/mcp", serveMetadata);
|
|
34
|
+
}
|
|
35
|
+
app.use("/mcp", createBearerAuth(options));
|
|
36
|
+
const transports = {};
|
|
37
|
+
const sessions = {};
|
|
38
|
+
function sessionTransport(req, res) {
|
|
39
|
+
const sessionId = req.headers["mcp-session-id"];
|
|
40
|
+
if (!sessionId) {
|
|
41
|
+
jsonRpcError(res, 400, -32000, "Bad Request: Mcp-Session-Id header is required");
|
|
42
|
+
return undefined;
|
|
43
|
+
}
|
|
44
|
+
const session = sessions[sessionId];
|
|
45
|
+
if (!session || !transports[sessionId]) {
|
|
46
|
+
jsonRpcError(res, 404, -32001, "Session not found");
|
|
47
|
+
return undefined;
|
|
48
|
+
}
|
|
49
|
+
if (!sameCaller(req, session.key)) {
|
|
50
|
+
console.error(`Rejected session ${sessionId}: caller differs from the one that opened it.`);
|
|
51
|
+
jsonRpcError(res, 403, -32001, "Forbidden: this session belongs to a different caller.");
|
|
52
|
+
return undefined;
|
|
53
|
+
}
|
|
54
|
+
applyGate(session.auth, req.perfaiAuth);
|
|
55
|
+
return transports[sessionId];
|
|
56
|
+
}
|
|
57
|
+
app.post("/mcp", async (req, res) => {
|
|
58
|
+
const sessionId = req.headers["mcp-session-id"];
|
|
59
|
+
try {
|
|
60
|
+
if (sessionId) {
|
|
61
|
+
const transport = sessionTransport(req, res);
|
|
62
|
+
if (transport)
|
|
63
|
+
await transport.handleRequest(req, res, req.body);
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
const gate = req.perfaiAuth;
|
|
67
|
+
if (gate && isInitializeRequest(req.body)) {
|
|
68
|
+
const auth = new AuthManager({ useEnv: false });
|
|
69
|
+
applyGate(auth, gate);
|
|
70
|
+
const transport = new StreamableHTTPServerTransport({
|
|
71
|
+
sessionIdGenerator: () => randomUUID(),
|
|
72
|
+
onsessioninitialized: (sid) => {
|
|
73
|
+
transports[sid] = transport;
|
|
74
|
+
sessions[sid] = { auth, key: sessionKey(gate) };
|
|
75
|
+
console.error(`Session initialized: ${sid} (${gate.method}: ${auth.describeIdentity()})`);
|
|
76
|
+
},
|
|
77
|
+
});
|
|
78
|
+
transport.onclose = () => {
|
|
79
|
+
const sid = transport.sessionId;
|
|
80
|
+
if (sid) {
|
|
81
|
+
delete transports[sid];
|
|
82
|
+
delete sessions[sid];
|
|
83
|
+
console.error(`Session closed: ${sid}`);
|
|
84
|
+
}
|
|
85
|
+
};
|
|
86
|
+
const server = createMcpServer(auth);
|
|
87
|
+
await server.connect(transport);
|
|
88
|
+
await transport.handleRequest(req, res, req.body);
|
|
89
|
+
return;
|
|
90
|
+
}
|
|
91
|
+
jsonRpcError(res, 400, -32000, "Bad Request: No valid session ID provided");
|
|
92
|
+
}
|
|
93
|
+
catch (error) {
|
|
94
|
+
console.error("Error handling MCP request:", error instanceof Error ? error.message : String(error));
|
|
95
|
+
if (!res.headersSent)
|
|
96
|
+
jsonRpcError(res, 500, -32603, "Internal server error");
|
|
97
|
+
}
|
|
98
|
+
});
|
|
99
|
+
app.get("/mcp", async (req, res) => {
|
|
100
|
+
const transport = sessionTransport(req, res);
|
|
101
|
+
if (transport)
|
|
102
|
+
await transport.handleRequest(req, res);
|
|
103
|
+
});
|
|
104
|
+
app.delete("/mcp", async (req, res) => {
|
|
105
|
+
const transport = sessionTransport(req, res);
|
|
106
|
+
if (transport)
|
|
107
|
+
await transport.handleRequest(req, res);
|
|
108
|
+
});
|
|
109
|
+
app.get("/", (_req, res) => {
|
|
110
|
+
res.json({ status: "ok" });
|
|
111
|
+
});
|
|
112
|
+
app.get("/health", (_req, res) => {
|
|
113
|
+
res.json({ status: "ok" });
|
|
114
|
+
});
|
|
115
|
+
return {
|
|
116
|
+
app,
|
|
117
|
+
async closeAll() {
|
|
118
|
+
for (const sid of Object.keys(transports)) {
|
|
119
|
+
await transports[sid].close().catch(() => { });
|
|
120
|
+
delete transports[sid];
|
|
121
|
+
delete sessions[sid];
|
|
122
|
+
}
|
|
123
|
+
},
|
|
124
|
+
};
|
|
125
|
+
}
|