serena-mcp-gateway 1.1.0 → 1.3.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.
package/README.md CHANGED
@@ -14,12 +14,17 @@ npm i -g serena-mcp-gateway
14
14
  npx serena-mcp-gateway ./proj-a ./proj-b
15
15
  ```
16
16
 
17
- > **内置依赖自动安装**:首次运行时如果本机缺少 `uvx` 或 `cloudflared`,工具会按当前系统自动选择可用方式安装并立即生效(无需重开终端):
18
- > - **Windows**:自动依次尝试 `winget` → `scoop` → `choco` → 官方 PowerShell 脚本(`uv`)/ GitHub Releases 直下二进制到 `~/.serena-mcp/bin`(`cloudflared`,无需 `winget` 和管理员权限)。
19
- > - **macOS**:自动尝试 `brew` → 官方脚本 / GitHub Releases 直下二进制。
20
- > - **Linux**:自动使用官方脚本 / 静态二进制。
21
- > - 也可单独执行 `serena-mcp --setup` 预先完成环境自检与安装。
17
+ 缺少依赖时,`uv` 可通过系统包管理器安装。需要回退到 astral.sh 的远端安装脚本时,显式传入 `--allow-remote-install` 才会执行。需要自动安装 `cloudflared` 时,下载 Cloudflare 2026.11.2 对应平台的发行文件,核对预置 SHA-256 后再安装到 `~/.serena-mcp/bin`。已安装的 `cloudflared` 继续沿用。Windows ARM64 可先手动准备兼容的 `cloudflared`。
22
18
 
19
+ ### 推荐的本地使用方式
20
+
21
+ ```bash
22
+ serena-mcp --no-tunnel ~/projects/my-app
23
+ ```
24
+
25
+ 传入具体项目目录可使用项目锁定模式;无目录的全局模式允许已授权客户端切换项目。只有远程连接需要 Cloudflare Tunnel。固定令牌请通过环境变量 `MCP_TOKEN` 注入(至少 32 个字符)。未指定时,启动器生成随机令牌并打印一次。
26
+
27
+ OAuth 客户端需要先注册回调地址,并在授权和换取令牌时提交同一个客户端 ID 和回调地址。回调支持 HTTPS 和本机回环 HTTP,PKCE 必须使用 S256。
23
28
  ---
24
29
 
25
30
  ## 二、常用启动方式
@@ -57,7 +62,7 @@ serena-mcp --config ./projects.json
57
62
  ```
58
63
 
59
64
  ### 4. 多项目并行(方式 B:多终端独立运行)
60
- 直接开多个终端分别运行 `serena-mcp <项目A>` 和 `serena-mcp <项目B>` 即可。启动器会自动检测并分配空闲端口,不再出现 `9121 / 9122` 端口冲突。
65
+ 直接开多个终端分别运行 `serena-mcp <项目A>` 和 `serena-mcp <项目B>` 即可。启动器通过本机端口锁协调同一用户下的并发实例,并跳过已占用的端口。
61
66
 
62
67
  ---
63
68
 
@@ -69,7 +74,12 @@ serena-mcp --config ./projects.json
69
74
  | `-p, --port <port>` | 起始本地端口(默认 `9121`,被占用会自动顺延) |
70
75
  | `-t, --token <token>` | 指定固定 Bearer Token(至少 32 位;默认每次随机生成) |
71
76
  | `--context <name>` | 传给 Serena 的 `--context`(默认 `claude-code`) |
77
+ | `--serena-ref <ref>` | 默认使用上游 `v2.1.0`,可指定其他 release tag 或完整 40 位 commit SHA |
78
+ | `--allow-remote-install` | 允许在需要时下载并执行 astral.sh 的 uv 安装脚本 |
72
79
  | `--no-tunnel` | 仅启动本地 Serena + OAuth 代理,不启动 `cloudflared` |
73
- | `--setup` | 仅检查并自动安装缺失依赖(`uvx` / `cloudflared`),不启动服务 |
80
+ | `--setup` | 仅检查并自动安装缺失依赖(`uvx` / `cloudflared`),可结合 `--no-tunnel` 仅检查本地模式依赖 |
74
81
  | `--no-auto-install` | 缺依赖时仅提示手动命令,不自动安装 |
82
+ | `-v, --version` | 查看版本 |
75
83
  | `-h, --help` | 查看帮助 |
84
+
85
+ 从源码全局安装时,可运行 `./install.sh --no-tunnel` 或 `./install.ps1 --no-tunnel`。安装脚本使用同一套依赖检查,接受 `--no-auto-install` 和 `--allow-remote-install`。
package/auth-proxy.mjs CHANGED
@@ -1,10 +1,21 @@
1
+ import { isIP } from 'node:net';
1
2
  import http from 'node:http';
2
3
  import crypto from 'node:crypto';
3
4
  import { URL, pathToFileURL } from 'node:url';
4
5
 
6
+ const MAX_CLIENTS = 50;
7
+ const MAX_AUTH_CODES = 50;
8
+ const MAX_ACCESS_TOKENS = 50;
9
+ const MAX_CSRF_TOKENS = 100;
10
+ const AUTH_CODE_TTL_MS = 5 * 60 * 1000;
11
+ const CSRF_TTL_MS = 10 * 60 * 1000;
12
+ const ACCESS_TOKEN_TTL_MS = 24 * 60 * 60 * 1000;
13
+ const RATE_WINDOW_MS = 5 * 60 * 1000;
14
+ const MAX_FAILED_AUTH = 10;
15
+
5
16
  function safeEqual(a = '', b = '') {
6
- const bufA = Buffer.from(a);
7
- const bufB = Buffer.from(b);
17
+ const bufA = Buffer.from(String(a));
18
+ const bufB = Buffer.from(String(b));
8
19
  if (bufA.length !== bufB.length) return false;
9
20
  return crypto.timingSafeEqual(bufA, bufB);
10
21
  }
@@ -18,18 +29,41 @@ function escapeHtml(str = '') {
18
29
  .replace(/>/g, '&gt;');
19
30
  }
20
31
 
21
- function getOrigin(req, listenPort) {
22
- const proto = req.headers['x-forwarded-proto'] || 'https';
23
- const host =
24
- req.headers['x-forwarded-host'] ||
25
- req.headers['host'] ||
26
- `127.0.0.1:${listenPort}`;
27
- return `${proto}://${host}`;
32
+ const CORS_HEADERS = {
33
+ 'access-control-allow-origin': '*',
34
+ 'access-control-allow-methods': 'GET, POST, DELETE, HEAD, OPTIONS',
35
+ 'access-control-allow-headers': 'Authorization, Content-Type, Mcp-Session-Id, Last-Event-ID, MCP-Protocol-Version',
36
+ 'access-control-expose-headers': 'Mcp-Session-Id, WWW-Authenticate, MCP-Protocol-Version',
37
+ };
38
+
39
+ function getClientKey(req, trustProxy) {
40
+ const ip = trustProxy && req.headers['cf-connecting-ip'];
41
+ return (ip && isIP(ip) ? ip : req.socket.remoteAddress) || 'unknown';
42
+ }
43
+
44
+ function getOrigin(req, listenPort, trustProxy) {
45
+ const host = req.headers.host;
46
+ if (trustProxy && /^[a-z0-9-]+\.trycloudflare\.com$/i.test(host || '')) {
47
+ return `https://${host.toLowerCase()}`;
48
+ }
49
+ return `http://127.0.0.1:${listenPort}`;
28
50
  }
29
51
 
30
- function readBody(req, maxBytes = 1024 * 1024) {
52
+ function parseCookies(req) {
53
+ const out = {};
54
+ const raw = req.headers.cookie || '';
55
+ for (const part of raw.split(';')) {
56
+ const idx = part.indexOf('=');
57
+ if (idx > 0) {
58
+ out[part.slice(0, idx).trim()] = part.slice(idx + 1).trim();
59
+ }
60
+ }
61
+ return out;
62
+ }
63
+
64
+ function readBody(req, maxBytes = 256 * 1024) {
31
65
  return new Promise((resolve, reject) => {
32
- let data = '';
66
+ const chunks = [];
33
67
  let size = 0;
34
68
  req.on('data', (chunk) => {
35
69
  size += chunk.length;
@@ -38,9 +72,9 @@ function readBody(req, maxBytes = 1024 * 1024) {
38
72
  reject(new Error('Payload too large'));
39
73
  return;
40
74
  }
41
- data += chunk;
75
+ chunks.push(chunk);
42
76
  });
43
- req.on('end', () => resolve(data));
77
+ req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
44
78
  req.on('error', reject);
45
79
  });
46
80
  }
@@ -49,19 +83,44 @@ function sendJson(res, status, obj, extraHeaders = {}) {
49
83
  if (res.headersSent) return;
50
84
  res.writeHead(status, {
51
85
  'Content-Type': 'application/json',
52
- 'Access-Control-Allow-Origin': '*',
53
- 'Access-Control-Allow-Headers': '*',
86
+ 'Cache-Control': 'no-store',
87
+ 'X-Content-Type-Options': 'nosniff',
88
+ ...CORS_HEADERS,
54
89
  ...extraHeaders,
55
90
  });
56
91
  res.end(JSON.stringify(obj));
57
92
  }
58
93
 
94
+ function pruneMap(map, maxSize, now = Date.now()) {
95
+ for (const [k, v] of map.entries()) {
96
+ if (v && typeof v.expiresAt === 'number' && v.expiresAt <= now) {
97
+ map.delete(k);
98
+ }
99
+ }
100
+ while (map.size > maxSize) {
101
+ const oldestKey = map.keys().next().value;
102
+ if (oldestKey === undefined) break;
103
+ map.delete(oldestKey);
104
+ }
105
+ }
106
+
107
+ function isValidHttpUrl(raw) {
108
+ try {
109
+ const parsed = new URL(raw);
110
+ return (parsed.protocol === 'https:' ||
111
+ (parsed.protocol === 'http:' && ['127.0.0.1', '[::1]', 'localhost'].includes(parsed.hostname))) &&
112
+ !parsed.username && !parsed.password && !raw.includes('#') &&
113
+ raw === raw.trim() && !/[\s\\]/.test(raw);
114
+ } catch {
115
+ return false;
116
+ }
117
+ }
118
+
59
119
  function resolveRoute(routes, reqUrl) {
60
120
  const parsed = new URL(reqUrl || '/', 'http://127.0.0.1');
61
121
  const pathname = parsed.pathname;
62
122
  const search = parsed.search || '';
63
123
 
64
- // Match longest non-empty prefix first
65
124
  const sorted = [...routes].sort((a, b) => b.prefix.length - a.prefix.length);
66
125
  for (const route of sorted) {
67
126
  if (!route.prefix) {
@@ -76,7 +135,7 @@ function resolveRoute(routes, reqUrl) {
76
135
  }
77
136
 
78
137
  /**
79
- * Start the OAuth 2.1 + Bearer Token reverse proxy for one or more Serena MCP backends.
138
+ * Start the hardened OAuth 2.1 + Bearer Token reverse proxy for one or more Serena MCP backends.
80
139
  *
81
140
  * @param {object} options
82
141
  * @param {number} [options.listenPort=9122]
@@ -88,6 +147,7 @@ export function startAuthProxy({
88
147
  listenPort = 9122,
89
148
  masterToken,
90
149
  routes,
150
+ trustProxy = false,
91
151
  }) {
92
152
  if (!masterToken || masterToken.length < 32) {
93
153
  throw new Error('MCP_TOKEN must be at least 32 characters.');
@@ -96,25 +156,83 @@ export function startAuthProxy({
96
156
  throw new Error('At least one target route is required.');
97
157
  }
98
158
 
159
+ const registeredClients = new Map();
160
+ const csrfTokens = new Map();
99
161
  const authCodes = new Map();
100
- const accessTokens = new Set();
162
+ const accessTokens = new Map();
163
+ const failedAttempts = new Map();
164
+
165
+ function isRateLimited(clientKey) {
166
+ const now = Date.now();
167
+ const rec = failedAttempts.get(clientKey);
168
+ if (!rec) return false;
169
+ if (rec.expiresAt <= now) {
170
+ failedAttempts.delete(clientKey);
171
+ return false;
172
+ }
173
+ return rec.count >= MAX_FAILED_AUTH;
174
+ }
101
175
 
176
+ function recordFailure(clientKey) {
177
+ const now = Date.now();
178
+ const rec = failedAttempts.get(clientKey);
179
+ if (!rec || rec.expiresAt <= now) {
180
+ failedAttempts.set(clientKey, { count: 1, expiresAt: now + RATE_WINDOW_MS });
181
+ } else {
182
+ rec.count += 1;
183
+ }
184
+ pruneMap(failedAttempts, 500, now);
185
+ }
186
+
187
+ function clearFailures(clientKey) {
188
+ failedAttempts.delete(clientKey);
189
+ }
190
+
191
+ const registrationRequests = new Map();
192
+ const authorizationRequests = new Map();
193
+
194
+ function allowRequest(buckets, clientKey, limit) {
195
+ const now = Date.now();
196
+ pruneMap(buckets, 500, now);
197
+ const prior = buckets.get(clientKey);
198
+ if (!prior && buckets.size >= 500) return false;
199
+ const timestamps = (prior?.timestamps || []).filter((time) => time > now - RATE_WINDOW_MS);
200
+ if (timestamps.length >= limit) return false;
201
+ timestamps.push(now);
202
+ buckets.set(clientKey, { timestamps, expiresAt: now + RATE_WINDOW_MS });
203
+ return true;
204
+ }
205
+
206
+ function validClient(clientId, redirectUri) {
207
+ const client = registeredClients.get(clientId);
208
+ return client && client.expiresAt > Date.now() && client.redirectUris.includes(redirectUri);
209
+ }
210
+
211
+ function validAuthorization(params) {
212
+ return validClient(params.get('client_id'), params.get('redirect_uri')) &&
213
+ /^[A-Za-z0-9_-]{43}$/.test(params.get('code_challenge') || '') &&
214
+ params.get('code_challenge_method') === 'S256';
215
+ }
216
+
217
+ const grantFields = ['client_id', 'redirect_uri', 'state', 'code_challenge', 'code_challenge_method'];
102
218
  const server = http.createServer(async (req, res) => {
103
- const origin = getOrigin(req, listenPort);
104
- const url = new URL(req.url || '/', origin);
219
+ const origin = getOrigin(req, server.address().port, trustProxy);
220
+ let url;
221
+ try {
222
+ url = new URL(req.url || '/', origin);
223
+ } catch {
224
+ return sendJson(res, 400, { error: 'invalid_request' });
225
+ }
105
226
  const pathname = url.pathname;
227
+ const clientKey = getClientKey(req, trustProxy);
106
228
 
107
229
  if (req.method === 'OPTIONS') {
108
- res.writeHead(204, {
109
- 'Access-Control-Allow-Origin': '*',
110
- 'Access-Control-Allow-Methods': 'GET, POST, DELETE, HEAD, OPTIONS',
111
- 'Access-Control-Allow-Headers': '*',
112
- });
230
+ res.writeHead(204, CORS_HEADERS);
113
231
  res.end();
114
232
  return;
115
233
  }
116
234
 
117
- // 1. OAuth 2.0 Protected Resource Metadata (RFC 9728, supports root & path-scoped discovery)
235
+ // 1. OAuth 2.0 Protected Resource Metadata (RFC 9728)
118
236
  const prmPrefix = '/.well-known/oauth-protected-resource';
119
237
  if (pathname === prmPrefix || pathname.startsWith(`${prmPrefix}/`)) {
120
238
  const suffix = pathname.slice(prmPrefix.length);
@@ -139,13 +257,16 @@ export function startAuthProxy({
139
257
  registration_endpoint: `${origin}/oauth/register`,
140
258
  response_types_supported: ['code'],
141
259
  grant_types_supported: ['authorization_code'],
142
- code_challenge_methods_supported: ['S256', 'plain'],
143
- token_endpoint_auth_methods_supported: ['none', 'client_secret_post'],
260
+ code_challenge_methods_supported: ['S256'],
261
+ token_endpoint_auth_methods_supported: ['none'],
144
262
  });
145
263
  }
146
264
 
147
265
  // 3. Dynamic Client Registration (RFC 7591)
148
266
  if (pathname === '/oauth/register' && req.method === 'POST') {
267
+ if (isRateLimited(clientKey) || !allowRequest(registrationRequests, clientKey, 10)) {
268
+ return sendJson(res, 429, { error: 'too_many_requests' });
269
+ }
149
270
  let body = {};
150
271
  try {
151
272
  const raw = await readBody(req);
@@ -153,21 +274,70 @@ export function startAuthProxy({
153
274
  } catch {
154
275
  return sendJson(res, 400, { error: 'invalid_client_metadata' });
155
276
  }
277
+ const redirectUris = body?.redirect_uris;
278
+ if (!Array.isArray(redirectUris) || redirectUris.length === 0 || redirectUris.length > 20 ||
279
+ !redirectUris.every((uri) => typeof uri === 'string' && uri.length <= 2048 && isValidHttpUrl(uri))) {
280
+ return sendJson(res, 400, { error: 'invalid_redirect_uri' });
281
+ }
282
+ const clientId = `mcp-client-${crypto.randomBytes(16).toString('hex')}`;
283
+ pruneMap(registeredClients, MAX_CLIENTS);
284
+ if (registeredClients.size >= MAX_CLIENTS) {
285
+ return sendJson(res, 429, { error: 'too_many_requests' });
286
+ }
287
+ registeredClients.set(clientId, {
288
+ redirectUris,
289
+ expiresAt: Date.now() + ACCESS_TOKEN_TTL_MS,
290
+ });
156
291
  return sendJson(res, 201, {
157
- client_id: `mcp-client-${crypto.randomBytes(8).toString('hex')}`,
292
+ client_id: clientId,
158
293
  client_id_issued_at: Math.floor(Date.now() / 1000),
159
- redirect_uris: Array.isArray(body.redirect_uris) ? body.redirect_uris : [],
294
+ redirect_uris: redirectUris,
160
295
  grant_types: ['authorization_code'],
161
296
  response_types: ['code'],
162
297
  token_endpoint_auth_method: 'none',
163
298
  });
164
299
  }
165
300
 
166
- // 4. OAuth Authorize Page (GET displays password form, POST validates and redirects)
301
+ // 4. OAuth Authorize Page (CSRF-protected, clickjacking-hardened, redirect_uri validated)
167
302
  if (pathname === '/oauth/authorize') {
168
303
  if (req.method === 'GET') {
169
304
  const q = url.searchParams;
170
- res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
305
+ if (!allowRequest(authorizationRequests, clientKey, 20)) {
306
+ return sendJson(res, 429, { error: 'too_many_requests' });
307
+ }
308
+ if (q.get('response_type') !== 'code' || !validAuthorization(q)) {
309
+ return sendJson(res, 400, { error: 'invalid_request' });
310
+ }
311
+ const csrf = crypto.randomBytes(24).toString('hex');
312
+ pruneMap(csrfTokens, MAX_CSRF_TOKENS);
313
+ if (csrfTokens.size >= MAX_CSRF_TOKENS) {
314
+ return sendJson(res, 429, { error: 'too_many_requests' });
315
+ }
316
+ csrfTokens.set(csrf, {
317
+ expiresAt: Date.now() + CSRF_TTL_MS,
318
+ grant: grantFields.map((field) => q.get(field) || ''),
319
+ });
320
+
321
+ const isHttps = origin.startsWith('https://');
322
+ const cookieFlags = [
323
+ `mcp_csrf=${csrf}`,
324
+ 'HttpOnly',
325
+ 'SameSite=Strict',
326
+ 'Path=/oauth/authorize',
327
+ `Max-Age=${Math.floor(CSRF_TTL_MS / 1000)}`,
328
+ ...(isHttps ? ['Secure'] : []),
329
+ ].join('; ');
330
+
331
+ res.writeHead(200, {
332
+ 'Content-Type': 'text/html; charset=utf-8',
333
+ 'Cache-Control': 'no-store',
334
+ 'X-Frame-Options': 'DENY',
335
+ 'X-Content-Type-Options': 'nosniff',
336
+ 'Referrer-Policy': 'no-referrer',
337
+ 'Content-Security-Policy':
338
+ "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'",
339
+ 'Set-Cookie': cookieFlags,
340
+ });
171
341
  res.end(`<!doctype html>
172
342
  <html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
173
343
  <title>Serena MCP OAuth 授权</title>
@@ -178,16 +348,25 @@ button{background:#1a73e8;color:#fff;border:none;font-weight:600;cursor:pointer}
178
348
  <body><form method="POST" action="/oauth/authorize">
179
349
  <h3 style="margin:0 0 8px">授权访问本地 Serena MCP</h3>
180
350
  <p style="margin:0;font-size:13px;color:#57606a">粘贴终端打印的本次会话 Token 完成验证:</p>
351
+ <p style="overflow-wrap:anywhere">回调地址:${escapeHtml(q.get('redirect_uri'))}</p>
181
352
  <input type="password" name="token" placeholder="粘贴 MCP Token" required autofocus />
353
+ <input type="hidden" name="csrf_token" value="${escapeHtml(csrf)}" />
354
+ <input type="hidden" name="client_id" value="${escapeHtml(q.get('client_id') || '')}" />
182
355
  <input type="hidden" name="redirect_uri" value="${escapeHtml(q.get('redirect_uri') || '')}" />
183
356
  <input type="hidden" name="state" value="${escapeHtml(q.get('state') || '')}" />
184
357
  <input type="hidden" name="code_challenge" value="${escapeHtml(q.get('code_challenge') || '')}" />
185
- <input type="hidden" name="code_challenge_method" value="${escapeHtml(q.get('code_challenge_method') || 'S256')}" />
358
+ <input type="hidden" name="code_challenge_method" value="${escapeHtml(q.get('code_challenge_method'))}" />
186
359
  <button type="submit">确认授权连接</button></form></body></html>`);
187
360
  return;
188
361
  }
189
362
 
190
363
  if (req.method === 'POST') {
364
+ if (isRateLimited(clientKey)) {
365
+ res.writeHead(429, { 'Content-Type': 'text/plain; charset=utf-8' });
366
+ res.end('尝试次数过多,请 5 分钟后再试。');
367
+ return;
368
+ }
369
+
191
370
  let form;
192
371
  try {
193
372
  form = new URLSearchParams(await readBody(req));
@@ -196,47 +375,68 @@ button{background:#1a73e8;color:#fff;border:none;font-weight:600;cursor:pointer}
196
375
  res.end('请求体无效。');
197
376
  return;
198
377
  }
378
+
379
+ if (!validAuthorization(form)) {
380
+ return sendJson(res, 400, { error: 'invalid_request' });
381
+ }
382
+
383
+ // Verify the form matches the request shown to the user.
384
+ const formCsrf = form.get('csrf_token') || '';
385
+ const cookieCsrf = parseCookies(req).mcp_csrf || '';
386
+ const csrfRecord = csrfTokens.get(formCsrf);
387
+ if (
388
+ !formCsrf ||
389
+ !csrfRecord ||
390
+ csrfRecord.expiresAt <= Date.now() ||
391
+ !safeEqual(formCsrf, cookieCsrf) ||
392
+ grantFields.some((field, index) => (form.get(field) || '') !== csrfRecord.grant[index])
393
+ ) {
394
+ res.writeHead(403, { 'Content-Type': 'text/plain; charset=utf-8' });
395
+ res.end('授权页面已过期或校验失败,请刷新重试。');
396
+ return;
397
+ }
398
+
399
+ csrfTokens.delete(formCsrf);
199
400
  const token = (form.get('token') || '').trim();
200
401
  if (!safeEqual(token, masterToken)) {
402
+ recordFailure(clientKey);
201
403
  res.writeHead(403, { 'Content-Type': 'text/plain; charset=utf-8' });
202
404
  res.end('Token 错误,请返回核对终端输出的 Token。');
203
405
  return;
204
406
  }
205
- const redirectUriRaw = form.get('redirect_uri') || '';
206
- let redirect;
207
- try {
208
- redirect = new URL(redirectUriRaw);
209
- if (redirect.protocol !== 'http:' && redirect.protocol !== 'https:') {
210
- throw new Error('Invalid protocol');
211
- }
212
- } catch {
213
- res.writeHead(400, { 'Content-Type': 'text/plain; charset=utf-8' });
214
- res.end('redirect_uri 无效。');
215
- return;
216
- }
407
+ clearFailures(clientKey);
408
+
409
+ const redirectUriRaw = form.get('redirect_uri');
410
+ const clientId = form.get('client_id');
217
411
 
218
- // Prune expired codes
219
412
  const now = Date.now();
220
- for (const [k, v] of authCodes.entries()) {
221
- if (v.expiresAt < now) authCodes.delete(k);
222
- }
413
+ pruneMap(authCodes, MAX_AUTH_CODES - 1, now);
223
414
 
224
415
  const code = crypto.randomBytes(24).toString('hex');
225
416
  authCodes.set(code, {
226
417
  codeChallenge: form.get('code_challenge') || '',
227
- method: form.get('code_challenge_method') || 'S256',
228
- expiresAt: now + 5 * 60 * 1000,
418
+ redirectUri: redirectUriRaw,
419
+ clientId,
420
+ expiresAt: now + AUTH_CODE_TTL_MS,
229
421
  });
422
+
423
+ const redirect = new URL(redirectUriRaw);
230
424
  redirect.searchParams.set('code', code);
231
425
  if (form.get('state')) redirect.searchParams.set('state', form.get('state'));
232
- res.writeHead(302, { Location: redirect.toString() });
426
+ res.writeHead(302, {
427
+ Location: redirect.toString(),
428
+ 'Cache-Control': 'no-store',
429
+ });
233
430
  res.end();
234
431
  return;
235
432
  }
236
433
  }
237
434
 
238
- // 5. OAuth Token Exchange (PKCE verification + Access Token issuance)
435
+ // 5. OAuth Token Exchange (PKCE verification + expiring Access Token issuance)
239
436
  if (pathname === '/oauth/token' && req.method === 'POST') {
437
+ if (isRateLimited(clientKey)) {
438
+ return sendJson(res, 429, { error: 'too_many_requests' });
439
+ }
240
440
  let form;
241
441
  try {
242
442
  form = new URLSearchParams(await readBody(req));
@@ -245,37 +445,68 @@ button{background:#1a73e8;color:#fff;border:none;font-weight:600;cursor:pointer}
245
445
  }
246
446
  const code = form.get('code') || '';
247
447
  const verifier = form.get('code_verifier') || '';
448
+ const redirectUri = form.get('redirect_uri') || '';
248
449
  const record = authCodes.get(code);
249
- authCodes.delete(code);
250
450
 
251
- if (!record || record.expiresAt < Date.now()) {
451
+ const now = Date.now();
452
+ if (!record || record.expiresAt <= now) {
453
+ recordFailure(clientKey);
252
454
  return sendJson(res, 400, { error: 'invalid_grant' });
253
455
  }
254
- if (record.codeChallenge) {
255
- const computed =
256
- record.method === 'S256'
257
- ? crypto.createHash('sha256').update(verifier).digest('base64url')
258
- : verifier;
259
- if (computed !== record.codeChallenge) {
260
- return sendJson(res, 400, {
261
- error: 'invalid_grant',
262
- error_description: 'PKCE failed',
263
- });
264
- }
456
+ const clientId = form.get('client_id');
457
+ const computed = crypto.createHash('sha256').update(verifier).digest('base64url');
458
+ if (form.get('grant_type') !== 'authorization_code' ||
459
+ clientId !== record.clientId || redirectUri !== record.redirectUri ||
460
+ !validClient(clientId, redirectUri) ||
461
+ !/^[A-Za-z0-9._~-]{43,128}$/.test(verifier) ||
462
+ !safeEqual(computed, record.codeChallenge)) {
463
+ recordFailure(clientKey);
464
+ return sendJson(res, 400, { error: 'invalid_grant' });
265
465
  }
466
+ authCodes.delete(code);
467
+
468
+ clearFailures(clientKey);
469
+ pruneMap(accessTokens, MAX_ACCESS_TOKENS - 1, now);
266
470
  const accessToken = crypto.randomBytes(32).toString('hex');
267
- accessTokens.add(accessToken);
471
+ accessTokens.set(accessToken, {
472
+ expiresAt: now + ACCESS_TOKEN_TTL_MS,
473
+ clientId: record.clientId,
474
+ });
268
475
  return sendJson(res, 200, {
269
476
  access_token: accessToken,
270
477
  token_type: 'Bearer',
271
- expires_in: 86400,
478
+ expires_in: Math.floor(ACCESS_TOKEN_TTL_MS / 1000),
272
479
  });
273
480
  }
274
481
 
275
- // 6. Verify Bearer Access Token on all MCP endpoints
482
+ // 6. Verify Bearer Access Token (with TTL enforcement & brute-force rate limit)
483
+ if (isRateLimited(clientKey)) {
484
+ return sendJson(res, 429, { error: 'Too many failed authentication attempts' });
485
+ }
486
+
276
487
  const auth = req.headers['authorization'] || '';
277
488
  const bearer = auth.startsWith('Bearer ') ? auth.slice(7) : '';
278
- if (!bearer || (!accessTokens.has(bearer) && !safeEqual(bearer, masterToken))) {
489
+ let isAuthorized = false;
490
+
491
+ if (bearer) {
492
+ if (safeEqual(bearer, masterToken)) {
493
+ isAuthorized = true;
494
+ } else {
495
+ const tokenRec = accessTokens.get(bearer);
496
+ if (tokenRec) {
497
+ if (tokenRec.expiresAt > Date.now()) {
498
+ isAuthorized = true;
499
+ } else {
500
+ accessTokens.delete(bearer);
501
+ }
502
+ }
503
+ }
504
+ }
505
+
506
+ if (!isAuthorized) {
507
+ if (bearer) {
508
+ recordFailure(clientKey);
509
+ }
279
510
  const metadataPath = `${prmPrefix}${pathname === '/' ? '' : pathname}`;
280
511
  return sendJson(
281
512
  res,
@@ -297,20 +528,28 @@ button{background:#1a73e8;color:#fff;border:none;font-weight:600;cursor:pointer}
297
528
  }
298
529
 
299
530
  const { route, forwardPath } = matched;
531
+ const headers = { ...req.headers, host: `127.0.0.1:${route.targetPort}` };
532
+ for (const name of [
533
+ 'authorization', 'cookie', 'proxy-authorization', 'connection',
534
+ 'keep-alive', 'upgrade', 'te', 'trailer', 'transfer-encoding',
535
+ ...String(req.headers.connection || '').toLowerCase().split(',').map((value) => value.trim()),
536
+ ]) {
537
+ delete headers[name];
538
+ }
539
+ for (const name of Object.keys(headers)) {
540
+ if (/^(cf-|x-forwarded-|forwarded$)/.test(name)) delete headers[name];
541
+ }
300
542
  const proxyReq = http.request(
301
543
  {
302
544
  hostname: '127.0.0.1',
303
545
  port: route.targetPort,
304
546
  path: forwardPath,
305
547
  method: req.method,
306
- headers: {
307
- ...req.headers,
308
- host: `127.0.0.1:${route.targetPort}`,
309
- },
548
+ headers,
310
549
  },
311
550
  (proxyRes) => {
312
551
  if (!res.headersSent) {
313
- res.writeHead(proxyRes.statusCode || 502, proxyRes.headers);
552
+ res.writeHead(proxyRes.statusCode || 502, { ...proxyRes.headers, ...CORS_HEADERS });
314
553
  }
315
554
  proxyRes.pipe(res);
316
555
  }
package/install.ps1 CHANGED
@@ -1,35 +1,13 @@
1
- $ErrorActionPreference = "Stop"
1
+ $ErrorActionPreference = "Stop"
2
2
 
3
- Write-Host "==> 检查运行环境 (Windows)..." -ForegroundColor Cyan
4
-
5
- if (-not (Get-Command node -ErrorAction SilentlyContinue)) {
6
- Write-Host "[缺少依赖] 请先安装 Node.js (>= 18): winget install --id OpenJS.NodeJS.LTS -e" -ForegroundColor Red
3
+ if (-not (Get-Command node -ErrorAction SilentlyContinue) -or
4
+ -not (Get-Command npm -ErrorAction SilentlyContinue)) {
5
+ Write-Host "[缺少依赖] 请先安装带 npm 的 Node.js (>= 18): https://nodejs.org/"
7
6
  exit 1
8
7
  }
9
8
 
10
- if (-not (Get-Command uvx -ErrorAction SilentlyContinue)) {
11
- if (Get-Command winget -ErrorAction SilentlyContinue) {
12
- Write-Host "==> 正在通过 winget 安装 uv..." -ForegroundColor Yellow
13
- winget install --id astral-sh.uv -e --accept-source-agreements --accept-package-agreements
14
- } else {
15
- Write-Host "[提示] 请手动安装 uv: powershell -ExecutionPolicy ByPass -c `"irm https://astral.sh/uv/install.ps1 | iex`"" -ForegroundColor Yellow
16
- }
17
- }
18
-
19
- if (-not (Get-Command cloudflared -ErrorAction SilentlyContinue)) {
20
- if (Get-Command winget -ErrorAction SilentlyContinue) {
21
- Write-Host "==> 正在通过 winget 安装 cloudflared..." -ForegroundColor Yellow
22
- winget install --id Cloudflare.cloudflared -e --accept-source-agreements --accept-package-agreements
23
- } else {
24
- Write-Host "[提示] 请手动安装 cloudflared: https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/" -ForegroundColor Yellow
25
- }
26
- }
27
-
28
- Write-Host "==> 全局注册 serena-mcp 命令..." -ForegroundColor Cyan
29
- npm install -g $PSScriptRoot
30
-
31
- Write-Host ""
32
- Write-Host "[完成] 请重新打开 PowerShell / CMD 后,在任意目录直接运行:" -ForegroundColor Green
33
- Write-Host " serena-mcp # 全局模式"
34
- Write-Host " serena-mcp . # 当前目录单项目"
35
- Write-Host " serena-mcp D:\code\proj-a D:\code\proj-b # 多项目并行"
9
+ & node (Join-Path $PSScriptRoot "serena-mcp.mjs") @args --setup
10
+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
11
+ & npm install -g $PSScriptRoot
12
+ if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE }
13
+ Write-Host "[完成] 可以用 serena-mcp --no-tunnel . 启动当前项目。"