@lexapi/mcp 0.2.0 → 0.5.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.
@@ -1,165 +1,598 @@
1
+ import { timingSafeEqual } from 'node:crypto';
1
2
  import { createServer } from 'node:http';
2
- import { Server } from '@modelcontextprotocol/sdk/server/index.js';
3
3
  import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
4
- import { CallToolRequestSchema, ListToolsRequestSchema, } from '@modelcontextprotocol/sdk/types.js';
5
- import { LexAPIClient, LexAPIError } from './client.js';
6
- import { tools, toolsByName } from './tools.js';
4
+ import { WebStandardStreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/webStandardStreamableHttp.js';
5
+ import { isWellFormedKey, LexAPIClient } from './client.js';
6
+ import { classifyCredential, deriveClientAddress } from './credentials.js';
7
+ import { bearerChallenge, OAuthConfigError, oauthConfigFromEnv, protectedResourceMetadata } from './oauth/config.js';
8
+ import { EXCHANGE_DEADLINE_MS, TokenExchanger } from './oauth/exchange.js';
9
+ import { InvalidTokenError, JwksCache, JwksUnavailableError, verifyAccessToken } from './oauth/jwt.js';
10
+ import { redact } from './oauth/redact.js';
11
+ import { OAuthUpstreamAuth, ResponseGate } from './oauth/upstream.js';
12
+ import { clientFromEnv, createLexServer, PACKAGE_NAME, PROGRESS_INTERVAL_MS, readOnlyFromEnv } from './server.js';
13
+ import { selectTools } from './tools.js';
7
14
  import { PACKAGE_VERSION } from './version.js';
8
- const PACKAGE_NAME = 'lexapi-mcp';
9
15
  const MCP_PATH = '/v1';
10
- function extractBearer(req) {
11
- const header = req.headers['authorization'];
12
- if (!header || typeof header !== 'string')
13
- return null;
14
- const match = header.match(/^Bearer\s+(.+)$/i);
15
- return match ? match[1].trim() : null;
16
+ const MAX_BODY_BYTES = 1_000_000;
17
+ /**
18
+ * An oversized body is still read (and discarded) up to this much / this
19
+ * long, so the client finishes uploading and actually receives the 413 —
20
+ * closing the socket mid-upload makes clients report EPIPE / ECONNRESET.
21
+ */
22
+ const DRAIN_MAX_BYTES = 16_000_000;
23
+ const DRAIN_MAX_MS = 5000;
24
+ /**
25
+ * SSE keep-alive of the OAuth transport, pinned (the SDK default could
26
+ * change). Together with the first progress frame (PROGRESS_INTERVAL_MS) it
27
+ * commits the 200; a token exchange is bounded below both
28
+ * (EXCHANGE_DEADLINE_MS), so its refusal is still answered as an HTTP status.
29
+ */
30
+ export const SSE_KEEP_ALIVE_MS = 15_000;
31
+ if (EXCHANGE_DEADLINE_MS >= Math.min(SSE_KEEP_ALIVE_MS, PROGRESS_INTERVAL_MS)) {
32
+ throw new Error('EXCHANGE_DEADLINE_MS must stay below the first frame that commits a response');
16
33
  }
17
- async function readJsonBody(req) {
18
- const chunks = [];
19
- for await (const chunk of req) {
20
- chunks.push(chunk);
21
- // 1 MB request-body cap — MCP JSON-RPC messages are tiny; anything larger is abuse.
22
- if (chunks.reduce((n, c) => n + c.length, 0) > 1_000_000) {
23
- throw new Error('request body too large');
24
- }
34
+ export { classifyCredential, extractApiKey } from './credentials.js';
35
+ /**
36
+ * Origin validation (MCP Streamable HTTP: servers MUST validate Origin, a
37
+ * DNS-rebinding defence). Requests without an Origin header — every
38
+ * non-browser MCP client — are allowed. A browser request is allowed only
39
+ * when its Origin is listed in LEXAPI_MCP_ALLOWED_ORIGINS (comma-separated;
40
+ * "*" allows any). Auth is a bearer key with no ambient credentials, so this
41
+ * is defence in depth, not the access control.
42
+ */
43
+ export function originAllowed(origin, env = process.env) {
44
+ if (!origin)
45
+ return true;
46
+ const list = (env.LEXAPI_MCP_ALLOWED_ORIGINS ?? '').split(',').map((s) => s.trim()).filter(Boolean);
47
+ return list.includes('*') || list.includes(origin);
48
+ }
49
+ class BodyTooLargeError extends Error {
50
+ drained;
51
+ constructor(drained) {
52
+ super('request body too large');
53
+ this.drained = drained;
25
54
  }
26
- const text = Buffer.concat(chunks).toString('utf8');
27
- if (!text)
28
- return undefined;
29
- return JSON.parse(text);
30
55
  }
31
- function buildMcpServer(apiKey) {
32
- const baseUrl = process.env.LEXAPI_BASE_URL;
33
- const client = new LexAPIClient({
34
- apiKey,
35
- ...(baseUrl ? { baseUrl } : {}),
56
+ /** Discard the rest of an oversized body; resolves true if it ended within the caps. */
57
+ function drain(req, alreadyRead) {
58
+ return new Promise((resolve) => {
59
+ if (req.readableEnded)
60
+ return resolve(true);
61
+ let seen = alreadyRead;
62
+ const done = (ok) => {
63
+ clearTimeout(timer);
64
+ req.removeListener('data', onData);
65
+ req.removeListener('end', onEnd);
66
+ req.removeListener('error', onEnd);
67
+ resolve(ok);
68
+ };
69
+ const onData = (chunk) => {
70
+ seen += chunk.length;
71
+ if (seen > DRAIN_MAX_BYTES)
72
+ done(false);
73
+ };
74
+ const onEnd = () => done(true);
75
+ const timer = setTimeout(() => done(false), DRAIN_MAX_MS);
76
+ req.on('data', onData);
77
+ req.once('end', onEnd);
78
+ req.once('error', onEnd);
79
+ req.resume();
36
80
  });
37
- const server = new Server({ name: PACKAGE_NAME, version: PACKAGE_VERSION }, { capabilities: { tools: {} } });
38
- server.setRequestHandler(ListToolsRequestSchema, async () => ({
39
- tools: tools.map(({ name, description, inputSchema, annotations }) => ({
40
- name,
41
- description,
42
- inputSchema,
43
- annotations,
44
- })),
45
- }));
46
- server.setRequestHandler(CallToolRequestSchema, async (request) => {
47
- const { name, arguments: args = {} } = request.params;
48
- const tool = toolsByName[name];
49
- if (!tool) {
50
- return {
51
- isError: true,
52
- content: [{ type: 'text', text: `Unknown tool: ${name}` }],
53
- };
54
- }
55
- try {
56
- const result = await tool.handler(args, client);
57
- return {
58
- content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
59
- };
60
- }
61
- catch (err) {
62
- if (err instanceof LexAPIError) {
63
- return {
64
- isError: true,
65
- content: [
66
- {
67
- type: 'text',
68
- text: `LexAPI error (${err.status} ${err.slug}): ${err.message}`,
69
- },
70
- ],
71
- };
81
+ }
82
+ async function readJsonBody(req) {
83
+ const declared = Number(req.headers['content-length']);
84
+ if (Number.isFinite(declared) && declared > MAX_BODY_BYTES) {
85
+ throw new BodyTooLargeError(await drain(req, 0));
86
+ }
87
+ // Event listeners, not `for await`: leaving a for-await loop early destroys
88
+ // the stream, and the remaining body must stay readable for drain().
89
+ const text = await new Promise((resolve, reject) => {
90
+ const chunks = [];
91
+ let size = 0;
92
+ const cleanup = () => {
93
+ req.removeListener('data', onData);
94
+ req.removeListener('end', onEnd);
95
+ req.removeListener('error', onError);
96
+ };
97
+ const onData = (chunk) => {
98
+ size += chunk.length;
99
+ if (size > MAX_BODY_BYTES) {
100
+ cleanup();
101
+ req.pause();
102
+ drain(req, size).then((ok) => resolve(new BodyTooLargeError(ok)));
103
+ return;
72
104
  }
73
- const message = err instanceof Error ? err.message : String(err);
74
- return {
75
- isError: true,
76
- content: [{ type: 'text', text: `Tool execution failed: ${message}` }],
77
- };
78
- }
105
+ chunks.push(chunk);
106
+ };
107
+ const onEnd = () => { cleanup(); resolve(Buffer.concat(chunks).toString('utf8')); };
108
+ const onError = (e) => { cleanup(); reject(e); };
109
+ req.on('data', onData);
110
+ req.on('end', onEnd);
111
+ req.on('error', onError);
79
112
  });
80
- return server;
113
+ if (text instanceof BodyTooLargeError)
114
+ throw text;
115
+ if (!text)
116
+ return undefined;
117
+ return JSON.parse(text);
81
118
  }
82
- function writeJson(res, status, body) {
119
+ function writeJson(res, status, body, extra = {}) {
83
120
  res.writeHead(status, {
84
121
  'Content-Type': 'application/json',
85
122
  'Cache-Control': 'no-store, private',
123
+ ...extra,
86
124
  });
87
125
  res.end(JSON.stringify(body));
88
126
  }
89
- async function handleMcp(req, res) {
90
- const apiKey = extractBearer(req);
91
- if (!apiKey) {
92
- writeJson(res, 401, {
93
- error: {
94
- code: 'unauthorized',
95
- message: 'Missing or invalid Authorization header. Send: Authorization: Bearer <your LexAPI key>. Get a key at https://lex-api.com/dashboard.',
96
- },
97
- });
127
+ function jsonRpcError(res, status, code, message, extra = {}) {
128
+ writeJson(res, status, { jsonrpc: '2.0', error: { code, message }, id: null }, extra);
129
+ }
130
+ export function createOAuthRuntime(cfg, fetchImpl) {
131
+ return {
132
+ cfg,
133
+ jwks: new JwksCache({ url: cfg.jwksUri, ...(fetchImpl ? { fetch: fetchImpl } : {}) }),
134
+ exchanger: new TokenExchanger({
135
+ tokenEndpoint: cfg.tokenEndpoint,
136
+ clientId: cfg.clientId,
137
+ clientSecret: cfg.clientSecret,
138
+ apiAudience: cfg.apiAudience,
139
+ limits: { exchangesPerSubPerMin: cfg.exchangesPerUserPerMin },
140
+ ...(fetchImpl ? { fetch: fetchImpl } : {}),
141
+ }),
142
+ };
143
+ }
144
+ /** `oauthAlerts.proxyHopsMismatch` stays set this long after the last mismatched request, then clears by itself. */
145
+ export const PROXY_MISMATCH_ALERT_MS = 10 * 60_000;
146
+ /**
147
+ * Derives each request's client address and makes a wrong
148
+ * LEXAPI_MCP_TRUST_PROXY_HOPS visible: an X-Forwarded-For with fewer
149
+ * entries than the configured hops is counted and logged — once, then at
150
+ * most every 10 minutes — instead of silently falling back to the proxy's
151
+ * address. The /health alert reflects the last PROXY_MISMATCH_ALERT_MS only,
152
+ * so a fixed hop count clears it without a restart; the operator count
153
+ * (`shortXffRequests`) is cumulative.
154
+ */
155
+ class ClientAddressMonitor {
156
+ hops;
157
+ shortXff = 0;
158
+ lastWarnAt = -Infinity;
159
+ lastShortAt = -Infinity;
160
+ constructor(hops) {
161
+ this.hops = hops;
162
+ }
163
+ /** A mismatched request within the last PROXY_MISMATCH_ALERT_MS. */
164
+ get recentMismatch() {
165
+ return Date.now() - this.lastShortAt < PROXY_MISMATCH_ALERT_MS;
166
+ }
167
+ derive(req) {
168
+ const a = deriveClientAddress(req, this.hops);
169
+ if (a.short) {
170
+ this.shortXff += 1;
171
+ const now = Date.now();
172
+ this.lastShortAt = now;
173
+ if (now - this.lastWarnAt >= 10 * 60_000) {
174
+ this.lastWarnAt = now;
175
+ console.error(`[${PACKAGE_NAME}] WARNING: X-Forwarded-For has ${a.xffEntries} entr${a.xffEntries === 1 ? 'y' : 'ies'} but LEXAPI_MCP_TRUST_PROXY_HOPS=${this.hops}: using the socket address (a proxy) for per-IP limits. Fix the hop count (${this.shortXff} such request(s) so far; repeats are reported at most every 10 min)`);
176
+ }
177
+ }
178
+ return a;
179
+ }
180
+ /** The startup description of how client addresses are derived. */
181
+ static describe(hops) {
182
+ return hops > 0 ? `X-Forwarded-For, entry ${hops} from the right (LEXAPI_MCP_TRUST_PROXY_HOPS=${hops})` : 'the socket peer (LEXAPI_MCP_TRUST_PROXY_HOPS=0)';
183
+ }
184
+ }
185
+ /** LEXAPI_MCP_HEALTH_TOKEN: when set, `/health` with `Authorization: Bearer <token>` adds the operator details. */
186
+ function isOperator(req, token) {
187
+ if (!token)
188
+ return false;
189
+ const m = /^Bearer\s+(\S+)\s*$/i.exec(typeof req.headers.authorization === 'string' ? req.headers.authorization : '');
190
+ if (!m)
191
+ return false;
192
+ const a = Buffer.from(m[1]);
193
+ const b = Buffer.from(token);
194
+ return a.length === b.length && timingSafeEqual(a, b);
195
+ }
196
+ export const MIN_HEALTH_TOKEN_LENGTH = 32;
197
+ function methodNotAllowed(res) {
198
+ jsonRpcError(res, 405, -32000, 'Method not allowed: this server is stateless; send JSON-RPC requests with POST.', { Allow: 'POST, OPTIONS' });
199
+ }
200
+ /** 0.3.0's answer to a keyless request — still the answer when OAuth is off. */
201
+ function missingKey(res) {
202
+ writeJson(res, 401, {
203
+ error: {
204
+ code: 'unauthorized',
205
+ message: 'Missing API key. Send "Authorization: Bearer <your LexAPI key>" (or "x-api-key: <key>"). Get a key at https://lex-api.com/dashboard?ref=mcp-hosted.',
206
+ },
207
+ }, { 'WWW-Authenticate': 'Bearer realm="lexapi"' });
208
+ }
209
+ function malformedKey(res) {
210
+ // Never echo the value.
211
+ writeJson(res, 401, {
212
+ error: { code: 'malformed_api_key', message: 'Malformed API key: it contains whitespace or control characters. Send the key exactly as shown in the dashboard, on one line.' },
213
+ }, { 'WWW-Authenticate': 'Bearer realm="lexapi", error="invalid_token"' });
214
+ }
215
+ /** A credential that must not be used (too long, or a token where an API key belongs) — never forwarded. */
216
+ function rejectedCredential(res, cred, cfg) {
217
+ if (cred.header === 'authorization' && cfg) {
218
+ // With OAuth on a Bearer value is a token: refused like any bad token.
219
+ invalidTokenChallenge(res, cfg, 'malformed token');
98
220
  return;
99
221
  }
100
- let body;
222
+ const message = cred.reason === 'too_long'
223
+ ? 'Credential too long: a LexAPI API key is a single short value (lex_…).'
224
+ : cred.header === 'x-api-key'
225
+ ? 'x-api-key must carry a LexAPI API key (lex_…). An OAuth access token goes in "Authorization: Bearer <token>".'
226
+ : 'Not a LexAPI API key. Send "Authorization: Bearer <your LexAPI key>" with the key exactly as shown in the dashboard (lex_…).';
227
+ writeJson(res, 401, { error: { code: 'malformed_api_key', message } }, {
228
+ 'WWW-Authenticate': cfg
229
+ ? bearerChallenge(cfg, { code: 'invalid_token', description: cred.header === 'x-api-key' ? 'x-api-key is not a LexAPI API key' : 'malformed credential' })
230
+ : 'Bearer realm="lexapi", error="invalid_token"',
231
+ });
232
+ }
233
+ /** No usable credential at all. */
234
+ function oauthChallenge(res, cfg) {
235
+ writeJson(res, 401, { error: 'unauthorized', error_description: 'Sign in with LexAPI or send an API key' }, {
236
+ 'WWW-Authenticate': bearerChallenge(cfg),
237
+ });
238
+ }
239
+ /** A Bearer token was presented and refused. */
240
+ function invalidTokenChallenge(res, cfg, reason) {
241
+ writeJson(res, 401, { error: 'invalid_token', error_description: reason }, {
242
+ 'WWW-Authenticate': bearerChallenge(cfg, { code: 'invalid_token', description: reason }),
243
+ });
244
+ }
245
+ /** The parsed JSON-RPC body, or undefined after an error response was written. */
246
+ async function readBodyOrRespond(req, res) {
101
247
  try {
102
- body = await readJsonBody(req);
248
+ return { body: await readJsonBody(req) };
103
249
  }
104
250
  catch (err) {
105
- const message = err instanceof Error ? err.message : String(err);
106
- writeJson(res, 400, { error: { code: 'bad_request', message } });
251
+ if (err instanceof BodyTooLargeError) {
252
+ // The body was drained (up to the caps), so the client receives this
253
+ // 413. Close the connection anyway: if the drain hit a cap, the rest of
254
+ // the body is still on the socket and must not be read as a request.
255
+ res.on('finish', () => { if (!err.drained)
256
+ req.destroy(); });
257
+ jsonRpcError(res, 413, -32600, `Request body too large (max ${MAX_BODY_BYTES} bytes)`, { Connection: 'close' });
258
+ }
259
+ else
260
+ jsonRpcError(res, 400, -32700, 'Parse error: body is not valid JSON');
261
+ return undefined;
262
+ }
263
+ }
264
+ /** The 0.3.0 request path: an API key, forwarded to LexAPI as x-api-key. */
265
+ async function serveWithApiKey(req, res, apiKey, ctx) {
266
+ if (!isWellFormedKey(apiKey)) {
267
+ malformedKey(res);
107
268
  return;
108
269
  }
109
- // Defense-in-depth headers — Cloudflare + intermediate proxies should not
110
- // buffer streamed responses, and per-user MCP responses must never be cached.
270
+ const parsed = await readBodyOrRespond(req, res);
271
+ if (!parsed)
272
+ return;
273
+ // Per-user responses must never be cached or buffered by proxies.
111
274
  res.setHeader('X-Accel-Buffering', 'no');
112
275
  res.setHeader('Cache-Control', 'no-store, private');
113
- const mcpServer = buildMcpServer(apiKey);
114
- const transport = new StreamableHTTPServerTransport({
115
- sessionIdGenerator: undefined,
276
+ const server = createLexServer(clientFromEnv(apiKey, ctx.env), { readOnly: readOnlyFromEnv(ctx.env) });
277
+ const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
278
+ res.on('close', () => {
279
+ transport.close().catch(() => { });
280
+ server.close().catch(() => { });
281
+ });
282
+ await server.connect(transport);
283
+ await transport.handleRequest(req, res, parsed.body);
284
+ }
285
+ async function handleMcp(req, res, ctx) {
286
+ const { oauth } = ctx;
287
+ if (!oauth) {
288
+ // OAuth off: exactly the 0.3.0 behaviour.
289
+ // Stateless server: there is no session to open a GET event stream on or to
290
+ // DELETE, so only POST is meaningful (MCP Streamable HTTP, stateless mode).
291
+ if (req.method !== 'POST') {
292
+ methodNotAllowed(res);
293
+ return;
294
+ }
295
+ const cred = classifyCredential(req, false);
296
+ if (cred.kind === 'rejected') {
297
+ rejectedCredential(res, cred, null);
298
+ return;
299
+ }
300
+ if (cred.kind !== 'apiKey') {
301
+ missingKey(res);
302
+ return;
303
+ }
304
+ await serveWithApiKey(req, res, cred.key, ctx);
305
+ return;
306
+ }
307
+ // OAuth on. Every method on the MCP endpoint without a usable credential
308
+ // gets the authorization challenge — that is how MCP clients discover the AS.
309
+ const cred = classifyCredential(req, true);
310
+ if (cred.kind === 'none') {
311
+ oauthChallenge(res, oauth.cfg);
312
+ return;
313
+ }
314
+ if (cred.kind === 'rejected') {
315
+ rejectedCredential(res, cred, oauth.cfg);
316
+ return;
317
+ }
318
+ if (cred.kind === 'apiKey') {
319
+ if (req.method !== 'POST') {
320
+ methodNotAllowed(res);
321
+ return;
322
+ }
323
+ await serveWithApiKey(req, res, cred.key, ctx);
324
+ return;
325
+ }
326
+ let claims;
327
+ try {
328
+ claims = await verifyAccessToken(cred.token, { issuer: oauth.cfg.issuer, audience: oauth.cfg.resource, jwks: oauth.jwks });
329
+ }
330
+ catch (err) {
331
+ if (err instanceof InvalidTokenError) {
332
+ invalidTokenChallenge(res, oauth.cfg, err.message);
333
+ return;
334
+ }
335
+ if (err instanceof JwksUnavailableError) {
336
+ // Not the token's fault (issuer unreachable, or a JWKS without a usable
337
+ // key): no challenge, so clients don't re-authorize. Logged by JwksCache.
338
+ jsonRpcError(res, 503, -32603, 'Sign-in with LexAPI is temporarily unavailable; retry shortly.', { 'Retry-After': '5' });
339
+ return;
340
+ }
341
+ throw err;
342
+ }
343
+ if (req.method !== 'POST') {
344
+ methodNotAllowed(res);
345
+ return;
346
+ }
347
+ const parsed = await readBodyOrRespond(req, res);
348
+ if (!parsed)
349
+ return;
350
+ await serveWithOAuth(req, res, parsed.body, cred.token, claims, oauth, ctx);
351
+ }
352
+ /**
353
+ * The OAuth request path. The MCP transport runs on Web-standard
354
+ * Request/Response so the response can be held until its first frame: a
355
+ * tool call that finds the connection revoked (API 401 → re-exchange 400)
356
+ * or the exchange misconfigured records it on the gate first, and the
357
+ * client gets the matching HTTP status instead of a 200. Frames that go
358
+ * out before (progress every 10 s, SSE keep-alive every 15 s) commit the
359
+ * 200; later failures stay tool errors.
360
+ */
361
+ async function serveWithOAuth(req, res, body, token, claims, oauth, ctx) {
362
+ const gate = new ResponseGate();
363
+ const client = new LexAPIClient({
364
+ auth: new OAuthUpstreamAuth(token, claims.exp, oauth.exchanger, gate, { ip: ctx.clientAddress.derive(req).ip, sub: claims.sub }),
365
+ baseUrl: oauth.cfg.apiBase,
366
+ ...(ctx.fetch ? { fetch: ctx.fetch } : {}),
116
367
  });
368
+ const server = createLexServer(client, { readOnly: readOnlyFromEnv(ctx.env) });
369
+ const transport = new WebStandardStreamableHTTPServerTransport({ sessionIdGenerator: undefined, keepAliveMs: SSE_KEEP_ALIVE_MS });
370
+ const streams = {};
117
371
  res.on('close', () => {
372
+ streams.reader?.cancel().catch(() => { });
118
373
  transport.close().catch(() => { });
119
- mcpServer.close().catch(() => { });
374
+ server.close().catch(() => { });
375
+ });
376
+ await server.connect(transport);
377
+ const webRes = await transport.handleRequest(toWebRequest(req), { parsedBody: body });
378
+ const reader = webRes.body?.getReader();
379
+ streams.reader = reader;
380
+ let first = { done: true, value: undefined };
381
+ if (reader) {
382
+ try {
383
+ first = await reader.read();
384
+ }
385
+ catch {
386
+ first = { done: true, value: undefined };
387
+ }
388
+ }
389
+ if (res.destroyed || res.writableEnded)
390
+ return;
391
+ const failure = gate.failure;
392
+ if (failure) {
393
+ reader?.cancel().catch(() => { });
394
+ writeUpstreamAuthFailure(res, failure, oauth.cfg);
395
+ return;
396
+ }
397
+ const headers = {};
398
+ webRes.headers.forEach((v, k) => { headers[k] = v; });
399
+ // Per-user responses must never be cached or buffered by proxies.
400
+ headers['cache-control'] = 'no-store, private, no-transform';
401
+ headers['x-accel-buffering'] = 'no';
402
+ res.writeHead(webRes.status, headers);
403
+ if (first.done || !reader) {
404
+ res.end();
405
+ return;
406
+ }
407
+ res.write(first.value);
408
+ for (;;) {
409
+ let chunk;
410
+ try {
411
+ chunk = await reader.read();
412
+ }
413
+ catch {
414
+ break;
415
+ }
416
+ if (chunk.done || res.destroyed)
417
+ break;
418
+ if (!res.write(chunk.value))
419
+ await drained(res);
420
+ }
421
+ if (!res.destroyed && !res.writableEnded)
422
+ res.end();
423
+ }
424
+ function drained(res) {
425
+ return new Promise((resolve) => {
426
+ const done = () => {
427
+ res.removeListener('drain', done);
428
+ res.removeListener('close', done);
429
+ resolve();
430
+ };
431
+ res.once('drain', done);
432
+ res.once('close', done);
120
433
  });
121
- await mcpServer.connect(transport);
122
- await transport.handleRequest(req, res, body);
123
434
  }
124
- export function createHttpServer() {
125
- return createServer(async (req, res) => {
435
+ /** Credentials and hop-by-hop headers never reach the MCP layer. */
436
+ const DROPPED_HEADERS = new Set(['authorization', 'x-api-key', 'cookie', 'host', 'connection', 'content-length', 'transfer-encoding', 'keep-alive', 'upgrade']);
437
+ /** The request the MCP layer sees: no credential headers (exported for tests). */
438
+ export function toWebRequest(req) {
439
+ const headers = new Headers();
440
+ for (const [name, value] of Object.entries(req.headers)) {
441
+ if (value === undefined || DROPPED_HEADERS.has(name.toLowerCase()))
442
+ continue;
443
+ if (Array.isArray(value))
444
+ for (const v of value)
445
+ headers.append(name, v);
446
+ else
447
+ headers.set(name, value);
448
+ }
449
+ return new Request(new URL(req.url ?? '/', 'http://localhost'), { method: req.method ?? 'POST', headers });
450
+ }
451
+ function writeUpstreamAuthFailure(res, err, cfg) {
452
+ if (err.httpStatus === 401) {
453
+ invalidTokenChallenge(res, cfg, err.description);
454
+ return;
455
+ }
456
+ const message = err.httpStatus === 500
457
+ ? 'Sign-in with LexAPI is misconfigured on this server; the operator has been alerted.'
458
+ : 'Sign-in with LexAPI is temporarily unavailable; retry shortly.';
459
+ jsonRpcError(res, err.httpStatus, -32603, message, err.httpStatus === 503 ? { 'Retry-After': String(err.retryAfterSeconds ?? 30) } : {});
460
+ }
461
+ /** RFC 9728 metadata: public, cacheable, readable from any browser origin. */
462
+ function serveResourceMetadata(req, res, cfg) {
463
+ const cors = {
464
+ 'Access-Control-Allow-Origin': '*',
465
+ 'Access-Control-Allow-Methods': 'GET, HEAD, OPTIONS',
466
+ 'Access-Control-Allow-Headers': 'Authorization, Content-Type, Accept, MCP-Protocol-Version',
467
+ };
468
+ if (req.method === 'OPTIONS') {
469
+ res.writeHead(204, { ...cors, 'Access-Control-Max-Age': '86400' });
470
+ res.end();
471
+ return;
472
+ }
473
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
474
+ writeJson(res, 405, { error: { code: 'method_not_allowed', message: 'Use GET.' } }, { ...cors, Allow: 'GET, HEAD, OPTIONS' });
475
+ return;
476
+ }
477
+ const body = JSON.stringify(protectedResourceMetadata(cfg));
478
+ res.writeHead(200, {
479
+ ...cors,
480
+ 'Content-Type': 'application/json',
481
+ 'Cache-Control': 'public, max-age=3600',
482
+ 'Content-Length': Buffer.byteLength(body),
483
+ });
484
+ res.end(req.method === 'HEAD' ? undefined : body);
485
+ }
486
+ /** True when something needs an operator — configuration, not traffic. */
487
+ function oauthAlerts(oauth, clientAddress) {
488
+ const ex = oauth.exchanger.stats();
489
+ const jwks = oauth.jwks.stats();
490
+ return {
491
+ configErrors: ex.configErrors > 0,
492
+ clientAuthErrors: ex.clientAuthErrors > 0,
493
+ jwksUnavailable: jwks.keys === 0 ? jwks.failures > 0 : jwks.consecutiveFailures > 0,
494
+ proxyHopsMismatch: clientAddress.recentMismatch,
495
+ };
496
+ }
497
+ /**
498
+ * For verifying LEXAPI_MCP_TRUST_PROXY_HOPS after a deploy:
499
+ * how many X-Forwarded-For entries THIS request arrived with and whether the
500
+ * address came from it. Never the address itself.
501
+ */
502
+ function clientAddressReport(req, monitor) {
503
+ const a = deriveClientAddress(req, monitor.hops);
504
+ return {
505
+ mode: monitor.hops > 0 ? 'x-forwarded-for' : 'socket',
506
+ trustProxyHops: monitor.hops,
507
+ xffEntriesThisRequest: a.xffEntries,
508
+ derivedFrom: monitor.hops > 0 && !a.short ? 'x-forwarded-for' : 'socket',
509
+ shortXffRequests: monitor.shortXff,
510
+ };
511
+ }
512
+ export function createHttpServer(opts = {}) {
513
+ const env = opts.env ?? process.env;
514
+ const cfg = opts.oauth === undefined ? oauthConfigFromEnv(env) : opts.oauth;
515
+ const oauth = cfg ? createOAuthRuntime(cfg, opts.fetch) : null;
516
+ const clientAddress = new ClientAddressMonitor(cfg?.trustProxyHops ?? 0);
517
+ const ctx = { oauth, env, clientAddress, ...(opts.fetch ? { fetch: opts.fetch } : {}) };
518
+ const healthToken = (env.LEXAPI_MCP_HEALTH_TOKEN ?? '').trim() || undefined;
519
+ if (healthToken && healthToken.length < MIN_HEALTH_TOKEN_LENGTH) {
520
+ throw new OAuthConfigError(`LEXAPI_MCP_HEALTH_TOKEN must be at least ${MIN_HEALTH_TOKEN_LENGTH} characters`);
521
+ }
522
+ if (healthToken && !oauth) {
523
+ // Every operator field is about OAuth (exchange / JWKS counters, the
524
+ // client address for the per-IP limits): with OAuth off there is
525
+ // nothing to add, so the token does nothing. Say so rather than look on.
526
+ console.error(`[${PACKAGE_NAME}] WARNING: LEXAPI_MCP_HEALTH_TOKEN is set but OAuth is off (LEXAPI_OAUTH_CLIENT_SECRET not set): the /health operator view only adds OAuth fields, so it is the same as the public view. Unset it, or turn OAuth on.`);
527
+ }
528
+ const metadataPaths = cfg
529
+ ? new Set([`/.well-known/oauth-protected-resource${cfg.resourcePath}`, '/.well-known/oauth-protected-resource'])
530
+ : new Set();
531
+ const mcpPath = cfg ? cfg.resourcePath : MCP_PATH;
532
+ const server = createServer(async (req, res) => {
126
533
  try {
127
- // CORS preflight — MCP clients called from browsers need this.
534
+ const path = (req.url ?? '/').split('?')[0];
535
+ // Protected Resource Metadata is public and must be readable by
536
+ // browser-based clients from any origin: served before the Origin check.
537
+ if (cfg && metadataPaths.has(path)) {
538
+ serveResourceMetadata(req, res, cfg);
539
+ return;
540
+ }
541
+ const origin = typeof req.headers.origin === 'string' ? req.headers.origin : undefined;
542
+ if (!originAllowed(origin, env)) {
543
+ writeJson(res, 403, { error: { code: 'origin_not_allowed', message: `Origin ${origin} is not allowed. Browser clients must be listed in LEXAPI_MCP_ALLOWED_ORIGINS.` } });
544
+ return;
545
+ }
546
+ // CORS for allowed browser origins (echoed, never a wildcard with a real origin).
128
547
  if (req.method === 'OPTIONS') {
129
548
  res.writeHead(204, {
130
- 'Access-Control-Allow-Origin': '*',
131
- 'Access-Control-Allow-Methods': 'GET, POST, DELETE, OPTIONS',
132
- 'Access-Control-Allow-Headers': 'Authorization, Content-Type, Mcp-Session-Id, Mcp-Protocol-Version',
549
+ ...(origin ? { 'Access-Control-Allow-Origin': origin, Vary: 'Origin' } : {}),
550
+ 'Access-Control-Allow-Methods': 'POST, OPTIONS',
551
+ 'Access-Control-Allow-Headers': 'Authorization, X-API-Key, Content-Type, Accept, Mcp-Session-Id, Mcp-Protocol-Version, Last-Event-ID',
133
552
  'Access-Control-Max-Age': '86400',
134
553
  });
135
554
  res.end();
136
555
  return;
137
556
  }
138
- res.setHeader('Access-Control-Allow-Origin', '*');
139
- res.setHeader('Access-Control-Expose-Headers', 'Mcp-Session-Id');
140
- if (req.method === 'GET' && req.url === '/health') {
557
+ if (origin) {
558
+ res.setHeader('Access-Control-Allow-Origin', origin);
559
+ res.setHeader('Vary', 'Origin');
560
+ }
561
+ res.setHeader('Access-Control-Expose-Headers', 'Mcp-Session-Id, Mcp-Protocol-Version, WWW-Authenticate');
562
+ if (path === '/health' && (req.method === 'GET' || req.method === 'HEAD')) {
141
563
  writeJson(res, 200, {
142
564
  status: 'ok',
143
565
  name: PACKAGE_NAME,
144
566
  version: PACKAGE_VERSION,
145
- tools: tools.length,
567
+ tools: selectTools({ readOnly: readOnlyFromEnv(env) }).length,
568
+ oauth: Boolean(oauth),
569
+ // Public: coarse booleans only — enough for an uptime check
570
+ // to alert on a misconfiguration, nothing about traffic volume,
571
+ // limits or configuration values.
572
+ ...(oauth ? { oauthAlerts: oauthAlerts(oauth, clientAddress) } : {}),
573
+ // Operator view (LEXAPI_MCP_HEALTH_TOKEN): counters and the
574
+ // client-address derivation — never addresses, tokens or config values.
575
+ ...(oauth && isOperator(req, healthToken) ? {
576
+ oauthStats: { exchange: oauth.exchanger.stats(), jwks: oauth.jwks.stats() },
577
+ clientAddress: clientAddressReport(req, clientAddress),
578
+ } : {}),
146
579
  });
147
580
  return;
148
581
  }
149
- if (req.url === MCP_PATH || req.url === MCP_PATH + '/') {
150
- await handleMcp(req, res);
582
+ if (path === mcpPath || path === `${mcpPath}/`) {
583
+ await handleMcp(req, res, ctx);
151
584
  return;
152
585
  }
153
- writeJson(res, 404, { error: { code: 'not_found', message: `No route for ${req.method} ${req.url}` } });
586
+ writeJson(res, 404, { error: { code: 'not_found', message: `No route for ${req.method} ${path}. The MCP endpoint is POST ${mcpPath}.` } });
154
587
  }
155
588
  catch (err) {
156
- const message = err instanceof Error ? err.message : String(err);
157
- if (!res.headersSent) {
158
- writeJson(res, 500, { error: { code: 'internal_error', message } });
159
- }
160
- else {
589
+ // Log server-side only, scrubbed; the client gets a generic message (no internals).
590
+ console.error(`[${PACKAGE_NAME}] request failed:`, redact(err instanceof Error ? err.message : String(err), [cfg?.clientSecret]));
591
+ if (!res.headersSent)
592
+ jsonRpcError(res, 500, -32603, 'Internal server error');
593
+ else
161
594
  res.end();
162
- }
163
595
  }
164
596
  });
597
+ return Object.assign(server, { oauth, clientAddressMode: ClientAddressMonitor.describe(cfg?.trustProxyHops ?? 0) });
165
598
  }