perfai-cloud-mcp 0.3.0 → 0.5.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +45 -24
- package/dist/auth/bearerAuth.js +53 -0
- package/dist/auth/oauthFlow.js +1 -19
- package/dist/auth/pkce.js +0 -8
- package/dist/auth/tokenValidator.js +77 -67
- package/dist/cli.js +85 -52
- package/dist/client/apiClient.js +18 -25
- package/dist/client/authManager.js +42 -51
- package/dist/client/errors.js +42 -14
- package/dist/config.js +35 -38
- package/dist/env.js +0 -6
- package/dist/log-guard.js +0 -9
- package/dist/prompts.js +2 -8
- package/dist/server.js +45 -176
- package/dist/tools/protected/autoFix.js +0 -1
- package/dist/tools/protected/autoFixAll.js +4 -7
- package/dist/tools/protected/checkAppStatus.js +34 -32
- package/dist/tools/protected/checkTaskStatus.js +29 -28
- package/dist/tools/protected/getFixSummary.js +41 -11
- package/dist/tools/protected/getVulnerabilities.js +58 -8
- package/dist/tools/protected/manageOrganizations.js +4 -5
- package/dist/tools/protected/registerApp.js +17 -33
- package/dist/tools/protected/runSecurityTest.js +82 -26
- package/dist/tools/protected/submitAppCredentials.js +4 -3
- package/dist/tools/protected/vulnerabilityActions.js +32 -8
- package/dist/tools/public/authStatus.js +2 -2
- package/dist/tools/public/login.js +3 -27
- package/dist/utils/appResolver.js +25 -85
- package/dist/utils/formatters.js +9 -9
- package/dist/utils/poll.js +0 -7
- package/dist/utils/promptBuilder.js +93 -94
- package/dist/utils/registrationState.js +28 -0
- package/dist/utils/runState.js +129 -0
- package/package.json +6 -2
- package/dist/auth/oauthFlow.d.ts +0 -23
- package/dist/auth/oauthFlow.d.ts.map +0 -1
- package/dist/auth/pkce.d.ts +0 -11
- package/dist/auth/pkce.d.ts.map +0 -1
- package/dist/auth/tokenValidator.d.ts +0 -40
- package/dist/auth/tokenValidator.d.ts.map +0 -1
- package/dist/cli.d.ts +0 -3
- package/dist/cli.d.ts.map +0 -1
- package/dist/client/apiClient.d.ts +0 -36
- package/dist/client/apiClient.d.ts.map +0 -1
- package/dist/client/authManager.d.ts +0 -61
- package/dist/client/authManager.d.ts.map +0 -1
- package/dist/client/errors.d.ts +0 -10
- package/dist/client/errors.d.ts.map +0 -1
- package/dist/client/types.d.ts +0 -72
- package/dist/client/types.d.ts.map +0 -1
- package/dist/config.d.ts +0 -27
- package/dist/config.d.ts.map +0 -1
- package/dist/env.d.ts +0 -2
- package/dist/env.d.ts.map +0 -1
- package/dist/log-guard.d.ts +0 -2
- package/dist/log-guard.d.ts.map +0 -1
- package/dist/prompts.d.ts +0 -31
- package/dist/prompts.d.ts.map +0 -1
- package/dist/server.d.ts +0 -4
- package/dist/server.d.ts.map +0 -1
- package/dist/tools/index.d.ts +0 -404
- package/dist/tools/index.d.ts.map +0 -1
- package/dist/tools/protected/autoFix.d.ts +0 -26
- package/dist/tools/protected/autoFix.d.ts.map +0 -1
- package/dist/tools/protected/autoFixAll.d.ts +0 -30
- package/dist/tools/protected/autoFixAll.d.ts.map +0 -1
- package/dist/tools/protected/checkAppStatus.d.ts +0 -21
- package/dist/tools/protected/checkAppStatus.d.ts.map +0 -1
- package/dist/tools/protected/checkTaskStatus.d.ts +0 -21
- package/dist/tools/protected/checkTaskStatus.d.ts.map +0 -1
- package/dist/tools/protected/getFixSummary.d.ts +0 -21
- package/dist/tools/protected/getFixSummary.d.ts.map +0 -1
- package/dist/tools/protected/getVulnerabilities.d.ts +0 -33
- package/dist/tools/protected/getVulnerabilities.d.ts.map +0 -1
- package/dist/tools/protected/listApps.d.ts +0 -25
- package/dist/tools/protected/listApps.d.ts.map +0 -1
- package/dist/tools/protected/logout.d.ts +0 -12
- package/dist/tools/protected/logout.d.ts.map +0 -1
- package/dist/tools/protected/manageOrganizations.d.ts +0 -26
- package/dist/tools/protected/manageOrganizations.d.ts.map +0 -1
- package/dist/tools/protected/registerApp.d.ts +0 -33
- package/dist/tools/protected/registerApp.d.ts.map +0 -1
- package/dist/tools/protected/runSecurityTest.d.ts +0 -21
- package/dist/tools/protected/runSecurityTest.d.ts.map +0 -1
- package/dist/tools/protected/selectApp.d.ts +0 -18
- package/dist/tools/protected/selectApp.d.ts.map +0 -1
- package/dist/tools/protected/submitAppCredentials.d.ts +0 -22
- package/dist/tools/protected/submitAppCredentials.d.ts.map +0 -1
- package/dist/tools/protected/suggestFix.d.ts +0 -22
- package/dist/tools/protected/suggestFix.d.ts.map +0 -1
- package/dist/tools/protected/vulnerabilityActions.d.ts +0 -70
- package/dist/tools/protected/vulnerabilityActions.d.ts.map +0 -1
- package/dist/tools/public/authStatus.d.ts +0 -12
- package/dist/tools/public/authStatus.d.ts.map +0 -1
- package/dist/tools/public/login.d.ts +0 -31
- package/dist/tools/public/login.d.ts.map +0 -1
- package/dist/utils/appResolver.d.ts +0 -24
- package/dist/utils/appResolver.d.ts.map +0 -1
- package/dist/utils/formatters.d.ts +0 -8
- package/dist/utils/formatters.d.ts.map +0 -1
- package/dist/utils/poll.d.ts +0 -19
- package/dist/utils/poll.d.ts.map +0 -1
- package/dist/utils/promptBuilder.d.ts +0 -26
- package/dist/utils/promptBuilder.d.ts.map +0 -1
package/README.md
CHANGED
|
@@ -5,7 +5,7 @@ A standalone Model Context Protocol (MCP) server for the **hosted Perfai cloud A
|
|
|
5
5
|
|
|
6
6
|
## Authentication
|
|
7
7
|
|
|
8
|
-
1. **`
|
|
8
|
+
1. **`PERFAI_API_KEY` env var** (recommended) — a PerfAI API key (`pfk_…`). Create one with `POST /api/v1/api-keys`; it is shown once, expires (default 90 days, max 365) and can be revoked. The server starts already authenticated as the key's owner. `PERFAI_TOKEN` also accepts a key, or an id_token you already have.
|
|
9
9
|
2. **Explicit args** — `login {"email": "...", "password": "..."}`
|
|
10
10
|
3. **Env credentials** — `PERFAI_EMAIL` / `PERFAI_PASSWORD` set in the server's env; `login {}` authenticates directly.
|
|
11
11
|
4. **OAuth login** (Auth0 Authorization Code + PKCE) — if none of the above is available and `AUTH0_CLIENT_ID` is configured (it defaults to Perfai's own client, so this is on by default), `login {}` opens your browser to Auth0's hosted login page and starts a local callback server on `OAUTH_CALLBACK_PORT` (default `5173`). If your browser already has an active Auth0 session, this can complete silently via SSO without prompting for credentials again.
|
|
@@ -33,14 +33,14 @@ logout # clear session
|
|
|
33
33
|
### Organization Management
|
|
34
34
|
| Tool | Description |
|
|
35
35
|
| --- | --- |
|
|
36
|
-
| `manage_organizations` | List the organizations (tenants) your account belongs to and switch between them. Actions: `list` (default), `select` (by `sequence` or `org_id`), `refresh`.
|
|
36
|
+
| `manage_organizations` | List the organizations (tenants) your account belongs to and switch between them. Actions: `list` (default), `select` (by `sequence` or `org_id`), `refresh`. App names are only looked up in the selected organization — select another org here to work in it. |
|
|
37
37
|
|
|
38
38
|
|
|
39
39
|
### App Management
|
|
40
40
|
| Tool | Description |
|
|
41
41
|
| --- | --- |
|
|
42
42
|
| `register_app` | Register a new app by URL for security testing. |
|
|
43
|
-
| `check_app_status` |
|
|
43
|
+
| `check_app_status` | Check onboarding status once (on demand — never polled). |
|
|
44
44
|
| `list_apps` | List all your registered apps. |
|
|
45
45
|
| `select_app` | Switch to a different registered app. |
|
|
46
46
|
| `submit_app_credentials` | Provide login credentials for apps that require authentication. |
|
|
@@ -48,30 +48,44 @@ logout # clear session
|
|
|
48
48
|
### Security Testing
|
|
49
49
|
| Tool | Description |
|
|
50
50
|
| --- | --- |
|
|
51
|
-
| `run_security_test` | Start a security
|
|
52
|
-
| `check_task_status` |
|
|
51
|
+
| `run_security_test` | Start a security test. Accepts `app` (name or URL — a new URL is registered) or `appId`. |
|
|
52
|
+
| `check_task_status` | Check a security test's status once (on demand — never polled). |
|
|
53
53
|
|
|
54
54
|
### Vulnerability Management
|
|
55
55
|
| Tool | Description |
|
|
56
56
|
| --- | --- |
|
|
57
|
-
| `get_vulnerabilities` | List
|
|
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
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. |
|
|
61
|
-
| `get_fix_summary` | Fix progress: fixed, skipped as not applicable, still open — by severity. Accepts `app` (name). |
|
|
62
|
-
| `dismiss_vulnerability` | Dismiss a finding (false positive, accepted risk, etc.) with an optional `reason`, stored on the finding. |
|
|
63
|
-
| `reopen_vulnerability` | Reopen a
|
|
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 (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
|
+
| `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
|
|
|
66
66
|
---
|
|
67
67
|
|
|
68
|
+
## Test, issues, fix
|
|
69
|
+
|
|
70
|
+
| Say | Does |
|
|
71
|
+
| --- | --- |
|
|
72
|
+
| `perfai test <url>` | A new URL is registered and onboarded; onboarding runs the first security test itself. Replies "Onboarding <App>. Say perfai issues later to view issues." |
|
|
73
|
+
| `perfai test` (onboarded app) | Starts a new security test. |
|
|
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 — or says the app is still onboarding. |
|
|
76
|
+
| `perfai fix` / `<App_name> fix all` | Fixes the findings (see below). |
|
|
77
|
+
|
|
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.
|
|
79
|
+
|
|
68
80
|
## One-line fix
|
|
69
81
|
|
|
70
82
|
Connect the server to your code agent, sign in with `login`, open the app's codebase, and type:
|
|
71
83
|
|
|
72
84
|
> **<App_name> fix all**
|
|
73
85
|
|
|
74
|
-
That's it: no listing
|
|
86
|
+
That's it: no listing apps or selecting a project. The agent calls `auto_fix_all` with `app: "<App_name>"`; the name is looked up in your current organization, and the agent fixes every open finding from critical to low by editing code — it does not run commands. Findings that don't apply to your code are dismissed silently with a reason, and the run ends with one line of counts.
|
|
87
|
+
|
|
88
|
+
If your account belongs to several organizations, the app must be in the selected one. Apps in other organizations are never searched; if the name isn't found, select the right org first (*"Switch to the Acme organization"* → `manage_organizations`), then say `<App_name> fix all` again.
|
|
75
89
|
|
|
76
90
|
| Say | Does |
|
|
77
91
|
| --- | --- |
|
|
@@ -98,10 +112,11 @@ The AI handles all the tool calls automatically.
|
|
|
98
112
|
```
|
|
99
113
|
1. login → authenticate
|
|
100
114
|
2. register_app {"appUrl": "https://myapp.com"} → register your app
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
115
|
+
(onboarding runs the first security test in the background)
|
|
116
|
+
3. check_app_status → check onboarding (when you ask)
|
|
117
|
+
4. get_vulnerabilities → see the findings
|
|
118
|
+
5. run_security_test → re-test later (optional)
|
|
119
|
+
6. check_task_status → check that test (when you ask)
|
|
105
120
|
7. auto_fix_all → get fix instructions
|
|
106
121
|
8. (apply fixes in your code)
|
|
107
122
|
9. mark_vulnerability_fixed {"vulnerability_id": "1"} → mark each as done
|
|
@@ -126,6 +141,8 @@ Here are some things you can say to your AI assistant:
|
|
|
126
141
|
| **List my apps** | *"List all my registered apps."* |
|
|
127
142
|
| **Switch apps** | *"Select the app with URL https://other-app.com."* |
|
|
128
143
|
| **Dismiss a finding** | *"Dismiss vulnerability #3 — it's a false positive."* |
|
|
144
|
+
| **Undo a dismissal** | *"Reopen the finding I just dismissed."* |
|
|
145
|
+
| **List dismissed findings** (Perfai staff) | *"Perfai issues dismissed."* |
|
|
129
146
|
|
|
130
147
|
---
|
|
131
148
|
|
|
@@ -167,16 +184,17 @@ $env:MCP_TRANSPORT="http"; node dist/server.js
|
|
|
167
184
|
| --- | --- | --- | --- |
|
|
168
185
|
| `MCP_TRANSPORT` | No | `stdio` | Set to `http` for remote HTTP server mode |
|
|
169
186
|
| `PORT` | No | `3000` | Port for the HTTP server |
|
|
170
|
-
| `
|
|
171
|
-
| `
|
|
172
|
-
| `
|
|
187
|
+
| `PERFAI_API_KEY` | No | — | PerfAI API key (`pfk_…`) — **recommended for headless / cloud workspaces** (Replit, Lovable, Bolt, v0, CI). Skips login entirely. |
|
|
188
|
+
| `PERFAI_TOKEN` | No | — | Same as `PERFAI_API_KEY` (wins if both are set); also accepts a pre-obtained id_token. |
|
|
189
|
+
| `PERFAI_EMAIL` | No | — | Auto-login email (stdio only — ignored in HTTP mode) |
|
|
190
|
+
| `PERFAI_PASSWORD` | No | — | Auto-login password (stdio only — ignored in HTTP mode) |
|
|
173
191
|
| `AUTH0_DOMAIN` | No | `auth.perfai.ai` | Auth0 tenant domain used for OAuth PKCE login and HTTP bearer-token validation |
|
|
174
192
|
| `AUTH0_CLIENT_ID` | No | *(Perfai's public client)* | Auth0 application client ID for the OAuth PKCE browser flow |
|
|
175
193
|
| `AUTH0_AUDIENCE` | No | — | Auth0 API audience, if your tenant requires one |
|
|
176
194
|
| `OAUTH_CALLBACK_PORT` | No | `5173` | Local port the OAuth flow listens on for the Auth0 redirect |
|
|
177
195
|
| `OAUTH_SCOPES` | No | `openid profile email offline_access` | Scopes requested during OAuth login |
|
|
178
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 |
|
|
179
|
-
| `MCP_API_KEY` | No | — | Legacy
|
|
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. |
|
|
180
198
|
|
|
181
199
|
### Deploy with Docker
|
|
182
200
|
|
|
@@ -192,8 +210,8 @@ docker run -p 3000:3000 -e MCP_TRANSPORT=http perfai-mcp
|
|
|
192
210
|
| `POST` | `/mcp` | MCP JSON-RPC requests |
|
|
193
211
|
| `GET` | `/mcp` | SSE stream (server-initiated messages) |
|
|
194
212
|
| `DELETE` | `/mcp` | Session termination |
|
|
195
|
-
| `GET` | `/health` | Health check — `{"status":"ok"}` |
|
|
196
|
-
| `GET` | `/` |
|
|
213
|
+
| `GET` | `/health` | Health check — `{"status":"ok"}` only |
|
|
214
|
+
| `GET` | `/` | `{"status":"ok"}` only. The running version is in the MCP `initialize` reply (`serverInfo.version`). |
|
|
197
215
|
|
|
198
216
|
### Test with MCP Inspector
|
|
199
217
|
|
|
@@ -220,11 +238,11 @@ Every tool maps directly to a Perfai cloud API endpoint:
|
|
|
220
238
|
| `submit_app_credentials` | `POST /v1/apps/{appId}/account-setup` |
|
|
221
239
|
| `run_security_test` | `POST /v1/apps/{appId}/security-agent` |
|
|
222
240
|
| `check_task_status` | `GET /v1/tasks/{taskId}` |
|
|
223
|
-
| `get_vulnerabilities` | `GET /v1/apps/{appId}/vulnerabilities` |
|
|
241
|
+
| `get_vulnerabilities` | `GET /v1/apps/{appId}/vulnerabilities` (`status` → `isFixed` / `isDismissed`) |
|
|
224
242
|
| `suggest_fix` | Local prompt builder (no API call) |
|
|
225
243
|
| `auto_fix` | Local prompt builder (no API call) |
|
|
226
244
|
| `auto_fix_all` | `GET /v1/apps/{appId}/vulnerabilities` + local prompt builder |
|
|
227
|
-
| `get_fix_summary` | `GET /v1/apps/{appId}/vulnerabilities`
|
|
245
|
+
| `get_fix_summary` | `GET /v1/apps/{appId}/vulnerabilities` — default (with `dismissedCount`), `isFixed=true` and `isDismissed=true` — merged locally |
|
|
228
246
|
| `dismiss_vulnerability` | `POST /v1/vulnerabilities/{id}/dismiss` (`reason` → `comment`) |
|
|
229
247
|
| `reopen_vulnerability` | `POST /v1/vulnerabilities/{id}/reopen` |
|
|
230
248
|
| `mark_vulnerability_fixed` | `POST /v1/vulnerabilities/{id}/fix` |
|
|
@@ -241,8 +259,11 @@ Every tool maps directly to a Perfai cloud API endpoint:
|
|
|
241
259
|
| **401 Unauthorized** | Regenerate your access token — make sure email and password are correct |
|
|
242
260
|
| **No tools visible after connecting** | Check that the access token is valid; try refreshing the connection |
|
|
243
261
|
| **"Authentication required" on every tool** | Call `login` first, or verify credentials are set |
|
|
244
|
-
| **`check_app_status`
|
|
245
|
-
|
|
|
262
|
+
| **`check_app_status` says still onboarding** | Normal for first-time onboarding — it runs in the background; check again later |
|
|
263
|
+
| **Status reads Needs input / Needs login** | Onboarding is waiting on you — supply a login with `submit_app_credentials` (or resolve it in the Perfai console), then check again |
|
|
264
|
+
| **Status reads Interrupted** | A problem on Perfai's side; results so far are saved. If it stays that way, run `register_app` again with the same URL |
|
|
265
|
+
| **Status reads Completed — partial** | Some checks didn't run, so `get_vulnerabilities` shows incomplete findings — an area with no finding was not necessarily tested. `run_security_test` can be tried; Perfai says if the app can't be tested until onboarding finishes |
|
|
266
|
+
| **`run_security_test` says the app is still onboarding** | Onboarding runs the first security test itself — check again later, then say `perfai issues` |
|
|
246
267
|
| **429 rate limit errors** | Wait for the `Retry-After` duration and try again |
|
|
247
268
|
| **`suggest_fix` / `auto_fix` says "not found"** | Call `get_vulnerabilities` first in the same session to load the findings |
|
|
248
269
|
| **`MCP error -32000: Connection closed`** | Ensure you ran `npm run build` — clients need `dist/server.js`, not `src/` |
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { createHash, timingSafeEqual } from "node:crypto";
|
|
2
|
+
import { apiKeyId, isPerfaiApiKey } from "../client/authManager.js";
|
|
3
|
+
import { isJWT, validateBearerToken } from "./tokenValidator.js";
|
|
4
|
+
export function hashCredential(value) {
|
|
5
|
+
return createHash("sha256").update(value).digest("hex");
|
|
6
|
+
}
|
|
7
|
+
export function constantTimeEquals(a, b) {
|
|
8
|
+
return timingSafeEqual(createHash("sha256").update(a).digest(), createHash("sha256").update(b).digest());
|
|
9
|
+
}
|
|
10
|
+
function reject(res, status, message) {
|
|
11
|
+
res.status(status).json({ jsonrpc: "2.0", error: { code: -32001, message }, id: null });
|
|
12
|
+
}
|
|
13
|
+
export function createBearerAuth({ mcpApiKey, validateToken = validateBearerToken, }) {
|
|
14
|
+
return async (req, res, next) => {
|
|
15
|
+
const match = /^Bearer\s+(\S+)\s*$/i.exec(req.headers.authorization ?? "");
|
|
16
|
+
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.");
|
|
19
|
+
return;
|
|
20
|
+
}
|
|
21
|
+
const token = match[1];
|
|
22
|
+
const credentialHash = hashCredential(token);
|
|
23
|
+
if (mcpApiKey && constantTimeEquals(token, mcpApiKey)) {
|
|
24
|
+
req.perfaiAuth = { method: "mcp_api_key", credentialHash };
|
|
25
|
+
return next();
|
|
26
|
+
}
|
|
27
|
+
if (isPerfaiApiKey(token)) {
|
|
28
|
+
req.perfaiAuth = { method: "api_key", credentialHash, token };
|
|
29
|
+
console.error(`Authenticated (api_key): pfk_${apiKeyId(token)}`);
|
|
30
|
+
return next();
|
|
31
|
+
}
|
|
32
|
+
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"}`);
|
|
37
|
+
return next();
|
|
38
|
+
}
|
|
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.");
|
|
42
|
+
return;
|
|
43
|
+
}
|
|
44
|
+
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.");
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
export function sameCaller(req, sessionCredentialHash) {
|
|
51
|
+
const presented = req.perfaiAuth?.credentialHash;
|
|
52
|
+
return Boolean(presented) && constantTimeEquals(presented, sessionCredentialHash);
|
|
53
|
+
}
|
package/dist/auth/oauthFlow.js
CHANGED
|
@@ -12,20 +12,6 @@ function openBrowser(url) {
|
|
|
12
12
|
: `xdg-open "${url}"`;
|
|
13
13
|
exec(cmd, () => { });
|
|
14
14
|
}
|
|
15
|
-
/**
|
|
16
|
-
* Full Auth0 Authorization Code + PKCE flow.
|
|
17
|
-
*
|
|
18
|
-
* 1. Generates PKCE code_verifier + code_challenge
|
|
19
|
-
* 2. Starts a temporary local HTTP server on OAUTH_CALLBACK_PORT (default 5173)
|
|
20
|
-
* 3. Opens the browser to Auth0's /authorize endpoint
|
|
21
|
-
* 4. Catches the authorization code via redirect to localhost
|
|
22
|
-
* 5. Exchanges the code for id_token + access_token at Auth0's /oauth/token
|
|
23
|
-
* 6. Returns the tokens
|
|
24
|
-
*
|
|
25
|
-
* Reuses the existing login token — no new auth mechanism — just the
|
|
26
|
-
* standard Auth0 PKCE handshake that produces the same id_token the
|
|
27
|
-
* Perfai API already accepts.
|
|
28
|
-
*/
|
|
29
15
|
export function startOAuthBrowserFlow() {
|
|
30
16
|
return new Promise((resolve, reject) => {
|
|
31
17
|
if (!AUTH0_DOMAIN || !AUTH0_CLIENT_ID) {
|
|
@@ -91,7 +77,6 @@ h1{color:#e53e3e;font-size:24px;margin-bottom:12px}p{color:#666;font-size:14px;l
|
|
|
91
77
|
reject(new Error("OAuth state mismatch"));
|
|
92
78
|
return;
|
|
93
79
|
}
|
|
94
|
-
// Exchange authorization code for tokens
|
|
95
80
|
try {
|
|
96
81
|
const tokens = await exchangeCodeForTokens(code, codeVerifier, redirectUri);
|
|
97
82
|
res.writeHead(200, { "Content-Type": "text/html" });
|
|
@@ -107,7 +92,6 @@ h1{color:#e53e3e;font-size:24px;margin-bottom:12px}p{color:#666;font-size:14px;l
|
|
|
107
92
|
reject(err);
|
|
108
93
|
}
|
|
109
94
|
});
|
|
110
|
-
// 5-minute timeout
|
|
111
95
|
timeoutId = setTimeout(() => {
|
|
112
96
|
cleanup();
|
|
113
97
|
reject(new Error("OAuth login timed out after 5 minutes. Try again."));
|
|
@@ -117,7 +101,6 @@ h1{color:#e53e3e;font-size:24px;margin-bottom:12px}p{color:#666;font-size:14px;l
|
|
|
117
101
|
reject(new Error(`Cannot start OAuth callback server on port ${OAUTH_CALLBACK_PORT}: ${err.message}`));
|
|
118
102
|
});
|
|
119
103
|
callbackServer.listen(OAUTH_CALLBACK_PORT, "127.0.0.1", () => {
|
|
120
|
-
// Build the Auth0 authorize URL
|
|
121
104
|
const authorizeUrl = buildAuthorizeUrl(codeChallenge, state, redirectUri);
|
|
122
105
|
console.error(`OAuth: opening browser to ${AUTH0_DOMAIN}/authorize`);
|
|
123
106
|
console.error(`OAuth: callback listening on ${redirectUri}`);
|
|
@@ -157,13 +140,12 @@ async function exchangeCodeForTokens(code, codeVerifier, redirectUri) {
|
|
|
157
140
|
if (!data.id_token && !data.access_token) {
|
|
158
141
|
throw new Error("Token exchange response missing both id_token and access_token");
|
|
159
142
|
}
|
|
160
|
-
// Extract email from the id_token payload (JWT is base64url-encoded)
|
|
161
143
|
let email;
|
|
162
144
|
try {
|
|
163
145
|
const payload = JSON.parse(Buffer.from(data.id_token.split(".")[1], "base64url").toString());
|
|
164
146
|
email = payload.email;
|
|
165
147
|
}
|
|
166
|
-
catch {
|
|
148
|
+
catch { }
|
|
167
149
|
return {
|
|
168
150
|
idToken: data.id_token,
|
|
169
151
|
accessToken: data.access_token,
|
package/dist/auth/pkce.js
CHANGED
|
@@ -1,17 +1,9 @@
|
|
|
1
1
|
import { randomBytes, createHash } from "node:crypto";
|
|
2
|
-
/**
|
|
3
|
-
* Generate a cryptographically random code_verifier (43–128 chars, unreserved charset).
|
|
4
|
-
* RFC 7636 §4.1
|
|
5
|
-
*/
|
|
6
2
|
export function generateCodeVerifier(length = 64) {
|
|
7
3
|
return randomBytes(length)
|
|
8
4
|
.toString("base64url")
|
|
9
5
|
.slice(0, Math.max(43, Math.min(length, 128)));
|
|
10
6
|
}
|
|
11
|
-
/**
|
|
12
|
-
* Derive the code_challenge from a code_verifier using S256.
|
|
13
|
-
* RFC 7636 §4.2
|
|
14
|
-
*/
|
|
15
7
|
export function generateCodeChallenge(verifier) {
|
|
16
8
|
return createHash("sha256").update(verifier).digest("base64url");
|
|
17
9
|
}
|
|
@@ -1,17 +1,16 @@
|
|
|
1
|
+
import { createHash, createPublicKey, verify } from "node:crypto";
|
|
1
2
|
import axios from "axios";
|
|
2
|
-
import { AUTH0_DOMAIN
|
|
3
|
-
// In-memory cache: token → { email, validatedAt }
|
|
3
|
+
import { AUTH0_DOMAIN } from "../config.js";
|
|
4
4
|
const validatedTokens = new Map();
|
|
5
|
-
const CACHE_TTL_MS = 30 * 60 * 1000;
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
5
|
+
const CACHE_TTL_MS = 30 * 60 * 1000;
|
|
6
|
+
const JWKS_TTL_MS = 10 * 60 * 1000;
|
|
7
|
+
const JWKS_MIN_REFRESH_MS = 30 * 1000;
|
|
8
|
+
let jwks = null;
|
|
9
9
|
export function isJWT(token) {
|
|
10
10
|
const parts = token.split(".");
|
|
11
11
|
if (parts.length !== 3)
|
|
12
12
|
return false;
|
|
13
13
|
try {
|
|
14
|
-
// Verify each part is valid base64url
|
|
15
14
|
for (const part of parts) {
|
|
16
15
|
Buffer.from(part, "base64url");
|
|
17
16
|
}
|
|
@@ -21,10 +20,6 @@ export function isJWT(token) {
|
|
|
21
20
|
return false;
|
|
22
21
|
}
|
|
23
22
|
}
|
|
24
|
-
/**
|
|
25
|
-
* Decode JWT payload without signature verification.
|
|
26
|
-
* Returns null if the token is not a valid JWT.
|
|
27
|
-
*/
|
|
28
23
|
export function decodeJWTPayload(token) {
|
|
29
24
|
try {
|
|
30
25
|
const parts = token.split(".");
|
|
@@ -36,58 +31,77 @@ export function decodeJWTPayload(token) {
|
|
|
36
31
|
return null;
|
|
37
32
|
}
|
|
38
33
|
}
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
export async function validateBearerToken(token) {
|
|
46
|
-
// 1. Check cache
|
|
47
|
-
const cached = validatedTokens.get(token);
|
|
48
|
-
if (cached && Date.now() - cached.validatedAt < CACHE_TTL_MS) {
|
|
49
|
-
return { valid: true, email: cached.email };
|
|
34
|
+
function decodeJWTHeader(token) {
|
|
35
|
+
try {
|
|
36
|
+
return JSON.parse(Buffer.from(token.split(".")[0], "base64url").toString());
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
return null;
|
|
50
40
|
}
|
|
51
|
-
|
|
41
|
+
}
|
|
42
|
+
function tokenHash(token) {
|
|
43
|
+
return createHash("sha256").update(token).digest("hex");
|
|
44
|
+
}
|
|
45
|
+
async function fetchJwks() {
|
|
46
|
+
const response = await axios.get(`https://${AUTH0_DOMAIN}/.well-known/jwks.json`, { timeout: 10_000 });
|
|
47
|
+
const keys = new Map();
|
|
48
|
+
for (const jwk of (response.data?.keys ?? [])) {
|
|
49
|
+
if (jwk.kty !== "RSA" || !jwk.kid)
|
|
50
|
+
continue;
|
|
51
|
+
keys.set(jwk.kid, createPublicKey({ key: jwk, format: "jwk" }));
|
|
52
|
+
}
|
|
53
|
+
jwks = { keys, fetchedAt: Date.now() };
|
|
54
|
+
return keys;
|
|
55
|
+
}
|
|
56
|
+
async function signingKey(kid) {
|
|
57
|
+
const age = jwks ? Date.now() - jwks.fetchedAt : Infinity;
|
|
58
|
+
if (jwks && age < JWKS_TTL_MS && jwks.keys.has(kid))
|
|
59
|
+
return jwks.keys.get(kid);
|
|
60
|
+
if (jwks && age < JWKS_MIN_REFRESH_MS)
|
|
61
|
+
return jwks.keys.get(kid);
|
|
62
|
+
return (await fetchJwks()).get(kid);
|
|
63
|
+
}
|
|
64
|
+
async function verifyJWT(token) {
|
|
65
|
+
const header = decodeJWTHeader(token);
|
|
52
66
|
const payload = decodeJWTPayload(token);
|
|
53
|
-
if (payload)
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
}
|
|
66
|
-
const email = payload.email ?? payload.sub;
|
|
67
|
-
// If Auth0 domain is configured, validate via /userinfo for access_tokens
|
|
68
|
-
if (AUTH0_DOMAIN) {
|
|
69
|
-
const userInfoResult = await validateViaUserInfo(token);
|
|
70
|
-
if (userInfoResult.valid) {
|
|
71
|
-
const resolvedEmail = userInfoResult.email ?? email;
|
|
72
|
-
if (resolvedEmail) {
|
|
73
|
-
validatedTokens.set(token, { email: resolvedEmail, validatedAt: Date.now() });
|
|
74
|
-
}
|
|
75
|
-
return { valid: true, email: resolvedEmail };
|
|
76
|
-
}
|
|
77
|
-
// /userinfo might fail for id_tokens — fall back to structural + expiry check
|
|
78
|
-
}
|
|
79
|
-
// Structural + expiry check passed — trust the token and let the Perfai
|
|
80
|
-
// API do final validation when tools make API calls
|
|
81
|
-
if (email) {
|
|
82
|
-
validatedTokens.set(token, { email, validatedAt: Date.now() });
|
|
83
|
-
}
|
|
84
|
-
return { valid: true, email };
|
|
67
|
+
if (!header || !payload)
|
|
68
|
+
return { valid: false, error: "Malformed token" };
|
|
69
|
+
if (header.alg !== "RS256" || typeof header.kid !== "string") {
|
|
70
|
+
return { valid: false, error: "Unsupported token signature" };
|
|
71
|
+
}
|
|
72
|
+
if (typeof payload.exp !== "number")
|
|
73
|
+
return { valid: false, error: "Token has no expiry" };
|
|
74
|
+
if (payload.exp * 1000 <= Date.now())
|
|
75
|
+
return { valid: false, error: "Token expired" };
|
|
76
|
+
let key;
|
|
77
|
+
try {
|
|
78
|
+
key = await signingKey(header.kid);
|
|
85
79
|
}
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
return
|
|
80
|
+
catch (err) {
|
|
81
|
+
console.error(`JWKS fetch failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
82
|
+
return { valid: false, error: "Could not reach authorization server for validation" };
|
|
83
|
+
}
|
|
84
|
+
if (!key)
|
|
85
|
+
return { valid: false, error: "Unknown signing key" };
|
|
86
|
+
const [h, p, s] = token.split(".");
|
|
87
|
+
const signatureOk = verify("RSA-SHA256", Buffer.from(`${h}.${p}`), key, Buffer.from(s, "base64url"));
|
|
88
|
+
if (!signatureOk)
|
|
89
|
+
return { valid: false, error: "Invalid token signature" };
|
|
90
|
+
const email = payload.email ?? payload.sub;
|
|
91
|
+
validatedTokens.set(tokenHash(token), {
|
|
92
|
+
email,
|
|
93
|
+
expiresAt: Math.min(Date.now() + CACHE_TTL_MS, payload.exp * 1000),
|
|
94
|
+
});
|
|
95
|
+
return { valid: true, email };
|
|
96
|
+
}
|
|
97
|
+
export async function validateBearerToken(token) {
|
|
98
|
+
const cached = validatedTokens.get(tokenHash(token));
|
|
99
|
+
if (cached && Date.now() < cached.expiresAt) {
|
|
100
|
+
return { valid: true, email: cached.email };
|
|
89
101
|
}
|
|
90
|
-
|
|
102
|
+
if (isJWT(token))
|
|
103
|
+
return verifyJWT(token);
|
|
104
|
+
return validateViaUserInfo(token);
|
|
91
105
|
}
|
|
92
106
|
async function validateViaUserInfo(token) {
|
|
93
107
|
try {
|
|
@@ -96,22 +110,18 @@ async function validateViaUserInfo(token) {
|
|
|
96
110
|
timeout: 10_000,
|
|
97
111
|
});
|
|
98
112
|
const email = response.data?.email ?? response.data?.sub;
|
|
99
|
-
|
|
100
|
-
validatedTokens.set(token, { email, validatedAt: Date.now() });
|
|
101
|
-
}
|
|
113
|
+
validatedTokens.set(tokenHash(token), { email, expiresAt: Date.now() + CACHE_TTL_MS });
|
|
102
114
|
return { valid: true, email };
|
|
103
115
|
}
|
|
104
116
|
catch (err) {
|
|
105
117
|
if (axios.isAxiosError(err) && err.response?.status === 401) {
|
|
106
118
|
return { valid: false, error: "Token rejected by authorization server" };
|
|
107
119
|
}
|
|
108
|
-
|
|
109
|
-
return { valid:
|
|
120
|
+
console.error(`Auth0 /userinfo check failed: ${err instanceof Error ? err.message : String(err)}`);
|
|
121
|
+
return { valid: false, error: "Could not reach authorization server for validation" };
|
|
110
122
|
}
|
|
111
123
|
}
|
|
112
|
-
/**
|
|
113
|
-
* Clear the validation cache (useful for logout).
|
|
114
|
-
*/
|
|
115
124
|
export function clearTokenCache() {
|
|
116
125
|
validatedTokens.clear();
|
|
126
|
+
jwks = null;
|
|
117
127
|
}
|