@zereight/mcp-gitlab 2.1.70 → 2.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (158) hide show
  1. package/README.ko.md +9 -5
  2. package/README.md +15 -11
  3. package/README.pt-BR.md +9 -5
  4. package/README.zh-CN.md +9 -5
  5. package/build/config.js +12 -4
  6. package/build/deprecated-env.js +63 -0
  7. package/build/index.js +430 -200
  8. package/build/oauth-device-flow.js +80 -0
  9. package/build/oauth.js +135 -18
  10. package/build/schemas.js +1 -1
  11. package/build/server/remote-http-stack.js +39 -0
  12. package/build/tools/discover-activation.js +38 -0
  13. package/build/tools/exposed-tools.js +35 -0
  14. package/build/tools/listed-tools.js +76 -0
  15. package/build/tools/registry.js +232 -63
  16. package/build/tools/tool-descriptions.js +3 -3
  17. package/build/tools/tool-profile.js +66 -0
  18. package/build/utils/compact-tool-allowlist.js +14 -0
  19. package/build/utils/logger.js +34 -12
  20. package/package.json +3 -3
  21. package/build/scripts/check-skill-sync.js +0 -143
  22. package/build/scripts/generate-server-card.js +0 -39
  23. package/build/scripts/generate-tool-coverage.js +0 -58
  24. package/build/scripts/generate-tool-docs.js +0 -430
  25. package/build/scripts/tool-coverage/coverage.js +0 -341
  26. package/build/scripts/tool-coverage/coverage.test.js +0 -142
  27. package/build/test/callback-proxy-tests.js +0 -321
  28. package/build/test/cli/args.test.js +0 -175
  29. package/build/test/cli/boolean-flags.test.js +0 -106
  30. package/build/test/cli/compact-mcp-result.test.js +0 -93
  31. package/build/test/cli/credentials.test.js +0 -153
  32. package/build/test/cli/exposure.test.js +0 -104
  33. package/build/test/cli/load-config-snapshot.js +0 -5
  34. package/build/test/cli/output.test.js +0 -74
  35. package/build/test/cli/replay-command.test.js +0 -37
  36. package/build/test/cli/router.test.js +0 -183
  37. package/build/test/client-pool-test.js +0 -109
  38. package/build/test/clients/client.js +0 -34
  39. package/build/test/clients/custom-header-client.js +0 -122
  40. package/build/test/clients/sse-client.js +0 -95
  41. package/build/test/clients/stdio-client.js +0 -113
  42. package/build/test/clients/streamable-http-client.js +0 -95
  43. package/build/test/config-allowed-groups.test.js +0 -97
  44. package/build/test/create-commit-actions.test.js +0 -102
  45. package/build/test/draft-note-schema.test.js +0 -44
  46. package/build/test/dynamic-api-url-allowlist.test.js +0 -121
  47. package/build/test/dynamic-api-url-test.js +0 -304
  48. package/build/test/dynamic-routing-tests.js +0 -495
  49. package/build/test/get-merge-request-discussion-schema.test.js +0 -30
  50. package/build/test/gitlab-api-tool-errors.test.js +0 -112
  51. package/build/test/gitlab-artifact-entry-schema.test.js +0 -44
  52. package/build/test/gitlab-diff-schema.test.js +0 -36
  53. package/build/test/gitlab-pipeline-schedule-schema.test.js +0 -32
  54. package/build/test/gitlab-tag-schema.test.js +0 -51
  55. package/build/test/group-milestone-schema.test.js +0 -45
  56. package/build/test/mcp-oauth-tests.js +0 -905
  57. package/build/test/mcp-server-name.test.js +0 -87
  58. package/build/test/merge-merge-request-schema.test.js +0 -75
  59. package/build/test/multi-server-test.js +0 -190
  60. package/build/test/no-proxy-integration-test.js +0 -183
  61. package/build/test/no-proxy-test.js +0 -149
  62. package/build/test/nullable-gitlab-response-fields.test.js +0 -37
  63. package/build/test/nullish-tool-arguments-schema.test.js +0 -118
  64. package/build/test/oauth-device-flow-tests.js +0 -450
  65. package/build/test/oauth-download-url.test.js +0 -157
  66. package/build/test/oauth-startup.test.js +0 -204
  67. package/build/test/oauth-tests.js +0 -428
  68. package/build/test/path-segment-encoding.test.js +0 -98
  69. package/build/test/remote-auth-simple-test.js +0 -277
  70. package/build/test/remote-auth-tests.js +0 -314
  71. package/build/test/response-masking.test.js +0 -445
  72. package/build/test/schema-tests.js +0 -1679
  73. package/build/test/server/metrics.test.js +0 -47
  74. package/build/test/server/request-helpers.test.js +0 -48
  75. package/build/test/server/version.test.js +0 -13
  76. package/build/test/sse-auth-guard.test.js +0 -96
  77. package/build/test/sse-session-limits.test.js +0 -273
  78. package/build/test/stateless/callback-proxy.test.js +0 -510
  79. package/build/test/stateless/client-id.test.js +0 -177
  80. package/build/test/stateless/codec.test.js +0 -328
  81. package/build/test/stateless/config-ttl.test.js +0 -149
  82. package/build/test/stateless/consumed-proxy-code-cache.test.js +0 -150
  83. package/build/test/stateless/session-id-integration.test.js +0 -675
  84. package/build/test/stateless/session-id.test.js +0 -157
  85. package/build/test/streamable-http-concurrent-session.test.js +0 -171
  86. package/build/test/streamable-http-dns-rebinding.test.js +0 -185
  87. package/build/test/streamable-http-sse-stream.test.js +0 -350
  88. package/build/test/streamable-http-static-token-auth.test.js +0 -157
  89. package/build/test/streamable-http-unauthenticated-discovery.test.js +0 -207
  90. package/build/test/test-all-transport-server.js +0 -255
  91. package/build/test/test-auth-retry.js +0 -195
  92. package/build/test/test-blank-filters.js +0 -156
  93. package/build/test/test-ci-catalog.js +0 -177
  94. package/build/test/test-ci-lint.js +0 -191
  95. package/build/test/test-ci-variables.js +0 -309
  96. package/build/test/test-create-repository.js +0 -120
  97. package/build/test/test-dependency-proxy.js +0 -195
  98. package/build/test/test-deployment-tools.js +0 -463
  99. package/build/test/test-download-attachment.js +0 -190
  100. package/build/test/test-dynamic-project-scope.js +0 -524
  101. package/build/test/test-empty-toolsets.js +0 -535
  102. package/build/test/test-get-file-blame.js +0 -145
  103. package/build/test/test-get-file-contents.js +0 -128
  104. package/build/test/test-geteffectiveprojectid.js +0 -804
  105. package/build/test/test-health-check.js +0 -115
  106. package/build/test/test-issue-description-patch.js +0 -256
  107. package/build/test/test-job-artifacts.js +0 -275
  108. package/build/test/test-json-schema.js +0 -166
  109. package/build/test/test-list-group-members.js +0 -150
  110. package/build/test/test-list-group-merge-requests.js +0 -165
  111. package/build/test/test-list-issues.js +0 -170
  112. package/build/test/test-list-merge-requests.js +0 -201
  113. package/build/test/test-list-milestones.js +0 -145
  114. package/build/test/test-list-project-members.js +0 -132
  115. package/build/test/test-merge-request-approval-state-tools.js +0 -213
  116. package/build/test/test-merge-request-approvals.js +0 -187
  117. package/build/test/test-merge-request-pipelines.js +0 -106
  118. package/build/test/test-mr-diffs-filter.js +0 -132
  119. package/build/test/test-mr-file-diffs.js +0 -251
  120. package/build/test/test-oauth-proxy-rate-limit.js +0 -133
  121. package/build/test/test-orbit.js +0 -155
  122. package/build/test/test-permission-mode.js +0 -424
  123. package/build/test/test-pipeline-schedules.js +0 -484
  124. package/build/test/test-protected-branches.js +0 -174
  125. package/build/test/test-remote-downloads.js +0 -510
  126. package/build/test/test-search-code.js +0 -275
  127. package/build/test/test-snippets.js +0 -735
  128. package/build/test/test-tags.js +0 -220
  129. package/build/test/test-todos.js +0 -195
  130. package/build/test/test-token-optimizations.js +0 -691
  131. package/build/test/test-toolset-filtering.js +0 -499
  132. package/build/test/test-update-issue-slim.js +0 -141
  133. package/build/test/test-update-project.js +0 -112
  134. package/build/test/test-upload-markdown.js +0 -206
  135. package/build/test/test-vulnerabilities.js +0 -399
  136. package/build/test/test-webhooks.js +0 -218
  137. package/build/test/tool-description-quality.test.js +0 -50
  138. package/build/test/utils/bulk-publish-options.test.js +0 -32
  139. package/build/test/utils/download-token.test.js +0 -35
  140. package/build/test/utils/forwarded-public-base-url.test.js +0 -46
  141. package/build/test/utils/gitlab-instance-version.test.js +0 -32
  142. package/build/test/utils/gitlab-version-gate.test.js +0 -74
  143. package/build/test/utils/graphql-query.test.js +0 -168
  144. package/build/test/utils/helpers-path.test.js +0 -104
  145. package/build/test/utils/jmespath-tool-result.test.js +0 -91
  146. package/build/test/utils/masking.test.js +0 -384
  147. package/build/test/utils/merge-request-position.test.js +0 -57
  148. package/build/test/utils/mock-gitlab-server.js +0 -614
  149. package/build/test/utils/proxy-client-ip.test.js +0 -28
  150. package/build/test/utils/redact-sensitive.test.js +0 -32
  151. package/build/test/utils/safe-redirect-fetch.test.js +0 -463
  152. package/build/test/utils/server-launcher.js +0 -231
  153. package/build/test/utils/tool-args.test.js +0 -210
  154. package/build/test/utils/url.test.js +0 -141
  155. package/build/test/utils/version-check.test.js +0 -239
  156. package/build/test/utils/wiki-title.test.js +0 -21
  157. package/build/test-note.js +0 -54
  158. package/build/test-resolve-issue-note.js +0 -127
@@ -1,47 +0,0 @@
1
- import { describe, test } from "node:test";
2
- import assert from "node:assert";
3
- import { escapePrometheusLabel, formatPrometheusMetrics } from "../../server/metrics.js";
4
- describe("Prometheus metrics formatting", () => {
5
- test("escapes label values", () => {
6
- assert.strictEqual(escapePrometheusLabel('a"b\\c\nd'), 'a\\"b\\\\c\\nd');
7
- });
8
- test("formats current MCP metrics", () => {
9
- const body = formatPrometheusMetrics({
10
- requestsProcessed: 2,
11
- rejectedByRateLimit: 1,
12
- rejectedByCapacity: 0,
13
- authFailures: 3,
14
- totalSessions: 4,
15
- expiredSessions: 5,
16
- activeSessions: 6,
17
- authenticatedSessions: 7,
18
- gitlabClientPool: { size: 8, maxSize: 100 },
19
- uptime: 9,
20
- memoryUsage: {
21
- rss: 10,
22
- heapTotal: 11,
23
- heapUsed: 12,
24
- external: 13,
25
- arrayBuffers: 14,
26
- },
27
- statelessRequests: 15,
28
- statelessAuthFromHeader: 16,
29
- statelessAuthFromSealedSid: 17,
30
- statelessAuthFailures: 18,
31
- statelessSidRotated: 19,
32
- config: {
33
- maxSessions: 1000,
34
- maxRequestsPerMinute: 60,
35
- sessionTimeoutSeconds: 3600,
36
- remoteAuthEnabled: true,
37
- mcpOAuthEnabled: false,
38
- statelessModeEnabled: false,
39
- statelessRotationKey: false,
40
- },
41
- });
42
- assert.match(body, /# HELP gitlab_mcp_requests_processed_total/);
43
- assert.match(body, /gitlab_mcp_requests_processed_total 2/);
44
- assert.match(body, /gitlab_mcp_requests_rejected_total\{reason="rate_limit"\} 1/);
45
- assert.match(body, /gitlab_mcp_config_info\{[^}]*remote_auth_enabled="true"/);
46
- });
47
- });
@@ -1,48 +0,0 @@
1
- import { describe, test } from "node:test";
2
- import assert from "node:assert";
3
- import { isInitializationRequestBody, isUnauthenticatedDiscoveryRequestBody, readAcceptHeader, readMcpSessionIdHeader, redactSessionIdForLog, } from "../../server/request-helpers.js";
4
- describe("streamable request helpers", () => {
5
- test("redacts stateless session ids and truncates legacy ids", () => {
6
- assert.strictEqual(redactSessionIdForLog(undefined), "<none>");
7
- assert.strictEqual(redactSessionIdForLog("v1.sid.secret-payload"), "v1.sid.<redacted>");
8
- assert.strictEqual(redactSessionIdForLog("123456789abcdef"), "12345678…");
9
- assert.strictEqual(redactSessionIdForLog("short"), "short");
10
- });
11
- test("detects initialize requests in single and batch bodies", () => {
12
- assert.strictEqual(isInitializationRequestBody({ method: "initialize" }), true);
13
- assert.strictEqual(isInitializationRequestBody([{ method: "tools/list" }, { method: "initialize" }]), true);
14
- assert.strictEqual(isInitializationRequestBody({ method: "tools/list" }), false);
15
- assert.strictEqual(isInitializationRequestBody(null), false);
16
- });
17
- test("allows only discovery methods in unauthenticated discovery bodies", () => {
18
- assert.strictEqual(isUnauthenticatedDiscoveryRequestBody({ method: "tools/list" }), true);
19
- assert.strictEqual(isUnauthenticatedDiscoveryRequestBody({ method: "server/discover" }), true);
20
- assert.strictEqual(isUnauthenticatedDiscoveryRequestBody([
21
- { method: "initialize" },
22
- { method: "notifications/initialized" },
23
- { method: "tools/list" },
24
- { method: "server/discover" },
25
- ]), true);
26
- assert.strictEqual(isUnauthenticatedDiscoveryRequestBody([
27
- { method: "tools/list" },
28
- { method: "call_tool" },
29
- { method: "tools/call" },
30
- ]), false);
31
- assert.strictEqual(isUnauthenticatedDiscoveryRequestBody([
32
- { method: "server/discover" },
33
- { method: "tools/call" },
34
- ]), false);
35
- assert.strictEqual(isUnauthenticatedDiscoveryRequestBody(undefined), false);
36
- });
37
- test("normalizes Mcp-Session-Id headers", () => {
38
- assert.strictEqual(readMcpSessionIdHeader({ headers: { "mcp-session-id": "sid-1" } }), "sid-1");
39
- assert.strictEqual(readMcpSessionIdHeader({ headers: { "mcp-session-id": "" } }), undefined);
40
- assert.strictEqual(readMcpSessionIdHeader({ headers: { "mcp-session-id": ["sid-1", "sid-2"] } }), undefined);
41
- assert.strictEqual(readMcpSessionIdHeader({ headers: {} }), undefined);
42
- });
43
- test("joins duplicate Accept headers so text/event-stream is not dropped", () => {
44
- assert.strictEqual(readAcceptHeader({ headers: { accept: "application/json, text/event-stream" } }), "application/json, text/event-stream");
45
- assert.strictEqual(readAcceptHeader({ headers: { accept: ["application/json", "text/event-stream"] } }), "application/json, text/event-stream");
46
- assert.strictEqual(readAcceptHeader({ headers: {} }), "");
47
- });
48
- });
@@ -1,13 +0,0 @@
1
- import { test } from "node:test";
2
- import assert from "node:assert";
3
- import fs from "node:fs";
4
- import path, { dirname } from "node:path";
5
- import { fileURLToPath } from "node:url";
6
- import { SERVER_VERSION } from "../../server/version.js";
7
- const __filename = fileURLToPath(import.meta.url);
8
- const __dirname = dirname(__filename);
9
- const packageJsonPath = path.resolve(__dirname, "../../package.json");
10
- const packageVersion = JSON.parse(fs.readFileSync(packageJsonPath, "utf8")).version;
11
- test("SERVER_VERSION matches package.json", () => {
12
- assert.strictEqual(SERVER_VERSION, packageVersion);
13
- });
@@ -1,96 +0,0 @@
1
- import assert from "node:assert/strict";
2
- import { spawn } from "node:child_process";
3
- import { once } from "node:events";
4
- import { afterEach, describe, test } from "node:test";
5
- import * as path from "node:path";
6
- import { findAvailablePort } from "./utils/server-launcher.js";
7
- const ERROR_MESSAGE = "SSE=true requires SSE_AUTH_TOKEN (or explicitly set SSE_DANGEROUSLY_ALLOW_UNAUTHENTICATED_REMOTE=true)";
8
- const LOOPBACK = "127.0.0.1";
9
- const SERVER_PATH = path.resolve(process.cwd(), "build/index.js");
10
- const running = new Set();
11
- function startSseServer(env, port) {
12
- const child = spawn("node", [SERVER_PATH], {
13
- env: {
14
- ...process.env,
15
- GITLAB_API_URL: "https://gitlab.example.com/api/v4",
16
- HOST: "0.0.0.0",
17
- PORT: String(port),
18
- SSE: "true",
19
- STREAMABLE_HTTP: "false",
20
- REMOTE_AUTHORIZATION: "false",
21
- GITLAB_MCP_OAUTH: "false",
22
- GITLAB_USE_OAUTH: "false",
23
- GITLAB_PERSONAL_ACCESS_TOKEN: "glpat_test",
24
- GITLAB_JOB_TOKEN: "",
25
- GITLAB_AUTH_COOKIE_PATH: "",
26
- ...env,
27
- },
28
- stdio: ["ignore", "pipe", "pipe"],
29
- });
30
- running.add(child);
31
- child.once("exit", () => running.delete(child));
32
- return child;
33
- }
34
- async function waitForExit(child, timeoutMs = 5000) {
35
- let output = "";
36
- child.stdout?.on("data", chunk => {
37
- output += chunk.toString();
38
- });
39
- child.stderr?.on("data", chunk => {
40
- output += chunk.toString();
41
- });
42
- let timeoutHandle;
43
- const timeout = new Promise((_, reject) => {
44
- timeoutHandle = setTimeout(() => reject(new Error(`server did not exit within ${timeoutMs}ms`)), timeoutMs);
45
- });
46
- try {
47
- const [code] = (await Promise.race([once(child, "exit"), timeout]));
48
- return { code, output };
49
- }
50
- finally {
51
- clearTimeout(timeoutHandle);
52
- }
53
- }
54
- async function waitForHealth(port, timeoutMs = 5000) {
55
- const deadline = Date.now() + timeoutMs;
56
- let lastError;
57
- while (Date.now() < deadline) {
58
- try {
59
- const response = await fetch(`http://${LOOPBACK}:${port}/health`);
60
- if (response.ok)
61
- return;
62
- }
63
- catch (error) {
64
- lastError = error;
65
- }
66
- await new Promise(resolve => setTimeout(resolve, 100));
67
- }
68
- throw new Error(`server did not become healthy: ${String(lastError)}`);
69
- }
70
- afterEach(() => {
71
- for (const child of running) {
72
- if (!child.killed)
73
- child.kill("SIGTERM");
74
- }
75
- running.clear();
76
- });
77
- describe("SSE remote auth guard", () => {
78
- test("refuses unauthenticated SSE", async () => {
79
- const port = await findAvailablePort(4400);
80
- const child = startSseServer({}, port);
81
- const { code, output } = await waitForExit(child);
82
- assert.notEqual(code, 0);
83
- assert.match(output, new RegExp(ERROR_MESSAGE.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")));
84
- });
85
- test("requires bearer auth on SSE endpoints when SSE_AUTH_TOKEN is configured", async () => {
86
- const port = await findAvailablePort(4410);
87
- startSseServer({ SSE_AUTH_TOKEN: "mcp_sse_secret" }, port);
88
- await waitForHealth(port);
89
- const sseResponse = await fetch(`http://${LOOPBACK}:${port}/sse`);
90
- assert.equal(sseResponse.status, 401);
91
- const unauthenticatedMessage = await fetch(`http://${LOOPBACK}:${port}/messages?sessionId=missing`, { method: "POST" });
92
- assert.equal(unauthenticatedMessage.status, 401);
93
- const authenticatedMessage = await fetch(`http://${LOOPBACK}:${port}/messages?sessionId=missing`, { method: "POST", headers: { Authorization: "Bearer mcp_sse_secret" } });
94
- assert.equal(authenticatedMessage.status, 400);
95
- });
96
- });
@@ -1,273 +0,0 @@
1
- import assert from "node:assert/strict";
2
- import { spawn } from "node:child_process";
3
- import http from "node:http";
4
- import { afterEach, describe, test } from "node:test";
5
- import * as path from "node:path";
6
- import { findAvailablePort } from "./utils/server-launcher.js";
7
- const LOOPBACK = "127.0.0.1";
8
- const SSE_TOKEN = "mcp_sse_secret";
9
- const SERVER_PATH = path.resolve(process.cwd(), "build/index.js");
10
- // Keeps connection churn from tripping the per-IP creation limit in tests that
11
- // are not about rate limiting.
12
- const UNTHROTTLED = "1000";
13
- const running = new Set();
14
- function startSseServer(env, port) {
15
- const child = spawn("node", [SERVER_PATH], {
16
- env: {
17
- ...process.env,
18
- GITLAB_API_URL: "https://gitlab.example.com/api/v4",
19
- HOST: "0.0.0.0",
20
- PORT: String(port),
21
- SSE: "true",
22
- STREAMABLE_HTTP: "false",
23
- REMOTE_AUTHORIZATION: "false",
24
- GITLAB_MCP_OAUTH: "false",
25
- GITLAB_USE_OAUTH: "false",
26
- GITLAB_PERSONAL_ACCESS_TOKEN: "glpat_test",
27
- GITLAB_JOB_TOKEN: "",
28
- GITLAB_AUTH_COOKIE_PATH: "",
29
- SSE_AUTH_TOKEN: SSE_TOKEN,
30
- ...env,
31
- },
32
- stdio: ["ignore", "pipe", "pipe"],
33
- });
34
- running.add(child);
35
- child.once("exit", () => running.delete(child));
36
- return child;
37
- }
38
- async function waitForHealth(port, timeoutMs = 10000) {
39
- const deadline = Date.now() + timeoutMs;
40
- let lastError;
41
- while (Date.now() < deadline) {
42
- try {
43
- const response = await fetch(`http://${LOOPBACK}:${port}/health`);
44
- if (response.ok)
45
- return;
46
- }
47
- catch (error) {
48
- lastError = error;
49
- }
50
- await new Promise(resolve => setTimeout(resolve, 100));
51
- }
52
- throw new Error(`server did not become healthy: ${String(lastError)}`);
53
- }
54
- function openSseConnection(port) {
55
- let statusCode;
56
- let text = "";
57
- let resolveEnded = () => { };
58
- const ended = new Promise(resolve => {
59
- resolveEnded = resolve;
60
- });
61
- const request = http.get({
62
- host: LOOPBACK,
63
- port,
64
- path: "/sse",
65
- headers: { Authorization: `Bearer ${SSE_TOKEN}`, Accept: "text/event-stream" },
66
- }, response => {
67
- statusCode = response.statusCode;
68
- response.on("data", chunk => {
69
- text += chunk.toString();
70
- });
71
- response.on("end", () => resolveEnded());
72
- response.on("close", () => resolveEnded());
73
- });
74
- request.on("error", () => resolveEnded());
75
- return {
76
- get statusCode() {
77
- return statusCode;
78
- },
79
- streamText: () => text,
80
- close: () => {
81
- request.destroy();
82
- resolveEnded();
83
- },
84
- ended,
85
- };
86
- }
87
- async function waitFor(predicate, timeoutMs = 5000, stepMs = 50) {
88
- const deadline = Date.now() + timeoutMs;
89
- while (Date.now() < deadline) {
90
- if (predicate())
91
- return true;
92
- await new Promise(resolve => setTimeout(resolve, stepMs));
93
- }
94
- return predicate();
95
- }
96
- /** Resolves true when the server ends the stream within the window. */
97
- async function endedWithin(connection, ms) {
98
- return Promise.race([
99
- connection.ended.then(() => true),
100
- new Promise(resolve => setTimeout(() => resolve(false), ms)),
101
- ]);
102
- }
103
- /** Reads the session id the transport advertises in its opening `endpoint` event. */
104
- async function readSessionId(connection, timeoutMs = 5000) {
105
- const deadline = Date.now() + timeoutMs;
106
- while (Date.now() < deadline) {
107
- const match = /data: \/messages\?sessionId=([^\s]+)/.exec(connection.streamText());
108
- if (match)
109
- return match[1];
110
- await new Promise(resolve => setTimeout(resolve, 25));
111
- }
112
- throw new Error(`SSE stream did not advertise a session id: ${connection.streamText()}`);
113
- }
114
- async function postSseMessage(port, sessionId, body) {
115
- const response = await fetch(`http://${LOOPBACK}:${port}/messages?sessionId=${sessionId}`, {
116
- method: "POST",
117
- headers: { Authorization: `Bearer ${SSE_TOKEN}`, "Content-Type": "application/json" },
118
- body: JSON.stringify(body),
119
- });
120
- await response.arrayBuffer();
121
- return response.status;
122
- }
123
- async function getSseStatus(port) {
124
- const response = await fetch(`http://${LOOPBACK}:${port}/sse`, {
125
- headers: { Authorization: `Bearer ${SSE_TOKEN}`, Accept: "text/event-stream" },
126
- });
127
- await response.arrayBuffer();
128
- return response.status;
129
- }
130
- /**
131
- * Connection attempts are rate-limited per IP, so a capacity slot released
132
- * asynchronously has to be polled for instead of raced with a single request.
133
- */
134
- async function waitForAcceptedConnection(port, timeoutMs = 5000) {
135
- const deadline = Date.now() + timeoutMs;
136
- let connection = openSseConnection(port);
137
- for (;;) {
138
- await waitFor(() => connection.statusCode !== undefined, 2000, 25);
139
- if (connection.statusCode === 200)
140
- return connection;
141
- connection.close();
142
- if (Date.now() >= deadline)
143
- return connection;
144
- await new Promise(resolve => setTimeout(resolve, 100));
145
- connection = openSseConnection(port);
146
- }
147
- }
148
- afterEach(() => {
149
- for (const child of running) {
150
- if (!child.killed)
151
- child.kill("SIGTERM");
152
- }
153
- running.clear();
154
- });
155
- describe("SSE session limits", { concurrency: 1 }, () => {
156
- test("rejects new SSE connections once MAX_SESSIONS is reached", async () => {
157
- const port = await findAvailablePort(4500);
158
- startSseServer({ MAX_SESSIONS: "2", MAX_REQUESTS_PER_MINUTE: UNTHROTTLED }, port);
159
- await waitForHealth(port);
160
- const first = openSseConnection(port);
161
- const second = openSseConnection(port);
162
- const bothConnected = await waitFor(() => first.statusCode === 200 && second.statusCode === 200, 5000);
163
- assert.ok(bothConnected, "expected the first two SSE connections to be accepted");
164
- const rejected = await fetch(`http://${LOOPBACK}:${port}/sse`, {
165
- headers: { Authorization: `Bearer ${SSE_TOKEN}`, Accept: "text/event-stream" },
166
- });
167
- assert.equal(rejected.status, 503);
168
- const body = (await rejected.json());
169
- assert.match(body.error ?? "", /capacity/i);
170
- first.close();
171
- second.close();
172
- });
173
- test("frees the capacity slot when a client closes the stream", async () => {
174
- const port = await findAvailablePort(4510);
175
- startSseServer({ MAX_SESSIONS: "2", MAX_REQUESTS_PER_MINUTE: UNTHROTTLED }, port);
176
- await waitForHealth(port);
177
- const first = openSseConnection(port);
178
- const second = openSseConnection(port);
179
- assert.ok(await waitFor(() => first.statusCode === 200 && second.statusCode === 200, 5000), "expected the first two SSE connections to be accepted");
180
- assert.equal(await getSseStatus(port), 503, "expected the server to be at capacity");
181
- first.close();
182
- // SESSION_TIMEOUT_SECONDS is left at its 3600s default, so the slot can
183
- // only come back through the response "close" handler - not the idle sweep.
184
- const reclaimed = await waitForAcceptedConnection(port);
185
- assert.equal(reclaimed.statusCode, 200, "closing a client connection should free its capacity slot");
186
- reclaimed.close();
187
- second.close();
188
- });
189
- test("rate-limits SSE connection creation per client IP", async () => {
190
- const port = await findAvailablePort(4520);
191
- startSseServer({ MAX_REQUESTS_PER_MINUTE: "2" }, port);
192
- await waitForHealth(port);
193
- const first = openSseConnection(port);
194
- const second = openSseConnection(port);
195
- assert.ok(await waitFor(() => first.statusCode === 200 && second.statusCode === 200, 5000), "expected the first two SSE connections to be accepted");
196
- const rejected = await fetch(`http://${LOOPBACK}:${port}/sse`, {
197
- headers: { Authorization: `Bearer ${SSE_TOKEN}`, Accept: "text/event-stream" },
198
- });
199
- assert.equal(rejected.status, 429);
200
- const body = (await rejected.json());
201
- assert.equal(body.error, "Rate limit exceeded");
202
- assert.match(body.message ?? "", /per minute/i);
203
- first.close();
204
- second.close();
205
- });
206
- test("closes SSE sessions that stay idle", async () => {
207
- const port = await findAvailablePort(4530);
208
- startSseServer({ SESSION_TIMEOUT_SECONDS: "2" }, port);
209
- await waitForHealth(port);
210
- const connection = openSseConnection(port);
211
- assert.ok(await waitFor(() => connection.statusCode === 200, 5000), "expected the SSE connection to be accepted");
212
- const closedByIdleTimeout = await Promise.race([
213
- connection.ended.then(() => true),
214
- new Promise(resolve => setTimeout(() => resolve(false), 12000)),
215
- ]);
216
- assert.equal(closedByIdleTimeout, true, "idle SSE session should be closed by the server");
217
- connection.close();
218
- });
219
- test("POST /messages keeps an SSE session alive past the idle timeout", async () => {
220
- const port = await findAvailablePort(4540);
221
- startSseServer({ SESSION_TIMEOUT_SECONDS: "2" }, port);
222
- await waitForHealth(port);
223
- const connection = openSseConnection(port);
224
- assert.ok(await waitFor(() => connection.statusCode === 200, 5000), "expected the SSE connection to be accepted");
225
- const sessionId = await readSessionId(connection);
226
- // Ping across several idle windows; every POST /messages must reset activity.
227
- const pingStatuses = [];
228
- const keepAlive = setInterval(() => {
229
- void postSseMessage(port, sessionId, { jsonrpc: "2.0", id: 1, method: "ping" })
230
- .then(status => pingStatuses.push(status))
231
- .catch(() => undefined);
232
- }, 400);
233
- try {
234
- await new Promise(resolve => setTimeout(resolve, 6000));
235
- }
236
- finally {
237
- clearInterval(keepAlive);
238
- }
239
- assert.ok(pingStatuses.length >= 8, `expected keep-alive pings to be sent, saw ${pingStatuses.length}`);
240
- assert.ok(pingStatuses.every(status => status === 202), `expected every ping to be accepted, saw ${JSON.stringify(pingStatuses)}`);
241
- assert.match(connection.streamText(), /"result"/, "expected a ping response on the stream");
242
- assert.equal(await endedWithin(connection, 300), false, "POST /messages activity should keep the SSE session open");
243
- assert.equal(await endedWithin(connection, 8000), true, "the session should close once POST /messages activity stops");
244
- connection.close();
245
- });
246
- test("treats inherited object keys as unknown SSE sessions", async () => {
247
- const port = await findAvailablePort(4560);
248
- startSseServer({}, port);
249
- await waitForHealth(port);
250
- const response = await fetch(`http://${LOOPBACK}:${port}/messages?sessionId=constructor`, {
251
- method: "POST",
252
- headers: { Authorization: `Bearer ${SSE_TOKEN}`, "Content-Type": "application/json" },
253
- body: JSON.stringify({ jsonrpc: "2.0", id: 1, method: "ping" }),
254
- signal: AbortSignal.timeout(3000),
255
- });
256
- assert.equal(response.status, 400);
257
- assert.match(await response.text(), /No transport found/);
258
- });
259
- test("reports degraded health while SSE capacity is exhausted", async () => {
260
- const port = await findAvailablePort(4550);
261
- startSseServer({ MAX_SESSIONS: "1" }, port);
262
- await waitForHealth(port);
263
- const connection = openSseConnection(port);
264
- assert.ok(await waitFor(() => connection.statusCode === 200, 5000), "expected the SSE connection to be accepted");
265
- const degraded = await fetch(`http://${LOOPBACK}:${port}/health`);
266
- const body = (await degraded.json());
267
- assert.equal(degraded.status, 503);
268
- assert.equal(body.status, "degraded");
269
- assert.equal(body.activeSessions, 1);
270
- assert.equal(body.maxSessions, 1);
271
- connection.close();
272
- });
273
- });