@launchdarkly/mcp-server 0.6.2 → 0.7.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 (52) hide show
  1. package/README.md +26 -22
  2. package/bin/mcp-server.js +1045 -168
  3. package/bin/mcp-server.js.map +27 -22
  4. package/dist/commonjs/lib/config.d.ts +2 -2
  5. package/dist/commonjs/lib/config.js +2 -2
  6. package/dist/commonjs/mcp-server/cli/start/command.d.ts.map +1 -1
  7. package/dist/commonjs/mcp-server/cli/start/command.js +12 -0
  8. package/dist/commonjs/mcp-server/cli/start/command.js.map +1 -1
  9. package/dist/commonjs/mcp-server/cli/start/impl.d.ts +2 -0
  10. package/dist/commonjs/mcp-server/cli/start/impl.d.ts.map +1 -1
  11. package/dist/commonjs/mcp-server/cli/start/impl.js +67 -20
  12. package/dist/commonjs/mcp-server/cli/start/impl.js.map +1 -1
  13. package/dist/commonjs/mcp-server/cli/start/sse-security.d.ts +5 -0
  14. package/dist/commonjs/mcp-server/cli/start/sse-security.d.ts.map +1 -0
  15. package/dist/commonjs/mcp-server/cli/start/sse-security.js +26 -0
  16. package/dist/commonjs/mcp-server/cli/start/sse-security.js.map +1 -0
  17. package/dist/commonjs/mcp-server/cli/start/tls-blocklist.d.ts +48 -0
  18. package/dist/commonjs/mcp-server/cli/start/tls-blocklist.d.ts.map +1 -0
  19. package/dist/commonjs/mcp-server/cli/start/tls-blocklist.js +206 -0
  20. package/dist/commonjs/mcp-server/cli/start/tls-blocklist.js.map +1 -0
  21. package/dist/commonjs/mcp-server/mcp-server.js +1 -1
  22. package/dist/commonjs/mcp-server/server.js +1 -1
  23. package/dist/esm/lib/config.d.ts +2 -2
  24. package/dist/esm/lib/config.js +2 -2
  25. package/dist/esm/mcp-server/cli/start/command.d.ts.map +1 -1
  26. package/dist/esm/mcp-server/cli/start/command.js +12 -0
  27. package/dist/esm/mcp-server/cli/start/command.js.map +1 -1
  28. package/dist/esm/mcp-server/cli/start/impl.d.ts +2 -0
  29. package/dist/esm/mcp-server/cli/start/impl.d.ts.map +1 -1
  30. package/dist/esm/mcp-server/cli/start/impl.js +67 -20
  31. package/dist/esm/mcp-server/cli/start/impl.js.map +1 -1
  32. package/dist/esm/mcp-server/cli/start/sse-security.d.ts +5 -0
  33. package/dist/esm/mcp-server/cli/start/sse-security.d.ts.map +1 -0
  34. package/dist/esm/mcp-server/cli/start/sse-security.js +21 -0
  35. package/dist/esm/mcp-server/cli/start/sse-security.js.map +1 -0
  36. package/dist/esm/mcp-server/cli/start/tls-blocklist.d.ts +48 -0
  37. package/dist/esm/mcp-server/cli/start/tls-blocklist.d.ts.map +1 -0
  38. package/dist/esm/mcp-server/cli/start/tls-blocklist.js +192 -0
  39. package/dist/esm/mcp-server/cli/start/tls-blocklist.js.map +1 -0
  40. package/dist/esm/mcp-server/mcp-server.js +1 -1
  41. package/dist/esm/mcp-server/server.js +1 -1
  42. package/jsr.json +1 -1
  43. package/package.json +3 -1
  44. package/src/lib/config.ts +2 -2
  45. package/src/mcp-server/cli/start/command.ts +14 -0
  46. package/src/mcp-server/cli/start/impl.ts +80 -20
  47. package/src/mcp-server/cli/start/sse-security.ts +31 -0
  48. package/src/mcp-server/cli/start/tls-blocklist.ts +252 -0
  49. package/src/mcp-server/mcp-server.ts +1 -1
  50. package/src/mcp-server/server.ts +1 -1
  51. package/test/sse-security.test.mjs +84 -0
  52. package/test/tls-blocklist.test.mjs +314 -0
@@ -4,6 +4,7 @@
4
4
 
5
5
  import { SSEServerTransport } from "@modelcontextprotocol/sdk/server/sse.js";
6
6
  import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
7
+ import { localhostHostValidation } from "@modelcontextprotocol/sdk/server/middleware/hostHeaderValidation.js";
7
8
  import express from "express";
8
9
  import { SDKOptions } from "../../../lib/config.js";
9
10
  import { LocalContext } from "../../cli.js";
@@ -13,10 +14,21 @@ import {
13
14
  } from "../../console-logger.js";
14
15
  import { MCPScope } from "../../scopes.js";
15
16
  import { createMCPServer } from "../../server.js";
17
+ import {
18
+ assertSafeSSEBind,
19
+ isLoopbackHost,
20
+ requireBearerToken,
21
+ } from "./sse-security.js";
22
+ import {
23
+ installTlsBlocklist,
24
+ unpatchedRuntimeWarning,
25
+ } from "./tls-blocklist.js";
16
26
 
17
27
  interface StartCommandFlags {
18
28
  readonly transport: "stdio" | "sse";
19
29
  readonly port: number;
30
+ readonly host: string;
31
+ readonly "auth-token"?: string | undefined;
20
32
  readonly tool?: string[];
21
33
  readonly scope?: MCPScope[];
22
34
  readonly "api-key"?: string | undefined;
@@ -27,6 +39,13 @@ interface StartCommandFlags {
27
39
  }
28
40
 
29
41
  export async function main(this: LocalContext, flags: StartCommandFlags) {
42
+ // INC-289: block the compromised eMudhra intermediates before any request.
43
+ installTlsBlocklist();
44
+ const runtimeWarning = unpatchedRuntimeWarning();
45
+ if (runtimeWarning) {
46
+ process.stderr.write(runtimeWarning);
47
+ }
48
+
30
49
  flags.env?.forEach(([key, value]) => {
31
50
  process.env[key] = value;
32
51
  });
@@ -66,37 +85,78 @@ async function startStdio(flags: StartCommandFlags) {
66
85
 
67
86
  async function startSSE(flags: StartCommandFlags) {
68
87
  const logger = createConsoleLogger(flags["log-level"]);
88
+ const host = flags.host;
89
+ const authToken = flags["auth-token"];
90
+ assertSafeSSEBind(host, authToken);
91
+
69
92
  const app = express();
70
- const mcpServer = createMCPServer({
71
- logger,
72
- allowedTools: flags.tool,
73
- scopes: flags.scope,
74
- ...{ apiKey: flags["api-key"] ?? "" },
75
- serverURL: flags["server-url"],
76
- serverIdx: flags["server-index"],
77
- });
78
- let transport: SSEServerTransport | undefined;
93
+ if (isLoopbackHost(host)) {
94
+ app.use(localhostHostValidation());
95
+ }
96
+ if (authToken) {
97
+ app.use(requireBearerToken(authToken));
98
+ }
99
+
100
+ const sessions = new Map<
101
+ string,
102
+ { transport: SSEServerTransport; server: ReturnType<typeof createMCPServer> }
103
+ >();
79
104
  const controller = new AbortController();
80
105
 
81
106
  app.get("/sse", async (_req, res) => {
82
- transport = new SSEServerTransport("/message", res);
107
+ const server = createMCPServer({
108
+ logger,
109
+ allowedTools: flags.tool,
110
+ scopes: flags.scope,
111
+ ...{ apiKey: flags["api-key"] ?? "" },
112
+ serverURL: flags["server-url"],
113
+ serverIdx: flags["server-index"],
114
+ });
115
+ const transport = new SSEServerTransport("/message", res);
116
+ sessions.set(transport.sessionId, { transport, server });
83
117
 
84
- await mcpServer.connect(transport);
118
+ res.on("close", () => {
119
+ sessions.delete(transport.sessionId);
120
+ void server.close();
121
+ });
85
122
 
86
- mcpServer.server.onclose = async () => {
87
- res.end();
88
- };
123
+ try {
124
+ await server.connect(transport);
125
+ } catch (err) {
126
+ logger.error("Failed to open SSE session", {
127
+ error: err instanceof Error ? err.message : String(err),
128
+ });
129
+ sessions.delete(transport.sessionId);
130
+ void server.close();
131
+ if (!res.headersSent) {
132
+ res.status(500).send("Internal Server Error");
133
+ }
134
+ }
89
135
  });
90
136
 
91
137
  app.post("/message", async (req, res) => {
92
- if (!transport) {
93
- throw new Error("Server transport not initialized");
138
+ const sessionId = typeof req.query["sessionId"] === "string"
139
+ ? req.query["sessionId"]
140
+ : "";
141
+ const session = sessions.get(sessionId);
142
+ if (!session) {
143
+ res.status(404).send("Unknown session");
144
+ return;
94
145
  }
95
146
 
96
- await transport.handlePostMessage(req, res);
147
+ try {
148
+ await session.transport.handlePostMessage(req, res);
149
+ } catch (err) {
150
+ logger.error("Failed to handle SSE message", {
151
+ error: err instanceof Error ? err.message : String(err),
152
+ });
153
+ if (!res.headersSent) {
154
+ res.status(500).send("Internal Server Error");
155
+ }
156
+ }
97
157
  });
98
158
 
99
- const httpServer = app.listen(flags.port, "0.0.0.0", () => {
159
+ const httpServer = app.listen(flags.port, host, () => {
100
160
  const ha = httpServer.address();
101
161
  const host = typeof ha === "string" ? ha : `${ha?.address}:${ha?.port}`;
102
162
  logger.info("MCP HTTP server started", { host });
@@ -110,9 +170,9 @@ async function startSSE(flags: StartCommandFlags) {
110
170
  }
111
171
  closing = true;
112
172
 
113
- logger.info("Shutting down MCP server");
173
+ logger.info("Shutting down MCP servers");
114
174
 
115
- await mcpServer.close();
175
+ await Promise.all([...sessions.values()].map(({ server }) => server.close()));
116
176
 
117
177
  logger.info("Shutting down HTTP server");
118
178
 
@@ -0,0 +1,31 @@
1
+ import type { RequestHandler } from "express";
2
+ import { timingSafeEqual } from "node:crypto";
3
+
4
+ export function isLoopbackHost(host: string): boolean {
5
+ return host === "127.0.0.1" || host === "localhost" || host === "::1";
6
+ }
7
+
8
+ export function assertSafeSSEBind(
9
+ host: string,
10
+ authToken: string | undefined,
11
+ ): void {
12
+ if (!authToken && !isLoopbackHost(host)) {
13
+ throw new Error(
14
+ `--auth-token is required when the SSE transport listens on a non-loopback host (${host})`,
15
+ );
16
+ }
17
+ }
18
+
19
+ export function requireBearerToken(token: string): RequestHandler {
20
+ const expected = Buffer.from(`Bearer ${token}`);
21
+ return (req, res, next) => {
22
+ const actual = Buffer.from(req.headers.authorization ?? "");
23
+ if (
24
+ actual.length !== expected.length || !timingSafeEqual(actual, expected)
25
+ ) {
26
+ res.status(401).send("Unauthorized");
27
+ return;
28
+ }
29
+ next();
30
+ };
31
+ }
@@ -0,0 +1,252 @@
1
+ import { createHash, X509Certificate } from "node:crypto";
2
+ import tls from "node:tls";
3
+
4
+ /*
5
+ * INC-289: rejects TLS chains that go through the compromised eMudhra
6
+ * intermediates (https://emudhra.we-have-a-problem.com/). Go 1.26.10, Node.js
7
+ * 22.23.4 / 24.22.1 / 26.12.1 and Bun (unreleased, oven-sh/bun#46300) block
8
+ * the same keys natively. This check covers runtimes that predate those fixes.
9
+ * It is installed only by the `mcp start` CLI, never for library consumers.
10
+ */
11
+
12
+ /**
13
+ * SHA-256 of the DER SubjectPublicKeyInfo of each compromised intermediate.
14
+ * Identical to Node.js's kBlockedSPKIs (nodejs/node#66871) and Go's fix
15
+ * (CVE-2026-111943). Each key was issued twice, under emSign Root TLS/CS CA -
16
+ * G3 and under Sectigo's AAA Certificate Services, so hashing the key rather
17
+ * than the certificate covers both.
18
+ */
19
+ export const BLOCKED_SPKI_SHA256: ReadonlySet<string> = new Set([
20
+ "43bffa19d6ef651451f6841e019931e96f6f2eaeff28ab4b6f1ce4576de2717b",
21
+ "49dd353dc2b919a3770645117d0e60c16115e7d1bc259eefe734b00ea434fe5f",
22
+ "5c0660a2b164910d8ff589c18e14552e9e0ec237dcefe2cb736d41a4811f81a0",
23
+ "63ecefee431d49523bc1136c4e72d0206a477086caf606cd5cf025686c109cf8",
24
+ "92c063d67e8f14db71d288e11266ffdaf69cbf115f7bab14f3bc2f68d25e0e30",
25
+ "e0254c7fcdc265e2f0f8a428dabb75ab4ae039b4872d62f5ee57f0877d5a8a41",
26
+ "ebed6475c2c2d80fcb199f3fe8dd6e6b3ce60b77eb15d4e42c3dec0c6f5b5105",
27
+ "ec4ffa1ad0ac88081314b7aaffef6a91f97cd57291bb5ba686c5415f5eb4f6b6",
28
+ ]);
29
+
30
+ /**
31
+ * Common names of the compromised intermediates. Every one of them has
32
+ * pathlen:0, so any leaf signed with one of their keys must name the
33
+ * intermediate as its issuer. Bun's fetch only exposes the leaf to
34
+ * checkServerIdentity, so the issuer name is what blocks these chains there.
35
+ */
36
+ const BLOCKED_ISSUER_CN = /^em (dv|ov|ev) (tls|cs) ca - g3[bc]$/;
37
+
38
+ /**
39
+ * Node.js releases that block these keys natively, by major version. Lines
40
+ * newer than the highest entry are treated as patched; any other line is
41
+ * treated as unpatched.
42
+ */
43
+ const FIXED_NODE_VERSIONS: Readonly<
44
+ Record<number, readonly [number, number, number]>
45
+ > = {
46
+ 22: [22, 23, 4],
47
+ 24: [24, 22, 1],
48
+ 26: [26, 12, 1],
49
+ };
50
+
51
+ /**
52
+ * First Bun release that blocks these keys natively. Set this once one ships
53
+ * (the fix is oven-sh/bun#46300). While it is undefined, every Bun version
54
+ * gets the warning.
55
+ */
56
+ const FIXED_BUN_VERSION: string | undefined = undefined;
57
+
58
+ export const BLOCKED_CERT_ERROR_CODE = "ERR_TLS_CERT_BLOCKED";
59
+
60
+ /** The subset of tls.PeerCertificate this check reads. */
61
+ export interface PeerCertificateLike {
62
+ raw?: Uint8Array | undefined;
63
+ fingerprint256?: string | undefined;
64
+ issuer?: { CN?: string | string[] | undefined } | undefined;
65
+ issuerCertificate?: PeerCertificateLike | undefined;
66
+ }
67
+
68
+ type CheckServerIdentity = (
69
+ hostname: string,
70
+ cert: tls.PeerCertificate,
71
+ ) => Error | undefined;
72
+
73
+ // Captured before installTlsBlocklist() replaces tls.checkServerIdentity.
74
+ const defaultCheckServerIdentity: CheckServerIdentity = tls.checkServerIdentity;
75
+
76
+ function normalizeName(value: string): string {
77
+ return value.normalize("NFKC").toLowerCase().replace(/\s+/g, " ").trim();
78
+ }
79
+
80
+ export function isBlockedIssuerName(
81
+ cn: string | string[] | undefined,
82
+ ): boolean {
83
+ const names = Array.isArray(cn) ? cn : cn === undefined ? [] : [cn];
84
+ return names.some((name) => BLOCKED_ISSUER_CN.test(normalizeName(name)));
85
+ }
86
+
87
+ export function spkiSha256(raw: Uint8Array): string {
88
+ const spki = new X509Certificate(raw).publicKey.export({
89
+ type: "spki",
90
+ format: "der",
91
+ });
92
+ return createHash("sha256").update(spki).digest("hex");
93
+ }
94
+
95
+ /**
96
+ * Walks the peer chain (the full chain on Node.js, the leaf only on Bun) and
97
+ * returns a description of the first blocked certificate, if any.
98
+ */
99
+ export function findBlockedCertificate(
100
+ cert: PeerCertificateLike,
101
+ ): string | undefined {
102
+ const seen = new Set<PeerCertificateLike>();
103
+ for (
104
+ let current: PeerCertificateLike | undefined = cert;
105
+ current && !seen.has(current);
106
+ current = current.issuerCertificate
107
+ ) {
108
+ seen.add(current);
109
+ if (isBlockedIssuerName(current.issuer?.CN)) {
110
+ return `certificate issued by "${String(current.issuer?.CN)}"`;
111
+ }
112
+ if (current.raw && current.raw.length > 0) {
113
+ const hash = spkiSha256(current.raw);
114
+ if (BLOCKED_SPKI_SHA256.has(hash)) {
115
+ return `certificate with blocked public key sha256/${hash}`;
116
+ }
117
+ }
118
+ }
119
+ return undefined;
120
+ }
121
+
122
+ /**
123
+ * A tls checkServerIdentity replacement: rejects blocked chains, then runs
124
+ * the runtime's normal hostname verification.
125
+ */
126
+ export function checkServerIdentity(
127
+ hostname: string,
128
+ cert: PeerCertificateLike,
129
+ ): Error | undefined {
130
+ let blocked: string | undefined;
131
+ try {
132
+ blocked = findBlockedCertificate(cert);
133
+ } catch (err) {
134
+ blocked = `certificate that could not be parsed (${String(err)})`;
135
+ }
136
+ if (blocked) {
137
+ return Object.assign(
138
+ new Error(
139
+ `Refusing TLS connection to ${hostname}: the chain contains a ${blocked}, ` +
140
+ "which belongs to a compromised eMudhra intermediate CA.",
141
+ ),
142
+ { code: BLOCKED_CERT_ERROR_CODE },
143
+ );
144
+ }
145
+ return defaultCheckServerIdentity(
146
+ hostname,
147
+ cert as unknown as tls.PeerCertificate,
148
+ );
149
+ }
150
+
151
+ let installed = false;
152
+
153
+ /**
154
+ * Installs the blocklist for this process. On Node.js, global fetch (undici)
155
+ * and node:https read tls.checkServerIdentity when they connect. Bun's fetch
156
+ * ignores it, so on Bun global fetch is wrapped to pass the check through
157
+ * Bun's `tls` fetch option.
158
+ */
159
+ export function installTlsBlocklist(): void {
160
+ if (installed) return;
161
+ installed = true;
162
+
163
+ if (isBun()) {
164
+ const originalFetch = globalThis.fetch;
165
+ const wrapped = (
166
+ input: Parameters<typeof fetch>[0],
167
+ init?: Parameters<typeof fetch>[1],
168
+ ): ReturnType<typeof fetch> => {
169
+ const tlsOptions = (
170
+ init as
171
+ { tls?: { checkServerIdentity?: CheckServerIdentity } } | undefined
172
+ )?.tls;
173
+ const callerCheck = tlsOptions?.checkServerIdentity;
174
+ const combined: CheckServerIdentity = callerCheck
175
+ ? (hostname, cert) =>
176
+ checkServerIdentity(hostname, cert) ?? callerCheck(hostname, cert)
177
+ : (checkServerIdentity as unknown as CheckServerIdentity);
178
+ return originalFetch(input, {
179
+ ...init,
180
+ tls: { ...tlsOptions, checkServerIdentity: combined },
181
+ } as RequestInit);
182
+ };
183
+ globalThis.fetch = Object.assign(wrapped, originalFetch);
184
+ } else {
185
+ tls.checkServerIdentity =
186
+ checkServerIdentity as unknown as CheckServerIdentity;
187
+ }
188
+ }
189
+
190
+ function isBun(): boolean {
191
+ return typeof (globalThis as { Bun?: unknown }).Bun !== "undefined";
192
+ }
193
+
194
+ function parseVersion(version: string): [number, number, number] | undefined {
195
+ const match = /^v?(\d+)\.(\d+)\.(\d+)/.exec(version);
196
+ if (!match) return undefined;
197
+ return [Number(match[1]), Number(match[2]), Number(match[3])];
198
+ }
199
+
200
+ function compareVersions(
201
+ a: readonly [number, number, number],
202
+ b: readonly [number, number, number],
203
+ ): number {
204
+ return a[0] - b[0] || a[1] - b[1] || a[2] - b[2];
205
+ }
206
+
207
+ export function isNodeVersionPatched(version: string): boolean {
208
+ const parsed = parseVersion(version);
209
+ if (!parsed) return false;
210
+ const fixed = FIXED_NODE_VERSIONS[parsed[0]];
211
+ if (fixed) return compareVersions(parsed, fixed) >= 0;
212
+ const newestLine = Math.max(...Object.keys(FIXED_NODE_VERSIONS).map(Number));
213
+ return parsed[0] > newestLine;
214
+ }
215
+
216
+ export function isBunVersionPatched(version: string): boolean {
217
+ if (FIXED_BUN_VERSION === undefined) return false;
218
+ const parsed = parseVersion(version);
219
+ const fixed = parseVersion(FIXED_BUN_VERSION);
220
+ return !!parsed && !!fixed && compareVersions(parsed, fixed) >= 0;
221
+ }
222
+
223
+ /**
224
+ * Returns a warning when the current runtime does not block the compromised
225
+ * eMudhra intermediates natively, or undefined when it does.
226
+ */
227
+ export function unpatchedRuntimeWarning(
228
+ versions: {
229
+ node?: string | undefined;
230
+ bun?: string | undefined;
231
+ } = process.versions,
232
+ ): string | undefined {
233
+ let runtime: string;
234
+ let upgrade: string;
235
+ if (versions.bun !== undefined) {
236
+ if (isBunVersionPatched(versions.bun)) return undefined;
237
+ runtime = `Bun ${versions.bun}`;
238
+ upgrade =
239
+ "run the server with Node.js 22.23.4, 24.22.1, 26.12.1 or later, or use the Docker image";
240
+ } else if (versions.node !== undefined) {
241
+ if (isNodeVersionPatched(versions.node)) return undefined;
242
+ runtime = `Node.js ${versions.node}`;
243
+ upgrade = "upgrade to Node.js 22.23.4, 24.22.1, 26.12.1 or later";
244
+ } else {
245
+ return undefined;
246
+ }
247
+ return (
248
+ `WARNING: ${runtime} does not block the compromised eMudhra intermediate CAs. ` +
249
+ "The LaunchDarkly MCP server rejects them for its own requests, but the runtime does not; " +
250
+ `${upgrade}. See https://github.com/launchdarkly/mcp-server#runtime-requirements\n`
251
+ );
252
+ }
@@ -19,7 +19,7 @@ const routes = buildRouteMap({
19
19
  export const app = buildApplication(routes, {
20
20
  name: "mcp",
21
21
  versionInfo: {
22
- currentVersion: "0.6.2",
22
+ currentVersion: "0.7.1",
23
23
  },
24
24
  });
25
25
 
@@ -44,7 +44,7 @@ export function createMCPServer(deps: {
44
44
  }) {
45
45
  const server = new McpServer({
46
46
  name: "LaunchDarkly",
47
- version: "0.6.2",
47
+ version: "0.7.1",
48
48
  });
49
49
 
50
50
  const client = new LaunchDarklyCore({
@@ -0,0 +1,84 @@
1
+ import assert from "node:assert/strict";
2
+ import process from "node:process";
3
+ import { after, before, describe, test } from "node:test";
4
+ import express from "express";
5
+ import { main } from "../dist/esm/mcp-server/cli/start/impl.js";
6
+ import {
7
+ assertSafeSSEBind,
8
+ requireBearerToken,
9
+ } from "../dist/esm/mcp-server/cli/start/sse-security.js";
10
+
11
+ const TOKEN = "0123456789abcdef";
12
+
13
+ describe("assertSafeSSEBind", () => {
14
+ for (const host of ["0.0.0.0", "::", "192.168.1.10", "example.com"]) {
15
+ test(`refuses ${host} without a token`, () => {
16
+ assert.throws(
17
+ () => assertSafeSSEBind(host, undefined),
18
+ /--auth-token is required/,
19
+ );
20
+ });
21
+
22
+ test(`allows ${host} with a token`, () => {
23
+ assert.doesNotThrow(() => assertSafeSSEBind(host, TOKEN));
24
+ });
25
+ }
26
+
27
+ for (const host of ["127.0.0.1", "localhost", "::1"]) {
28
+ test(`allows loopback ${host} without a token`, () => {
29
+ assert.doesNotThrow(() => assertSafeSSEBind(host, undefined));
30
+ });
31
+ }
32
+ });
33
+
34
+ test("start --transport sse refuses a non-loopback host without a token", async () => {
35
+ await assert.rejects(
36
+ main.call({ process }, {
37
+ transport: "sse",
38
+ host: "0.0.0.0",
39
+ port: 0,
40
+ "log-level": "error",
41
+ }),
42
+ /--auth-token is required/,
43
+ );
44
+ });
45
+
46
+ describe("requireBearerToken", () => {
47
+ let server;
48
+ let url;
49
+
50
+ before(async () => {
51
+ const app = express();
52
+ app.use(requireBearerToken(TOKEN));
53
+ app.get("/", (_req, res) => res.send("ok"));
54
+ await new Promise((resolve) => {
55
+ server = app.listen(0, "127.0.0.1", resolve);
56
+ });
57
+ url = `http://127.0.0.1:${server.address().port}/`;
58
+ });
59
+
60
+ after(() => new Promise((resolve) => server.close(resolve)));
61
+
62
+ const cases = [
63
+ ["a missing header", undefined],
64
+ ["a wrong token of the same length", "Bearer fedcba9876543210"],
65
+ ["a token prefix", `Bearer ${TOKEN.slice(0, -1)}`],
66
+ ["the token without the Bearer scheme", TOKEN],
67
+ ];
68
+ for (const [name, header] of cases) {
69
+ test(`returns 401 for ${name}`, async () => {
70
+ const res = await fetch(url, {
71
+ headers: header === undefined ? {} : { Authorization: header },
72
+ });
73
+ assert.equal(res.status, 401);
74
+ });
75
+ }
76
+
77
+ test("passes the request through for the right token", async () => {
78
+ const res = await fetch(url, {
79
+ headers: { Authorization: `Bearer ${TOKEN}` },
80
+ });
81
+ assert.equal(res.status, 200);
82
+ assert.equal(await res.text(), "ok");
83
+ });
84
+ });