@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.
@@ -0,0 +1,124 @@
1
+ import { type KeyObject } from 'node:crypto';
2
+ /**
3
+ * Clock skew allowed on `exp`, `iat` and `nbf`: 5 s either way, kept
4
+ * tight so this server does not accept a token the exchange then refuses as
5
+ * expired. The host must keep NTP time.
6
+ */
7
+ export declare const CLOCK_SKEW_S = 5;
8
+ /** JWKS lifetime bounds: `max-age` is respected, but never below 5 min or above a day. */
9
+ export declare const JWKS_MIN_TTL_MS: number;
10
+ export declare const JWKS_MAX_TTL_MS: number;
11
+ /**
12
+ * How long past its TTL a cached key set may still be used while the issuer
13
+ * cannot be reached. Beyond this the server answers 503 rather than
14
+ * trusting keys that may have been withdrawn during the outage.
15
+ */
16
+ export declare const JWKS_MAX_STALE_MS: number;
17
+ /** An unknown `kid` triggers at most one JWKS refetch per this interval. */
18
+ export declare const JWKS_UNKNOWN_KID_REFETCH_MS = 60000;
19
+ /**
20
+ * After a failed fetch the next attempt waits this long, measured from the
21
+ * END of the failed attempt and doubling per consecutive failure up to
22
+ * JWKS_RETRY_MAX_MS — so a hanging issuer is asked at most once per backoff
23
+ * interval, never back to back.
24
+ */
25
+ export declare const JWKS_RETRY_MIN_MS = 5000;
26
+ export declare const JWKS_RETRY_MAX_MS: number;
27
+ export declare const JWKS_TIMEOUT_MS = 5000;
28
+ export declare const JWKS_MAX_BYTES: number;
29
+ export declare const MAX_TOKEN_LENGTH = 8192;
30
+ export declare function looksLikeJwt(value: string): boolean;
31
+ /** The token was refused — answer 401 `invalid_token` with this (token-free) reason. */
32
+ export declare class InvalidTokenError extends Error {
33
+ constructor(reason: string);
34
+ }
35
+ /** The signing keys could not be obtained — not the token's fault: answer 503. */
36
+ export declare class JwksUnavailableError extends Error {
37
+ constructor(reason: string);
38
+ }
39
+ export interface AccessTokenClaims {
40
+ iss: string;
41
+ sub: string;
42
+ aud: string | string[];
43
+ client_id: string;
44
+ scope: string;
45
+ gid: string;
46
+ sid: string;
47
+ jti: string;
48
+ iat: number;
49
+ exp: number;
50
+ nbf?: number;
51
+ [claim: string]: unknown;
52
+ }
53
+ export interface JwksCacheOptions {
54
+ url: string;
55
+ fetch?: typeof fetch;
56
+ now?: () => number;
57
+ }
58
+ export interface JwksStats {
59
+ fetches: number;
60
+ failures: number;
61
+ consecutiveFailures: number;
62
+ keys: number;
63
+ /** The cached set is past its TTL (being served while a refresh is retried). */
64
+ stale: boolean;
65
+ /** Seconds since the last successful fetch (null: never). */
66
+ ageSeconds: number | null;
67
+ }
68
+ /**
69
+ * The issuer's JWKS, cached per `Cache-Control: max-age` (5 min – 24 h).
70
+ *
71
+ * - Cold start (no keys yet): requests wait for the fetch (concurrent ones
72
+ * share it); a failure is a 503 for them.
73
+ * - Expired: the stale set keeps serving and ONE refresh runs in the
74
+ * background — no request ever waits on a refetch while a usable set
75
+ * exists, so a slow or hanging issuer adds no latency.
76
+ * - Failed refreshes back off (5 s, doubling, max 5 min), measured from the
77
+ * end of the failed attempt.
78
+ * - A stale set is trusted for at most JWKS_MAX_STALE_MS past its TTL.
79
+ * - A fetched document without a single usable ES256 key is a failed fetch
80
+ * (503), never an empty key set that would refuse every token.
81
+ * - A token signed with a kid we don't know triggers one refetch at most
82
+ * every 60 s (key rotation publishes the next key in advance).
83
+ */
84
+ export declare class JwksCache {
85
+ private readonly opts;
86
+ private keys;
87
+ private expiresAt;
88
+ private lastSuccessAt;
89
+ /** End of the last fetch attempt, whatever its outcome. */
90
+ private lastCompletedAt;
91
+ /** No new attempt before this (backoff after a failure). */
92
+ private nextAttemptAt;
93
+ private consecutiveFailures;
94
+ private inflight;
95
+ private readonly fetchImpl;
96
+ private readonly now;
97
+ /** Number of network fetches started (tests / health). */
98
+ fetches: number;
99
+ failures: number;
100
+ constructor(opts: JwksCacheOptions);
101
+ /** A key set that may be used at `now`: fetched, non-empty, not stale beyond the ceiling. */
102
+ private usable;
103
+ /** The key for `kid`, undefined when the issuer does not publish it. Throws JwksUnavailableError. */
104
+ getKey(kid: string): Promise<KeyObject | undefined>;
105
+ /** Resolves once no fetch is in flight (tests). */
106
+ settled(): Promise<void>;
107
+ stats(): JwksStats;
108
+ private refresh;
109
+ private load;
110
+ private fetchKeys;
111
+ }
112
+ export interface VerifyOptions {
113
+ issuer: string;
114
+ audience: string;
115
+ jwks: JwksCache;
116
+ /** Milliseconds since the epoch. */
117
+ now?: () => number;
118
+ }
119
+ /**
120
+ * Verify an inbound MCP access token; returns its claims or throws
121
+ * InvalidTokenError (→ 401 invalid_token) / JwksUnavailableError (→ 503).
122
+ * Reasons are short and never contain token material.
123
+ */
124
+ export declare function verifyAccessToken(token: string, opts: VerifyOptions): Promise<AccessTokenClaims>;
@@ -0,0 +1,352 @@
1
+ // Local validation of inbound MCP access tokens: RFC 9068 JWTs verified
2
+ // against the authorization server's published JWKS.
3
+ //
4
+ // Deliberately no JWT library: the accepted shape is one algorithm and one
5
+ // key type, so the whole verifier is node:crypto plus explicit checks —
6
+ // nothing here can be talked into `none`, HS256-with-the-public-key, an
7
+ // embedded `jwk` / `jku` / `x5u`, or a key we did not fetch from the issuer.
8
+ import { createPublicKey, verify as cryptoVerify } from 'node:crypto';
9
+ import { readCappedText, ResponseTooLargeError } from './body.js';
10
+ import { OAUTH_SCOPE } from './config.js';
11
+ /**
12
+ * Clock skew allowed on `exp`, `iat` and `nbf`: 5 s either way, kept
13
+ * tight so this server does not accept a token the exchange then refuses as
14
+ * expired. The host must keep NTP time.
15
+ */
16
+ export const CLOCK_SKEW_S = 5;
17
+ /** JWKS lifetime bounds: `max-age` is respected, but never below 5 min or above a day. */
18
+ export const JWKS_MIN_TTL_MS = 5 * 60_000;
19
+ export const JWKS_MAX_TTL_MS = 24 * 60 * 60_000;
20
+ /**
21
+ * How long past its TTL a cached key set may still be used while the issuer
22
+ * cannot be reached. Beyond this the server answers 503 rather than
23
+ * trusting keys that may have been withdrawn during the outage.
24
+ */
25
+ export const JWKS_MAX_STALE_MS = 24 * 60 * 60_000;
26
+ /** An unknown `kid` triggers at most one JWKS refetch per this interval. */
27
+ export const JWKS_UNKNOWN_KID_REFETCH_MS = 60_000;
28
+ /**
29
+ * After a failed fetch the next attempt waits this long, measured from the
30
+ * END of the failed attempt and doubling per consecutive failure up to
31
+ * JWKS_RETRY_MAX_MS — so a hanging issuer is asked at most once per backoff
32
+ * interval, never back to back.
33
+ */
34
+ export const JWKS_RETRY_MIN_MS = 5_000;
35
+ export const JWKS_RETRY_MAX_MS = 5 * 60_000;
36
+ export const JWKS_TIMEOUT_MS = 5_000;
37
+ export const JWKS_MAX_BYTES = 64 * 1024;
38
+ export const MAX_TOKEN_LENGTH = 8192;
39
+ const B64URL = /^[A-Za-z0-9_-]+$/;
40
+ /** Three base64url segments — the shape of an access token. */
41
+ const JWT_SHAPE = /^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/;
42
+ export function looksLikeJwt(value) {
43
+ return value.length <= MAX_TOKEN_LENGTH && JWT_SHAPE.test(value);
44
+ }
45
+ /** The token was refused — answer 401 `invalid_token` with this (token-free) reason. */
46
+ export class InvalidTokenError extends Error {
47
+ constructor(reason) {
48
+ super(reason);
49
+ this.name = 'InvalidTokenError';
50
+ }
51
+ }
52
+ /** The signing keys could not be obtained — not the token's fault: answer 503. */
53
+ export class JwksUnavailableError extends Error {
54
+ constructor(reason) {
55
+ super(reason);
56
+ this.name = 'JwksUnavailableError';
57
+ }
58
+ }
59
+ /**
60
+ * The issuer's JWKS, cached per `Cache-Control: max-age` (5 min – 24 h).
61
+ *
62
+ * - Cold start (no keys yet): requests wait for the fetch (concurrent ones
63
+ * share it); a failure is a 503 for them.
64
+ * - Expired: the stale set keeps serving and ONE refresh runs in the
65
+ * background — no request ever waits on a refetch while a usable set
66
+ * exists, so a slow or hanging issuer adds no latency.
67
+ * - Failed refreshes back off (5 s, doubling, max 5 min), measured from the
68
+ * end of the failed attempt.
69
+ * - A stale set is trusted for at most JWKS_MAX_STALE_MS past its TTL.
70
+ * - A fetched document without a single usable ES256 key is a failed fetch
71
+ * (503), never an empty key set that would refuse every token.
72
+ * - A token signed with a kid we don't know triggers one refetch at most
73
+ * every 60 s (key rotation publishes the next key in advance).
74
+ */
75
+ export class JwksCache {
76
+ opts;
77
+ keys = null;
78
+ expiresAt = 0;
79
+ lastSuccessAt = -Infinity;
80
+ /** End of the last fetch attempt, whatever its outcome. */
81
+ lastCompletedAt = -Infinity;
82
+ /** No new attempt before this (backoff after a failure). */
83
+ nextAttemptAt = 0;
84
+ consecutiveFailures = 0;
85
+ inflight = null;
86
+ fetchImpl;
87
+ now;
88
+ /** Number of network fetches started (tests / health). */
89
+ fetches = 0;
90
+ failures = 0;
91
+ constructor(opts) {
92
+ this.opts = opts;
93
+ this.fetchImpl = opts.fetch ?? fetch;
94
+ this.now = opts.now ?? Date.now;
95
+ }
96
+ /** A key set that may be used at `now`: fetched, non-empty, not stale beyond the ceiling. */
97
+ usable(now) {
98
+ return !!this.keys && now < this.expiresAt + JWKS_MAX_STALE_MS;
99
+ }
100
+ /** The key for `kid`, undefined when the issuer does not publish it. Throws JwksUnavailableError. */
101
+ async getKey(kid) {
102
+ const now = this.now();
103
+ if (!this.usable(now)) {
104
+ // Nothing we may trust: this request has to wait for a fetch.
105
+ if (this.inflight || now >= this.nextAttemptAt)
106
+ await this.refresh().catch(() => { });
107
+ if (!this.usable(this.now()))
108
+ throw new JwksUnavailableError('signing keys unavailable');
109
+ }
110
+ else if (now >= this.expiresAt && !this.inflight && now >= this.nextAttemptAt) {
111
+ // Stale but usable: serve it, refresh in the background.
112
+ this.refresh().catch(() => { });
113
+ }
114
+ const keys = this.keys;
115
+ const hit = keys.get(kid);
116
+ if (hit)
117
+ return hit;
118
+ // Unknown kid: possibly a rotation we have not seen yet.
119
+ if (this.inflight) {
120
+ await this.refresh().catch(() => { });
121
+ if (this.consecutiveFailures > 0)
122
+ throw new JwksUnavailableError('signing keys unavailable');
123
+ return this.keys?.get(kid);
124
+ }
125
+ if (this.consecutiveFailures > 0) {
126
+ // The issuer is failing: we cannot tell a rotated key from a forged
127
+ // kid, and refusing the token would make every user re-authorize.
128
+ throw new JwksUnavailableError('signing keys unavailable');
129
+ }
130
+ if (this.now() - this.lastCompletedAt >= JWKS_UNKNOWN_KID_REFETCH_MS) {
131
+ try {
132
+ await this.refresh();
133
+ }
134
+ catch {
135
+ throw new JwksUnavailableError('signing keys unavailable');
136
+ }
137
+ return this.keys?.get(kid);
138
+ }
139
+ return undefined;
140
+ }
141
+ /** Resolves once no fetch is in flight (tests). */
142
+ async settled() {
143
+ while (this.inflight)
144
+ await this.inflight.catch(() => { });
145
+ }
146
+ stats() {
147
+ const now = this.now();
148
+ return {
149
+ fetches: this.fetches,
150
+ failures: this.failures,
151
+ consecutiveFailures: this.consecutiveFailures,
152
+ keys: this.keys?.size ?? 0,
153
+ stale: !!this.keys && now >= this.expiresAt,
154
+ ageSeconds: Number.isFinite(this.lastSuccessAt) ? Math.round((now - this.lastSuccessAt) / 1000) : null,
155
+ };
156
+ }
157
+ refresh() {
158
+ if (!this.inflight) {
159
+ this.inflight = this.load().finally(() => { this.inflight = null; });
160
+ }
161
+ return this.inflight;
162
+ }
163
+ async load() {
164
+ this.fetches += 1;
165
+ try {
166
+ const keys = await this.fetchKeys();
167
+ const now = this.now();
168
+ this.keys = keys.keys;
169
+ this.expiresAt = now + keys.ttlMs;
170
+ this.lastSuccessAt = now;
171
+ this.lastCompletedAt = now;
172
+ this.consecutiveFailures = 0;
173
+ this.nextAttemptAt = 0;
174
+ }
175
+ catch (err) {
176
+ const now = this.now();
177
+ this.failures += 1;
178
+ this.consecutiveFailures += 1;
179
+ this.lastCompletedAt = now;
180
+ const backoff = Math.min(JWKS_RETRY_MAX_MS, JWKS_RETRY_MIN_MS * 2 ** Math.min(this.consecutiveFailures - 1, 16));
181
+ this.nextAttemptAt = now + backoff;
182
+ const reason = err instanceof Error ? err.message : 'error';
183
+ console.error(`[lexapi-mcp] OAuth: JWKS fetch failed (${reason}); ${this.usable(now) ? 'serving the cached keys' : 'no usable keys'} — next attempt in ${Math.round(backoff / 1000)} s`);
184
+ throw err instanceof JwksUnavailableError ? err : new JwksUnavailableError(reason);
185
+ }
186
+ }
187
+ async fetchKeys() {
188
+ let res;
189
+ try {
190
+ res = await this.fetchImpl(this.opts.url, {
191
+ headers: { accept: 'application/json' },
192
+ redirect: 'error',
193
+ signal: AbortSignal.timeout(JWKS_TIMEOUT_MS),
194
+ });
195
+ }
196
+ catch (err) {
197
+ throw new JwksUnavailableError(`JWKS fetch failed (${err instanceof Error ? err.name : 'error'})`);
198
+ }
199
+ if (res.status !== 200) {
200
+ await res.body?.cancel().catch(() => { });
201
+ throw new JwksUnavailableError(`JWKS fetch answered ${res.status}`);
202
+ }
203
+ let text;
204
+ try {
205
+ text = await readCappedText(res, JWKS_MAX_BYTES);
206
+ }
207
+ catch (err) {
208
+ throw new JwksUnavailableError(err instanceof ResponseTooLargeError ? 'JWKS document too large' : 'JWKS body could not be read');
209
+ }
210
+ let doc;
211
+ try {
212
+ doc = JSON.parse(text);
213
+ }
214
+ catch {
215
+ throw new JwksUnavailableError('JWKS is not JSON');
216
+ }
217
+ const list = doc && typeof doc === 'object' ? doc.keys : undefined;
218
+ if (!Array.isArray(list))
219
+ throw new JwksUnavailableError('JWKS has no keys array');
220
+ const keys = new Map();
221
+ for (const jwk of list) {
222
+ const k = importEs256Jwk(jwk);
223
+ if (k)
224
+ keys.set(k.kid, k.key);
225
+ }
226
+ if (keys.size === 0)
227
+ throw new JwksUnavailableError('JWKS has no usable ES256 signing key');
228
+ return { keys, ttlMs: jwksTtlMs(res.headers.get('cache-control')) };
229
+ }
230
+ }
231
+ function jwksTtlMs(cacheControl) {
232
+ const m = /(?:^|,)\s*max-age\s*=\s*(\d+)/i.exec(cacheControl ?? '');
233
+ const ms = m ? Number(m[1]) * 1000 : JWKS_MIN_TTL_MS;
234
+ return Math.min(JWKS_MAX_TTL_MS, Math.max(JWKS_MIN_TTL_MS, ms));
235
+ }
236
+ /** A P-256 signing key from a JWK, or null for anything else (other kty/crv/alg/use, private parts). */
237
+ function importEs256Jwk(jwk) {
238
+ if (!jwk || typeof jwk !== 'object')
239
+ return null;
240
+ const j = jwk;
241
+ if (j.kty !== 'EC' || j.crv !== 'P-256')
242
+ return null;
243
+ if (typeof j.kid !== 'string' || !j.kid)
244
+ return null;
245
+ if (j.alg !== undefined && j.alg !== 'ES256')
246
+ return null;
247
+ if (j.use !== undefined && j.use !== 'sig')
248
+ return null;
249
+ if (typeof j.x !== 'string' || typeof j.y !== 'string' || j.d !== undefined)
250
+ return null;
251
+ try {
252
+ const key = createPublicKey({ key: { kty: 'EC', crv: 'P-256', x: j.x, y: j.y }, format: 'jwk' });
253
+ return { kid: j.kid, key };
254
+ }
255
+ catch {
256
+ return null;
257
+ }
258
+ }
259
+ /**
260
+ * The bytes of a base64url segment, refusing any non-canonical spelling
261
+ * (unused trailing bits set): one token has exactly one string form, so
262
+ * variants cannot multiply cache keys or exchanges.
263
+ */
264
+ function segmentBytes(seg) {
265
+ if (!B64URL.test(seg))
266
+ throw new InvalidTokenError('malformed token');
267
+ const bytes = Buffer.from(seg, 'base64url');
268
+ if (bytes.toString('base64url') !== seg)
269
+ throw new InvalidTokenError('malformed token');
270
+ return bytes;
271
+ }
272
+ function decodeSegment(seg) {
273
+ const bytes = segmentBytes(seg);
274
+ try {
275
+ return JSON.parse(bytes.toString('utf8'));
276
+ }
277
+ catch {
278
+ throw new InvalidTokenError('malformed token');
279
+ }
280
+ }
281
+ function nonEmptyString(v) {
282
+ return typeof v === 'string' && v.length > 0;
283
+ }
284
+ /**
285
+ * Verify an inbound MCP access token; returns its claims or throws
286
+ * InvalidTokenError (→ 401 invalid_token) / JwksUnavailableError (→ 503).
287
+ * Reasons are short and never contain token material.
288
+ */
289
+ export async function verifyAccessToken(token, opts) {
290
+ if (!looksLikeJwt(token))
291
+ throw new InvalidTokenError('malformed token');
292
+ const [h, p, s] = token.split('.');
293
+ const header = decodeSegment(h);
294
+ if (!header || typeof header !== 'object' || Array.isArray(header))
295
+ throw new InvalidTokenError('malformed token');
296
+ const hd = header;
297
+ // Exact match: JWS `alg` values are case-sensitive; none / HS* / RS* / PS* / ES384 … are all refused.
298
+ if (hd.alg !== 'ES256')
299
+ throw new InvalidTokenError('unsupported algorithm');
300
+ const typ = typeof hd.typ === 'string' ? hd.typ.toLowerCase() : '';
301
+ if (typ !== 'at+jwt' && typ !== 'application/at+jwt')
302
+ throw new InvalidTokenError('not an access token');
303
+ if (!nonEmptyString(hd.kid))
304
+ throw new InvalidTokenError('missing key id');
305
+ // We understand no critical extensions (RFC 7515 §4.1.11).
306
+ if (hd.crit !== undefined)
307
+ throw new InvalidTokenError('unsupported critical header');
308
+ const sig = segmentBytes(s);
309
+ if (sig.length !== 64)
310
+ throw new InvalidTokenError('invalid signature');
311
+ const key = await opts.jwks.getKey(hd.kid);
312
+ if (!key)
313
+ throw new InvalidTokenError('unknown signing key');
314
+ const ok = cryptoVerify('sha256', Buffer.from(`${h}.${p}`, 'ascii'), { key, dsaEncoding: 'ieee-p1363' }, sig);
315
+ if (!ok)
316
+ throw new InvalidTokenError('invalid signature');
317
+ const payload = decodeSegment(p);
318
+ if (!payload || typeof payload !== 'object' || Array.isArray(payload))
319
+ throw new InvalidTokenError('malformed token');
320
+ const c = payload;
321
+ if (c.iss !== opts.issuer)
322
+ throw new InvalidTokenError('wrong issuer');
323
+ // Exactly this resource. A token for any other audience — the LexAPI API
324
+ // audience included — is refused (no confused deputy). A one-element array
325
+ // naming only us is the same statement; a multi-audience token is not.
326
+ const aud = c.aud;
327
+ const audOk = aud === opts.audience || (Array.isArray(aud) && aud.length === 1 && aud[0] === opts.audience);
328
+ if (!audOk)
329
+ throw new InvalidTokenError('wrong audience');
330
+ const nowS = (opts.now ?? Date.now)() / 1000;
331
+ if (typeof c.exp !== 'number' || !Number.isFinite(c.exp))
332
+ throw new InvalidTokenError('missing expiry');
333
+ if (c.exp + CLOCK_SKEW_S <= nowS)
334
+ throw new InvalidTokenError('token expired');
335
+ if (typeof c.iat !== 'number' || !Number.isFinite(c.iat))
336
+ throw new InvalidTokenError('missing issued-at');
337
+ if (c.iat - CLOCK_SKEW_S > nowS)
338
+ throw new InvalidTokenError('token issued in the future');
339
+ if (c.nbf !== undefined) {
340
+ if (typeof c.nbf !== 'number' || !Number.isFinite(c.nbf))
341
+ throw new InvalidTokenError('malformed not-before');
342
+ if (c.nbf - CLOCK_SKEW_S > nowS)
343
+ throw new InvalidTokenError('token not yet valid');
344
+ }
345
+ if (typeof c.scope !== 'string' || !c.scope.split(' ').includes(OAUTH_SCOPE))
346
+ throw new InvalidTokenError('insufficient scope');
347
+ for (const name of ['sub', 'client_id', 'gid', 'sid', 'jti']) {
348
+ if (!nonEmptyString(c[name]))
349
+ throw new InvalidTokenError(`missing ${name} claim`);
350
+ }
351
+ return c;
352
+ }
@@ -0,0 +1 @@
1
+ export declare function redact(text: string, secrets?: Array<string | undefined>): string;
@@ -0,0 +1,23 @@
1
+ // Credential scrubbing for anything that is logged or shown: JWT-shaped
2
+ // strings, LexAPI API keys, opaque `lx…_` credential handles and explicitly
3
+ // named secrets are replaced before the text leaves
4
+ // the process.
5
+ const JWT_RE = /[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g;
6
+ const API_KEY_RE = /\blex_[A-Za-z0-9_]{8,}/g;
7
+ const HANDLE_RE = /\blx[a-z]{1,4}_[A-Za-z0-9_-]{8,}/g;
8
+ const BASIC_RE = /\bBasic\s+[A-Za-z0-9+/=]{8,}/gi;
9
+ const BEARER_RE = /\bBearer\s+[^\s"',;]{8,}/gi;
10
+ export function redact(text, secrets = []) {
11
+ let out = String(text);
12
+ for (const s of secrets) {
13
+ if (s && s.length >= 8)
14
+ out = out.split(s).join('[redacted]');
15
+ }
16
+ return out
17
+ .replace(BEARER_RE, 'Bearer [redacted]')
18
+ .replace(BASIC_RE, 'Basic [redacted]')
19
+ .replace(JWT_RE, '[token]')
20
+ .replace(API_KEY_RE, '[key]')
21
+ .replace(HANDLE_RE, '[token]')
22
+ .slice(0, 300);
23
+ }
@@ -0,0 +1,41 @@
1
+ import type { UpstreamAuth } from '../client.js';
2
+ import { UpstreamAuthError } from '../errors.js';
3
+ import { type ExchangeCaller, type TokenExchanger } from './exchange.js';
4
+ /**
5
+ * One per HTTP request. A tool call that hits an auth failure records it
6
+ * here; the response writer checks it before committing a status, so a
7
+ * revoked connection becomes `401 invalid_token` (what makes MCP clients
8
+ * refresh / re-authorize) instead of a 200 carrying a tool error. Once the
9
+ * status is committed (a progress or keep-alive frame went out first) the
10
+ * failure stays a tool error.
11
+ */
12
+ export declare class ResponseGate {
13
+ private first?;
14
+ fail(error: UpstreamAuthError): void;
15
+ get failure(): UpstreamAuthError | undefined;
16
+ }
17
+ /**
18
+ * Credential for one MCP request authenticated with an OAuth access token:
19
+ * exchanges it (cached per subject token) and sends the API token as
20
+ * `Authorization: Bearer` — never `x-api-key`, never the inbound token.
21
+ */
22
+ export declare class OAuthUpstreamAuth implements UpstreamAuth {
23
+ private readonly subjectToken;
24
+ private readonly subjectExpS;
25
+ private readonly exchanger;
26
+ private readonly gate?;
27
+ /** Client IP / user, for the exchanger's per-IP and per-user limits. */
28
+ private readonly caller;
29
+ private current?;
30
+ private reexchanged;
31
+ constructor(subjectToken: string, subjectExpS: number, exchanger: TokenExchanger, gate?: ResponseGate | undefined,
32
+ /** Client IP / user, for the exchanger's per-IP and per-user limits. */
33
+ caller?: ExchangeCaller);
34
+ headers(ctx: {
35
+ signal?: AbortSignal;
36
+ }): Promise<Record<string, string>>;
37
+ onUnauthorized(info: {
38
+ wwwAuthenticate: string | null;
39
+ body: string;
40
+ }): 'retry' | Error;
41
+ }
@@ -0,0 +1,95 @@
1
+ // The per-request OAuth credential of the hosted server and the gate that turns an auth failure discovered during a
2
+ // tool call into the HTTP status the MCP client must see.
3
+ import { UpstreamAuthError } from '../errors.js';
4
+ import { ExchangeError } from './exchange.js';
5
+ /**
6
+ * One per HTTP request. A tool call that hits an auth failure records it
7
+ * here; the response writer checks it before committing a status, so a
8
+ * revoked connection becomes `401 invalid_token` (what makes MCP clients
9
+ * refresh / re-authorize) instead of a 200 carrying a tool error. Once the
10
+ * status is committed (a progress or keep-alive frame went out first) the
11
+ * failure stays a tool error.
12
+ */
13
+ export class ResponseGate {
14
+ first;
15
+ fail(error) {
16
+ if (!this.first)
17
+ this.first = error;
18
+ }
19
+ get failure() {
20
+ return this.first;
21
+ }
22
+ }
23
+ const EXCHANGE_STATUS = {
24
+ invalid_token: 401,
25
+ config: 500,
26
+ client_auth: 503,
27
+ unavailable: 503,
28
+ rate_limited: 429,
29
+ upstream: 502,
30
+ };
31
+ /**
32
+ * The exchange failures that answer the MCP client with an HTTP status while the
33
+ * response is not committed yet (after commit every failure is a tool
34
+ * error). 429 and 502 stay tool errors: a model
35
+ * can act on "wait N s" / "retry later", an HTTP error only aborts the call.
36
+ */
37
+ const GATED = new Set(['invalid_token', 'config', 'client_auth', 'unavailable']);
38
+ /** `error="invalid_token"` in a WWW-Authenticate challenge (quoted or not). */
39
+ function isInvalidTokenChallenge(www) {
40
+ return !!www && /\berror\s*=\s*"?invalid_token"?/i.test(www);
41
+ }
42
+ /**
43
+ * Credential for one MCP request authenticated with an OAuth access token:
44
+ * exchanges it (cached per subject token) and sends the API token as
45
+ * `Authorization: Bearer` — never `x-api-key`, never the inbound token.
46
+ */
47
+ export class OAuthUpstreamAuth {
48
+ subjectToken;
49
+ subjectExpS;
50
+ exchanger;
51
+ gate;
52
+ caller;
53
+ current;
54
+ reexchanged = false;
55
+ constructor(subjectToken, subjectExpS, exchanger, gate,
56
+ /** Client IP / user, for the exchanger's per-IP and per-user limits. */
57
+ caller = {}) {
58
+ this.subjectToken = subjectToken;
59
+ this.subjectExpS = subjectExpS;
60
+ this.exchanger = exchanger;
61
+ this.gate = gate;
62
+ this.caller = caller;
63
+ }
64
+ async headers(ctx) {
65
+ try {
66
+ this.current = await this.exchanger.getApiToken(this.subjectToken, this.subjectExpS, ctx.signal, this.caller);
67
+ }
68
+ catch (err) {
69
+ if (err instanceof ExchangeError) {
70
+ const e = new UpstreamAuthError(err.kind, EXCHANGE_STATUS[err.kind], err.description, err.retryAfterSeconds);
71
+ if (GATED.has(err.kind))
72
+ this.gate?.fail(e);
73
+ throw e;
74
+ }
75
+ throw err;
76
+ }
77
+ return { authorization: `Bearer ${this.current}` };
78
+ }
79
+ onUnauthorized(info) {
80
+ const invalidToken = isInvalidTokenChallenge(info.wwwAuthenticate) || /"error"\s*:\s*"Invalid access token"/.test(info.body);
81
+ if (invalidToken && !this.reexchanged) {
82
+ // The API token expired or the connection was revoked since the
83
+ // exchange: drop it and exchange once more. A revoked grant
84
+ // makes that exchange answer 400 → 401 invalid_token above.
85
+ this.reexchanged = true;
86
+ this.exchanger.invalidate(this.subjectToken, this.current);
87
+ return 'retry';
88
+ }
89
+ // A freshly exchanged token refused again, or a 401 that is not a token
90
+ // verdict: a server-side problem, not something re-authorizing fixes —
91
+ // a tool error (never a 401 to the MCP client) and a log line.
92
+ console.error(`[lexapi-mcp] OAUTH: LexAPI API refused an exchanged token${this.reexchanged ? ' twice' : ''} (${invalidToken ? 'invalid_token' : 'no invalid_token challenge'}) — check the OAuth configuration`);
93
+ return new UpstreamAuthError('api_rejected', 502, 'the LexAPI API did not accept the exchanged token');
94
+ }
95
+ }