@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.
@@ -0,0 +1,573 @@
1
+ // RFC 8693 token exchange at the authorization server's token endpoint: the
2
+ // inbound MCP-audience token is traded for a short-lived API-audience token.
3
+ // The inbound token itself is never sent to the REST API (no passthrough).
4
+ //
5
+ // The exchange budget is shared by every user of this server, so nothing a
6
+ // single caller does may spend it freely:
7
+ // - a subject token LexAPI refused is remembered until it expires (negative
8
+ // cache): replaying it costs nothing upstream;
9
+ // - per subject token, per user (`sub`) and per client IP, the number of
10
+ // exchanges / refusals is bounded locally; every NEW exchange of a user,
11
+ // successful or refused, counts against a per-user cap, so minting
12
+ // fresh tokens cannot spend the budget faster than that;
13
+ // - when the server answers 429 / 503 temporarily_unavailable, the user's new
14
+ // exchanges wait out its Retry-After (with backoff); when the slow-down is
15
+ // global (see slowDown()) every new exchange waits and then ONE probe goes
16
+ // first, so recovery does not stampede.
17
+ import { createHash } from 'node:crypto';
18
+ import { readCappedText } from './body.js';
19
+ import { DEFAULT_EXCHANGES_PER_USER_PER_MIN } from './config.js';
20
+ import { CLOCK_SKEW_S } from './jwt.js';
21
+ import { redact } from './redact.js';
22
+ export const TOKEN_EXCHANGE_GRANT = 'urn:ietf:params:oauth:grant-type:token-exchange';
23
+ export const ACCESS_TOKEN_TYPE = 'urn:ietf:params:oauth:token-type:access_token';
24
+ /** A cached API token is dropped this long before its `exp`. */
25
+ export const EXPIRY_MARGIN_MS = 30_000;
26
+ export const DEFAULT_MAX_ENTRIES = 10_000;
27
+ /**
28
+ * One exchange (both attempts, the backoff between them included) never
29
+ * takes longer than this: under the first progress frame (10 s) and the SSE
30
+ * keep-alive (15 s), so a refusal found by the exchange is still answered
31
+ * with its HTTP status rather than as a tool error after the 200.
32
+ */
33
+ export const EXCHANGE_DEADLINE_MS = 9_000;
34
+ const ATTEMPT_TIMEOUT_MS = 6_000;
35
+ const MIN_RETRY_WINDOW_MS = 1_500;
36
+ const RETRY_BACKOFF_MS = 300;
37
+ const MAX_RESPONSE_BYTES = 16 * 1024;
38
+ /** Local limits. Windows are fixed, one minute unless stated. */
39
+ export const LIMITS = {
40
+ /** Exchanges started for one subject token per minute (normal use: one per ~4.5 min, two after an API 401). */
41
+ perTokenPerMin: 6,
42
+ /**
43
+ * Exchanges LexAPI refused (user-token rejections) per client IP per minute;
44
+ * past it, accounts with a recent refusal of their own are cut off from that
45
+ * address (never an account with a clean record).
46
+ */
47
+ refusedPerIpPerMin: 30,
48
+ /** …and per user (`sub`) per 10 minutes. */
49
+ refusedPerSubPer10Min: 10,
50
+ /**
51
+ * NEW exchanges started for one user (`sub`) per minute, successful or
52
+ * refused (LEXAPI_MCP_EXCHANGES_PER_USER_PER_MIN). Normal use is one
53
+ * per connection every ~4.5 min; cached tokens never count.
54
+ */
55
+ exchangesPerSubPerMin: DEFAULT_EXCHANGES_PER_USER_PER_MIN,
56
+ /**
57
+ * A slow-down (429 / 503 temporarily_unavailable) is treated as about one
58
+ * user until this many distinct users got one within a minute: then it is
59
+ * global, and every new exchange waits.
60
+ */
61
+ slowDownGlobalAfterUsers: 3,
62
+ /** Backoff after a 429 / 503 temporarily_unavailable: doubles per consecutive one; Retry-After is a floor. */
63
+ throttleMinMs: 1_000,
64
+ throttleMaxMs: 5 * 60_000,
65
+ /** A refusal is remembered no longer than this (the subject's `exp` normally ends it sooner). */
66
+ negativeMaxMs: 60 * 60_000,
67
+ };
68
+ /**
69
+ * How the token endpoint says "the subject token is not usable" (revoked,
70
+ * expired …): `400 invalid_request` whose description begins with exactly
71
+ * this prefix (RFC 8693 §2.2.2 leaves no distinct error code). Only this is
72
+ * the USER's problem (→ 401 invalid_token, refresh / re-authorize); every
73
+ * other 400 means our
74
+ * exchange request is wrong (→ 500, logged, counted) — mapping those to 401
75
+ * would push every user into a re-auth loop while hiding the bug.
76
+ */
77
+ export const SUBJECT_REJECTED_PREFIX = 'subject_token rejected: ';
78
+ /** After refused client authentication, slow-downs are treated as global for this long. */
79
+ const CLIENT_AUTH_GLOBAL_MS = 15 * 60_000;
80
+ export class ExchangeError extends Error {
81
+ kind;
82
+ description;
83
+ retryAfterSeconds;
84
+ constructor(kind,
85
+ /** Token-free description (the AS's error_description, or ours). */
86
+ description, retryAfterSeconds) {
87
+ super(`token exchange failed: ${kind}`);
88
+ this.kind = kind;
89
+ this.description = description;
90
+ this.retryAfterSeconds = retryAfterSeconds;
91
+ this.name = 'ExchangeError';
92
+ }
93
+ }
94
+ /** application/x-www-form-urlencoded encoding of a Basic credential part (RFC 6749 §2.3.1). */
95
+ function formEncode(s) {
96
+ return encodeURIComponent(s).replace(/%20/g, '+');
97
+ }
98
+ /**
99
+ * Cache key of a subject token: sha256 of its signed part (`header.payload`),
100
+ * never the token itself. The signature segment is left out on purpose: an
101
+ * ECDSA signature has a second valid form (s → n − s) for the same signed
102
+ * bytes, so keying on the whole
103
+ * string would let one token occupy two entries. Two tokens with the same
104
+ * signed part ARE the same token. Only used on tokens that passed local
105
+ * signature verification.
106
+ */
107
+ export function subjectKey(subjectToken) {
108
+ const parts = subjectToken.split('.');
109
+ const signed = parts.length === 3 ? `${parts[0]}.${parts[1]}` : subjectToken;
110
+ return createHash('sha256').update(signed).digest('base64url');
111
+ }
112
+ /** A fixed-window counter per key, bounded in size (oldest windows dropped first). */
113
+ class WindowCounter {
114
+ windowMs;
115
+ maxKeys;
116
+ windows = new Map();
117
+ constructor(windowMs, maxKeys) {
118
+ this.windowMs = windowMs;
119
+ this.maxKeys = maxKeys;
120
+ }
121
+ count(key, now) {
122
+ const w = this.windows.get(key);
123
+ return w && now < w.resetAt ? w.count : 0;
124
+ }
125
+ retryAfterS(key, now) {
126
+ const w = this.windows.get(key);
127
+ return w && now < w.resetAt ? Math.max(1, Math.ceil((w.resetAt - now) / 1000)) : 1;
128
+ }
129
+ hit(key, now) {
130
+ let w = this.windows.get(key);
131
+ if (!w || now >= w.resetAt) {
132
+ this.windows.delete(key);
133
+ w = { count: 0, resetAt: now + this.windowMs };
134
+ }
135
+ w.count += 1;
136
+ this.windows.set(key, w);
137
+ while (this.windows.size > this.maxKeys) {
138
+ const oldest = this.windows.keys().next().value;
139
+ if (oldest === undefined)
140
+ break;
141
+ this.windows.delete(oldest);
142
+ }
143
+ }
144
+ }
145
+ /**
146
+ * Exchanges subject tokens and caches the resulting API tokens per subject
147
+ * token until 30 s before they expire, in a bounded in-memory LRU; refused
148
+ * subject tokens are remembered until they expire. Concurrent requests
149
+ * carrying the same subject token share one exchange. Nothing is persisted
150
+ * or logged.
151
+ */
152
+ export class TokenExchanger {
153
+ opts;
154
+ cache = new Map();
155
+ refused = new Map();
156
+ inflight = new Map();
157
+ fetchImpl;
158
+ now;
159
+ sleep;
160
+ maxEntries;
161
+ basic;
162
+ limits;
163
+ perToken;
164
+ refusedPerIp;
165
+ refusedPerSub;
166
+ exchangesPerSub;
167
+ /** Backoff after a 429 / 503 temporarily_unavailable, for everyone. */
168
+ throttle = { until: 0, kind: 'rate_limited', consecutive: 0, probing: false };
169
+ /** …or for one user (`sub`): only that user's new exchanges wait. Bounded, oldest first. */
170
+ subThrottle = new Map();
171
+ /** Users slowed down in the last minute (sub → expiry), to tell a per-user slow-down from a global one. */
172
+ slowedSubs = new Map();
173
+ counters = {
174
+ requests: 0, succeeded: 0, userTokenRejected: 0, negativeCacheHits: 0, configErrors: 0,
175
+ clientAuthErrors: 0, rateLimited: 0, unavailable: 0, upstreamErrors: 0, locallyLimited: 0,
176
+ };
177
+ loud = new LoudLog();
178
+ lastClientAuthFailureAt = -Infinity;
179
+ constructor(opts) {
180
+ this.opts = opts;
181
+ this.fetchImpl = opts.fetch ?? fetch;
182
+ this.now = opts.now ?? Date.now;
183
+ this.sleep = opts.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms)));
184
+ this.maxEntries = Math.max(1, opts.maxEntries ?? DEFAULT_MAX_ENTRIES);
185
+ this.limits = { ...LIMITS, ...(opts.limits ?? {}) };
186
+ this.basic = `Basic ${Buffer.from(`${formEncode(opts.clientId)}:${formEncode(opts.clientSecret)}`).toString('base64')}`;
187
+ this.perToken = new WindowCounter(60_000, this.maxEntries);
188
+ this.refusedPerIp = new WindowCounter(60_000, this.maxEntries);
189
+ this.refusedPerSub = new WindowCounter(10 * 60_000, this.maxEntries);
190
+ this.exchangesPerSub = new WindowCounter(60_000, this.maxEntries);
191
+ }
192
+ get size() {
193
+ return this.cache.size;
194
+ }
195
+ get negativeSize() {
196
+ return this.refused.size;
197
+ }
198
+ /** Requests sent to the token endpoint, retries included. */
199
+ get exchanges() {
200
+ return this.counters.requests;
201
+ }
202
+ stats() {
203
+ const now = this.now();
204
+ return {
205
+ ...this.counters,
206
+ cacheSize: this.cache.size,
207
+ negativeCacheSize: this.refused.size,
208
+ backoffSeconds: now < this.throttle.until ? Math.ceil((this.throttle.until - now) / 1000) : 0,
209
+ usersBackingOff: [...this.subThrottle.values()].filter((st) => now < st.until).length,
210
+ };
211
+ }
212
+ /**
213
+ * An API token for this subject token: cached, or exchanged now.
214
+ * `subjectExpS` (the subject's `exp`) caps both caches. Throws
215
+ * ExchangeError; aborts with `signal` (the shared exchange keeps running
216
+ * for other waiters).
217
+ */
218
+ async getApiToken(subjectToken, subjectExpS, signal, caller = {}) {
219
+ const key = subjectKey(subjectToken);
220
+ const now = this.now();
221
+ const hit = this.cache.get(key);
222
+ if (hit) {
223
+ if (now < hit.useUntil) {
224
+ // LRU touch.
225
+ this.cache.delete(key);
226
+ this.cache.set(key, hit);
227
+ return hit.token;
228
+ }
229
+ this.cache.delete(key);
230
+ }
231
+ const no = this.refused.get(key);
232
+ if (no) {
233
+ if (now < no.until) {
234
+ this.counters.negativeCacheHits += 1;
235
+ throw new ExchangeError('invalid_token', no.description);
236
+ }
237
+ this.refused.delete(key);
238
+ }
239
+ let p = this.inflight.get(key);
240
+ if (!p) {
241
+ this.admit(key, now, caller);
242
+ p = this.exchange(subjectToken, subjectExpS, key, caller).finally(() => this.inflight.delete(key));
243
+ this.inflight.set(key, p);
244
+ }
245
+ const entry = await raceAbort(p, signal);
246
+ return entry.token;
247
+ }
248
+ /**
249
+ * Forget the cached API token of this subject after the API refused it
250
+ * (401 invalid_token) — only if it is still the one that was refused, so
251
+ * a fresher token another request just obtained survives.
252
+ */
253
+ invalidate(subjectToken, apiToken) {
254
+ const key = subjectKey(subjectToken);
255
+ const hit = this.cache.get(key);
256
+ if (hit && (apiToken === undefined || hit.token === apiToken))
257
+ this.cache.delete(key);
258
+ }
259
+ /** Local limits before a NEW exchange is started; throws a rate_limited ExchangeError. */
260
+ admit(key, now, caller) {
261
+ const refuse = (description, retryAfterS) => {
262
+ this.counters.locallyLimited += 1;
263
+ throw new ExchangeError('rate_limited', description, retryAfterS);
264
+ };
265
+ const t = this.throttle;
266
+ if (now < t.until) {
267
+ this.counters.locallyLimited += 1;
268
+ throw new ExchangeError(t.kind, 'LexAPI sign-in asked this server to slow down', Math.ceil((t.until - now) / 1000));
269
+ }
270
+ // Backoff over: one probe at a time until the server answers normally again.
271
+ if (t.consecutive > 0 && t.probing)
272
+ refuse('LexAPI sign-in is recovering from a rate limit', 1);
273
+ // This user only was slowed down: their new exchanges wait, nobody else's.
274
+ const st = caller.sub ? this.subThrottle.get(caller.sub) : undefined;
275
+ if (st && now < st.until) {
276
+ this.counters.locallyLimited += 1;
277
+ throw new ExchangeError(st.kind, 'LexAPI sign-in asked this server to slow down for this account', Math.ceil((st.until - now) / 1000));
278
+ }
279
+ if (this.perToken.count(key, now) >= this.limits.perTokenPerMin) {
280
+ refuse('too many sign-in checks for this connection', this.perToken.retryAfterS(key, now));
281
+ }
282
+ // The per-address limit only ever stops an account that has ALREADY been
283
+ // refused recently: many users can share one address (a hosted
284
+ // client's egress, a corporate NAT, or everyone when
285
+ // LEXAPI_MCP_TRUST_PROXY_HOPS is wrong), so a flood of refusals from an
286
+ // address must never block a user with a clean record there. A flood is
287
+ // still throttled: once the address is over its limit, every account
288
+ // that has been refused gets no further exchange until the window ends,
289
+ // so each attacker account costs at most one exchange per window.
290
+ const subRefused = caller.sub ? this.refusedPerSub.count(caller.sub, now) : 0;
291
+ if (caller.ip && subRefused > 0 && this.refusedPerIp.count(caller.ip, now) >= this.limits.refusedPerIpPerMin) {
292
+ refuse('too many refused sign-ins from this address', this.refusedPerIp.retryAfterS(caller.ip, now));
293
+ }
294
+ if (caller.sub && subRefused >= this.limits.refusedPerSubPer10Min) {
295
+ refuse('too many refused sign-ins for this account', this.refusedPerSub.retryAfterS(caller.sub, now));
296
+ }
297
+ // Every new exchange of a user counts, successful or refused: a
298
+ // clean account minting fresh tokens costs at most this many a minute.
299
+ if (caller.sub && this.exchangesPerSub.count(caller.sub, now) >= this.limits.exchangesPerSubPerMin) {
300
+ refuse(`too many new sign-ins for this account (at most ${this.limits.exchangesPerSubPerMin} a minute)`, this.exchangesPerSub.retryAfterS(caller.sub, now));
301
+ }
302
+ this.perToken.hit(key, now);
303
+ if (caller.sub)
304
+ this.exchangesPerSub.hit(caller.sub, now);
305
+ if (t.consecutive > 0)
306
+ t.probing = true;
307
+ }
308
+ store(key, entry) {
309
+ this.cache.delete(key);
310
+ this.cache.set(key, entry);
311
+ while (this.cache.size > this.maxEntries) {
312
+ const oldest = this.cache.keys().next().value;
313
+ if (oldest === undefined)
314
+ break;
315
+ this.cache.delete(oldest);
316
+ }
317
+ }
318
+ remember(key, refusal) {
319
+ this.refused.delete(key);
320
+ this.refused.set(key, refusal);
321
+ while (this.refused.size > this.maxEntries) {
322
+ const oldest = this.refused.keys().next().value;
323
+ if (oldest === undefined)
324
+ break;
325
+ this.refused.delete(oldest);
326
+ }
327
+ }
328
+ async exchange(subjectToken, subjectExpS, key, caller) {
329
+ let settledNormally = false;
330
+ try {
331
+ const entry = await this.attempts(subjectToken, subjectExpS, key, caller);
332
+ settledNormally = true;
333
+ return entry;
334
+ }
335
+ catch (err) {
336
+ settledNormally = !(err instanceof ExchangeError && (err.kind === 'rate_limited' || err.kind === 'unavailable'));
337
+ throw err;
338
+ }
339
+ finally {
340
+ if (this.throttle.probing) {
341
+ this.throttle.probing = false;
342
+ // The server answered something other than "slow down": the backoff is over.
343
+ if (settledNormally)
344
+ this.throttle.consecutive = 0;
345
+ }
346
+ if (settledNormally && caller.sub)
347
+ this.subThrottle.delete(caller.sub);
348
+ }
349
+ }
350
+ /** How long to hold back after the `consecutive`-th slow-down in a row: doubling, Retry-After as a floor. */
351
+ holdMs(consecutive, retryAfterS) {
352
+ const backoff = Math.min(this.limits.throttleMaxMs, this.limits.throttleMinMs * 2 ** Math.min(consecutive - 1, 16));
353
+ const floor = retryAfterS !== undefined ? Math.min(this.limits.throttleMaxMs, retryAfterS * 1000) : 0;
354
+ return Math.max(backoff, floor);
355
+ }
356
+ /** Hold every new exchange back (a global slow-down). */
357
+ backOff(kind, retryAfterS, now = this.now()) {
358
+ const t = this.throttle;
359
+ t.consecutive += 1;
360
+ t.until = now + this.holdMs(t.consecutive, retryAfterS);
361
+ t.kind = kind;
362
+ }
363
+ /**
364
+ * The token endpoint answered 429 / 503 `temporarily_unavailable`
365
+ * (+ Retry-After). Returns the seconds the caller must wait and whether it
366
+ * was global.
367
+ *
368
+ * The answer alone does not say whether it concerns one user or everyone.
369
+ * The rule: a slow-down is about THIS user — only their new
370
+ * exchanges wait, other users carry on — unless it is clearly global:
371
+ * - no user is known for the exchange;
372
+ * - it follows refused client authentication (that affects every user);
373
+ * - `slowDownGlobalAfterUsers` distinct users were slowed down within a
374
+ * minute.
375
+ * A global slow-down holds every new exchange back, then lets one probe go
376
+ * first (as before). Either way the answer is a 429 / 503, never a re-auth.
377
+ */
378
+ slowDown(kind, retryAfterS, caller) {
379
+ const now = this.now();
380
+ let global = !caller.sub || Date.now() - this.lastClientAuthFailureAt < CLIENT_AUTH_GLOBAL_MS;
381
+ if (caller.sub && !global) {
382
+ this.slowedSubs.delete(caller.sub);
383
+ this.slowedSubs.set(caller.sub, now + 60_000);
384
+ for (const [s, until] of this.slowedSubs) {
385
+ if (until > now && this.slowedSubs.size <= this.maxEntries)
386
+ break;
387
+ this.slowedSubs.delete(s);
388
+ }
389
+ global = this.slowedSubs.size >= this.limits.slowDownGlobalAfterUsers;
390
+ }
391
+ if (global) {
392
+ this.backOff(kind, retryAfterS, now);
393
+ return { waitS: Math.ceil((this.throttle.until - now) / 1000), global };
394
+ }
395
+ const sub = caller.sub;
396
+ const consecutive = (this.subThrottle.get(sub)?.consecutive ?? 0) + 1;
397
+ const until = now + this.holdMs(consecutive, retryAfterS);
398
+ this.subThrottle.delete(sub);
399
+ this.subThrottle.set(sub, { until, kind, consecutive });
400
+ while (this.subThrottle.size > this.maxEntries) {
401
+ const oldest = this.subThrottle.keys().next().value;
402
+ if (oldest === undefined)
403
+ break;
404
+ this.subThrottle.delete(oldest);
405
+ }
406
+ return { waitS: Math.ceil((until - now) / 1000), global };
407
+ }
408
+ async attempts(subjectToken, subjectExpS, key, caller) {
409
+ const body = new URLSearchParams({
410
+ grant_type: TOKEN_EXCHANGE_GRANT,
411
+ subject_token: subjectToken,
412
+ subject_token_type: ACCESS_TOKEN_TYPE,
413
+ requested_token_type: ACCESS_TOKEN_TYPE,
414
+ resource: this.opts.apiAudience,
415
+ }).toString();
416
+ const deadline = Date.now() + (this.opts.deadlineMs ?? EXCHANGE_DEADLINE_MS);
417
+ for (let attempt = 0;; attempt++) {
418
+ const remaining = () => deadline - Date.now();
419
+ const canRetry = () => attempt === 0 && remaining() - RETRY_BACKOFF_MS >= MIN_RETRY_WINDOW_MS;
420
+ let res;
421
+ this.counters.requests += 1;
422
+ try {
423
+ res = await this.fetchImpl(this.opts.tokenEndpoint, {
424
+ method: 'POST',
425
+ headers: {
426
+ authorization: this.basic,
427
+ 'content-type': 'application/x-www-form-urlencoded',
428
+ accept: 'application/json',
429
+ },
430
+ body,
431
+ redirect: 'error',
432
+ signal: AbortSignal.timeout(Math.max(1, Math.min(ATTEMPT_TIMEOUT_MS, remaining()))),
433
+ });
434
+ }
435
+ catch (err) {
436
+ if (canRetry()) {
437
+ await this.sleep(RETRY_BACKOFF_MS);
438
+ continue;
439
+ }
440
+ this.counters.upstreamErrors += 1;
441
+ // Runtime messages can quote request data: report the class only.
442
+ throw new ExchangeError('upstream', `the authorization server could not be reached (${err instanceof Error ? err.name : 'error'})`);
443
+ }
444
+ const text = await readCappedText(res, MAX_RESPONSE_BYTES).catch(() => '');
445
+ const json = safeJson(text);
446
+ const err = typeof json?.error === 'string' ? json.error : undefined;
447
+ const rawDesc = typeof json?.error_description === 'string' ? json.error_description : '';
448
+ const desc = redact(rawDesc || err || `HTTP ${res.status}`, [subjectToken, this.opts.clientSecret]);
449
+ if (res.status === 200) {
450
+ const token = json?.access_token;
451
+ const type = json?.token_type;
452
+ const expiresIn = json?.expires_in;
453
+ if (typeof token !== 'string' || !token || typeof type !== 'string' || type.toLowerCase() !== 'bearer') {
454
+ this.counters.upstreamErrors += 1;
455
+ throw new ExchangeError('upstream', 'the authorization server returned a malformed token response');
456
+ }
457
+ this.counters.succeeded += 1;
458
+ const now = this.now();
459
+ // Honour expires_in (may be well under 300 s) and never outlive the subject token.
460
+ const expMs = Math.min(typeof expiresIn === 'number' && Number.isFinite(expiresIn) && expiresIn > 0 ? now + expiresIn * 1000 : now, subjectExpS * 1000);
461
+ const entry = { token, useUntil: expMs - EXPIRY_MARGIN_MS };
462
+ // Too close to expiry to cache: this call uses it, the next one exchanges again.
463
+ if (entry.useUntil > now)
464
+ this.store(key, entry);
465
+ return entry;
466
+ }
467
+ if (res.status === 400) {
468
+ if (err === 'invalid_request' && rawDesc.startsWith(SUBJECT_REJECTED_PREFIX)) {
469
+ // The user's token is no longer usable — and never will be again:
470
+ // remember it until it expires, so replaying it costs nothing upstream.
471
+ this.counters.userTokenRejected += 1;
472
+ const now = this.now();
473
+ const until = Math.min(now + this.limits.negativeMaxMs, Math.max(now + 1_000, (subjectExpS + CLOCK_SKEW_S) * 1000));
474
+ this.remember(key, { description: desc, until });
475
+ if (caller.ip)
476
+ this.refusedPerIp.hit(caller.ip, now);
477
+ if (caller.sub)
478
+ this.refusedPerSub.hit(caller.sub, now);
479
+ throw new ExchangeError('invalid_token', desc);
480
+ }
481
+ this.counters.configErrors += 1;
482
+ this.loud.log('config', `token exchange refused our request (${err ?? 'HTTP 400'}): ${desc} — this is a bug or misconfiguration on this server, not the user's token`);
483
+ throw new ExchangeError('config', desc);
484
+ }
485
+ if (res.status === 401 || res.status === 403) {
486
+ this.counters.clientAuthErrors += 1;
487
+ this.lastClientAuthFailureAt = Date.now();
488
+ this.loud.log('client_auth', `token exchange: client authentication refused (${err ?? `HTTP ${res.status}`}): ${desc} — check LEXAPI_OAUTH_CLIENT_ID / LEXAPI_OAUTH_CLIENT_SECRET `);
489
+ throw new ExchangeError('client_auth', desc);
490
+ }
491
+ if (res.status === 429) {
492
+ // `temporarily_unavailable` (RFC 6749) or `rate_limited`, with Retry-After.
493
+ this.counters.rateLimited += 1;
494
+ const ra = retryAfterSeconds(res.headers.get('retry-after'));
495
+ const { waitS, global } = this.slowDown('rate_limited', ra, caller);
496
+ // Right after refused client authentication a 429 most likely has the
497
+ // same cause: say so, or a wrong secret looks like load.
498
+ const authHint = Date.now() - this.lastClientAuthFailureAt < CLIENT_AUTH_GLOBAL_MS
499
+ ? ' — this follows refused client authentication: check LEXAPI_OAUTH_CLIENT_SECRET'
500
+ : '';
501
+ // A per-user slow-down is not an operator problem; a global one is.
502
+ if (global)
503
+ this.loud.log('rate_limited', `token exchange rate limited (${err ?? 'HTTP 429'}); holding new exchanges back for ${waitS} s${authHint}`);
504
+ throw new ExchangeError('rate_limited', desc, waitS);
505
+ }
506
+ if (res.status === 503 && err === 'temporarily_unavailable') {
507
+ this.counters.unavailable += 1;
508
+ const { waitS, global } = this.slowDown('unavailable', retryAfterSeconds(res.headers.get('retry-after')), caller);
509
+ if (global)
510
+ this.loud.log('unavailable', `token exchange: sign-in temporarily unavailable: ${desc}`);
511
+ throw new ExchangeError('unavailable', desc, waitS);
512
+ }
513
+ if (res.status >= 500 && canRetry()) {
514
+ await this.sleep(RETRY_BACKOFF_MS);
515
+ continue;
516
+ }
517
+ this.counters.upstreamErrors += 1;
518
+ throw new ExchangeError('upstream', `the authorization server answered ${res.status}`);
519
+ }
520
+ }
521
+ }
522
+ /** Loud, scrubbed operator log lines — at most one per kind per 10 s, with a count of the ones held back. */
523
+ class LoudLog {
524
+ last = new Map();
525
+ log(kind, message) {
526
+ const now = Date.now();
527
+ const l = this.last.get(kind);
528
+ if (l && now - l.at < 10_000) {
529
+ l.suppressed += 1;
530
+ return;
531
+ }
532
+ const extra = l?.suppressed ? ` (+${l.suppressed} more since the last report)` : '';
533
+ this.last.set(kind, { at: now, suppressed: 0 });
534
+ console.error(`[lexapi-mcp] OAUTH CONFIGURATION PROBLEM: ${message}${extra}`);
535
+ }
536
+ }
537
+ function safeJson(text) {
538
+ if (!text)
539
+ return undefined;
540
+ try {
541
+ const j = JSON.parse(text);
542
+ return j && typeof j === 'object' && !Array.isArray(j) ? j : undefined;
543
+ }
544
+ catch {
545
+ return undefined;
546
+ }
547
+ }
548
+ function retryAfterSeconds(raw) {
549
+ if (!raw)
550
+ return undefined;
551
+ const n = Number(raw);
552
+ if (Number.isFinite(n) && n >= 0)
553
+ return Math.ceil(n);
554
+ const date = Date.parse(raw);
555
+ return Number.isNaN(date) ? undefined : Math.max(0, Math.ceil((date - Date.now()) / 1000));
556
+ }
557
+ /** Waits for `p`, or rejects as soon as `signal` aborts (without cancelling `p`). */
558
+ function raceAbort(p, signal) {
559
+ if (!signal)
560
+ return p;
561
+ if (signal.aborted)
562
+ return Promise.reject(abortError());
563
+ return new Promise((resolve, reject) => {
564
+ const onAbort = () => reject(abortError());
565
+ signal.addEventListener('abort', onAbort, { once: true });
566
+ p.then((v) => { signal.removeEventListener('abort', onAbort); resolve(v); }, (e) => { signal.removeEventListener('abort', onAbort); reject(e); });
567
+ });
568
+ }
569
+ function abortError() {
570
+ const e = new Error('aborted');
571
+ e.name = 'AbortError';
572
+ return e;
573
+ }