codebase-snapshot 0.20.2 → 0.20.4

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.
@@ -1,4 +1,4 @@
1
- import { createServer, buildTools, GENERATOR_VERSION } from './chunk-DUDF3CR5.js';
1
+ import { buildTools, createServer, GENERATOR_VERSION } from './chunk-AQZNT3QL.js';
2
2
  import * as http from 'http';
3
3
  import * as crypto from 'crypto';
4
4
 
@@ -37,8 +37,43 @@ async function startHttpTransport(options) {
37
37
  "Refusing to serve " + host + " without a token: a repository reachable from the network must require Authorization. Drop --no-auth, or bind the loopback address."
38
38
  );
39
39
  }
40
- const server = createServer({ cwd: options.cwd, log });
40
+ const createMcp = () => createServer({ cwd: options.cwd, log });
41
41
  const toolCount = buildTools().length;
42
+ const mcpSessions = /* @__PURE__ */ new Map();
43
+ const socketServers = /* @__PURE__ */ new WeakMap();
44
+ const anonymousServers = /* @__PURE__ */ new Map();
45
+ const serverFor = (request) => {
46
+ const header = request.headers["mcp-session-id"];
47
+ const supplied = typeof header === "string" ? header.trim() : "";
48
+ if (supplied !== "") {
49
+ let existing = mcpSessions.get(supplied);
50
+ if (existing === void 0) {
51
+ existing = createMcp();
52
+ if (mcpSessions.size >= 64) {
53
+ const oldest = mcpSessions.keys().next().value;
54
+ if (oldest !== void 0) mcpSessions.delete(oldest);
55
+ }
56
+ mcpSessions.set(supplied, existing);
57
+ }
58
+ return existing;
59
+ }
60
+ const onSocket = socketServers.get(request.socket);
61
+ if (onSocket !== void 0) return onSocket;
62
+ const userAgent = typeof request.headers["user-agent"] === "string" ? request.headers["user-agent"] : "";
63
+ const fallbackKey = (request.socket.remoteAddress ?? "unknown") + "\0" + userAgent;
64
+ let fallback = anonymousServers.get(fallbackKey);
65
+ if (fallback === void 0) {
66
+ fallback = createMcp();
67
+ if (anonymousServers.size >= 64) {
68
+ const oldest = anonymousServers.keys().next().value;
69
+ if (oldest !== void 0) anonymousServers.delete(oldest);
70
+ }
71
+ anonymousServers.set(fallbackKey, fallback);
72
+ }
73
+ socketServers.set(request.socket, fallback);
74
+ return fallback;
75
+ };
76
+ const newSessionId = () => crypto.randomBytes(12).toString("hex");
42
77
  const sseSessions = /* @__PURE__ */ new Map();
43
78
  const tokenAccepted = (request, url) => {
44
79
  if (token === null) return true;
@@ -59,6 +94,18 @@ async function startHttpTransport(options) {
59
94
  const method = request.method ?? "UNKNOWN";
60
95
  metrics.byMethod.set(method, (metrics.byMethod.get(method) ?? 0) + 1);
61
96
  };
97
+ const rateLimited = (request) => {
98
+ const remote = request.socket.remoteAddress ?? "unknown";
99
+ const now = Date.now();
100
+ const window = sessions.get(remote);
101
+ if (window === void 0 || window.resetAt <= now) {
102
+ sessions.set(remote, { count: 1, resetAt: now + RATE_WINDOW_MS });
103
+ return false;
104
+ }
105
+ if (window.count >= RATE_LIMIT) return true;
106
+ window.count += 1;
107
+ return false;
108
+ };
62
109
  const allowedOrigin = (origin) => {
63
110
  if (origin === void 0) return null;
64
111
  if (isLoopbackOrigin(origin)) return origin;
@@ -66,7 +113,10 @@ async function startHttpTransport(options) {
66
113
  };
67
114
  const httpServer = http.createServer((request, response) => {
68
115
  noteRequest(request);
116
+ let responseSent = false;
69
117
  const send = (status, body, extra = {}) => {
118
+ if (responseSent) return;
119
+ responseSent = true;
70
120
  const text = typeof body === "string" ? body : JSON.stringify(body);
71
121
  if (status >= 400 && status < 500 && status !== 429) metrics.refused += 1;
72
122
  response.writeHead(status, {
@@ -142,6 +192,11 @@ async function startHttpTransport(options) {
142
192
  send(401, { error: "unauthorized" }, { ...cors, "www-authenticate": 'Bearer realm="codebase-snapshot"' });
143
193
  return;
144
194
  }
195
+ if (rateLimited(request)) {
196
+ metrics.rateLimited += 1;
197
+ send(429, { error: "too many requests" }, { ...cors, "retry-after": "10" });
198
+ return;
199
+ }
145
200
  const id = crypto.randomBytes(12).toString("hex");
146
201
  response.writeHead(200, {
147
202
  ...cors,
@@ -153,7 +208,7 @@ async function startHttpTransport(options) {
153
208
  const write = (payload) => {
154
209
  response.write(payload);
155
210
  };
156
- sseSessions.set(id, { write, end: () => response.end() });
211
+ sseSessions.set(id, { write, end: () => response.end(), server: createMcp() });
157
212
  const heartbeat = setInterval(() => write(": ping\n\n"), 15e3);
158
213
  const cleanup = () => {
159
214
  clearInterval(heartbeat);
@@ -169,6 +224,11 @@ async function startHttpTransport(options) {
169
224
  send(401, { error: "unauthorized" }, { ...cors, "www-authenticate": 'Bearer realm="codebase-snapshot"' });
170
225
  return;
171
226
  }
227
+ if (rateLimited(request)) {
228
+ metrics.rateLimited += 1;
229
+ send(429, { error: "too many requests" }, { ...cors, "retry-after": "10" });
230
+ return;
231
+ }
172
232
  const id = url.searchParams.get("sessionId") ?? "";
173
233
  const stream = sseSessions.get(id);
174
234
  if (stream === void 0) {
@@ -177,9 +237,12 @@ async function startHttpTransport(options) {
177
237
  }
178
238
  const chunks2 = [];
179
239
  let received2 = 0;
240
+ let tooLarge2 = false;
180
241
  request.on("data", (chunk) => {
242
+ if (tooLarge2) return;
181
243
  received2 += chunk.length;
182
244
  if (received2 > maxBody) {
245
+ tooLarge2 = true;
183
246
  request.destroy();
184
247
  send(413, { error: "request body too large", limit: maxBody });
185
248
  return;
@@ -187,6 +250,7 @@ async function startHttpTransport(options) {
187
250
  chunks2.push(chunk);
188
251
  });
189
252
  request.on("end", () => {
253
+ if (tooLarge2) return;
190
254
  void (async () => {
191
255
  let message;
192
256
  try {
@@ -195,7 +259,7 @@ async function startHttpTransport(options) {
195
259
  send(400, { jsonrpc: "2.0", id: null, error: { code: -32700, message: String(error) } });
196
260
  return;
197
261
  }
198
- const answer = await server.handle(message);
262
+ const answer = await stream.server.handle(message);
199
263
  if (answer !== null) stream.write("event: message\ndata: " + JSON.stringify(answer) + "\n\n");
200
264
  send(202, "", cors);
201
265
  })();
@@ -222,20 +286,22 @@ async function startHttpTransport(options) {
222
286
  return;
223
287
  }
224
288
  }
225
- const remote = request.socket.remoteAddress ?? "unknown";
226
- const now = Date.now();
227
- const window = sessions.get(remote);
228
- if (window === void 0 || window.resetAt <= now) sessions.set(remote, { count: 1, resetAt: now + RATE_WINDOW_MS });
229
- else if (window.count >= RATE_LIMIT) {
289
+ if (rateLimited(request)) {
230
290
  metrics.rateLimited += 1;
231
291
  send(429, { error: "too many requests" }, { ...cors, "retry-after": "10" });
232
292
  return;
233
- } else window.count += 1;
293
+ }
294
+ const activeServer = serverFor(request);
295
+ const sessionHeader = request.headers["mcp-session-id"];
296
+ let sessionId = typeof sessionHeader === "string" ? sessionHeader.trim() : "";
234
297
  let received = 0;
298
+ let tooLarge = false;
235
299
  const chunks = [];
236
300
  request.on("data", (chunk) => {
301
+ if (tooLarge) return;
237
302
  received += chunk.length;
238
303
  if (received > maxBody) {
304
+ tooLarge = true;
239
305
  request.destroy();
240
306
  send(413, { error: "request body too large", limit: maxBody }, cors);
241
307
  return;
@@ -243,6 +309,7 @@ async function startHttpTransport(options) {
243
309
  chunks.push(chunk);
244
310
  });
245
311
  request.on("end", () => {
312
+ if (tooLarge) return;
246
313
  void (async () => {
247
314
  let message;
248
315
  try {
@@ -251,17 +318,26 @@ async function startHttpTransport(options) {
251
318
  send(400, { jsonrpc: "2.0", id: null, error: { code: -32700, message: "Parse error: " + error.message } }, cors);
252
319
  return;
253
320
  }
254
- const answers = [];
255
321
  const batch = Array.isArray(message) ? message : [message];
322
+ if (batch.length > 100) {
323
+ send(400, { error: "JSON-RPC batch is limited to 100 messages" }, cors);
324
+ return;
325
+ }
326
+ if (sessionId === "" && !Array.isArray(message) && message.method === "initialize") {
327
+ sessionId = newSessionId();
328
+ mcpSessions.set(sessionId, activeServer);
329
+ }
330
+ const sessionHeaders = sessionId === "" ? cors : { ...cors, "mcp-session-id": sessionId };
331
+ const answers = [];
256
332
  for (const item of batch) {
257
- const answer = await server.handle(item);
333
+ const answer = await activeServer.handle(item);
258
334
  if (answer !== null) answers.push(answer);
259
335
  }
260
336
  if (answers.length === 0) {
261
- send(202, "", cors);
337
+ send(202, "", sessionHeaders);
262
338
  return;
263
339
  }
264
- send(200, Array.isArray(message) ? answers : answers[0], cors);
340
+ send(200, Array.isArray(message) ? answers : answers[0], sessionHeaders);
265
341
  })().catch((error) => {
266
342
  log("mcp/http: " + error.message);
267
343
  send(500, { jsonrpc: "2.0", id: null, error: { code: -32603, message: "Internal error" } }, cors);