@lexapi/mcp 0.3.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.
- package/CHANGELOG.md +54 -5
- package/README.md +75 -21
- package/dist/client.d.ts +34 -4
- package/dist/client.js +163 -24
- package/dist/credentials.d.ts +67 -0
- package/dist/credentials.js +118 -0
- package/dist/errors.d.ts +18 -0
- package/dist/errors.js +155 -6
- package/dist/http-entry.js +19 -2
- package/dist/http-server.d.ts +36 -4
- package/dist/http-server.js +417 -50
- package/dist/oauth/body.d.ts +5 -0
- package/dist/oauth/body.js +35 -0
- package/dist/oauth/config.d.ts +59 -0
- package/dist/oauth/config.js +149 -0
- package/dist/oauth/exchange.d.ts +196 -0
- package/dist/oauth/exchange.js +573 -0
- package/dist/oauth/jwt.d.ts +124 -0
- package/dist/oauth/jwt.js +352 -0
- package/dist/oauth/redact.d.ts +1 -0
- package/dist/oauth/redact.js +23 -0
- package/dist/oauth/upstream.d.ts +41 -0
- package/dist/oauth/upstream.js +95 -0
- package/dist/server.d.ts +2 -1
- package/dist/server.js +4 -1
- package/dist/shape.d.ts +54 -0
- package/dist/shape.js +444 -8
- package/dist/tools.d.ts +5 -1
- package/dist/tools.js +295 -25
- package/package.json +2 -2
package/dist/http-server.js
CHANGED
|
@@ -1,7 +1,15 @@
|
|
|
1
|
+
import { timingSafeEqual } from 'node:crypto';
|
|
1
2
|
import { createServer } from 'node:http';
|
|
2
3
|
import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js';
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
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';
|
|
5
13
|
import { selectTools } from './tools.js';
|
|
6
14
|
import { PACKAGE_VERSION } from './version.js';
|
|
7
15
|
const MCP_PATH = '/v1';
|
|
@@ -14,23 +22,16 @@ const MAX_BODY_BYTES = 1_000_000;
|
|
|
14
22
|
const DRAIN_MAX_BYTES = 16_000_000;
|
|
15
23
|
const DRAIN_MAX_MS = 5000;
|
|
16
24
|
/**
|
|
17
|
-
*
|
|
18
|
-
*
|
|
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.
|
|
19
29
|
*/
|
|
20
|
-
export
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
// Everything after "Bearer " is the key; a value with inner whitespace
|
|
24
|
-
// is returned as-is so it is reported as malformed, not as missing.
|
|
25
|
-
const m = auth.match(/^Bearer\s+(.+?)\s*$/i);
|
|
26
|
-
if (m)
|
|
27
|
-
return m[1];
|
|
28
|
-
}
|
|
29
|
-
const x = req.headers['x-api-key'];
|
|
30
|
-
if (typeof x === 'string' && x.trim())
|
|
31
|
-
return x.trim();
|
|
32
|
-
return null;
|
|
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');
|
|
33
33
|
}
|
|
34
|
+
export { classifyCredential, extractApiKey } from './credentials.js';
|
|
34
35
|
/**
|
|
35
36
|
* Origin validation (MCP Streamable HTTP: servers MUST validate Origin, a
|
|
36
37
|
* DNS-rebinding defence). Requests without an Origin header — every
|
|
@@ -126,33 +127,125 @@ function writeJson(res, status, body, extra = {}) {
|
|
|
126
127
|
function jsonRpcError(res, status, code, message, extra = {}) {
|
|
127
128
|
writeJson(res, status, { jsonrpc: '2.0', error: { code, message }, id: null }, extra);
|
|
128
129
|
}
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
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;
|
|
135
162
|
}
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
error: {
|
|
140
|
-
code: 'unauthorized',
|
|
141
|
-
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.',
|
|
142
|
-
},
|
|
143
|
-
}, { 'WWW-Authenticate': 'Bearer realm="lexapi"' });
|
|
144
|
-
return;
|
|
163
|
+
/** A mismatched request within the last PROXY_MISMATCH_ALERT_MS. */
|
|
164
|
+
get recentMismatch() {
|
|
165
|
+
return Date.now() - this.lastShortAt < PROXY_MISMATCH_ALERT_MS;
|
|
145
166
|
}
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
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');
|
|
151
220
|
return;
|
|
152
221
|
}
|
|
153
|
-
|
|
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) {
|
|
154
247
|
try {
|
|
155
|
-
body
|
|
248
|
+
return { body: await readJsonBody(req) };
|
|
156
249
|
}
|
|
157
250
|
catch (err) {
|
|
158
251
|
if (err instanceof BodyTooLargeError) {
|
|
@@ -165,26 +258,288 @@ async function handleMcp(req, res) {
|
|
|
165
258
|
}
|
|
166
259
|
else
|
|
167
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);
|
|
168
268
|
return;
|
|
169
269
|
}
|
|
270
|
+
const parsed = await readBodyOrRespond(req, res);
|
|
271
|
+
if (!parsed)
|
|
272
|
+
return;
|
|
170
273
|
// Per-user responses must never be cached or buffered by proxies.
|
|
171
274
|
res.setHeader('X-Accel-Buffering', 'no');
|
|
172
275
|
res.setHeader('Cache-Control', 'no-store, private');
|
|
173
|
-
const server = createLexServer(clientFromEnv(apiKey), { readOnly: readOnlyFromEnv() });
|
|
276
|
+
const server = createLexServer(clientFromEnv(apiKey, ctx.env), { readOnly: readOnlyFromEnv(ctx.env) });
|
|
174
277
|
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined });
|
|
175
278
|
res.on('close', () => {
|
|
176
279
|
transport.close().catch(() => { });
|
|
177
280
|
server.close().catch(() => { });
|
|
178
281
|
});
|
|
179
282
|
await server.connect(transport);
|
|
180
|
-
await transport.handleRequest(req, res, body);
|
|
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 } : {}),
|
|
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 = {};
|
|
371
|
+
res.on('close', () => {
|
|
372
|
+
streams.reader?.cancel().catch(() => { });
|
|
373
|
+
transport.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();
|
|
181
423
|
}
|
|
182
|
-
|
|
183
|
-
return
|
|
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);
|
|
433
|
+
});
|
|
434
|
+
}
|
|
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) => {
|
|
184
533
|
try {
|
|
185
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
|
+
}
|
|
186
541
|
const origin = typeof req.headers.origin === 'string' ? req.headers.origin : undefined;
|
|
187
|
-
if (!originAllowed(origin)) {
|
|
542
|
+
if (!originAllowed(origin, env)) {
|
|
188
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.` } });
|
|
189
544
|
return;
|
|
190
545
|
}
|
|
@@ -209,23 +564,35 @@ export function createHttpServer() {
|
|
|
209
564
|
status: 'ok',
|
|
210
565
|
name: PACKAGE_NAME,
|
|
211
566
|
version: PACKAGE_VERSION,
|
|
212
|
-
tools: selectTools({ readOnly: readOnlyFromEnv() }).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
|
+
} : {}),
|
|
213
579
|
});
|
|
214
580
|
return;
|
|
215
581
|
}
|
|
216
|
-
if (path ===
|
|
217
|
-
await handleMcp(req, res);
|
|
582
|
+
if (path === mcpPath || path === `${mcpPath}/`) {
|
|
583
|
+
await handleMcp(req, res, ctx);
|
|
218
584
|
return;
|
|
219
585
|
}
|
|
220
|
-
writeJson(res, 404, { error: { code: 'not_found', message: `No route for ${req.method} ${path}. The MCP endpoint is POST ${
|
|
586
|
+
writeJson(res, 404, { error: { code: 'not_found', message: `No route for ${req.method} ${path}. The MCP endpoint is POST ${mcpPath}.` } });
|
|
221
587
|
}
|
|
222
588
|
catch (err) {
|
|
223
|
-
// Log server-side only; the client gets a generic message (no internals).
|
|
224
|
-
console.error(`[${PACKAGE_NAME}] request failed:`, err instanceof Error ? err.message : err);
|
|
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]));
|
|
225
591
|
if (!res.headersSent)
|
|
226
592
|
jsonRpcError(res, 500, -32603, 'Internal server error');
|
|
227
593
|
else
|
|
228
594
|
res.end();
|
|
229
595
|
}
|
|
230
596
|
});
|
|
597
|
+
return Object.assign(server, { oauth, clientAddressMode: ClientAddressMonitor.describe(cfg?.trustProxyHops ?? 0) });
|
|
231
598
|
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
// Size-capped reading of an outbound response body (JWKS, token endpoint).
|
|
2
|
+
// The cap is enforced while streaming: a body larger than the cap is never
|
|
3
|
+
// buffered in full — reading stops, and the stream is cancelled, as soon as
|
|
4
|
+
// the running total passes it.
|
|
5
|
+
export class ResponseTooLargeError extends Error {
|
|
6
|
+
constructor() {
|
|
7
|
+
super('response body too large');
|
|
8
|
+
this.name = 'ResponseTooLargeError';
|
|
9
|
+
}
|
|
10
|
+
}
|
|
11
|
+
/** The body as UTF-8 text, or ResponseTooLargeError once more than `maxBytes` arrived. */
|
|
12
|
+
export async function readCappedText(res, maxBytes) {
|
|
13
|
+
const declared = Number(res.headers.get('content-length'));
|
|
14
|
+
if (Number.isFinite(declared) && declared > maxBytes) {
|
|
15
|
+
await res.body?.cancel().catch(() => { });
|
|
16
|
+
throw new ResponseTooLargeError();
|
|
17
|
+
}
|
|
18
|
+
if (!res.body)
|
|
19
|
+
return '';
|
|
20
|
+
const reader = res.body.getReader();
|
|
21
|
+
const chunks = [];
|
|
22
|
+
let size = 0;
|
|
23
|
+
for (;;) {
|
|
24
|
+
const { done, value } = await reader.read();
|
|
25
|
+
if (done)
|
|
26
|
+
break;
|
|
27
|
+
size += value.byteLength;
|
|
28
|
+
if (size > maxBytes) {
|
|
29
|
+
await reader.cancel().catch(() => { });
|
|
30
|
+
throw new ResponseTooLargeError();
|
|
31
|
+
}
|
|
32
|
+
chunks.push(value);
|
|
33
|
+
}
|
|
34
|
+
return Buffer.concat(chunks).toString('utf8');
|
|
35
|
+
}
|
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
export declare const OAUTH_SCOPE = "lex";
|
|
2
|
+
export declare const DEFAULT_ISSUER = "https://lex-api.com";
|
|
3
|
+
export declare const DEFAULT_RESOURCE = "https://mcp.lex-api.com/v1";
|
|
4
|
+
export declare const DEFAULT_CLIENT_ID = "lexapi-mcp-server";
|
|
5
|
+
/** Shortest accepted client secret. */
|
|
6
|
+
export declare const MIN_SECRET_LENGTH = 32;
|
|
7
|
+
export interface OAuthConfig {
|
|
8
|
+
/** `iss` of every token; the AS endpoints hang off it. */
|
|
9
|
+
issuer: string;
|
|
10
|
+
/** This server's RFC 8707 resource — byte-identical to the PRM `resource` and the MCP token `aud`. */
|
|
11
|
+
resource: string;
|
|
12
|
+
clientId: string;
|
|
13
|
+
clientSecret: string;
|
|
14
|
+
/** Audience of the exchanged API token (LexAPI: `${issuer}/api/v1`). */
|
|
15
|
+
apiAudience: string;
|
|
16
|
+
tokenEndpoint: string;
|
|
17
|
+
jwksUri: string;
|
|
18
|
+
/** Path the resource lives on (`/v1`) — the MCP endpoint and the PRM path suffix. */
|
|
19
|
+
resourcePath: string;
|
|
20
|
+
/** `https://mcp.lex-api.com/.well-known/oauth-protected-resource/v1`. */
|
|
21
|
+
resourceMetadataUrl: string;
|
|
22
|
+
/**
|
|
23
|
+
* LexAPI's REST base for OAuth requests: LEXAPI_BASE_URL (else the
|
|
24
|
+
* default), resolved exactly as on the API-key path; same origin as the
|
|
25
|
+
* issuer, so exchanged API tokens can only ever go to LexAPI.
|
|
26
|
+
*/
|
|
27
|
+
apiBase: string;
|
|
28
|
+
/** Reverse proxies in front of this server (LEXAPI_MCP_TRUST_PROXY_HOPS) — for the per-IP limit. */
|
|
29
|
+
trustProxyHops: number;
|
|
30
|
+
/** New token exchanges per user per minute (LEXAPI_MCP_EXCHANGES_PER_USER_PER_MIN, default 20). */
|
|
31
|
+
exchangesPerUserPerMin: number;
|
|
32
|
+
}
|
|
33
|
+
/** Default per-user cap on new token exchanges a minute; one per connection every ~4.5 min is normal. */
|
|
34
|
+
export declare const DEFAULT_EXCHANGES_PER_USER_PER_MIN = 20;
|
|
35
|
+
export declare class OAuthConfigError extends Error {
|
|
36
|
+
constructor(message: string);
|
|
37
|
+
}
|
|
38
|
+
/**
|
|
39
|
+
* The OAuth configuration from env, or null when OAuth is off (no client
|
|
40
|
+
* secret). Throws OAuthConfigError when the secret is set but a value is
|
|
41
|
+
* unusable — the hosted server must not start half-configured.
|
|
42
|
+
*/
|
|
43
|
+
export declare function oauthConfigFromEnv(env?: NodeJS.ProcessEnv): OAuthConfig | null;
|
|
44
|
+
/** RFC 9728 Protected Resource Metadata. */
|
|
45
|
+
export declare function protectedResourceMetadata(cfg: OAuthConfig): {
|
|
46
|
+
resource: string;
|
|
47
|
+
authorization_servers: string[];
|
|
48
|
+
scopes_supported: string[];
|
|
49
|
+
bearer_methods_supported: string[];
|
|
50
|
+
resource_name: string;
|
|
51
|
+
resource_documentation: string;
|
|
52
|
+
};
|
|
53
|
+
/** A quoted-string-safe value for a WWW-Authenticate parameter. */
|
|
54
|
+
export declare function authParam(value: string): string;
|
|
55
|
+
/** The RFC 6750 / MCP authorization challenge; `error` is set when a Bearer token was presented and refused. */
|
|
56
|
+
export declare function bearerChallenge(cfg: OAuthConfig, error?: {
|
|
57
|
+
code: 'invalid_token';
|
|
58
|
+
description: string;
|
|
59
|
+
}): string;
|