serena-mcp-gateway 1.1.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/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, '>');
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 CHANGED
@@ -1,3 +1,4 @@
1
+ import crypto from 'node:crypto';
1
2
  import fs from 'node:fs';
2
3
  import os from 'node:os';
3
4
  import path from 'node:path';
@@ -6,6 +7,8 @@ import { spawnSync } from 'node:child_process';
6
7
  const IS_WIN = process.platform === 'win32';
7
8
  const IS_MAC = process.platform === 'darwin';
8
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;
9
12
 
10
13
  function getExtraSearchDirs() {
11
14
  const home = os.homedir();
@@ -63,10 +66,10 @@ export function hydratePath() {
63
66
  }
64
67
  }
65
68
 
66
- export function commandExists(cmd) {
69
+ export function commandExists(cmd, { useShell = false } = {}) {
67
70
  const res = spawnSync(cmd, ['--version'], {
68
71
  stdio: 'ignore',
69
- shell: IS_WIN,
72
+ shell: useShell,
70
73
  });
71
74
  return !res.error && res.status === 0;
72
75
  }
@@ -75,22 +78,44 @@ function runStep(label, cmd, args, extraOpts = {}) {
75
78
  console.log(`[Setup] ${label}...`);
76
79
  const res = spawnSync(cmd, args, {
77
80
  stdio: 'inherit',
78
- shell: IS_WIN,
81
+ shell: false,
79
82
  ...extraOpts,
80
83
  });
81
84
  return !res.error && res.status === 0;
82
85
  }
83
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
+
84
98
  async function downloadFile(url, destPath) {
85
- fs.mkdirSync(path.dirname(destPath), { recursive: true });
86
- const res = await fetch(url, { redirect: 'follow' });
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
+ });
87
107
  if (!res.ok) {
88
108
  throw new Error(`HTTP ${res.status} ${res.statusText}`);
89
109
  }
90
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');
91
115
  const tmpPath = `${destPath}.tmp-${Date.now()}`;
92
- fs.writeFileSync(tmpPath, buf);
116
+ fs.writeFileSync(tmpPath, buf, { mode: 0o755 });
93
117
  fs.renameSync(tmpPath, destPath);
118
+ console.log(`[Setup] 下载校验完成 SHA-256: ${sha256}`);
94
119
  }
95
120
 
96
121
  async function installUv() {
@@ -111,15 +136,23 @@ async function installUv() {
111
136
  }
112
137
  }
113
138
 
114
- if (commandExists('scoop')) {
115
- if (runStep('通过 scoop 安装 uv', 'scoop', ['install', 'uv'])) {
139
+ if (commandExists('scoop', { useShell: true })) {
140
+ if (
141
+ runStep('通过 scoop 安装 uv', 'scoop', ['install', 'uv'], {
142
+ shell: true,
143
+ })
144
+ ) {
116
145
  hydratePath();
117
146
  if (commandExists('uvx')) return true;
118
147
  }
119
148
  }
120
149
 
121
- if (commandExists('choco')) {
122
- if (runStep('通过 choco 安装 uv', 'choco', ['install', 'uv', '-y'])) {
150
+ if (commandExists('choco', { useShell: true })) {
151
+ if (
152
+ runStep('通过 choco 安装 uv', 'choco', ['install', 'uv', '-y'], {
153
+ shell: true,
154
+ })
155
+ ) {
123
156
  hydratePath();
124
157
  if (commandExists('uvx')) return true;
125
158
  }
@@ -246,25 +279,25 @@ async function installCloudflared() {
246
279
  }
247
280
  }
248
281
 
249
- if (commandExists('scoop')) {
282
+ if (commandExists('scoop', { useShell: true })) {
250
283
  if (
251
284
  runStep('通过 scoop 安装 cloudflared', 'scoop', [
252
285
  'install',
253
286
  'cloudflared',
254
- ])
287
+ ], { shell: true })
255
288
  ) {
256
289
  hydratePath();
257
290
  if (commandExists('cloudflared')) return true;
258
291
  }
259
292
  }
260
293
 
261
- if (commandExists('choco')) {
294
+ if (commandExists('choco', { useShell: true })) {
262
295
  if (
263
296
  runStep('通过 choco 安装 cloudflared', 'choco', [
264
297
  'install',
265
298
  'cloudflared',
266
299
  '-y',
267
- ])
300
+ ], { shell: true })
268
301
  ) {
269
302
  hydratePath();
270
303
  if (commandExists('cloudflared')) return true;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "serena-mcp-gateway",
3
- "version": "1.1.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",
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';
9
10
  import { ensureDependencies, hydratePath } from './installer.mjs';
10
11
 
11
12
  const IS_WIN = process.platform === 'win32';
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(`
@@ -29,6 +36,7 @@ Serena MCP Gateway (跨平台单项目 / 多项目并行启动器)
29
36
  --no-tunnel 仅启动本地 Serena + OAuth 代理,不启动 cloudflared
30
37
  --setup 仅检查并自动安装缺失依赖(uvx / cloudflared),不启动服务
31
38
  --no-auto-install 缺依赖时仅提示手动安装命令,不自动安装
39
+ -v, --version 显示当前版本号
32
40
  -h, --help 显示帮助信息
33
41
 
34
42
  多终端并行:
@@ -112,6 +120,7 @@ function parseArgs(argv) {
112
120
  noTunnel: false,
113
121
  setup: false,
114
122
  noAutoInstall: false,
123
+ version: false,
115
124
  help: false,
116
125
  projects: [],
117
126
  };
@@ -120,6 +129,8 @@ function parseArgs(argv) {
120
129
  const arg = argv[i];
121
130
  if (arg === '-h' || arg === '--help') {
122
131
  opts.help = true;
132
+ } else if (arg === '-v' || arg === '--version') {
133
+ opts.version = true;
123
134
  } else if (arg === '--no-tunnel') {
124
135
  opts.noTunnel = true;
125
136
  } else if (arg === '--setup') {
@@ -264,6 +275,11 @@ async function main() {
264
275
  process.exit(1);
265
276
  }
266
277
 
278
+ if (opts.version) {
279
+ console.log(`serena-mcp-gateway v${PKG_VERSION}`);
280
+ process.exit(0);
281
+ }
282
+
267
283
  if (opts.help) {
268
284
  printHelp();
269
285
  process.exit(0);
@@ -329,6 +345,7 @@ async function main() {
329
345
 
330
346
  if (opts.projects.length === 0) {
331
347
  console.log('[Mode] 全局多项目模式(可在对话中随时指定/切换项目路径)');
348
+ console.log('[Security] 提示:全局模式允许授权客户端访问本机任意项目,建议优先传入具体项目目录以遵循最小权限原则。');
332
349
  } else if (opts.projects.length === 1) {
333
350
  console.log(`[Mode] 锁定单项目工作区: ${opts.projects[0].projectPath}`);
334
351
  } else {
@@ -371,7 +388,7 @@ async function main() {
371
388
 
372
389
  const child = spawn('uvx', serenaArgs, {
373
390
  stdio: ['ignore', 'pipe', 'pipe'],
374
- shell: IS_WIN,
391
+ shell: false,
375
392
  });
376
393
  children.push(child);
377
394
 
@@ -422,7 +439,7 @@ async function main() {
422
439
  ['tunnel', '--protocol', 'http2', '--url', `http://127.0.0.1:${proxyPort}`],
423
440
  {
424
441
  stdio: ['ignore', 'pipe', 'pipe'],
425
- shell: IS_WIN,
442
+ shell: false,
426
443
  }
427
444
  );
428
445
  children.push(cf);