perfai-cloud-mcp 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +243 -0
  3. package/dist/auth/oauthFlow.d.ts +23 -0
  4. package/dist/auth/oauthFlow.d.ts.map +1 -0
  5. package/dist/auth/oauthFlow.js +174 -0
  6. package/dist/auth/pkce.d.ts +11 -0
  7. package/dist/auth/pkce.d.ts.map +1 -0
  8. package/dist/auth/pkce.js +17 -0
  9. package/dist/auth/tokenValidator.d.ts +40 -0
  10. package/dist/auth/tokenValidator.d.ts.map +1 -0
  11. package/dist/auth/tokenValidator.js +117 -0
  12. package/dist/cli.d.ts +3 -0
  13. package/dist/cli.d.ts.map +1 -0
  14. package/dist/cli.js +387 -0
  15. package/dist/client/apiClient.d.ts +27 -0
  16. package/dist/client/apiClient.d.ts.map +1 -0
  17. package/dist/client/apiClient.js +81 -0
  18. package/dist/client/authManager.d.ts +42 -0
  19. package/dist/client/authManager.d.ts.map +1 -0
  20. package/dist/client/authManager.js +136 -0
  21. package/dist/client/errors.d.ts +10 -0
  22. package/dist/client/errors.d.ts.map +1 -0
  23. package/dist/client/errors.js +29 -0
  24. package/dist/client/types.d.ts +54 -0
  25. package/dist/client/types.d.ts.map +1 -0
  26. package/dist/client/types.js +1 -0
  27. package/dist/config.d.ts +23 -0
  28. package/dist/config.d.ts.map +1 -0
  29. package/dist/config.js +50 -0
  30. package/dist/env.d.ts +2 -0
  31. package/dist/env.d.ts.map +1 -0
  32. package/dist/env.js +8 -0
  33. package/dist/log-guard.d.ts +2 -0
  34. package/dist/log-guard.d.ts.map +1 -0
  35. package/dist/log-guard.js +17 -0
  36. package/dist/server.d.ts +4 -0
  37. package/dist/server.d.ts.map +1 -0
  38. package/dist/server.js +370 -0
  39. package/dist/tools/index.d.ts +352 -0
  40. package/dist/tools/index.d.ts.map +1 -0
  41. package/dist/tools/index.js +39 -0
  42. package/dist/tools/protected/autoFix.d.ts +22 -0
  43. package/dist/tools/protected/autoFix.d.ts.map +1 -0
  44. package/dist/tools/protected/autoFix.js +64 -0
  45. package/dist/tools/protected/autoFixAll.d.ts +26 -0
  46. package/dist/tools/protected/autoFixAll.d.ts.map +1 -0
  47. package/dist/tools/protected/autoFixAll.js +79 -0
  48. package/dist/tools/protected/checkAppStatus.d.ts +21 -0
  49. package/dist/tools/protected/checkAppStatus.d.ts.map +1 -0
  50. package/dist/tools/protected/checkAppStatus.js +57 -0
  51. package/dist/tools/protected/checkTaskStatus.d.ts +21 -0
  52. package/dist/tools/protected/checkTaskStatus.d.ts.map +1 -0
  53. package/dist/tools/protected/checkTaskStatus.js +53 -0
  54. package/dist/tools/protected/getFixSummary.d.ts +17 -0
  55. package/dist/tools/protected/getFixSummary.d.ts.map +1 -0
  56. package/dist/tools/protected/getFixSummary.js +90 -0
  57. package/dist/tools/protected/getVulnerabilities.d.ts +29 -0
  58. package/dist/tools/protected/getVulnerabilities.d.ts.map +1 -0
  59. package/dist/tools/protected/getVulnerabilities.js +41 -0
  60. package/dist/tools/protected/listApps.d.ts +25 -0
  61. package/dist/tools/protected/listApps.d.ts.map +1 -0
  62. package/dist/tools/protected/listApps.js +32 -0
  63. package/dist/tools/protected/logout.d.ts +12 -0
  64. package/dist/tools/protected/logout.d.ts.map +1 -0
  65. package/dist/tools/protected/logout.js +9 -0
  66. package/dist/tools/protected/registerApp.d.ts +33 -0
  67. package/dist/tools/protected/registerApp.d.ts.map +1 -0
  68. package/dist/tools/protected/registerApp.js +96 -0
  69. package/dist/tools/protected/runSecurityTest.d.ts +17 -0
  70. package/dist/tools/protected/runSecurityTest.d.ts.map +1 -0
  71. package/dist/tools/protected/runSecurityTest.js +48 -0
  72. package/dist/tools/protected/selectApp.d.ts +18 -0
  73. package/dist/tools/protected/selectApp.d.ts.map +1 -0
  74. package/dist/tools/protected/selectApp.js +29 -0
  75. package/dist/tools/protected/submitAppCredentials.d.ts +22 -0
  76. package/dist/tools/protected/submitAppCredentials.d.ts.map +1 -0
  77. package/dist/tools/protected/submitAppCredentials.js +43 -0
  78. package/dist/tools/protected/suggestFix.d.ts +22 -0
  79. package/dist/tools/protected/suggestFix.d.ts.map +1 -0
  80. package/dist/tools/protected/suggestFix.js +37 -0
  81. package/dist/tools/protected/vulnerabilityActions.d.ts +62 -0
  82. package/dist/tools/protected/vulnerabilityActions.d.ts.map +1 -0
  83. package/dist/tools/protected/vulnerabilityActions.js +69 -0
  84. package/dist/tools/public/authStatus.d.ts +12 -0
  85. package/dist/tools/public/authStatus.d.ts.map +1 -0
  86. package/dist/tools/public/authStatus.js +13 -0
  87. package/dist/tools/public/login.d.ts +21 -0
  88. package/dist/tools/public/login.d.ts.map +1 -0
  89. package/dist/tools/public/login.js +305 -0
  90. package/dist/utils/formatters.d.ts +7 -0
  91. package/dist/utils/formatters.d.ts.map +1 -0
  92. package/dist/utils/formatters.js +47 -0
  93. package/dist/utils/poll.d.ts +19 -0
  94. package/dist/utils/poll.d.ts.map +1 -0
  95. package/dist/utils/poll.js +32 -0
  96. package/dist/utils/promptBuilder.d.ts +20 -0
  97. package/dist/utils/promptBuilder.d.ts.map +1 -0
  98. package/dist/utils/promptBuilder.js +131 -0
  99. package/package.json +55 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 PerfAI Team
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,243 @@
1
+ # PerfAI Cloud MCP Server
2
+
3
+ A standalone Model Context Protocol (MCP) server for the **hosted PerfAI cloud API**. Register an app by its URL, let PerfAI run a security test in the cloud, pull the findings, and get an AI-powered fix prompt — from any MCP-compatible client.
4
+
5
+
6
+ ## Authentication
7
+
8
+ 1. **`PERFAI_TOKEN` env var** — if set, the server starts already authenticated, no `login` call needed. This is the same session token the OAuth/browser flows below produce — paste in one you already have.
9
+ 2. **Explicit args** — `login {"email": "...", "password": "..."}`
10
+ 3. **Env credentials** — `PERFAI_EMAIL` / `PERFAI_PASSWORD` set in the server's env; `login {}` authenticates directly.
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.
12
+ 5. **Legacy browser login form** — fallback if OAuth is explicitly disabled (`AUTH0_CLIENT_ID=""`): opens a local HTML login form on `http://127.0.0.1:18200–18300`.
13
+
14
+ Once you see "Authenticated!" in the browser, call `login` again to confirm the session server-side.
15
+
16
+ ```
17
+ login # tries token / env / OAuth / browser login in the order above
18
+ auth_status # verify you're authenticated, see auth method, current app/task
19
+ logout # clear session
20
+ ```
21
+
22
+ For cloud workspace environments, set `PERFAI_TOKEN` in the MCP server's env config instead. It's the same session token the browser/OAuth flow already produces:
23
+
24
+ 1. Sign in once at [cloud.perfai.ai](https://cloud.perfai.ai) (or run the OAuth flow locally once).
25
+ 2. Copy your `id_token` from the console, or from the `login` tool's confirmation output.
26
+ 3. Paste it into your cloud workspace's MCP server config as `PERFAI_TOKEN`. No password ever touches that environment.
27
+
28
+
29
+ See `.env.example` for the full token/OAuth configuration reference.
30
+
31
+ ---
32
+
33
+ ## Available Tools
34
+
35
+ ### Authentication
36
+ | Tool | Description |
37
+ | --- | --- |
38
+ | `login` | Sign in to PerfAI. Opens browser or uses provided credentials. |
39
+ | `auth_status` | Check if you're currently authenticated. |
40
+ | `logout` | Sign out and clear session. |
41
+
42
+ ### App Management
43
+ | Tool | Description |
44
+ | --- | --- |
45
+ | `register_app` | Register a new app by URL for security testing. |
46
+ | `check_app_status` | Poll registration progress until complete. |
47
+ | `list_apps` | List all your registered apps. |
48
+ | `select_app` | Switch to a different registered app. |
49
+ | `submit_app_credentials` | Provide login credentials for apps that require authentication. |
50
+
51
+ ### Security Testing
52
+ | Tool | Description |
53
+ | --- | --- |
54
+ | `run_security_test` | Start a security scan on the current app. |
55
+ | `check_task_status` | Poll scan progress until complete. |
56
+
57
+ ### Vulnerability Management
58
+ | Tool | Description |
59
+ | --- | --- |
60
+ | `get_vulnerabilities` | List all findings from the latest scan. |
61
+ | `suggest_fix` | Get a conversational fix prompt for a specific vulnerability. |
62
+ | `auto_fix` | Get structured, step-by-step fix instructions for one vulnerability. |
63
+ | `auto_fix_all` | Get a prioritized fix plan for ALL unfixed vulnerabilities. |
64
+ | `get_fix_summary` | View fix progress dashboard (fixed/unfixed/dismissed by severity). |
65
+ | `dismiss_vulnerability` | Dismiss a finding (false positive, accepted risk, etc.). |
66
+ | `reopen_vulnerability` | Reopen a previously dismissed finding. |
67
+ | `mark_vulnerability_fixed` | Mark a finding as fixed after applying the code change. |
68
+
69
+ ---
70
+
71
+ ## Typical Workflow
72
+
73
+ ### The simple version
74
+
75
+ Just tell your AI assistant:
76
+
77
+ > *"Register https://myapp.com, run a security test, show me the results, and auto-fix everything."*
78
+
79
+ The AI handles all the tool calls automatically.
80
+
81
+ ### Step-by-step version
82
+
83
+ ```
84
+ 1. login → authenticate
85
+ 2. register_app {"appUrl": "https://myapp.com"} → register your app
86
+ 3. check_app_status → wait for registration
87
+ 4. run_security_test → start the scan
88
+ 5. check_task_status → wait for scan to finish
89
+ 6. get_vulnerabilities → see the findings
90
+ 7. auto_fix_all → get fix instructions
91
+ 8. (apply fixes in your code)
92
+ 9. mark_vulnerability_fixed {"vulnerability_id": "1"} → mark each as done
93
+ 10. get_fix_summary → verify progress
94
+ ```
95
+
96
+ ---
97
+
98
+ ## Example Prompts
99
+
100
+ Here are some things you can say to your AI assistant:
101
+
102
+ | What you want | What to say |
103
+ | --- | --- |
104
+ | **Full scan** | *"Register https://api.myapp.com, run a security test, and show me all vulnerabilities."* |
105
+ | **Fix everything** | *"Auto-fix all vulnerabilities for my current app."* |
106
+ | **Fix one issue** | *"Show me how to fix vulnerability #2."* |
107
+ | **Check progress** | *"Show me the fix summary for my app."* |
108
+ | **List my apps** | *"List all my registered apps."* |
109
+ | **Switch apps** | *"Select the app with URL https://other-app.com."* |
110
+ | **Dismiss a finding** | *"Dismiss vulnerability #3 — it's a false positive."* |
111
+
112
+ ---
113
+
114
+ ## Self-Hosting / Development
115
+
116
+ ### Prerequisites
117
+
118
+ - Node.js 18+
119
+ - npm
120
+
121
+ ### Build from source
122
+
123
+ ```bash
124
+ git clone https://github.com/user/mcp-server.git
125
+ cd mcp-server
126
+ npm install
127
+ npm run build
128
+ ```
129
+
130
+ ### Run locally
131
+
132
+ **Stdio mode** (for Cursor / Claude Code):
133
+ ```bash
134
+ npm start
135
+ ```
136
+
137
+ **HTTP mode** (for ChatGPT / remote access):
138
+ ```bash
139
+ # Linux / Mac
140
+ MCP_TRANSPORT=http node dist/server.js
141
+
142
+ # Windows PowerShell
143
+ $env:MCP_TRANSPORT="http"; node dist/server.js
144
+ ```
145
+
146
+ ### Environment Variables
147
+
148
+ | Variable | Required | Default | Description |
149
+ | --- | --- | --- | --- |
150
+ | `MCP_TRANSPORT` | No | `stdio` | Set to `http` for remote HTTP server mode |
151
+ | `PORT` | No | `3000` | Port for the HTTP server |
152
+ | `PERFAI_TOKEN` | No | — | Pre-obtained session token — **recommended for headless / cloud workspaces** (Replit, Lovable, Bolt, v0, CI). Skips login entirely. |
153
+ | `PERFAI_EMAIL` | No | — | Auto-login email (for local/stdio mode) |
154
+ | `PERFAI_PASSWORD` | No | — | Auto-login password (for local/stdio mode) |
155
+ | `AUTH0_DOMAIN` | No | `auth.perfai.ai` | Auth0 tenant domain used for OAuth PKCE login and HTTP bearer-token validation |
156
+ | `AUTH0_CLIENT_ID` | No | *(PerfAI's public client)* | Auth0 application client ID for the OAuth PKCE browser flow |
157
+ | `AUTH0_AUDIENCE` | No | — | Auth0 API audience, if your tenant requires one |
158
+ | `OAUTH_CALLBACK_PORT` | No | `5173` | Local port the OAuth flow listens on for the Auth0 redirect |
159
+ | `OAUTH_SCOPES` | No | `openid profile email offline_access` | Scopes requested during OAuth login |
160
+ | `MCP_API_KEY` | No | — | Legacy static API key (accepted alongside credential tokens) |
161
+
162
+ ### Deploy with Docker
163
+
164
+ ```bash
165
+ docker build -t perfai-mcp .
166
+ docker run -p 3000:3000 -e MCP_TRANSPORT=http perfai-mcp
167
+ ```
168
+
169
+ ### Endpoints (HTTP mode)
170
+
171
+ | Method | Path | Description |
172
+ | --- | --- | --- |
173
+ | `POST` | `/mcp` | MCP JSON-RPC requests |
174
+ | `GET` | `/mcp` | SSE stream (server-initiated messages) |
175
+ | `DELETE` | `/mcp` | Session termination |
176
+ | `GET` | `/health` | Health check — `{"status":"ok"}` |
177
+ | `GET` | `/` | Server info |
178
+
179
+ ### Test with MCP Inspector
180
+
181
+ ```bash
182
+ npm run mcp:inspect
183
+ ```
184
+
185
+ Opens the Inspector UI at `http://localhost:6274` where you can test tools interactively.
186
+
187
+ ---
188
+
189
+ ## API Mapping
190
+
191
+ Every tool maps directly to a PerfAI cloud API endpoint:
192
+
193
+ | Tool | API Endpoint |
194
+ | --- | --- |
195
+ | `login` | `POST /api/v1/auth/token` |
196
+ | `register_app` | `POST /v1/apps` |
197
+ | `check_app_status` | `GET /v1/apps/{appId}` |
198
+ | `list_apps` | `GET /v1/apps` |
199
+ | `select_app` | `GET /v1/apps/{appId}` |
200
+ | `submit_app_credentials` | `POST /v1/apps/{appId}/account-setup` |
201
+ | `run_security_test` | `POST /v1/apps/{appId}/security-agent` |
202
+ | `check_task_status` | `GET /v1/tasks/{taskId}` |
203
+ | `get_vulnerabilities` | `GET /v1/apps/{appId}/vulnerabilities` |
204
+ | `suggest_fix` | Local prompt builder (no API call) |
205
+ | `auto_fix` | Local prompt builder (no API call) |
206
+ | `auto_fix_all` | `GET /v1/apps/{appId}/vulnerabilities` + local prompt builder |
207
+ | `get_fix_summary` | `GET /v1/apps/{appId}/vulnerabilities` + local aggregation |
208
+ | `dismiss_vulnerability` | `POST /v1/vulnerabilities/{id}/dismiss` |
209
+ | `reopen_vulnerability` | `POST /v1/vulnerabilities/{id}/reopen` |
210
+ | `mark_vulnerability_fixed` | `POST /v1/vulnerabilities/{id}/fix` |
211
+ | `auth_status` / `logout` | Local session state only |
212
+
213
+ ---
214
+
215
+ ## Troubleshooting
216
+
217
+ | Problem | Solution |
218
+ | --- | --- |
219
+ | **Can't connect from ChatGPT** | Make sure the URL ends with `/mcp`: `https://mcp-server.perfai.ai/mcp` |
220
+ | **401 Unauthorized** | Regenerate your access token — make sure email and password are correct |
221
+ | **No tools visible after connecting** | Check that the access token is valid; try refreshing the connection |
222
+ | **"Authentication required" on every tool** | Call `login` first, or verify credentials are set |
223
+ | **`check_app_status` keeps returning non-terminal** | Normal for first-time onboarding — keep calling it, or pass a larger `wait_seconds` |
224
+ | **`run_security_test` returns 400** | App isn't fully registered yet — call `check_app_status` until it shows `COMPLETED` |
225
+ | **429 rate limit errors** | Wait for the `Retry-After` duration and try again |
226
+ | **`suggest_fix` / `auto_fix` says "not found"** | Call `get_vulnerabilities` first in the same session to load the findings |
227
+ | **`MCP error -32000: Connection closed`** | Ensure you ran `npm run build` — clients need `dist/server.js`, not `src/` |
228
+
229
+ ---
230
+
231
+ ## Security
232
+
233
+ - Access tokens are transmitted over **HTTPS** only
234
+ - Tokens are validated against the PerfAI cloud auth API on every new session
235
+ - Validated tokens are cached server-side for 30 minutes to reduce auth API calls
236
+ - Each MCP session gets its own isolated authentication state
237
+ - No credentials are stored on disk by the MCP server
238
+
239
+ ---
240
+
241
+ ## License
242
+
243
+ MIT
@@ -0,0 +1,23 @@
1
+ export interface OAuthTokens {
2
+ idToken: string;
3
+ accessToken: string;
4
+ refreshToken?: string;
5
+ expiresIn?: number;
6
+ email?: string;
7
+ }
8
+ /**
9
+ * Full Auth0 Authorization Code + PKCE flow.
10
+ *
11
+ * 1. Generates PKCE code_verifier + code_challenge
12
+ * 2. Starts a temporary local HTTP server on OAUTH_CALLBACK_PORT (default 5173)
13
+ * 3. Opens the browser to Auth0's /authorize endpoint
14
+ * 4. Catches the authorization code via redirect to localhost
15
+ * 5. Exchanges the code for id_token + access_token at Auth0's /oauth/token
16
+ * 6. Returns the tokens
17
+ *
18
+ * Reuses the existing login token — no new auth mechanism — just the
19
+ * standard Auth0 PKCE handshake that produces the same id_token the
20
+ * PerfAI API already accepts.
21
+ */
22
+ export declare function startOAuthBrowserFlow(): Promise<OAuthTokens>;
23
+ //# sourceMappingURL=oauthFlow.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"oauthFlow.d.ts","sourceRoot":"","sources":["../../src/auth/oauthFlow.ts"],"names":[],"mappings":"AAeA,MAAM,WAAW,WAAW;IAC1B,OAAO,EAAE,MAAM,CAAC;IAChB,WAAW,EAAE,MAAM,CAAC;IACpB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAUD;;;;;;;;;;;;;GAaG;AACH,wBAAgB,qBAAqB,IAAI,OAAO,CAAC,WAAW,CAAC,CAiH5D"}
@@ -0,0 +1,174 @@
1
+ import { createServer } from "node:http";
2
+ import { exec } from "node:child_process";
3
+ import { platform } from "node:os";
4
+ import { URL, URLSearchParams } from "node:url";
5
+ import { randomBytes } from "node:crypto";
6
+ import axios from "axios";
7
+ import { generateCodeVerifier, generateCodeChallenge } from "./pkce.js";
8
+ import { AUTH0_DOMAIN, AUTH0_CLIENT_ID, AUTH0_AUDIENCE, OAUTH_CALLBACK_PORT, OAUTH_SCOPES, } from "../config.js";
9
+ function openBrowser(url) {
10
+ const cmd = platform() === "win32" ? `start "" "${url}"`
11
+ : platform() === "darwin" ? `open "${url}"`
12
+ : `xdg-open "${url}"`;
13
+ exec(cmd, () => { });
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
+ export function startOAuthBrowserFlow() {
30
+ return new Promise((resolve, reject) => {
31
+ if (!AUTH0_DOMAIN || !AUTH0_CLIENT_ID) {
32
+ reject(new Error("OAuth not configured. Set AUTH0_DOMAIN and AUTH0_CLIENT_ID environment variables. " +
33
+ "Fall back to PERFAI_EMAIL/PERFAI_PASSWORD or PERFAI_TOKEN for non-interactive login."));
34
+ return;
35
+ }
36
+ const codeVerifier = generateCodeVerifier();
37
+ const codeChallenge = generateCodeChallenge(codeVerifier);
38
+ const state = randomBytes(16).toString("hex");
39
+ const redirectUri = `http://localhost:${OAUTH_CALLBACK_PORT}`;
40
+ let callbackServer = null;
41
+ let timeoutId = null;
42
+ const cleanup = () => {
43
+ if (timeoutId)
44
+ clearTimeout(timeoutId);
45
+ if (callbackServer) {
46
+ callbackServer.close();
47
+ callbackServer = null;
48
+ }
49
+ };
50
+ const SUCCESS_HTML = `<!DOCTYPE html><html><head><meta charset="UTF-8">
51
+ <title>PerfAI — Authenticated</title>
52
+ <style>*{margin:0;padding:0;box-sizing:border-box}body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;background:#f5f5f5;display:flex;align-items:center;justify-content:center;min-height:100vh}
53
+ .c{background:#fff;border-radius:12px;padding:40px;box-shadow:0 4px 24px rgba(0,0,0,.1);max-width:420px;text-align:center}
54
+ h1{color:#38a169;font-size:24px;margin-bottom:12px}p{color:#666;font-size:14px;line-height:1.5}</style></head>
55
+ <body><div class="c"><h1>Authenticated!</h1><p>You can close this tab and return to your AI assistant.</p></div></body></html>`;
56
+ const ERROR_HTML = (msg) => `<!DOCTYPE html><html><head><meta charset="UTF-8">
57
+ <title>PerfAI — Error</title>
58
+ <style>*{margin:0;padding:0;box-sizing:border-box}body{font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;background:#f5f5f5;display:flex;align-items:center;justify-content:center;min-height:100vh}
59
+ .c{background:#fff;border-radius:12px;padding:40px;box-shadow:0 4px 24px rgba(0,0,0,.1);max-width:420px;text-align:center}
60
+ h1{color:#e53e3e;font-size:24px;margin-bottom:12px}p{color:#666;font-size:14px;line-height:1.5}</style></head>
61
+ <body><div class="c"><h1>Login Failed</h1><p>${msg}</p></div></body></html>`;
62
+ callbackServer = createServer(async (req, res) => {
63
+ const url = new URL(req.url ?? "/", `http://localhost:${OAUTH_CALLBACK_PORT}`);
64
+ if (url.pathname !== "/" && url.pathname !== "/callback") {
65
+ res.writeHead(404);
66
+ res.end("Not found");
67
+ return;
68
+ }
69
+ const error = url.searchParams.get("error");
70
+ if (error) {
71
+ const desc = url.searchParams.get("error_description") ?? error;
72
+ res.writeHead(200, { "Content-Type": "text/html" });
73
+ res.end(ERROR_HTML(desc));
74
+ cleanup();
75
+ reject(new Error(`OAuth error: ${desc}`));
76
+ return;
77
+ }
78
+ const code = url.searchParams.get("code");
79
+ const returnedState = url.searchParams.get("state");
80
+ if (!code) {
81
+ res.writeHead(200, { "Content-Type": "text/html" });
82
+ res.end(ERROR_HTML("No authorization code received."));
83
+ cleanup();
84
+ reject(new Error("No authorization code in callback"));
85
+ return;
86
+ }
87
+ if (returnedState !== state) {
88
+ res.writeHead(200, { "Content-Type": "text/html" });
89
+ res.end(ERROR_HTML("State mismatch — possible CSRF. Try again."));
90
+ cleanup();
91
+ reject(new Error("OAuth state mismatch"));
92
+ return;
93
+ }
94
+ // Exchange authorization code for tokens
95
+ try {
96
+ const tokens = await exchangeCodeForTokens(code, codeVerifier, redirectUri);
97
+ res.writeHead(200, { "Content-Type": "text/html" });
98
+ res.end(SUCCESS_HTML);
99
+ setTimeout(cleanup, 1000);
100
+ resolve(tokens);
101
+ }
102
+ catch (err) {
103
+ const msg = err instanceof Error ? err.message : String(err);
104
+ res.writeHead(200, { "Content-Type": "text/html" });
105
+ res.end(ERROR_HTML(msg));
106
+ cleanup();
107
+ reject(err);
108
+ }
109
+ });
110
+ // 5-minute timeout
111
+ timeoutId = setTimeout(() => {
112
+ cleanup();
113
+ reject(new Error("OAuth login timed out after 5 minutes. Try again."));
114
+ }, 5 * 60 * 1000);
115
+ callbackServer.on("error", (err) => {
116
+ cleanup();
117
+ reject(new Error(`Cannot start OAuth callback server on port ${OAUTH_CALLBACK_PORT}: ${err.message}`));
118
+ });
119
+ callbackServer.listen(OAUTH_CALLBACK_PORT, "127.0.0.1", () => {
120
+ // Build the Auth0 authorize URL
121
+ const authorizeUrl = buildAuthorizeUrl(codeChallenge, state, redirectUri);
122
+ console.error(`OAuth: opening browser to ${AUTH0_DOMAIN}/authorize`);
123
+ console.error(`OAuth: callback listening on ${redirectUri}`);
124
+ openBrowser(authorizeUrl);
125
+ });
126
+ });
127
+ }
128
+ function buildAuthorizeUrl(codeChallenge, state, redirectUri) {
129
+ const params = new URLSearchParams({
130
+ response_type: "code",
131
+ client_id: AUTH0_CLIENT_ID,
132
+ redirect_uri: redirectUri,
133
+ scope: OAUTH_SCOPES,
134
+ state,
135
+ code_challenge: codeChallenge,
136
+ code_challenge_method: "S256",
137
+ });
138
+ if (AUTH0_AUDIENCE) {
139
+ params.set("audience", AUTH0_AUDIENCE);
140
+ }
141
+ return `https://${AUTH0_DOMAIN}/authorize?${params.toString()}`;
142
+ }
143
+ async function exchangeCodeForTokens(code, codeVerifier, redirectUri) {
144
+ const tokenUrl = `https://${AUTH0_DOMAIN}/oauth/token`;
145
+ const body = {
146
+ grant_type: "authorization_code",
147
+ client_id: AUTH0_CLIENT_ID,
148
+ code,
149
+ code_verifier: codeVerifier,
150
+ redirect_uri: redirectUri,
151
+ };
152
+ const response = await axios.post(tokenUrl, body, {
153
+ headers: { "Content-Type": "application/json" },
154
+ timeout: 30_000,
155
+ });
156
+ const data = response.data;
157
+ if (!data.id_token && !data.access_token) {
158
+ throw new Error("Token exchange response missing both id_token and access_token");
159
+ }
160
+ // Extract email from the id_token payload (JWT is base64url-encoded)
161
+ let email;
162
+ try {
163
+ const payload = JSON.parse(Buffer.from(data.id_token.split(".")[1], "base64url").toString());
164
+ email = payload.email;
165
+ }
166
+ catch { /* non-critical */ }
167
+ return {
168
+ idToken: data.id_token,
169
+ accessToken: data.access_token,
170
+ refreshToken: data.refresh_token,
171
+ expiresIn: data.expires_in,
172
+ email,
173
+ };
174
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Generate a cryptographically random code_verifier (43–128 chars, unreserved charset).
3
+ * RFC 7636 §4.1
4
+ */
5
+ export declare function generateCodeVerifier(length?: number): string;
6
+ /**
7
+ * Derive the code_challenge from a code_verifier using S256.
8
+ * RFC 7636 §4.2
9
+ */
10
+ export declare function generateCodeChallenge(verifier: string): string;
11
+ //# sourceMappingURL=pkce.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pkce.d.ts","sourceRoot":"","sources":["../../src/auth/pkce.ts"],"names":[],"mappings":"AAEA;;;GAGG;AACH,wBAAgB,oBAAoB,CAAC,MAAM,SAAK,GAAG,MAAM,CAIxD;AAED;;;GAGG;AACH,wBAAgB,qBAAqB,CAAC,QAAQ,EAAE,MAAM,GAAG,MAAM,CAE9D"}
@@ -0,0 +1,17 @@
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
+ export function generateCodeVerifier(length = 64) {
7
+ return randomBytes(length)
8
+ .toString("base64url")
9
+ .slice(0, Math.max(43, Math.min(length, 128)));
10
+ }
11
+ /**
12
+ * Derive the code_challenge from a code_verifier using S256.
13
+ * RFC 7636 §4.2
14
+ */
15
+ export function generateCodeChallenge(verifier) {
16
+ return createHash("sha256").update(verifier).digest("base64url");
17
+ }
@@ -0,0 +1,40 @@
1
+ /**
2
+ * Lightweight JWT validation for the HTTP transport's bearer auth.
3
+ *
4
+ * Strategy: call Auth0's /userinfo endpoint with the access_token.
5
+ * If Auth0 accepts it, the token is valid and we get the user's email.
6
+ * This avoids pulling in a JWKS library while still validating tokens
7
+ * against the real authorization server.
8
+ *
9
+ * For id_tokens (which the PerfAI API accepts as Bearer), we also
10
+ * support a basic structural check + expiry validation without
11
+ * signature verification — the PerfAI API itself is the final
12
+ * authority on token validity.
13
+ */
14
+ interface TokenValidation {
15
+ valid: boolean;
16
+ email?: string;
17
+ error?: string;
18
+ }
19
+ /**
20
+ * Check if a bearer token is a structurally valid JWT (three base64url segments).
21
+ */
22
+ export declare function isJWT(token: string): boolean;
23
+ /**
24
+ * Decode JWT payload without signature verification.
25
+ * Returns null if the token is not a valid JWT.
26
+ */
27
+ export declare function decodeJWTPayload(token: string): Record<string, unknown> | null;
28
+ /**
29
+ * Validate a bearer token. Supports:
30
+ * 1. Cached tokens (skip re-validation for 30 min)
31
+ * 2. JWT tokens — decode payload, check expiry, optionally validate via Auth0 /userinfo
32
+ * 3. Opaque tokens — validate via Auth0 /userinfo if AUTH0_DOMAIN is configured
33
+ */
34
+ export declare function validateBearerToken(token: string): Promise<TokenValidation>;
35
+ /**
36
+ * Clear the validation cache (useful for logout).
37
+ */
38
+ export declare function clearTokenCache(): void;
39
+ export {};
40
+ //# sourceMappingURL=tokenValidator.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"tokenValidator.d.ts","sourceRoot":"","sources":["../../src/auth/tokenValidator.ts"],"names":[],"mappings":"AAGA;;;;;;;;;;;;GAYG;AAEH,UAAU,eAAe;IACvB,KAAK,EAAE,OAAO,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC;IACf,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAMD;;GAEG;AACH,wBAAgB,KAAK,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAY5C;AAED;;;GAGG;AACH,wBAAgB,gBAAgB,CAAC,KAAK,EAAE,MAAM,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,GAAG,IAAI,CAQ9E;AAED;;;;;GAKG;AACH,wBAAsB,mBAAmB,CAAC,KAAK,EAAE,MAAM,GAAG,OAAO,CAAC,eAAe,CAAC,CAqDjF;AAsBD;;GAEG;AACH,wBAAgB,eAAe,IAAI,IAAI,CAEtC"}
@@ -0,0 +1,117 @@
1
+ import axios from "axios";
2
+ import { AUTH0_DOMAIN, AUTH0_AUDIENCE } from "../config.js";
3
+ // In-memory cache: token → { email, validatedAt }
4
+ const validatedTokens = new Map();
5
+ const CACHE_TTL_MS = 30 * 60 * 1000; // 30 minutes
6
+ /**
7
+ * Check if a bearer token is a structurally valid JWT (three base64url segments).
8
+ */
9
+ export function isJWT(token) {
10
+ const parts = token.split(".");
11
+ if (parts.length !== 3)
12
+ return false;
13
+ try {
14
+ // Verify each part is valid base64url
15
+ for (const part of parts) {
16
+ Buffer.from(part, "base64url");
17
+ }
18
+ return true;
19
+ }
20
+ catch {
21
+ return false;
22
+ }
23
+ }
24
+ /**
25
+ * Decode JWT payload without signature verification.
26
+ * Returns null if the token is not a valid JWT.
27
+ */
28
+ export function decodeJWTPayload(token) {
29
+ try {
30
+ const parts = token.split(".");
31
+ if (parts.length !== 3)
32
+ return null;
33
+ return JSON.parse(Buffer.from(parts[1], "base64url").toString());
34
+ }
35
+ catch {
36
+ return null;
37
+ }
38
+ }
39
+ /**
40
+ * Validate a bearer token. Supports:
41
+ * 1. Cached tokens (skip re-validation for 30 min)
42
+ * 2. JWT tokens — decode payload, check expiry, optionally validate via Auth0 /userinfo
43
+ * 3. Opaque tokens — validate via Auth0 /userinfo if AUTH0_DOMAIN is configured
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 };
50
+ }
51
+ // 2. Try JWT decode
52
+ const payload = decodeJWTPayload(token);
53
+ if (payload) {
54
+ // Check expiry
55
+ if (typeof payload.exp === "number" && payload.exp * 1000 < Date.now()) {
56
+ return { valid: false, error: "Token expired" };
57
+ }
58
+ // Check audience if configured
59
+ if (AUTH0_AUDIENCE && payload.aud) {
60
+ const audiences = Array.isArray(payload.aud) ? payload.aud : [payload.aud];
61
+ if (!audiences.includes(AUTH0_AUDIENCE)) {
62
+ // Don't reject — the id_token's audience might be the Auth0 client_id,
63
+ // not the API audience. The PerfAI API is the final validator.
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 };
85
+ }
86
+ // 3. Not a JWT — try /userinfo if Auth0 is configured
87
+ if (AUTH0_DOMAIN) {
88
+ return validateViaUserInfo(token);
89
+ }
90
+ return { valid: false, error: "Unrecognized token format" };
91
+ }
92
+ async function validateViaUserInfo(token) {
93
+ try {
94
+ const response = await axios.get(`https://${AUTH0_DOMAIN}/userinfo`, {
95
+ headers: { Authorization: `Bearer ${token}` },
96
+ timeout: 10_000,
97
+ });
98
+ const email = response.data?.email ?? response.data?.sub;
99
+ if (email) {
100
+ validatedTokens.set(token, { email, validatedAt: Date.now() });
101
+ }
102
+ return { valid: true, email };
103
+ }
104
+ catch (err) {
105
+ if (axios.isAxiosError(err) && err.response?.status === 401) {
106
+ return { valid: false, error: "Token rejected by authorization server" };
107
+ }
108
+ // Network error — don't reject the token, let PerfAI API validate it
109
+ return { valid: true, error: "Could not reach authorization server for validation" };
110
+ }
111
+ }
112
+ /**
113
+ * Clear the validation cache (useful for logout).
114
+ */
115
+ export function clearTokenCache() {
116
+ validatedTokens.clear();
117
+ }
package/dist/cli.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ #!/usr/bin/env node
2
+ import "./env.js";
3
+ //# sourceMappingURL=cli.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"cli.d.ts","sourceRoot":"","sources":["../src/cli.ts"],"names":[],"mappings":";AAEA,OAAO,UAAU,CAAC"}