mcp-compress-router 3.2.0 → 3.2.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/cli/add-command.js +18 -10
- package/build/cli/config-io.js +141 -30
- package/build/cli/login-command.js +4 -0
- package/build/cli/remove-command.js +9 -3
- package/build/cli/tools-command.js +2 -2
- package/build/services/auth-retry-fetch.js +116 -0
- package/build/services/auth-status.js +25 -14
- package/build/services/credential-binding.js +112 -0
- package/build/services/discovery.js +13 -4
- package/build/services/index.js +1 -0
- package/build/services/oauth-discovery.js +156 -54
- package/build/services/oauth-token-refresh.js +133 -0
- package/build/services/oauth.js +325 -134
- package/build/services/server-connection.js +2 -4
- package/build/utils/file-lock.js +167 -0
- package/build/utils/index.js +1 -0
- package/build/utils/open-browser.js +9 -7
- package/package.json +2 -1
package/build/services/oauth.js
CHANGED
|
@@ -1,45 +1,25 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
1
|
+
import { mutateCredentials, readCredentials, withRefreshLock } from '../cli/config-io.js';
|
|
2
|
+
import { bindingFieldsFor, credentialsUsableFor } from './credential-binding.js';
|
|
3
|
+
import { computeExpiresAt, dueRefreshToken, requestTokenRefresh, tokensNeedInvalidation, } from './oauth-token-refresh.js';
|
|
4
4
|
import { GuidedAuthError } from './index.js';
|
|
5
5
|
/**
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
* not expire in the gap between the refresh check and the request.
|
|
11
|
-
*/
|
|
12
|
-
const REFRESH_BUFFER_MS = 60_000;
|
|
13
|
-
/**
|
|
14
|
-
* Computes the absolute ISO-8601 expiry timestamp from a relative
|
|
15
|
-
* `expires_in` (seconds from now). Returns `undefined` when the TTL
|
|
16
|
-
* is absent or non-finite, so callers can skip proactive refresh for
|
|
17
|
-
* tokens that never expire or carry no expiry information.
|
|
6
|
+
* Base auth-failure backoff window, in milliseconds. After a 401
|
|
7
|
+
* survives an adopted or freshly refreshed access token, the provider
|
|
8
|
+
* refuses further refreshes for a jittered multiple of this window so
|
|
9
|
+
* a server that keeps rejecting tokens cannot drive a refresh loop.
|
|
18
10
|
*
|
|
19
|
-
* @
|
|
20
|
-
* @returns Absolute expiry timestamp, or undefined.
|
|
11
|
+
* @internal Exported for tests only; not part of the public module API.
|
|
21
12
|
*/
|
|
22
|
-
|
|
23
|
-
if (expiresIn === undefined || !Number.isFinite(expiresIn)) {
|
|
24
|
-
return undefined;
|
|
25
|
-
}
|
|
26
|
-
return new Date(Date.now() + expiresIn * 1000).toISOString();
|
|
27
|
-
}
|
|
13
|
+
export const AUTH_FAILURE_COOLDOWN_MS = 30_000;
|
|
28
14
|
/**
|
|
29
|
-
*
|
|
30
|
-
*
|
|
31
|
-
*
|
|
15
|
+
* Relative jitter applied to {@link AUTH_FAILURE_COOLDOWN_MS}, as a
|
|
16
|
+
* fraction of the base window (±20 %). The jitter spreads the backoff
|
|
17
|
+
* deadlines of concurrent router instances so they do not retry a
|
|
18
|
+
* failing server in lockstep.
|
|
32
19
|
*
|
|
33
|
-
* @
|
|
34
|
-
* @returns True when the token should be refreshed now.
|
|
20
|
+
* @internal Exported for tests only; not part of the public module API.
|
|
35
21
|
*/
|
|
36
|
-
|
|
37
|
-
const expiresAtMs = Date.parse(expiresAtIso);
|
|
38
|
-
if (Number.isNaN(expiresAtMs)) {
|
|
39
|
-
return false;
|
|
40
|
-
}
|
|
41
|
-
return expiresAtMs - Date.now() <= REFRESH_BUFFER_MS;
|
|
42
|
-
}
|
|
22
|
+
export const AUTH_FAILURE_COOLDOWN_JITTER = 0.2;
|
|
43
23
|
/**
|
|
44
24
|
* The OAuth redirect callback path served by the temporary local HTTP
|
|
45
25
|
* server started during `login`. The authorization-request redirect URI
|
|
@@ -77,12 +57,30 @@ export class OAuthCredentialManager {
|
|
|
77
57
|
_codeVerifier;
|
|
78
58
|
_staticClientInfo;
|
|
79
59
|
_actualPort = 0;
|
|
60
|
+
/**
|
|
61
|
+
* Authorization server issuer recorded for the current flow, when
|
|
62
|
+
* discovered. Stamped onto saved credentials and used to reject a
|
|
63
|
+
* stored entry obtained from a different authorization server.
|
|
64
|
+
*/
|
|
65
|
+
_issuer;
|
|
80
66
|
/**
|
|
81
67
|
* In-flight proactive refresh promise. When set, concurrent
|
|
82
68
|
* callers of {@link refreshIfNeeded} await this shared promise
|
|
83
69
|
* instead of triggering duplicate refresh requests.
|
|
84
70
|
*/
|
|
85
71
|
_refreshInFlight;
|
|
72
|
+
/**
|
|
73
|
+
* In-flight coordinated 401 refresh promise. When set, concurrent
|
|
74
|
+
* callers of {@link refreshAfterUnauthorized} await this shared
|
|
75
|
+
* attempt instead of racing duplicate adopt/refresh requests.
|
|
76
|
+
*/
|
|
77
|
+
_authRefreshInFlight;
|
|
78
|
+
/**
|
|
79
|
+
* Wall-clock deadline (epoch milliseconds) until which refreshes are
|
|
80
|
+
* refused after a 401 survived an adopted or freshly refreshed token.
|
|
81
|
+
* Zero means no backoff is active.
|
|
82
|
+
*/
|
|
83
|
+
_authFailureUntil = 0;
|
|
86
84
|
constructor(configPath, server) {
|
|
87
85
|
this._configPath = configPath;
|
|
88
86
|
this._server = server;
|
|
@@ -107,6 +105,13 @@ export class OAuthCredentialManager {
|
|
|
107
105
|
get redirectUrl() {
|
|
108
106
|
return `http://127.0.0.1:${this._actualPort}${OAUTH_CALLBACK_PATH}`;
|
|
109
107
|
}
|
|
108
|
+
/**
|
|
109
|
+
* The configured name of the downstream server this manager serves,
|
|
110
|
+
* used to attribute auth-retry and backoff log records.
|
|
111
|
+
*/
|
|
112
|
+
get serverName() {
|
|
113
|
+
return this._server.name;
|
|
114
|
+
}
|
|
110
115
|
/**
|
|
111
116
|
* Client metadata used for dynamic client registration. The registered
|
|
112
117
|
* redirect URI is the portless loopback form
|
|
@@ -158,6 +163,17 @@ export class OAuthCredentialManager {
|
|
|
158
163
|
hasStaticClient() {
|
|
159
164
|
return this._staticClientInfo !== undefined;
|
|
160
165
|
}
|
|
166
|
+
/**
|
|
167
|
+
* Records the discovered authorization server issuer for the current
|
|
168
|
+
* flow. Saved credentials are stamped with it, and a stored entry
|
|
169
|
+
* whose recorded issuer differs is not reused.
|
|
170
|
+
*
|
|
171
|
+
* @param issuer - The authorization server issuer from RFC 8414 /
|
|
172
|
+
* OIDC metadata.
|
|
173
|
+
*/
|
|
174
|
+
setIssuer(issuer) {
|
|
175
|
+
this._issuer = issuer;
|
|
176
|
+
}
|
|
161
177
|
async clientInformation() {
|
|
162
178
|
// Static overrides take precedence
|
|
163
179
|
if (this._staticClientInfo) {
|
|
@@ -171,44 +187,57 @@ export class OAuthCredentialManager {
|
|
|
171
187
|
// Don't overwrite static overrides
|
|
172
188
|
return;
|
|
173
189
|
}
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
190
|
+
await mutateCredentials(this._configPath, this._server.name, (current) => {
|
|
191
|
+
const creds = this._usableEntry(current);
|
|
192
|
+
return {
|
|
193
|
+
...bindingFieldsFor(creds, this._server.url, this._issuer),
|
|
194
|
+
clientRegistration: clientInformation,
|
|
195
|
+
// Preserve existing tokens; omit when none (tokens is optional).
|
|
196
|
+
...(creds?.tokens ? { tokens: creds.tokens } : {}),
|
|
197
|
+
// Successful OAuth client registration proves the server supports
|
|
198
|
+
// OAuth. Override any stale cached requirement.
|
|
199
|
+
authRequirement: 'oauth',
|
|
200
|
+
checkedAt: new Date().toISOString(),
|
|
201
|
+
};
|
|
202
|
+
});
|
|
185
203
|
}
|
|
186
204
|
async tokens() {
|
|
187
205
|
const creds = await this._loadCredentials();
|
|
188
206
|
if (!creds?.tokens?.access_token) {
|
|
189
207
|
return undefined;
|
|
190
208
|
}
|
|
209
|
+
if (this._isAuthFailureBackoffActive()) {
|
|
210
|
+
// The SDK's auth() refreshes unconditionally whenever the stored
|
|
211
|
+
// tokens carry a refresh token. During the backoff, hand it the
|
|
212
|
+
// access token without the refresh token so it skips its refresh
|
|
213
|
+
// branch and terminates through redirectToAuthorization instead
|
|
214
|
+
// of driving another doomed refresh.
|
|
215
|
+
const { refresh_token: _refreshToken, ...rest } = creds.tokens;
|
|
216
|
+
return rest;
|
|
217
|
+
}
|
|
191
218
|
return creds.tokens;
|
|
192
219
|
}
|
|
193
220
|
async saveTokens(tokens) {
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
221
|
+
await mutateCredentials(this._configPath, this._server.name, (current) => {
|
|
222
|
+
const creds = this._usableEntry(current);
|
|
223
|
+
return {
|
|
224
|
+
...bindingFieldsFor(creds, this._server.url, this._issuer),
|
|
225
|
+
clientRegistration: creds?.clientRegistration,
|
|
226
|
+
tokens: {
|
|
227
|
+
access_token: tokens.access_token,
|
|
228
|
+
refresh_token: tokens.refresh_token,
|
|
229
|
+
expires_in: tokens.expires_in,
|
|
230
|
+
expires_at: computeExpiresAt(tokens.expires_in),
|
|
231
|
+
scope: tokens.scope,
|
|
232
|
+
token_type: tokens.token_type,
|
|
233
|
+
},
|
|
234
|
+
// A successful OAuth token exchange proves the server supports
|
|
235
|
+
// OAuth. Override any stale cached requirement (e.g. 'none' from
|
|
236
|
+
// a failed startup probe) with 'oauth'.
|
|
237
|
+
authRequirement: 'oauth',
|
|
238
|
+
checkedAt: new Date().toISOString(),
|
|
239
|
+
};
|
|
240
|
+
});
|
|
212
241
|
}
|
|
213
242
|
/**
|
|
214
243
|
* Called by the SDK's `auth()` flow when an access token cannot be
|
|
@@ -244,15 +273,16 @@ export class OAuthCredentialManager {
|
|
|
244
273
|
*/
|
|
245
274
|
async clearTokens() {
|
|
246
275
|
this._codeVerifier = undefined;
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
276
|
+
await mutateCredentials(this._configPath, this._server.name, (current) => {
|
|
277
|
+
const creds = this._usableEntry(current);
|
|
278
|
+
if (creds?.authRequirement) {
|
|
279
|
+
return {
|
|
280
|
+
authRequirement: creds.authRequirement,
|
|
281
|
+
checkedAt: creds.checkedAt,
|
|
282
|
+
};
|
|
283
|
+
}
|
|
284
|
+
return undefined;
|
|
285
|
+
});
|
|
256
286
|
}
|
|
257
287
|
/**
|
|
258
288
|
* Invalidates stored credentials for this server in the scope the
|
|
@@ -284,25 +314,33 @@ export class OAuthCredentialManager {
|
|
|
284
314
|
await this.clearTokens();
|
|
285
315
|
return;
|
|
286
316
|
}
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
317
|
+
await mutateCredentials(this._configPath, this._server.name, (current) => {
|
|
318
|
+
const creds = this._usableEntry(current);
|
|
319
|
+
if (!creds) {
|
|
320
|
+
return current;
|
|
321
|
+
}
|
|
322
|
+
if (scope === 'tokens' && !tokensNeedInvalidation(creds.tokens)) {
|
|
323
|
+
// The stored tokens are not the stale ones this invalidation
|
|
324
|
+
// refers to: another process refreshed them while this one was
|
|
325
|
+
// failing, and clearing them would discard valid credentials.
|
|
326
|
+
return current;
|
|
327
|
+
}
|
|
328
|
+
const remaining = {
|
|
329
|
+
...bindingFieldsFor(creds, this._server.url, this._issuer),
|
|
330
|
+
clientRegistration: scope === 'client' ? undefined : creds.clientRegistration,
|
|
331
|
+
tokens: scope === 'tokens' ? undefined : creds.tokens,
|
|
332
|
+
authRequirement: creds.authRequirement,
|
|
333
|
+
checkedAt: creds.checkedAt,
|
|
334
|
+
};
|
|
335
|
+
// Drop the entry entirely when nothing credential-like or
|
|
336
|
+
// probe-related remains, mirroring clearTokens' cleanup.
|
|
337
|
+
if (remaining.clientRegistration === undefined &&
|
|
338
|
+
remaining.tokens === undefined &&
|
|
339
|
+
remaining.authRequirement === undefined) {
|
|
340
|
+
return undefined;
|
|
341
|
+
}
|
|
342
|
+
return remaining;
|
|
343
|
+
});
|
|
306
344
|
}
|
|
307
345
|
/**
|
|
308
346
|
* Proactively refreshes the access token when it is near or past
|
|
@@ -333,56 +371,92 @@ export class OAuthCredentialManager {
|
|
|
333
371
|
});
|
|
334
372
|
await this._refreshInFlight;
|
|
335
373
|
}
|
|
374
|
+
/**
|
|
375
|
+
* Coordinates the reactive 401 path for an access token the server
|
|
376
|
+
* just rejected: adopts a token another process stored while the
|
|
377
|
+
* rejected request was in flight, or performs exactly one refresh
|
|
378
|
+
* under the cross-process refresh lock. Concurrent 401s in this
|
|
379
|
+
* process share a single attempt.
|
|
380
|
+
*
|
|
381
|
+
* Unlike {@link refreshIfNeeded}, a failure propagates to the caller
|
|
382
|
+
* so the reactive path can report it — except when the failed
|
|
383
|
+
* attempt finds that another process stored a different access token
|
|
384
|
+
* while it was running: that winner is adopted and returned, so a
|
|
385
|
+
* losing cross-process race does not surface as a failure.
|
|
386
|
+
*
|
|
387
|
+
* @param usedToken - The access token the rejected request carried.
|
|
388
|
+
* @returns The adopted or refreshed tokens, or undefined when no
|
|
389
|
+
* adoption or refresh could be attempted (no stored tokens, no
|
|
390
|
+
* refresh token, or an active auth-failure backoff).
|
|
391
|
+
* @throws When the token request or Protected Resource Metadata
|
|
392
|
+
* discovery fails and no concurrently stored token can be adopted.
|
|
393
|
+
*/
|
|
394
|
+
async refreshAfterUnauthorized(usedToken) {
|
|
395
|
+
if (this._authRefreshInFlight) {
|
|
396
|
+
return this._authRefreshInFlight;
|
|
397
|
+
}
|
|
398
|
+
// Claim the slot synchronously so concurrent callers await the same
|
|
399
|
+
// attempt rather than racing duplicate refreshes.
|
|
400
|
+
this._authRefreshInFlight = this._runRefreshAfterUnauthorized(usedToken).finally(() => {
|
|
401
|
+
this._authRefreshInFlight = undefined;
|
|
402
|
+
});
|
|
403
|
+
return this._authRefreshInFlight;
|
|
404
|
+
}
|
|
405
|
+
/**
|
|
406
|
+
* Records that a 401 survived an adopted or freshly refreshed access
|
|
407
|
+
* token and starts the auth-failure backoff. During the backoff
|
|
408
|
+
* {@link tokens} hides the refresh token from the SDK's `auth()` flow
|
|
409
|
+
* and {@link refreshIfNeeded} skips proactive refreshes, so a server
|
|
410
|
+
* that keeps rejecting tokens cannot drive a refresh loop.
|
|
411
|
+
*/
|
|
412
|
+
noteAuthFailure() {
|
|
413
|
+
// Uniform jitter in [-1, 1) spreads the deadlines of concurrent
|
|
414
|
+
// router instances so they do not retry a failing server in
|
|
415
|
+
// lockstep.
|
|
416
|
+
const jitter = Math.random() * 2 - 1;
|
|
417
|
+
this._authFailureUntil =
|
|
418
|
+
Date.now() + AUTH_FAILURE_COOLDOWN_MS * (1 + jitter * AUTH_FAILURE_COOLDOWN_JITTER);
|
|
419
|
+
}
|
|
420
|
+
/**
|
|
421
|
+
* Clears the auth-failure backoff after a request with an adopted or
|
|
422
|
+
* refreshed token succeeded, restoring normal refresh behavior.
|
|
423
|
+
*/
|
|
424
|
+
noteAuthSuccess() {
|
|
425
|
+
this._authFailureUntil = 0;
|
|
426
|
+
}
|
|
427
|
+
/**
|
|
428
|
+
* Whether the auth-failure backoff is currently active.
|
|
429
|
+
*
|
|
430
|
+
* @returns True while refreshes are refused after a repeated 401.
|
|
431
|
+
*/
|
|
432
|
+
_isAuthFailureBackoffActive() {
|
|
433
|
+
return Date.now() < this._authFailureUntil;
|
|
434
|
+
}
|
|
336
435
|
async _runRefreshIfNeeded(logger) {
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
436
|
+
if (this._isAuthFailureBackoffActive()) {
|
|
437
|
+
// A 401 just survived an adopted or freshly refreshed token;
|
|
438
|
+
// another proactive refresh would only burn a token request.
|
|
340
439
|
return;
|
|
341
440
|
}
|
|
342
|
-
|
|
441
|
+
// Cheap freshness check before taking the cross-process lock: the
|
|
442
|
+
// common case (token still valid) must not touch the lock file.
|
|
443
|
+
if (!dueRefreshToken((await this._loadCredentials())?.tokens)) {
|
|
343
444
|
return;
|
|
344
445
|
}
|
|
345
|
-
await this._refreshTokens(tokens.refresh_token, logger);
|
|
346
|
-
}
|
|
347
|
-
/**
|
|
348
|
-
* Performs the token refresh: discovers the authorization server
|
|
349
|
-
* metadata, calls the SDK's `refreshAuthorization`, and persists the
|
|
350
|
-
* refreshed tokens via {@link saveTokens} (which recomputes
|
|
351
|
-
* `expires_at`). The request carries the RFC 8707 `resource`
|
|
352
|
-
* indicator selected from the server's Protected Resource Metadata —
|
|
353
|
-
* the same indicator `login` sent — so a provider that binds tokens
|
|
354
|
-
* to a specific resource accepts the refresh. Errors are logged
|
|
355
|
-
* (when a logger is supplied) and swallowed — proactive refresh is
|
|
356
|
-
* best-effort; the SDK's 401 path handles terminal failures.
|
|
357
|
-
*/
|
|
358
|
-
async _refreshTokens(refreshToken, logger) {
|
|
359
446
|
try {
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
const clientInformation = await this.clientInformation();
|
|
369
|
-
if (!clientInformation) {
|
|
370
|
-
return;
|
|
371
|
-
}
|
|
372
|
-
const resource = await selectResourceURL(serverUrl, this, discovered.resourceMetadata);
|
|
373
|
-
const newTokens = await refreshAuthorization(discovered.authorizationServerUrl, {
|
|
374
|
-
metadata: discovered.serverMetadata,
|
|
375
|
-
clientInformation,
|
|
376
|
-
refreshToken,
|
|
377
|
-
resource,
|
|
447
|
+
await withRefreshLock(this._configPath, async () => {
|
|
448
|
+
// Re-read under the lock: when another process refreshed while
|
|
449
|
+
// this one waited, its fresh tokens are used as-is.
|
|
450
|
+
const refreshToken = dueRefreshToken((await this._loadCredentials())?.tokens);
|
|
451
|
+
if (!refreshToken) {
|
|
452
|
+
return;
|
|
453
|
+
}
|
|
454
|
+
await this._refreshTokens(refreshToken);
|
|
378
455
|
});
|
|
379
|
-
await this.saveTokens(newTokens);
|
|
380
456
|
}
|
|
381
457
|
catch (err) {
|
|
382
|
-
// Proactive refresh is best-effort;
|
|
383
|
-
//
|
|
384
|
-
// the error when a logger is available so the failure is
|
|
385
|
-
// visible without waiting for the 401.
|
|
458
|
+
// Proactive refresh is best-effort; a lock failure must not break
|
|
459
|
+
// the tool call. The SDK's reactive 401 path remains the fallback.
|
|
386
460
|
if (logger) {
|
|
387
461
|
logger.error('Proactive OAuth token refresh failed', {
|
|
388
462
|
server: this._server.name,
|
|
@@ -391,8 +465,125 @@ export class OAuthCredentialManager {
|
|
|
391
465
|
}
|
|
392
466
|
}
|
|
393
467
|
}
|
|
468
|
+
/**
|
|
469
|
+
* The coordinated attempt behind {@link refreshAfterUnauthorized}.
|
|
470
|
+
*
|
|
471
|
+
* Reads the usable stored entry first: a stored access token that
|
|
472
|
+
* differs from `usedToken` is another process's fresh token and is
|
|
473
|
+
* adopted without taking the refresh lock — even during the
|
|
474
|
+
* auth-failure backoff. When the stored token is still the rejected
|
|
475
|
+
* one and the backoff is active, no refresh is attempted. Otherwise
|
|
476
|
+
* the cross-process refresh lock is taken and the entry re-read: a
|
|
477
|
+
* changed token is adopted, a missing refresh token yields undefined,
|
|
478
|
+
* and only a still-unchanged entry is refreshed once.
|
|
479
|
+
*
|
|
480
|
+
* When the coordinated attempt itself fails (refresh-lock timeout,
|
|
481
|
+
* network error, transient Protected Resource Metadata discovery
|
|
482
|
+
* failure, or a losing `invalid_grant` race), the entry is re-read
|
|
483
|
+
* once more: a changed access token is adopted and returned, because
|
|
484
|
+
* a peer has usually just stored a winner. Only when no adoptable
|
|
485
|
+
* token exists does the original error propagate.
|
|
486
|
+
*
|
|
487
|
+
* @param usedToken - The access token the rejected request carried.
|
|
488
|
+
* @returns The adopted or refreshed tokens, or undefined when no
|
|
489
|
+
* adoption or refresh could be attempted.
|
|
490
|
+
* @throws When the token request or Protected Resource Metadata
|
|
491
|
+
* discovery fails and no concurrently stored token can be adopted.
|
|
492
|
+
*/
|
|
493
|
+
async _runRefreshAfterUnauthorized(usedToken) {
|
|
494
|
+
const stored = await this._loadCredentials();
|
|
495
|
+
const adopted = this._adoptStoredToken(usedToken, stored);
|
|
496
|
+
if (adopted) {
|
|
497
|
+
return adopted;
|
|
498
|
+
}
|
|
499
|
+
if (this._isAuthFailureBackoffActive()) {
|
|
500
|
+
// A recent 401 survived an adopted or freshly refreshed token;
|
|
501
|
+
// another refresh would only burn a token request.
|
|
502
|
+
return undefined;
|
|
503
|
+
}
|
|
504
|
+
try {
|
|
505
|
+
return await withRefreshLock(this._configPath, async () => {
|
|
506
|
+
// Re-read under the lock: when another process refreshed while
|
|
507
|
+
// this one waited, adopt its token instead of refreshing again.
|
|
508
|
+
const current = await this._loadCredentials();
|
|
509
|
+
const adoptedUnderLock = this._adoptStoredToken(usedToken, current);
|
|
510
|
+
if (adoptedUnderLock) {
|
|
511
|
+
return adoptedUnderLock;
|
|
512
|
+
}
|
|
513
|
+
const refreshToken = current?.tokens?.refresh_token;
|
|
514
|
+
if (!refreshToken) {
|
|
515
|
+
return undefined;
|
|
516
|
+
}
|
|
517
|
+
return this._refreshTokens(refreshToken);
|
|
518
|
+
});
|
|
519
|
+
}
|
|
520
|
+
catch (err) {
|
|
521
|
+
// The attempt failed. A peer may have stored a winner while it
|
|
522
|
+
// was running (the losing `invalid_grant` race, or a refresh that
|
|
523
|
+
// landed during a lock timeout or a transient failure): adopt it
|
|
524
|
+
// instead of surfacing the failure.
|
|
525
|
+
const storedAfterFailure = await this._loadCredentials();
|
|
526
|
+
const winner = this._adoptStoredToken(usedToken, storedAfterFailure);
|
|
527
|
+
if (winner) {
|
|
528
|
+
return winner;
|
|
529
|
+
}
|
|
530
|
+
throw err;
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
/**
|
|
534
|
+
* Returns the tokens of a stored entry when its access token differs
|
|
535
|
+
* from the one a rejected request carried — a token another process
|
|
536
|
+
* stored while that request was in flight. Returns undefined when the
|
|
537
|
+
* stored token is still the rejected one or no usable entry exists.
|
|
538
|
+
*
|
|
539
|
+
* @param usedToken - The access token the rejected request carried.
|
|
540
|
+
* @param stored - The usable stored entry, if any.
|
|
541
|
+
* @returns The adopted tokens, or undefined when there is nothing to
|
|
542
|
+
* adopt.
|
|
543
|
+
*/
|
|
544
|
+
_adoptStoredToken(usedToken, stored) {
|
|
545
|
+
if (stored?.tokens && stored.tokens.access_token !== usedToken) {
|
|
546
|
+
return stored.tokens;
|
|
547
|
+
}
|
|
548
|
+
return undefined;
|
|
549
|
+
}
|
|
550
|
+
/**
|
|
551
|
+
* Performs one token refresh through the shared refresh request:
|
|
552
|
+
* discovers the authorization server metadata, calls the SDK's
|
|
553
|
+
* `refreshAuthorization` with the RFC 8707 `resource` indicator
|
|
554
|
+
* selected from the server's Protected Resource Metadata, and persists
|
|
555
|
+
* the refreshed tokens via {@link saveTokens} (which recomputes
|
|
556
|
+
* `expires_at`). Errors propagate to the caller so the coordinated
|
|
557
|
+
* path can report the outcome; {@link refreshIfNeeded} keeps its
|
|
558
|
+
* swallow-and-log behavior.
|
|
559
|
+
*
|
|
560
|
+
* @param refreshToken - The refresh token to present.
|
|
561
|
+
* @returns The refreshed tokens, or undefined when no refresh could be
|
|
562
|
+
* attempted.
|
|
563
|
+
* @throws When discovery or the token request fails, or when the
|
|
564
|
+
* Protected Resource Metadata probe failed transiently.
|
|
565
|
+
*/
|
|
566
|
+
async _refreshTokens(refreshToken) {
|
|
567
|
+
return requestTokenRefresh({
|
|
568
|
+
serverUrl: this._server.url,
|
|
569
|
+
provider: this,
|
|
570
|
+
setIssuer: (issuer) => this.setIssuer(issuer),
|
|
571
|
+
saveTokens: (tokens) => this.saveTokens(tokens),
|
|
572
|
+
}, refreshToken);
|
|
573
|
+
}
|
|
574
|
+
/**
|
|
575
|
+
* Filters a raw stored entry down to the one this manager may use: an
|
|
576
|
+
* entry bound to a different server URL or authorization server is
|
|
577
|
+
* treated as absent so it is never sent anywhere.
|
|
578
|
+
*
|
|
579
|
+
* @param entry - The raw on-disk entry, if any.
|
|
580
|
+
* @returns The usable entry, or undefined when it does not belong here.
|
|
581
|
+
*/
|
|
582
|
+
_usableEntry(entry) {
|
|
583
|
+
return credentialsUsableFor(entry, this._server.url, this._issuer) ? entry : undefined;
|
|
584
|
+
}
|
|
394
585
|
async _loadCredentials() {
|
|
395
586
|
const all = await readCredentials(this._configPath);
|
|
396
|
-
return all[this._server.name];
|
|
587
|
+
return this._usableEntry(all[this._server.name]);
|
|
397
588
|
}
|
|
398
589
|
}
|
|
@@ -220,10 +220,8 @@ export class ServerConnection {
|
|
|
220
220
|
async doConnect() {
|
|
221
221
|
this.client = new Client({ name: 'mcp-compress-router', version: '1.0.0' }, { capabilities: {} });
|
|
222
222
|
this.authProvider = await this.createAuthProvider();
|
|
223
|
-
const
|
|
224
|
-
|
|
225
|
-
: undefined;
|
|
226
|
-
const transport = createTransport(this.server, getAuthProvider);
|
|
223
|
+
const authProvider = this.authProvider;
|
|
224
|
+
const transport = createTransport(this.server, authProvider ? () => authProvider : undefined, this.logger);
|
|
227
225
|
// Cap the initialize handshake and tools/list call so a hung
|
|
228
226
|
// downstream server fails fast instead of stalling startup (or
|
|
229
227
|
// self-recovery) for the SDK's 60s default.
|