serena-mcp-gateway 1.0.0 → 1.2.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
@@ -4,24 +4,21 @@
4
4
 
5
5
  ---
6
6
 
7
- ## 一、给同事复用(下载即用)
7
+ ## 一、安装即用(Windows / macOS / Linux)
8
8
 
9
- 将本目录打包发给同事,或推送到公司 Git 仓库(如 `git clone <repo> serena-mcp-gateway`),然后执行对应平台的一键脚本:
10
-
11
- ### macOS / Linux
12
9
  ```bash
13
- cd serena-mcp-gateway
14
- ./install.sh
15
- ```
10
+ # 全局安装(推荐)
11
+ npm i -g serena-mcp-gateway
16
12
 
17
- ### Windows (PowerShell)
18
- ```powershell
19
- cd serena-mcp-gateway
20
- powershell -ExecutionPolicy Bypass -File .\install.ps1
13
+ # 或免安装直接运行
14
+ npx serena-mcp-gateway ./proj-a ./proj-b
21
15
  ```
22
16
 
23
- > 一键脚本会自动检查并安装缺失的 `uv`(提供 `uvx`)与 `cloudflared`,并通过 `npm install -g .` 注册全局命令 `serena-mcp`(无需手动改 `.zshrc` 或环境变量)。
24
- > 不想全局安装也可以直接运行:`node serena-mcp.mjs <项目路径>`(Windows 也可直接运行 `start-serena.cmd`)。
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` 预先完成环境自检与安装。
25
22
 
26
23
  ---
27
24
 
@@ -73,4 +70,6 @@ serena-mcp --config ./projects.json
73
70
  | `-t, --token <token>` | 指定固定 Bearer Token(至少 32 位;默认每次随机生成) |
74
71
  | `--context <name>` | 传给 Serena 的 `--context`(默认 `claude-code`) |
75
72
  | `--no-tunnel` | 仅启动本地 Serena + OAuth 代理,不启动 `cloudflared` |
73
+ | `--setup` | 仅检查并自动安装缺失依赖(`uvx` / `cloudflared`),不启动服务 |
74
+ | `--no-auto-install` | 缺依赖时仅提示手动命令,不自动安装 |
76
75
  | `-h, --help` | 查看帮助 |
package/auth-proxy.mjs CHANGED
@@ -2,9 +2,19 @@ import http from 'node:http';
2
2
  import crypto from 'node:crypto';
3
3
  import { URL, pathToFileURL } from 'node:url';
4
4
 
5
+ const MAX_CLIENTS = 50;
6
+ const MAX_AUTH_CODES = 50;
7
+ const MAX_ACCESS_TOKENS = 50;
8
+ const MAX_CSRF_TOKENS = 100;
9
+ const AUTH_CODE_TTL_MS = 5 * 60 * 1000;
10
+ const CSRF_TTL_MS = 10 * 60 * 1000;
11
+ const ACCESS_TOKEN_TTL_MS = 24 * 60 * 60 * 1000;
12
+ const RATE_WINDOW_MS = 5 * 60 * 1000;
13
+ const MAX_FAILED_AUTH = 10;
14
+
5
15
  function safeEqual(a = '', b = '') {
6
- const bufA = Buffer.from(a);
7
- const bufB = Buffer.from(b);
16
+ const bufA = Buffer.from(String(a));
17
+ const bufB = Buffer.from(String(b));
8
18
  if (bufA.length !== bufB.length) return false;
9
19
  return crypto.timingSafeEqual(bufA, bufB);
10
20
  }
@@ -18,6 +28,14 @@ function escapeHtml(str = '') {
18
28
  .replace(/>/g, '&gt;');
19
29
  }
20
30
 
31
+ function getClientKey(req) {
32
+ const fwd = req.headers['cf-connecting-ip'] || req.headers['x-forwarded-for'];
33
+ if (typeof fwd === 'string' && fwd.trim()) {
34
+ return fwd.split(',')[0].trim();
35
+ }
36
+ return req.socket?.remoteAddress || 'unknown';
37
+ }
38
+
21
39
  function getOrigin(req, listenPort) {
22
40
  const proto = req.headers['x-forwarded-proto'] || 'https';
23
41
  const host =
@@ -27,7 +45,19 @@ function getOrigin(req, listenPort) {
27
45
  return `${proto}://${host}`;
28
46
  }
29
47
 
30
- function readBody(req, maxBytes = 1024 * 1024) {
48
+ function parseCookies(req) {
49
+ const out = {};
50
+ const raw = req.headers.cookie || '';
51
+ for (const part of raw.split(';')) {
52
+ const idx = part.indexOf('=');
53
+ if (idx > 0) {
54
+ out[part.slice(0, idx).trim()] = part.slice(idx + 1).trim();
55
+ }
56
+ }
57
+ return out;
58
+ }
59
+
60
+ function readBody(req, maxBytes = 256 * 1024) {
31
61
  return new Promise((resolve, reject) => {
32
62
  let data = '';
33
63
  let size = 0;
@@ -49,6 +79,8 @@ function sendJson(res, status, obj, extraHeaders = {}) {
49
79
  if (res.headersSent) return;
50
80
  res.writeHead(status, {
51
81
  'Content-Type': 'application/json',
82
+ 'Cache-Control': 'no-store',
83
+ 'X-Content-Type-Options': 'nosniff',
52
84
  'Access-Control-Allow-Origin': '*',
53
85
  'Access-Control-Allow-Headers': '*',
54
86
  ...extraHeaders,
@@ -56,12 +88,33 @@ function sendJson(res, status, obj, extraHeaders = {}) {
56
88
  res.end(JSON.stringify(obj));
57
89
  }
58
90
 
91
+ function pruneMap(map, maxSize, now = Date.now()) {
92
+ for (const [k, v] of map.entries()) {
93
+ if (v && typeof v.expiresAt === 'number' && v.expiresAt <= now) {
94
+ map.delete(k);
95
+ }
96
+ }
97
+ while (map.size > maxSize) {
98
+ const oldestKey = map.keys().next().value;
99
+ if (oldestKey === undefined) break;
100
+ map.delete(oldestKey);
101
+ }
102
+ }
103
+
104
+ function isValidHttpUrl(raw) {
105
+ try {
106
+ const parsed = new URL(raw);
107
+ return parsed.protocol === 'http:' || parsed.protocol === 'https:';
108
+ } catch {
109
+ return false;
110
+ }
111
+ }
112
+
59
113
  function resolveRoute(routes, reqUrl) {
60
114
  const parsed = new URL(reqUrl || '/', 'http://127.0.0.1');
61
115
  const pathname = parsed.pathname;
62
116
  const search = parsed.search || '';
63
117
 
64
- // Match longest non-empty prefix first
65
118
  const sorted = [...routes].sort((a, b) => b.prefix.length - a.prefix.length);
66
119
  for (const route of sorted) {
67
120
  if (!route.prefix) {
@@ -76,7 +129,7 @@ function resolveRoute(routes, reqUrl) {
76
129
  }
77
130
 
78
131
  /**
79
- * Start the OAuth 2.1 + Bearer Token reverse proxy for one or more Serena MCP backends.
132
+ * Start the hardened OAuth 2.1 + Bearer Token reverse proxy for one or more Serena MCP backends.
80
133
  *
81
134
  * @param {object} options
82
135
  * @param {number} [options.listenPort=9122]
@@ -96,13 +149,47 @@ export function startAuthProxy({
96
149
  throw new Error('At least one target route is required.');
97
150
  }
98
151
 
152
+ const registeredClients = new Map();
153
+ const csrfTokens = new Map();
99
154
  const authCodes = new Map();
100
- const accessTokens = new Set();
155
+ const accessTokens = new Map();
156
+ const failedAttempts = new Map();
157
+
158
+ function isRateLimited(clientKey) {
159
+ const now = Date.now();
160
+ const rec = failedAttempts.get(clientKey);
161
+ if (!rec) return false;
162
+ if (rec.resetAt <= now) {
163
+ failedAttempts.delete(clientKey);
164
+ return false;
165
+ }
166
+ return rec.count >= MAX_FAILED_AUTH;
167
+ }
168
+
169
+ function recordFailure(clientKey) {
170
+ const now = Date.now();
171
+ const rec = failedAttempts.get(clientKey);
172
+ if (!rec || rec.resetAt <= now) {
173
+ failedAttempts.set(clientKey, { count: 1, resetAt: now + RATE_WINDOW_MS });
174
+ } else {
175
+ rec.count += 1;
176
+ }
177
+ if (failedAttempts.size > 500) {
178
+ for (const [k, v] of failedAttempts.entries()) {
179
+ if (v.resetAt <= now) failedAttempts.delete(k);
180
+ }
181
+ }
182
+ }
183
+
184
+ function clearFailures(clientKey) {
185
+ failedAttempts.delete(clientKey);
186
+ }
101
187
 
102
188
  const server = http.createServer(async (req, res) => {
103
189
  const origin = getOrigin(req, listenPort);
104
190
  const url = new URL(req.url || '/', origin);
105
191
  const pathname = url.pathname;
192
+ const clientKey = getClientKey(req);
106
193
 
107
194
  if (req.method === 'OPTIONS') {
108
195
  res.writeHead(204, {
@@ -114,7 +201,7 @@ export function startAuthProxy({
114
201
  return;
115
202
  }
116
203
 
117
- // 1. OAuth 2.0 Protected Resource Metadata (RFC 9728, supports root & path-scoped discovery)
204
+ // 1. OAuth 2.0 Protected Resource Metadata (RFC 9728)
118
205
  const prmPrefix = '/.well-known/oauth-protected-resource';
119
206
  if (pathname === prmPrefix || pathname.startsWith(`${prmPrefix}/`)) {
120
207
  const suffix = pathname.slice(prmPrefix.length);
@@ -146,6 +233,9 @@ export function startAuthProxy({
146
233
 
147
234
  // 3. Dynamic Client Registration (RFC 7591)
148
235
  if (pathname === '/oauth/register' && req.method === 'POST') {
236
+ if (isRateLimited(clientKey)) {
237
+ return sendJson(res, 429, { error: 'too_many_requests' });
238
+ }
149
239
  let body = {};
150
240
  try {
151
241
  const raw = await readBody(req);
@@ -153,21 +243,53 @@ export function startAuthProxy({
153
243
  } catch {
154
244
  return sendJson(res, 400, { error: 'invalid_client_metadata' });
155
245
  }
246
+ const redirectUris = Array.isArray(body.redirect_uris)
247
+ ? body.redirect_uris.filter((u) => typeof u === 'string' && isValidHttpUrl(u))
248
+ : [];
249
+ const clientId = `mcp-client-${crypto.randomBytes(8).toString('hex')}`;
250
+ pruneMap(registeredClients, MAX_CLIENTS - 1);
251
+ registeredClients.set(clientId, {
252
+ redirectUris,
253
+ expiresAt: Date.now() + ACCESS_TOKEN_TTL_MS,
254
+ });
156
255
  return sendJson(res, 201, {
157
- client_id: `mcp-client-${crypto.randomBytes(8).toString('hex')}`,
256
+ client_id: clientId,
158
257
  client_id_issued_at: Math.floor(Date.now() / 1000),
159
- redirect_uris: Array.isArray(body.redirect_uris) ? body.redirect_uris : [],
258
+ redirect_uris: redirectUris,
160
259
  grant_types: ['authorization_code'],
161
260
  response_types: ['code'],
162
261
  token_endpoint_auth_method: 'none',
163
262
  });
164
263
  }
165
264
 
166
- // 4. OAuth Authorize Page (GET displays password form, POST validates and redirects)
265
+ // 4. OAuth Authorize Page (CSRF-protected, clickjacking-hardened, redirect_uri validated)
167
266
  if (pathname === '/oauth/authorize') {
168
267
  if (req.method === 'GET') {
169
268
  const q = url.searchParams;
170
- res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
269
+ const csrf = crypto.randomBytes(24).toString('hex');
270
+ pruneMap(csrfTokens, MAX_CSRF_TOKENS - 1);
271
+ csrfTokens.set(csrf, { expiresAt: Date.now() + CSRF_TTL_MS });
272
+
273
+ const isHttps = origin.startsWith('https://');
274
+ const cookieFlags = [
275
+ `mcp_csrf=${csrf}`,
276
+ 'HttpOnly',
277
+ 'SameSite=Strict',
278
+ 'Path=/oauth/authorize',
279
+ `Max-Age=${Math.floor(CSRF_TTL_MS / 1000)}`,
280
+ ...(isHttps ? ['Secure'] : []),
281
+ ].join('; ');
282
+
283
+ res.writeHead(200, {
284
+ 'Content-Type': 'text/html; charset=utf-8',
285
+ 'Cache-Control': 'no-store',
286
+ 'X-Frame-Options': 'DENY',
287
+ 'X-Content-Type-Options': 'nosniff',
288
+ 'Referrer-Policy': 'no-referrer',
289
+ 'Content-Security-Policy':
290
+ "default-src 'none'; style-src 'unsafe-inline'; form-action 'self'; frame-ancestors 'none'",
291
+ 'Set-Cookie': cookieFlags,
292
+ });
171
293
  res.end(`<!doctype html>
172
294
  <html lang="zh-CN"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
173
295
  <title>Serena MCP OAuth 授权</title>
@@ -179,6 +301,8 @@ button{background:#1a73e8;color:#fff;border:none;font-weight:600;cursor:pointer}
179
301
  <h3 style="margin:0 0 8px">授权访问本地 Serena MCP</h3>
180
302
  <p style="margin:0;font-size:13px;color:#57606a">粘贴终端打印的本次会话 Token 完成验证:</p>
181
303
  <input type="password" name="token" placeholder="粘贴 MCP Token" required autofocus />
304
+ <input type="hidden" name="csrf_token" value="${escapeHtml(csrf)}" />
305
+ <input type="hidden" name="client_id" value="${escapeHtml(q.get('client_id') || '')}" />
182
306
  <input type="hidden" name="redirect_uri" value="${escapeHtml(q.get('redirect_uri') || '')}" />
183
307
  <input type="hidden" name="state" value="${escapeHtml(q.get('state') || '')}" />
184
308
  <input type="hidden" name="code_challenge" value="${escapeHtml(q.get('code_challenge') || '')}" />
@@ -188,6 +312,12 @@ button{background:#1a73e8;color:#fff;border:none;font-weight:600;cursor:pointer}
188
312
  }
189
313
 
190
314
  if (req.method === 'POST') {
315
+ if (isRateLimited(clientKey)) {
316
+ res.writeHead(429, { 'Content-Type': 'text/plain; charset=utf-8' });
317
+ res.end('尝试次数过多,请 5 分钟后再试。');
318
+ return;
319
+ }
320
+
191
321
  let form;
192
322
  try {
193
323
  form = new URLSearchParams(await readBody(req));
@@ -196,47 +326,82 @@ button{background:#1a73e8;color:#fff;border:none;font-weight:600;cursor:pointer}
196
326
  res.end('请求体无效。');
197
327
  return;
198
328
  }
329
+
330
+ // Verify double-submit CSRF token
331
+ const formCsrf = form.get('csrf_token') || '';
332
+ const cookieCsrf = parseCookies(req).mcp_csrf || '';
333
+ const csrfRecord = csrfTokens.get(formCsrf);
334
+ csrfTokens.delete(formCsrf);
335
+ if (
336
+ !formCsrf ||
337
+ !csrfRecord ||
338
+ csrfRecord.expiresAt <= Date.now() ||
339
+ !safeEqual(formCsrf, cookieCsrf)
340
+ ) {
341
+ res.writeHead(403, { 'Content-Type': 'text/plain; charset=utf-8' });
342
+ res.end('授权页面已过期或校验失败,请刷新重试。');
343
+ return;
344
+ }
345
+
199
346
  const token = (form.get('token') || '').trim();
200
347
  if (!safeEqual(token, masterToken)) {
348
+ recordFailure(clientKey);
201
349
  res.writeHead(403, { 'Content-Type': 'text/plain; charset=utf-8' });
202
350
  res.end('Token 错误,请返回核对终端输出的 Token。');
203
351
  return;
204
352
  }
353
+ clearFailures(clientKey);
354
+
205
355
  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 {
356
+ if (!isValidHttpUrl(redirectUriRaw)) {
213
357
  res.writeHead(400, { 'Content-Type': 'text/plain; charset=utf-8' });
214
358
  res.end('redirect_uri 无效。');
215
359
  return;
216
360
  }
217
361
 
218
- // Prune expired codes
219
- const now = Date.now();
220
- for (const [k, v] of authCodes.entries()) {
221
- if (v.expiresAt < now) authCodes.delete(k);
362
+ // If client_id was dynamically registered with redirect_uris, enforce strict match
363
+ const clientId = form.get('client_id') || '';
364
+ if (clientId && registeredClients.has(clientId)) {
365
+ const client = registeredClients.get(clientId);
366
+ if (
367
+ client.redirectUris.length > 0 &&
368
+ !client.redirectUris.includes(redirectUriRaw)
369
+ ) {
370
+ res.writeHead(400, { 'Content-Type': 'text/plain; charset=utf-8' });
371
+ res.end('redirect_uri 与已注册客户端不匹配。');
372
+ return;
373
+ }
222
374
  }
223
375
 
376
+ const now = Date.now();
377
+ pruneMap(authCodes, MAX_AUTH_CODES - 1, now);
378
+
224
379
  const code = crypto.randomBytes(24).toString('hex');
225
380
  authCodes.set(code, {
226
381
  codeChallenge: form.get('code_challenge') || '',
227
382
  method: form.get('code_challenge_method') || 'S256',
228
- expiresAt: now + 5 * 60 * 1000,
383
+ redirectUri: redirectUriRaw,
384
+ clientId,
385
+ expiresAt: now + AUTH_CODE_TTL_MS,
229
386
  });
387
+
388
+ const redirect = new URL(redirectUriRaw);
230
389
  redirect.searchParams.set('code', code);
231
390
  if (form.get('state')) redirect.searchParams.set('state', form.get('state'));
232
- res.writeHead(302, { Location: redirect.toString() });
391
+ res.writeHead(302, {
392
+ Location: redirect.toString(),
393
+ 'Cache-Control': 'no-store',
394
+ });
233
395
  res.end();
234
396
  return;
235
397
  }
236
398
  }
237
399
 
238
- // 5. OAuth Token Exchange (PKCE verification + Access Token issuance)
400
+ // 5. OAuth Token Exchange (PKCE verification + expiring Access Token issuance)
239
401
  if (pathname === '/oauth/token' && req.method === 'POST') {
402
+ if (isRateLimited(clientKey)) {
403
+ return sendJson(res, 429, { error: 'too_many_requests' });
404
+ }
240
405
  let form;
241
406
  try {
242
407
  form = new URLSearchParams(await readBody(req));
@@ -245,37 +410,78 @@ button{background:#1a73e8;color:#fff;border:none;font-weight:600;cursor:pointer}
245
410
  }
246
411
  const code = form.get('code') || '';
247
412
  const verifier = form.get('code_verifier') || '';
413
+ const redirectUri = form.get('redirect_uri') || '';
248
414
  const record = authCodes.get(code);
249
415
  authCodes.delete(code);
250
416
 
251
- if (!record || record.expiresAt < Date.now()) {
417
+ const now = Date.now();
418
+ if (!record || record.expiresAt <= now) {
419
+ recordFailure(clientKey);
252
420
  return sendJson(res, 400, { error: 'invalid_grant' });
253
421
  }
422
+ if (redirectUri && redirectUri !== record.redirectUri) {
423
+ recordFailure(clientKey);
424
+ return sendJson(res, 400, {
425
+ error: 'invalid_grant',
426
+ error_description: 'redirect_uri mismatch',
427
+ });
428
+ }
254
429
  if (record.codeChallenge) {
255
430
  const computed =
256
431
  record.method === 'S256'
257
432
  ? crypto.createHash('sha256').update(verifier).digest('base64url')
258
433
  : verifier;
259
- if (computed !== record.codeChallenge) {
434
+ if (!verifier || !safeEqual(computed, record.codeChallenge)) {
435
+ recordFailure(clientKey);
260
436
  return sendJson(res, 400, {
261
437
  error: 'invalid_grant',
262
438
  error_description: 'PKCE failed',
263
439
  });
264
440
  }
265
441
  }
442
+
443
+ clearFailures(clientKey);
444
+ pruneMap(accessTokens, MAX_ACCESS_TOKENS - 1, now);
266
445
  const accessToken = crypto.randomBytes(32).toString('hex');
267
- accessTokens.add(accessToken);
446
+ accessTokens.set(accessToken, {
447
+ expiresAt: now + ACCESS_TOKEN_TTL_MS,
448
+ clientId: record.clientId,
449
+ });
268
450
  return sendJson(res, 200, {
269
451
  access_token: accessToken,
270
452
  token_type: 'Bearer',
271
- expires_in: 86400,
453
+ expires_in: Math.floor(ACCESS_TOKEN_TTL_MS / 1000),
272
454
  });
273
455
  }
274
456
 
275
- // 6. Verify Bearer Access Token on all MCP endpoints
457
+ // 6. Verify Bearer Access Token (with TTL enforcement & brute-force rate limit)
458
+ if (isRateLimited(clientKey)) {
459
+ return sendJson(res, 429, { error: 'Too many failed authentication attempts' });
460
+ }
461
+
276
462
  const auth = req.headers['authorization'] || '';
277
463
  const bearer = auth.startsWith('Bearer ') ? auth.slice(7) : '';
278
- if (!bearer || (!accessTokens.has(bearer) && !safeEqual(bearer, masterToken))) {
464
+ let isAuthorized = false;
465
+
466
+ if (bearer) {
467
+ if (safeEqual(bearer, masterToken)) {
468
+ isAuthorized = true;
469
+ } else {
470
+ const tokenRec = accessTokens.get(bearer);
471
+ if (tokenRec) {
472
+ if (tokenRec.expiresAt > Date.now()) {
473
+ isAuthorized = true;
474
+ } else {
475
+ accessTokens.delete(bearer);
476
+ }
477
+ }
478
+ }
479
+ }
480
+
481
+ if (!isAuthorized) {
482
+ if (bearer) {
483
+ recordFailure(clientKey);
484
+ }
279
485
  const metadataPath = `${prmPrefix}${pathname === '/' ? '' : pathname}`;
280
486
  return sendJson(
281
487
  res,
package/installer.mjs ADDED
@@ -0,0 +1,421 @@
1
+ import crypto from 'node:crypto';
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+ import { spawnSync } from 'node:child_process';
6
+
7
+ const IS_WIN = process.platform === 'win32';
8
+ const IS_MAC = process.platform === 'darwin';
9
+ const LOCAL_BIN_DIR = path.join(os.homedir(), '.serena-mcp', 'bin');
10
+ const MIN_BINARY_BYTES = 100 * 1024;
11
+ const MAX_BINARY_BYTES = 200 * 1024 * 1024;
12
+
13
+ function getExtraSearchDirs() {
14
+ const home = os.homedir();
15
+ const dirs = [
16
+ LOCAL_BIN_DIR,
17
+ path.join(home, '.local', 'bin'),
18
+ path.join(home, '.cargo', 'bin'),
19
+ ];
20
+
21
+ if (IS_WIN) {
22
+ const localAppData =
23
+ process.env.LOCALAPPDATA || path.join(home, 'AppData', 'Local');
24
+ const programFiles = process.env.ProgramFiles || 'C:\\Program Files';
25
+ const programFilesX86 =
26
+ process.env['ProgramFiles(x86)'] || 'C:\\Program Files (x86)';
27
+ dirs.push(
28
+ path.join(localAppData, 'Microsoft', 'WinGet', 'Links'),
29
+ path.join(localAppData, 'Programs', 'uv'),
30
+ path.join(home, 'scoop', 'shims'),
31
+ path.join(programFiles, 'cloudflared'),
32
+ path.join(programFilesX86, 'cloudflared'),
33
+ 'C:\\ProgramData\\chocolatey\\bin'
34
+ );
35
+ } else if (IS_MAC) {
36
+ dirs.push('/opt/homebrew/bin', '/usr/local/bin');
37
+ } else {
38
+ dirs.push('/usr/local/bin');
39
+ }
40
+
41
+ return dirs;
42
+ }
43
+
44
+ /**
45
+ * Add common user/package-manager bin directories to process.env.PATH
46
+ * so freshly installed binaries work immediately without restarting the shell.
47
+ */
48
+ export function hydratePath() {
49
+ const sep = path.delimiter;
50
+ const current = (process.env.PATH || '').split(sep).filter(Boolean);
51
+ const currentSet = new Set(
52
+ current.map((p) => (IS_WIN ? p.toLowerCase() : p))
53
+ );
54
+
55
+ const toPrepend = [];
56
+ for (const dir of getExtraSearchDirs()) {
57
+ const key = IS_WIN ? dir.toLowerCase() : dir;
58
+ if (!currentSet.has(key) && fs.existsSync(dir)) {
59
+ toPrepend.push(dir);
60
+ currentSet.add(key);
61
+ }
62
+ }
63
+
64
+ if (toPrepend.length > 0) {
65
+ process.env.PATH = [...toPrepend, ...current].join(sep);
66
+ }
67
+ }
68
+
69
+ export function commandExists(cmd, { useShell = false } = {}) {
70
+ const res = spawnSync(cmd, ['--version'], {
71
+ stdio: 'ignore',
72
+ shell: useShell,
73
+ });
74
+ return !res.error && res.status === 0;
75
+ }
76
+
77
+ function runStep(label, cmd, args, extraOpts = {}) {
78
+ console.log(`[Setup] ${label}...`);
79
+ const res = spawnSync(cmd, args, {
80
+ stdio: 'inherit',
81
+ shell: false,
82
+ ...extraOpts,
83
+ });
84
+ return !res.error && res.status === 0;
85
+ }
86
+
87
+ function ensurePrivateBinDir() {
88
+ fs.mkdirSync(LOCAL_BIN_DIR, { recursive: true, mode: 0o700 });
89
+ if (!IS_WIN) {
90
+ try {
91
+ fs.chmodSync(LOCAL_BIN_DIR, 0o700);
92
+ } catch {
93
+ // ignore
94
+ }
95
+ }
96
+ }
97
+
98
+ async function downloadFile(url, destPath) {
99
+ if (!url.startsWith('https://')) {
100
+ throw new Error(`仅允许通过 HTTPS 下载: ${url}`);
101
+ }
102
+ ensurePrivateBinDir();
103
+ const res = await fetch(url, {
104
+ redirect: 'follow',
105
+ signal: AbortSignal.timeout(60_000),
106
+ });
107
+ if (!res.ok) {
108
+ throw new Error(`HTTP ${res.status} ${res.statusText}`);
109
+ }
110
+ const buf = Buffer.from(await res.arrayBuffer());
111
+ if (buf.length < MIN_BINARY_BYTES || buf.length > MAX_BINARY_BYTES) {
112
+ throw new Error(`下载文件大小异常 (${buf.length} bytes),已中止写入`);
113
+ }
114
+ const sha256 = crypto.createHash('sha256').update(buf).digest('hex');
115
+ const tmpPath = `${destPath}.tmp-${Date.now()}`;
116
+ fs.writeFileSync(tmpPath, buf, { mode: 0o755 });
117
+ fs.renameSync(tmpPath, destPath);
118
+ console.log(`[Setup] 下载校验完成 SHA-256: ${sha256}`);
119
+ }
120
+
121
+ async function installUv() {
122
+ if (IS_WIN) {
123
+ if (commandExists('winget')) {
124
+ if (
125
+ runStep('通过 winget 安装 uv', 'winget', [
126
+ 'install',
127
+ '--id',
128
+ 'astral-sh.uv',
129
+ '-e',
130
+ '--accept-source-agreements',
131
+ '--accept-package-agreements',
132
+ ])
133
+ ) {
134
+ hydratePath();
135
+ if (commandExists('uvx')) return true;
136
+ }
137
+ }
138
+
139
+ if (commandExists('scoop', { useShell: true })) {
140
+ if (
141
+ runStep('通过 scoop 安装 uv', 'scoop', ['install', 'uv'], {
142
+ shell: true,
143
+ })
144
+ ) {
145
+ hydratePath();
146
+ if (commandExists('uvx')) return true;
147
+ }
148
+ }
149
+
150
+ if (commandExists('choco', { useShell: true })) {
151
+ if (
152
+ runStep('通过 choco 安装 uv', 'choco', ['install', 'uv', '-y'], {
153
+ shell: true,
154
+ })
155
+ ) {
156
+ hydratePath();
157
+ if (commandExists('uvx')) return true;
158
+ }
159
+ }
160
+
161
+ // Zero-dependency official PowerShell installer (works without winget or admin)
162
+ if (
163
+ runStep(
164
+ '未检测到 winget/scoop,改用官方 PowerShell 脚本安装 uv',
165
+ 'powershell',
166
+ [
167
+ '-NoProfile',
168
+ '-ExecutionPolicy',
169
+ 'ByPass',
170
+ '-Command',
171
+ 'irm https://astral.sh/uv/install.ps1 | iex',
172
+ ],
173
+ { shell: false }
174
+ )
175
+ ) {
176
+ hydratePath();
177
+ if (commandExists('uvx')) return true;
178
+ }
179
+
180
+ if (commandExists('pip')) {
181
+ if (runStep('尝试通过 pip 安装 uv', 'pip', ['install', '--user', 'uv'])) {
182
+ hydratePath();
183
+ if (commandExists('uvx')) return true;
184
+ }
185
+ }
186
+
187
+ return false;
188
+ }
189
+
190
+ if (IS_MAC && commandExists('brew')) {
191
+ if (runStep('通过 Homebrew 安装 uv', 'brew', ['install', 'uv'])) {
192
+ hydratePath();
193
+ if (commandExists('uvx')) return true;
194
+ }
195
+ }
196
+
197
+ // macOS (without brew) / Linux fallback: official shell script
198
+ if (
199
+ runStep(
200
+ '通过官方脚本安装 uv',
201
+ 'sh',
202
+ ['-c', 'curl -LsSf https://astral.sh/uv/install.sh | sh'],
203
+ { shell: false }
204
+ )
205
+ ) {
206
+ hydratePath();
207
+ if (commandExists('uvx')) return true;
208
+ }
209
+
210
+ return false;
211
+ }
212
+
213
+ async function downloadCloudflaredDirect() {
214
+ fs.mkdirSync(LOCAL_BIN_DIR, { recursive: true });
215
+
216
+ if (IS_WIN) {
217
+ const arch = process.arch === 'ia32' ? '386' : 'amd64';
218
+ const url = `https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-windows-${arch}.exe`;
219
+ const dest = path.join(LOCAL_BIN_DIR, 'cloudflared.exe');
220
+ console.log(`[Setup] 直接下载 cloudflared (${arch}) -> ${dest}`);
221
+ await downloadFile(url, dest);
222
+ hydratePath();
223
+ return commandExists('cloudflared');
224
+ }
225
+
226
+ if (IS_MAC) {
227
+ const arch = process.arch === 'arm64' ? 'arm64' : 'amd64';
228
+ const url = `https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-darwin-${arch}.tgz`;
229
+ const tgzPath = path.join(LOCAL_BIN_DIR, `cloudflared-darwin-${arch}.tgz`);
230
+ const dest = path.join(LOCAL_BIN_DIR, 'cloudflared');
231
+ console.log(`[Setup] 直接下载 cloudflared (${arch}) -> ${dest}`);
232
+ await downloadFile(url, tgzPath);
233
+ const extracted = runStep(
234
+ '解压 cloudflared',
235
+ 'tar',
236
+ ['-xzf', tgzPath, '-C', LOCAL_BIN_DIR],
237
+ { shell: false }
238
+ );
239
+ try {
240
+ fs.unlinkSync(tgzPath);
241
+ } catch {
242
+ // ignore
243
+ }
244
+ if (extracted && fs.existsSync(dest)) {
245
+ fs.chmodSync(dest, 0o755);
246
+ hydratePath();
247
+ return commandExists('cloudflared');
248
+ }
249
+ return false;
250
+ }
251
+
252
+ // Linux static binary
253
+ const archMap = { x64: 'amd64', arm64: 'arm64', arm: 'arm', ia32: '386' };
254
+ const arch = archMap[process.arch] || 'amd64';
255
+ const url = `https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-linux-${arch}`;
256
+ const dest = path.join(LOCAL_BIN_DIR, 'cloudflared');
257
+ console.log(`[Setup] 直接下载 cloudflared (${arch}) -> ${dest}`);
258
+ await downloadFile(url, dest);
259
+ fs.chmodSync(dest, 0o755);
260
+ hydratePath();
261
+ return commandExists('cloudflared');
262
+ }
263
+
264
+ async function installCloudflared() {
265
+ if (IS_WIN) {
266
+ if (commandExists('winget')) {
267
+ if (
268
+ runStep('通过 winget 安装 cloudflared', 'winget', [
269
+ 'install',
270
+ '--id',
271
+ 'Cloudflare.cloudflared',
272
+ '-e',
273
+ '--accept-source-agreements',
274
+ '--accept-package-agreements',
275
+ ])
276
+ ) {
277
+ hydratePath();
278
+ if (commandExists('cloudflared')) return true;
279
+ }
280
+ }
281
+
282
+ if (commandExists('scoop', { useShell: true })) {
283
+ if (
284
+ runStep('通过 scoop 安装 cloudflared', 'scoop', [
285
+ 'install',
286
+ 'cloudflared',
287
+ ], { shell: true })
288
+ ) {
289
+ hydratePath();
290
+ if (commandExists('cloudflared')) return true;
291
+ }
292
+ }
293
+
294
+ if (commandExists('choco', { useShell: true })) {
295
+ if (
296
+ runStep('通过 choco 安装 cloudflared', 'choco', [
297
+ 'install',
298
+ 'cloudflared',
299
+ '-y',
300
+ ], { shell: true })
301
+ ) {
302
+ hydratePath();
303
+ if (commandExists('cloudflared')) return true;
304
+ }
305
+ }
306
+
307
+ try {
308
+ return await downloadCloudflaredDirect();
309
+ } catch (err) {
310
+ console.error(`[Setup] 直接下载 cloudflared 失败: ${err.message}`);
311
+ return false;
312
+ }
313
+ }
314
+
315
+ if (IS_MAC && commandExists('brew')) {
316
+ if (
317
+ runStep('通过 Homebrew 安装 cloudflared', 'brew', [
318
+ 'install',
319
+ 'cloudflared',
320
+ ])
321
+ ) {
322
+ hydratePath();
323
+ if (commandExists('cloudflared')) return true;
324
+ }
325
+ }
326
+
327
+ try {
328
+ return await downloadCloudflaredDirect();
329
+ } catch (err) {
330
+ console.error(`[Setup] 直接下载 cloudflared 失败: ${err.message}`);
331
+ return false;
332
+ }
333
+ }
334
+
335
+ function printManualGuide(missing) {
336
+ console.error(`\n[缺少依赖] 仍未找到: ${missing.join(', ')}\n`);
337
+ if (IS_MAC) {
338
+ const pkgs = [];
339
+ if (missing.includes('uvx')) pkgs.push('uv');
340
+ if (missing.includes('cloudflared')) pkgs.push('cloudflared');
341
+ console.error(`macOS 手动安装:\n brew install ${pkgs.join(' ')}\n`);
342
+ } else if (IS_WIN) {
343
+ console.error('Windows 手动安装 (无需 winget):');
344
+ if (missing.includes('uvx')) {
345
+ console.error(
346
+ ' uv: powershell -ExecutionPolicy ByPass -c "irm https://astral.sh/uv/install.ps1 | iex"'
347
+ );
348
+ }
349
+ if (missing.includes('cloudflared')) {
350
+ console.error(
351
+ ' cloudflared (.msi): https://github.com/cloudflare/cloudflared/releases/latest/download/cloudflared-windows-amd64.msi'
352
+ );
353
+ }
354
+ console.error('\n安装完成后重新打开终端再运行。\n');
355
+ } else {
356
+ if (missing.includes('uvx')) {
357
+ console.error(' uv: curl -LsSf https://astral.sh/uv/install.sh | sh');
358
+ }
359
+ if (missing.includes('cloudflared')) {
360
+ console.error(
361
+ ' cloudflared: https://github.com/cloudflare/cloudflared/releases/latest'
362
+ );
363
+ }
364
+ console.error('');
365
+ }
366
+ }
367
+
368
+ /**
369
+ * Ensure required external binaries (uvx, and optionally cloudflared) are available.
370
+ * Automatically installs missing tools using the best method available on the host OS.
371
+ */
372
+ export async function ensureDependencies({
373
+ needTunnel = true,
374
+ autoInstall = true,
375
+ } = {}) {
376
+ hydratePath();
377
+
378
+ const checkMissing = () => {
379
+ const list = [];
380
+ if (!commandExists('uvx')) list.push('uvx');
381
+ if (needTunnel && !commandExists('cloudflared')) list.push('cloudflared');
382
+ return list;
383
+ };
384
+
385
+ let missing = checkMissing();
386
+ if (missing.length === 0) return;
387
+
388
+ if (!autoInstall) {
389
+ printManualGuide(missing);
390
+ process.exit(1);
391
+ }
392
+
393
+ console.log(
394
+ `\n[Setup] 检测到缺少依赖: ${missing.join(', ')},正在按当前系统自动选择合适方式安装...\n`
395
+ );
396
+
397
+ if (missing.includes('uvx')) {
398
+ const ok = await installUv();
399
+ if (ok) {
400
+ console.log('[Setup] uv / uvx 安装成功!');
401
+ } else {
402
+ console.error('[Setup] uv / uvx 自动安装失败。');
403
+ }
404
+ }
405
+
406
+ if (missing.includes('cloudflared')) {
407
+ const ok = await installCloudflared();
408
+ if (ok) {
409
+ console.log('[Setup] cloudflared 安装成功!');
410
+ } else {
411
+ console.error('[Setup] cloudflared 自动安装失败。');
412
+ }
413
+ }
414
+
415
+ hydratePath();
416
+ missing = checkMissing();
417
+ if (missing.length > 0) {
418
+ printManualGuide(missing);
419
+ process.exit(1);
420
+ }
421
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "serena-mcp-gateway",
3
- "version": "1.0.0",
3
+ "version": "1.2.0",
4
4
  "description": "Cross-platform Serena MCP launcher with OAuth 2.1 proxy, Cloudflare Tunnel, and multi-project parallel routing",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -21,6 +21,7 @@
21
21
  "files": [
22
22
  "serena-mcp.mjs",
23
23
  "auth-proxy.mjs",
24
+ "installer.mjs",
24
25
  "start-serena.sh",
25
26
  "start-serena.cmd",
26
27
  "install.sh",
package/serena-mcp.mjs CHANGED
@@ -4,11 +4,18 @@ import fs from 'node:fs';
4
4
  import net from 'node:net';
5
5
  import os from 'node:os';
6
6
  import path from 'node:path';
7
+ import { fileURLToPath } from 'node:url';
7
8
  import { spawn, spawnSync } from 'node:child_process';
8
9
  import { startAuthProxy } from './auth-proxy.mjs';
10
+ import { ensureDependencies, hydratePath } from './installer.mjs';
9
11
 
10
12
  const IS_WIN = process.platform === 'win32';
11
- const IS_MAC = process.platform === 'darwin';
13
+ const PKG_VERSION = JSON.parse(
14
+ fs.readFileSync(
15
+ path.join(path.dirname(fileURLToPath(import.meta.url)), 'package.json'),
16
+ 'utf8'
17
+ )
18
+ ).version;
12
19
 
13
20
  function printHelp() {
14
21
  console.log(`
@@ -27,6 +34,9 @@ Serena MCP Gateway (跨平台单项目 / 多项目并行启动器)
27
34
  -t, --token <token> 自定义 Bearer Token(>=32 字符;默认每次随机生成)
28
35
  --context <name> 传给 Serena 的 --context(默认 claude-code)
29
36
  --no-tunnel 仅启动本地 Serena + OAuth 代理,不启动 cloudflared
37
+ --setup 仅检查并自动安装缺失依赖(uvx / cloudflared),不启动服务
38
+ --no-auto-install 缺依赖时仅提示手动安装命令,不自动安装
39
+ -v, --version 显示当前版本号
30
40
  -h, --help 显示帮助信息
31
41
 
32
42
  多终端并行:
@@ -108,6 +118,9 @@ function parseArgs(argv) {
108
118
  token: process.env.MCP_TOKEN || '',
109
119
  context: 'claude-code',
110
120
  noTunnel: false,
121
+ setup: false,
122
+ noAutoInstall: false,
123
+ version: false,
111
124
  help: false,
112
125
  projects: [],
113
126
  };
@@ -116,8 +129,14 @@ function parseArgs(argv) {
116
129
  const arg = argv[i];
117
130
  if (arg === '-h' || arg === '--help') {
118
131
  opts.help = true;
132
+ } else if (arg === '-v' || arg === '--version') {
133
+ opts.version = true;
119
134
  } else if (arg === '--no-tunnel') {
120
135
  opts.noTunnel = true;
136
+ } else if (arg === '--setup') {
137
+ opts.setup = true;
138
+ } else if (arg === '--no-auto-install') {
139
+ opts.noAutoInstall = true;
121
140
  } else if (arg === '-p' || arg === '--port') {
122
141
  const val = Number(argv[++i]);
123
142
  if (!Number.isInteger(val) || val < 1024 || val > 65535) {
@@ -152,49 +171,6 @@ function parseArgs(argv) {
152
171
  return opts;
153
172
  }
154
173
 
155
- function commandExists(cmd) {
156
- const res = spawnSync(cmd, ['--version'], {
157
- stdio: 'ignore',
158
- shell: IS_WIN,
159
- });
160
- return !res.error && res.status === 0;
161
- }
162
-
163
- function checkDependencies(needTunnel) {
164
- const missing = [];
165
- if (!commandExists('uvx')) missing.push('uvx');
166
- if (needTunnel && !commandExists('cloudflared')) missing.push('cloudflared');
167
-
168
- if (missing.length === 0) return;
169
-
170
- console.error(`\n[缺少依赖] 未在 PATH 中找到: ${missing.join(', ')}\n`);
171
- if (IS_MAC) {
172
- const pkgs = [];
173
- if (missing.includes('uvx')) pkgs.push('uv');
174
- if (missing.includes('cloudflared')) pkgs.push('cloudflared');
175
- console.error(`macOS 一键安装:\n brew install ${pkgs.join(' ')}\n`);
176
- } else if (IS_WIN) {
177
- console.error('Windows 一键安装 (PowerShell):');
178
- if (missing.includes('uvx')) {
179
- console.error(' winget install --id astral-sh.uv -e');
180
- }
181
- if (missing.includes('cloudflared')) {
182
- console.error(' winget install --id Cloudflare.cloudflared -e');
183
- }
184
- console.error('\n安装完成后请重新打开终端再运行。\n');
185
- } else {
186
- console.error('Linux 安装建议:');
187
- if (missing.includes('uvx')) {
188
- console.error(' curl -LsSf https://astral.sh/uv/install.sh | sh');
189
- }
190
- if (missing.includes('cloudflared')) {
191
- console.error(' 参考 https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/');
192
- }
193
- console.error('');
194
- }
195
- process.exit(1);
196
- }
197
-
198
174
  function isPortFree(port) {
199
175
  return new Promise((resolve) => {
200
176
  const tester = net.createServer();
@@ -299,12 +275,28 @@ async function main() {
299
275
  process.exit(1);
300
276
  }
301
277
 
278
+ if (opts.version) {
279
+ console.log(`serena-mcp-gateway v${PKG_VERSION}`);
280
+ process.exit(0);
281
+ }
282
+
302
283
  if (opts.help) {
303
284
  printHelp();
304
285
  process.exit(0);
305
286
  }
306
287
 
307
- checkDependencies(!opts.noTunnel);
288
+ hydratePath();
289
+
290
+ if (opts.setup) {
291
+ await ensureDependencies({ needTunnel: true, autoInstall: true });
292
+ console.log('\n[OK] 环境依赖检查完成,uvx 与 cloudflared 均已就绪!');
293
+ process.exit(0);
294
+ }
295
+
296
+ await ensureDependencies({
297
+ needTunnel: !opts.noTunnel,
298
+ autoInstall: !opts.noAutoInstall,
299
+ });
308
300
 
309
301
  const token = opts.token || crypto.randomBytes(24).toString('hex');
310
302
  if (token.length < 32) {
@@ -353,6 +345,7 @@ async function main() {
353
345
 
354
346
  if (opts.projects.length === 0) {
355
347
  console.log('[Mode] 全局多项目模式(可在对话中随时指定/切换项目路径)');
348
+ console.log('[Security] 提示:全局模式允许授权客户端访问本机任意项目,建议优先传入具体项目目录以遵循最小权限原则。');
356
349
  } else if (opts.projects.length === 1) {
357
350
  console.log(`[Mode] 锁定单项目工作区: ${opts.projects[0].projectPath}`);
358
351
  } else {
@@ -395,7 +388,7 @@ async function main() {
395
388
 
396
389
  const child = spawn('uvx', serenaArgs, {
397
390
  stdio: ['ignore', 'pipe', 'pipe'],
398
- shell: IS_WIN,
391
+ shell: false,
399
392
  });
400
393
  children.push(child);
401
394
 
@@ -446,7 +439,7 @@ async function main() {
446
439
  ['tunnel', '--protocol', 'http2', '--url', `http://127.0.0.1:${proxyPort}`],
447
440
  {
448
441
  stdio: ['ignore', 'pipe', 'pipe'],
449
- shell: IS_WIN,
442
+ shell: false,
450
443
  }
451
444
  );
452
445
  children.push(cf);