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
|
@@ -2,6 +2,7 @@ import { Client } from '@modelcontextprotocol/sdk/client/index.js';
|
|
|
2
2
|
import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
|
|
3
3
|
import { StreamableHTTPClientTransport } from '@modelcontextprotocol/sdk/client/streamableHttp.js';
|
|
4
4
|
import { getDownstreamTimeoutMs, killProcessTree } from '../utils/index.js';
|
|
5
|
+
import { createAuthRetryFetch } from './auth-retry-fetch.js';
|
|
5
6
|
import { createDedicatedFetch, createConnectTimeoutFetch } from './dedicated-fetch.js';
|
|
6
7
|
/** JSON-RPC error code for "Method not found". */
|
|
7
8
|
const METHOD_NOT_FOUND = -32601;
|
|
@@ -131,7 +132,7 @@ export async function discoverSingleServer(server, logger, getAuthProvider) {
|
|
|
131
132
|
server: server.name,
|
|
132
133
|
type: server.type,
|
|
133
134
|
});
|
|
134
|
-
const transport = createTransport(server, getAuthProvider);
|
|
135
|
+
const transport = createTransport(server, getAuthProvider, logger);
|
|
135
136
|
// Cap the initialize handshake and tools/list call so a server that
|
|
136
137
|
// accepts the connection but never replies surfaces a clear error
|
|
137
138
|
// instead of hanging the command indefinitely (the SDK's own default
|
|
@@ -173,12 +174,18 @@ export async function discoverSingleServer(server, logger, getAuthProvider) {
|
|
|
173
174
|
/**
|
|
174
175
|
* Creates the appropriate transport for a downstream server config.
|
|
175
176
|
*
|
|
177
|
+
* HTTP transports route their fetch through the auth-retry wrapper: a
|
|
178
|
+
* 401 that carried a bearer token is retried once with a token adopted
|
|
179
|
+
* from another process or freshly refreshed under the cross-process
|
|
180
|
+
* refresh lock.
|
|
181
|
+
*
|
|
176
182
|
* @param server - Downstream server configuration.
|
|
177
183
|
* @param getAuthProvider - Optional factory to provide OAuth credentials.
|
|
184
|
+
* @param logger - Optional structured logger for auth-retry diagnostics.
|
|
178
185
|
* @returns A configured transport instance (stdio or HTTP).
|
|
179
186
|
* @throws If required configuration (command or url) is missing.
|
|
180
187
|
*/
|
|
181
|
-
export function createTransport(server, getAuthProvider) {
|
|
188
|
+
export function createTransport(server, getAuthProvider, logger) {
|
|
182
189
|
if (server.type === 'stdio') {
|
|
183
190
|
if (!server.command) {
|
|
184
191
|
throw new Error(`Server "${server.name}" (stdio) is missing command`);
|
|
@@ -205,7 +212,9 @@ export function createTransport(server, getAuthProvider) {
|
|
|
205
212
|
// it uses a private connection pool instead of the shared default one,
|
|
206
213
|
// and bound the connect/auth handshakes (SSE session GET, OAuth
|
|
207
214
|
// metadata + token flows) so a silent server cannot stall startup —
|
|
208
|
-
// runtime message POSTs are deliberately left unbounded.
|
|
209
|
-
fetch
|
|
215
|
+
// runtime message POSTs are deliberately left unbounded. The auth
|
|
216
|
+
// retry wraps the timeout fetch so each retry gets a fresh connect
|
|
217
|
+
// timeout.
|
|
218
|
+
fetch: createAuthRetryFetch(createConnectTimeoutFetch(createDedicatedFetch(), getDownstreamTimeoutMs()), authProvider, logger),
|
|
210
219
|
});
|
|
211
220
|
}
|
package/build/services/index.js
CHANGED
|
@@ -7,6 +7,7 @@ export { installShutdownTriggers } from './shutdown-triggers.js';
|
|
|
7
7
|
export { invokeWithRecovery } from './invoke-with-recovery.js';
|
|
8
8
|
export { saveToolCache } from './tool-cache.js';
|
|
9
9
|
export { OAuthCredentialManager } from './oauth.js';
|
|
10
|
+
export { resolveBindingUrl } from './credential-binding.js';
|
|
10
11
|
export { computeAuthStatus, persistAuthRequirements } from './auth-status.js';
|
|
11
12
|
export { discoverAuth } from './oauth-discovery.js';
|
|
12
13
|
export { GuidedAuthError, isAuthError } from './auth-errors.js';
|
|
@@ -31,6 +31,31 @@ async function _getSdkAuth() {
|
|
|
31
31
|
function isNonJsonResponse(err) {
|
|
32
32
|
return err instanceof SyntaxError;
|
|
33
33
|
}
|
|
34
|
+
/**
|
|
35
|
+
* Returns true when the thrown error from the RFC 9728 Protected Resource
|
|
36
|
+
* Metadata probe means the server cleanly published no PRM — the normal
|
|
37
|
+
* legacy-server path, not a probe failure. The SDK reports both a 404 and
|
|
38
|
+
* a non-JSON body as errors:
|
|
39
|
+
*
|
|
40
|
+
* - `SyntaxError` — `response.json()` hit an HTML page or another non-JSON
|
|
41
|
+
* body: the endpoint answered, it just is not a PRM endpoint.
|
|
42
|
+
* - The SDK's "does not implement" message — a 404 (or an absent response)
|
|
43
|
+
* for the well-known endpoint.
|
|
44
|
+
*
|
|
45
|
+
* Everything else (5xx, network, timeout, schema-invalid body) is a
|
|
46
|
+
* transient probe failure.
|
|
47
|
+
*
|
|
48
|
+
* @param err - The thrown value from the SDK PRM discovery helper.
|
|
49
|
+
* @returns True when the error is a clean miss.
|
|
50
|
+
*/
|
|
51
|
+
function isResourceMetadataCleanMiss(err) {
|
|
52
|
+
if (err instanceof SyntaxError) {
|
|
53
|
+
return true;
|
|
54
|
+
}
|
|
55
|
+
return (err instanceof Error &&
|
|
56
|
+
(err.message === 'Resource server does not implement OAuth 2.0 Protected Resource Metadata.' ||
|
|
57
|
+
err.message.startsWith('HTTP 404 ')));
|
|
58
|
+
}
|
|
34
59
|
/**
|
|
35
60
|
* Converts a raw `authorization_servers` string into a URL. Returns
|
|
36
61
|
* `undefined` for malformed entries so a broken PRM advertisement is
|
|
@@ -80,6 +105,31 @@ function createRawMetadataFetch(base, capture) {
|
|
|
80
105
|
return response;
|
|
81
106
|
};
|
|
82
107
|
}
|
|
108
|
+
/**
|
|
109
|
+
* Wraps a fetch function so any rejection is recorded in `capture` and
|
|
110
|
+
* rethrown. The SDK's PRM discovery helper wraps its fetch calls in
|
|
111
|
+
* `fetchWithCorsRetry`, which catches a connection `TypeError`, retries
|
|
112
|
+
* without headers, and then returns `undefined`; the helper turns that
|
|
113
|
+
* into the same "does not implement" error a real 404 produces (SDK
|
|
114
|
+
* 1.30.0). The error text alone therefore cannot classify a network
|
|
115
|
+
* failure, so the fetch-level rejection is captured before the SDK
|
|
116
|
+
* swallows it.
|
|
117
|
+
*
|
|
118
|
+
* @param base - The fetch function to wrap.
|
|
119
|
+
* @param capture - Sink for the failure flag.
|
|
120
|
+
* @returns A fetch function that records rejections before rethrowing.
|
|
121
|
+
*/
|
|
122
|
+
function createFetchFailureCapture(base, capture) {
|
|
123
|
+
return async (input, init) => {
|
|
124
|
+
try {
|
|
125
|
+
return await base(input, init);
|
|
126
|
+
}
|
|
127
|
+
catch (err) {
|
|
128
|
+
capture.failed = true;
|
|
129
|
+
throw err;
|
|
130
|
+
}
|
|
131
|
+
};
|
|
132
|
+
}
|
|
83
133
|
/**
|
|
84
134
|
* Reads the RFC 9207 `authorization_response_iss_parameter_supported`
|
|
85
135
|
* flag from the captured raw metadata document.
|
|
@@ -140,15 +190,18 @@ function buildCandidateUrls(serverUrl, resourceMetadata) {
|
|
|
140
190
|
* @param resourceMetadata - Discovered Protected Resource Metadata, if any.
|
|
141
191
|
* @param hit - The winning AS candidate, or `undefined` on a full miss.
|
|
142
192
|
* @param serverUrl - The downstream MCP server URL (fallback AS URL).
|
|
193
|
+
* @param resourceMetadataDiscoveryFailed - Whether the PRM probe failed
|
|
194
|
+
* transiently (as opposed to a clean miss or a published PRM).
|
|
143
195
|
* @returns The discovery result.
|
|
144
196
|
*/
|
|
145
|
-
function toDiscoveredAuth(resourceMetadata, hit, serverUrl) {
|
|
197
|
+
function toDiscoveredAuth(resourceMetadata, hit, serverUrl, resourceMetadataDiscoveryFailed) {
|
|
146
198
|
if (!hit) {
|
|
147
199
|
return {
|
|
148
200
|
resourceMetadata,
|
|
149
201
|
serverMetadata: undefined,
|
|
150
202
|
authorizationServerUrl: serverUrl,
|
|
151
203
|
authorizationResponseIssParameterSupported: false,
|
|
204
|
+
resourceMetadataDiscoveryFailed,
|
|
152
205
|
};
|
|
153
206
|
}
|
|
154
207
|
return {
|
|
@@ -156,51 +209,58 @@ function toDiscoveredAuth(resourceMetadata, hit, serverUrl) {
|
|
|
156
209
|
serverMetadata: hit.metadata,
|
|
157
210
|
authorizationServerUrl: hit.url,
|
|
158
211
|
authorizationResponseIssParameterSupported: hit.authorizationResponseIssParameterSupported,
|
|
212
|
+
resourceMetadataDiscoveryFailed,
|
|
159
213
|
};
|
|
160
214
|
}
|
|
161
215
|
/**
|
|
162
|
-
*
|
|
163
|
-
* MCP 2025-06-18 authorization spec two-step flow:
|
|
216
|
+
* Probes RFC 9728 Protected Resource Metadata and classifies the outcome.
|
|
164
217
|
*
|
|
165
|
-
*
|
|
166
|
-
*
|
|
167
|
-
*
|
|
218
|
+
* A clean miss (404/absent or a non-JSON body) yields no metadata and no
|
|
219
|
+
* failure. Any other error — network, timeout, non-404 HTTP status, or a
|
|
220
|
+
* schema-invalid body — is a transient failure: the server may bind
|
|
221
|
+
* tokens to a resource, so a refresh must not proceed without the
|
|
222
|
+
* RFC 8707 `resource` indicator.
|
|
168
223
|
*
|
|
169
|
-
*
|
|
170
|
-
*
|
|
171
|
-
*
|
|
172
|
-
*
|
|
224
|
+
* The SDK's `fetchWithCorsRetry` swallows a connection `TypeError`, retries
|
|
225
|
+
* without headers, and reports "no PRM" exactly like a real 404 (SDK
|
|
226
|
+
* 1.30.0), so the fetch-level failure capture is what keeps a dropped
|
|
227
|
+
* connection classified as transient.
|
|
173
228
|
*
|
|
174
|
-
*
|
|
175
|
-
*
|
|
176
|
-
*
|
|
177
|
-
*
|
|
178
|
-
|
|
229
|
+
* @param serverUrl - The downstream MCP server URL.
|
|
230
|
+
* @param fetchFn - The bounded fetch function to probe with.
|
|
231
|
+
* @returns The discovered metadata (if any) and whether the probe failed
|
|
232
|
+
* transiently.
|
|
233
|
+
*/
|
|
234
|
+
async function probeResourceMetadata(serverUrl, fetchFn) {
|
|
235
|
+
const { discoverOAuthProtectedResourceMetadata } = await _getSdkAuth();
|
|
236
|
+
const capture = { failed: false };
|
|
237
|
+
try {
|
|
238
|
+
const resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, {}, createFetchFailureCapture(fetchFn, capture));
|
|
239
|
+
return { resourceMetadata, failed: false };
|
|
240
|
+
}
|
|
241
|
+
catch (err) {
|
|
242
|
+
return { failed: capture.failed || !isResourceMetadataCleanMiss(err) };
|
|
243
|
+
}
|
|
244
|
+
}
|
|
245
|
+
/**
|
|
246
|
+
* Probes the authorization-server candidate URL groups and returns the
|
|
247
|
+
* first hit. Advertised AS URLs (from PRM) are probed first; the legacy
|
|
248
|
+
* fallback group is only probed when no advertised AS yields metadata.
|
|
179
249
|
*
|
|
180
|
-
*
|
|
181
|
-
* "not
|
|
182
|
-
*
|
|
183
|
-
*
|
|
184
|
-
*
|
|
185
|
-
* genuine error, the last such error is re-thrown so callers can
|
|
186
|
-
* distinguish a clean "no OAuth published" (all 404s / non-JSON) from an
|
|
187
|
-
* actual server/network failure (e.g. the auth probe reports `'unknown'`,
|
|
188
|
-
* the login command throws a guided error).
|
|
250
|
+
* Any per-candidate error (5xx, network, timeout) is swallowed and treated
|
|
251
|
+
* as "not found" so a single flaky endpoint never aborts the flow. A
|
|
252
|
+
* non-JSON response is a clean miss and is not recorded. When every
|
|
253
|
+
* candidate misses and at least one threw a genuine error, the last such
|
|
254
|
+
* error is returned so the caller can surface it.
|
|
189
255
|
*
|
|
190
|
-
* @param serverUrl - The downstream MCP server URL
|
|
191
|
-
* @
|
|
192
|
-
*
|
|
193
|
-
*
|
|
194
|
-
*
|
|
195
|
-
* one candidate endpoint errored. Clean "not found" (all 404s or
|
|
196
|
-
* non-JSON responses) does not throw.
|
|
256
|
+
* @param serverUrl - The downstream MCP server URL.
|
|
257
|
+
* @param resourceMetadata - Discovered Protected Resource Metadata, if any.
|
|
258
|
+
* @param fetchFn - The bounded fetch function to probe with.
|
|
259
|
+
* @returns The first AS candidate hit, or the last genuine error when no
|
|
260
|
+
* candidate yielded metadata.
|
|
197
261
|
*/
|
|
198
|
-
|
|
199
|
-
const {
|
|
200
|
-
// The SDK discovery helpers use a raw fetch with no timeout; a server
|
|
201
|
-
// that hangs its well-known endpoint would trap discovery forever. Pass
|
|
202
|
-
// a fetch that aborts after a short, configurable budget.
|
|
203
|
-
const fetchFn = createTimeoutFetch(getAuthDiscoveryTimeoutMs());
|
|
262
|
+
async function discoverServerMetadata(serverUrl, resourceMetadata, fetchFn) {
|
|
263
|
+
const { discoverAuthorizationServerMetadata } = await _getSdkAuth();
|
|
204
264
|
// Tracks the last genuine error seen across all candidates so the caller
|
|
205
265
|
// can be notified when discovery failed entirely (vs. cleanly finding
|
|
206
266
|
// nothing). Non-JSON responses are excluded — they are clean misses.
|
|
@@ -231,32 +291,74 @@ export async function discoverAuth(serverUrl) {
|
|
|
231
291
|
return undefined;
|
|
232
292
|
}
|
|
233
293
|
};
|
|
234
|
-
// Step 1: RFC 9728 Protected Resource Metadata. This SDK function throws
|
|
235
|
-
// when no PRM is published (treated as "no PRM, fall through"), so its
|
|
236
|
-
// error is intentionally NOT recorded — absence of PRM is the normal
|
|
237
|
-
// legacy-server path, not a probe failure.
|
|
238
|
-
let resourceMetadata;
|
|
239
|
-
try {
|
|
240
|
-
resourceMetadata = await discoverOAuthProtectedResourceMetadata(serverUrl, {}, fetchFn);
|
|
241
|
-
}
|
|
242
|
-
catch {
|
|
243
|
-
// No PRM published; fall through to direct AS discovery below.
|
|
244
|
-
}
|
|
245
|
-
// Step 2: probe the candidates in parallel, first hit wins.
|
|
246
294
|
const { advertised, fallback } = buildCandidateUrls(serverUrl, resourceMetadata);
|
|
247
295
|
const advertisedHit = await raceCandidates(advertised, safeDiscoverAs);
|
|
248
296
|
if (advertisedHit) {
|
|
249
|
-
return
|
|
297
|
+
return { hit: advertisedHit, error: undefined };
|
|
250
298
|
}
|
|
251
299
|
const fallbackHit = await raceCandidates(fallback, safeDiscoverAs);
|
|
252
300
|
if (fallbackHit) {
|
|
253
|
-
return
|
|
301
|
+
return { hit: fallbackHit, error: undefined };
|
|
302
|
+
}
|
|
303
|
+
return { hit: undefined, error: lastError };
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* Discovers OAuth metadata for a downstream MCP server following the
|
|
307
|
+
* MCP 2025-06-18 authorization spec two-step flow:
|
|
308
|
+
*
|
|
309
|
+
* 1. RFC 9728 Protected Resource Metadata (PRM) at the server URL. When
|
|
310
|
+
* present, its `authorization_servers` array lists the AS URLs to query.
|
|
311
|
+
* 2. RFC 8414 / OIDC Authorization Server Metadata at each advertised AS URL.
|
|
312
|
+
*
|
|
313
|
+
* Legacy servers that publish AS metadata directly at their host root without
|
|
314
|
+
* PRM are still supported: when no PRM is found (or it advertises no usable
|
|
315
|
+
* AS), discovery falls back to the server URL and, if that URL has a path,
|
|
316
|
+
* its origin root.
|
|
317
|
+
*
|
|
318
|
+
* The candidates of each group are probed **in parallel** and the first
|
|
319
|
+
* hit wins, so a hung well-known endpoint on one candidate never delays
|
|
320
|
+
* discovery of another. PRM-advertised AS URLs are preferred over the
|
|
321
|
+
* legacy fallback candidates (the fallback group is only probed when no
|
|
322
|
+
* advertised AS yields metadata).
|
|
323
|
+
*
|
|
324
|
+
* A candidate that responds with a non-JSON body (e.g. HTML) is treated as
|
|
325
|
+
* "not an OAuth endpoint" — a clean miss, not a probe failure. All other
|
|
326
|
+
* per-candidate errors (5xx, network, timeout) are swallowed and treated as
|
|
327
|
+
* "not found" so a single flaky endpoint never aborts the whole flow.
|
|
328
|
+
* When no metadata is found anywhere AND at least one candidate threw a
|
|
329
|
+
* genuine error, the last such error is re-thrown so callers can
|
|
330
|
+
* distinguish a clean "no OAuth published" (all 404s / non-JSON) from an
|
|
331
|
+
* actual server/network failure (e.g. the auth probe reports `'unknown'`,
|
|
332
|
+
* the login command throws a guided error).
|
|
333
|
+
*
|
|
334
|
+
* @param serverUrl - The downstream MCP server URL to discover auth for.
|
|
335
|
+
* @returns The discovered resource and/or server metadata plus the AS URL
|
|
336
|
+
* that yielded the metadata. `serverMetadata` is `undefined` when no OAuth
|
|
337
|
+
* endpoints could be discovered.
|
|
338
|
+
* @throws The last discovery error when no metadata was found and at least
|
|
339
|
+
* one candidate endpoint errored. Clean "not found" (all 404s or
|
|
340
|
+
* non-JSON responses) does not throw.
|
|
341
|
+
*/
|
|
342
|
+
export async function discoverAuth(serverUrl) {
|
|
343
|
+
// The SDK discovery helpers use a raw fetch with no timeout; a server
|
|
344
|
+
// that hangs its well-known endpoint would trap discovery forever. Pass
|
|
345
|
+
// a fetch that aborts after a short, configurable budget.
|
|
346
|
+
const fetchFn = createTimeoutFetch(getAuthDiscoveryTimeoutMs());
|
|
347
|
+
// Step 1: RFC 9728 Protected Resource Metadata. A clean miss (404 or a
|
|
348
|
+
// non-JSON body) falls through to AS discovery below; a transient probe
|
|
349
|
+
// failure is flagged so callers can fail a refresh that would otherwise
|
|
350
|
+
// issue an unbound token.
|
|
351
|
+
const { resourceMetadata, failed: resourceMetadataDiscoveryFailed } = await probeResourceMetadata(serverUrl, fetchFn);
|
|
352
|
+
// Step 2: probe the AS candidates in parallel, first hit wins.
|
|
353
|
+
const { hit, error } = await discoverServerMetadata(serverUrl, resourceMetadata, fetchFn);
|
|
354
|
+
if (hit) {
|
|
355
|
+
return toDiscoveredAuth(resourceMetadata, hit, serverUrl, resourceMetadataDiscoveryFailed);
|
|
254
356
|
}
|
|
255
357
|
// No metadata found anywhere. If any candidate actually errored (vs. a
|
|
256
358
|
// clean 404 or a non-JSON response), surface that so callers can report
|
|
257
359
|
// a probe failure rather than a misleading "no OAuth supported".
|
|
258
|
-
if (
|
|
259
|
-
throw
|
|
360
|
+
if (error !== undefined) {
|
|
361
|
+
throw error;
|
|
260
362
|
}
|
|
261
|
-
return toDiscoveredAuth(resourceMetadata, undefined, serverUrl);
|
|
363
|
+
return toDiscoveredAuth(resourceMetadata, undefined, serverUrl, resourceMetadataDiscoveryFailed);
|
|
262
364
|
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { refreshAuthorization, selectResourceURL, } from '@modelcontextprotocol/sdk/client/auth.js';
|
|
2
|
+
import { createTimeoutFetch, getDownstreamTimeoutMs } from '../utils/index.js';
|
|
3
|
+
import { discoverAuth } from './oauth-discovery.js';
|
|
4
|
+
/**
|
|
5
|
+
* How long before expiry a token is considered due for proactive
|
|
6
|
+
* refresh, in milliseconds. A refresh is triggered when the token's
|
|
7
|
+
* absolute `expires_at` is within this window of (or already past)
|
|
8
|
+
* the current time. Keeps a small safety margin so the token does
|
|
9
|
+
* not expire in the gap between the refresh check and the request.
|
|
10
|
+
*/
|
|
11
|
+
const REFRESH_BUFFER_MS = 60_000;
|
|
12
|
+
/**
|
|
13
|
+
* Computes the absolute ISO-8601 expiry timestamp from a relative
|
|
14
|
+
* `expires_in` (seconds from now). Returns `undefined` when the TTL
|
|
15
|
+
* is absent or non-finite, so callers can skip proactive refresh for
|
|
16
|
+
* tokens that never expire or carry no expiry information.
|
|
17
|
+
*
|
|
18
|
+
* @param expiresIn - Token lifetime in seconds, or undefined.
|
|
19
|
+
* @returns Absolute expiry timestamp, or undefined.
|
|
20
|
+
*/
|
|
21
|
+
export function computeExpiresAt(expiresIn) {
|
|
22
|
+
if (expiresIn === undefined || !Number.isFinite(expiresIn)) {
|
|
23
|
+
return undefined;
|
|
24
|
+
}
|
|
25
|
+
return new Date(Date.now() + expiresIn * 1000).toISOString();
|
|
26
|
+
}
|
|
27
|
+
/**
|
|
28
|
+
* Determines whether a token with the given absolute expiry is due for
|
|
29
|
+
* proactive refresh. Returns true when the token is already expired or
|
|
30
|
+
* will expire within {@link REFRESH_BUFFER_MS}.
|
|
31
|
+
*
|
|
32
|
+
* @param expiresAtIso - ISO-8601 expiry timestamp.
|
|
33
|
+
* @returns True when the token should be refreshed now.
|
|
34
|
+
*/
|
|
35
|
+
function needsRefresh(expiresAtIso) {
|
|
36
|
+
const expiresAtMs = Date.parse(expiresAtIso);
|
|
37
|
+
if (Number.isNaN(expiresAtMs)) {
|
|
38
|
+
return false;
|
|
39
|
+
}
|
|
40
|
+
return expiresAtMs - Date.now() <= REFRESH_BUFFER_MS;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Returns the refresh token when the stored tokens are due for a
|
|
44
|
+
* proactive refresh (expired or within the refresh buffer), or undefined
|
|
45
|
+
* when no refresh is needed or none can be attempted.
|
|
46
|
+
*
|
|
47
|
+
* @param tokens - The stored tokens, if any.
|
|
48
|
+
* @returns The refresh token to present, or undefined.
|
|
49
|
+
*/
|
|
50
|
+
export function dueRefreshToken(tokens) {
|
|
51
|
+
if (!tokens?.refresh_token || !tokens.expires_at) {
|
|
52
|
+
return undefined;
|
|
53
|
+
}
|
|
54
|
+
return needsRefresh(tokens.expires_at) ? tokens.refresh_token : undefined;
|
|
55
|
+
}
|
|
56
|
+
/**
|
|
57
|
+
* Whether stored tokens should be cleared after a token request failed
|
|
58
|
+
* with a recoverable OAuth error. Tokens that are no longer due for a
|
|
59
|
+
* refresh were replaced by another process in the meantime — clearing
|
|
60
|
+
* them would discard that process's fresh credentials — so only stale
|
|
61
|
+
* (or legacy, expiry-less) tokens are invalidated.
|
|
62
|
+
*
|
|
63
|
+
* @param tokens - The tokens currently stored for the server.
|
|
64
|
+
* @returns True when the invalidation request should clear them.
|
|
65
|
+
*/
|
|
66
|
+
export function tokensNeedInvalidation(tokens) {
|
|
67
|
+
if (!tokens) {
|
|
68
|
+
return false;
|
|
69
|
+
}
|
|
70
|
+
if (tokens.expires_at === undefined) {
|
|
71
|
+
// No expiry information: cannot prove the tokens are fresh, so honor
|
|
72
|
+
// the invalidation request.
|
|
73
|
+
return true;
|
|
74
|
+
}
|
|
75
|
+
return needsRefresh(tokens.expires_at);
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* Performs one token refresh: discovers the authorization server
|
|
79
|
+
* metadata, calls the SDK's `refreshAuthorization`, and persists the
|
|
80
|
+
* refreshed tokens via `context.saveTokens` (which recomputes
|
|
81
|
+
* `expires_at`). The request carries the RFC 8707 `resource` indicator
|
|
82
|
+
* selected from the server's Protected Resource Metadata — the same
|
|
83
|
+
* indicator `login` sent — so a provider that binds tokens to a
|
|
84
|
+
* specific resource accepts the refresh.
|
|
85
|
+
*
|
|
86
|
+
* A transient Protected Resource Metadata discovery failure fails the
|
|
87
|
+
* refresh instead of issuing an unbound token: the server may bind
|
|
88
|
+
* tokens to a resource, and an unbound token is rejected as "not bound
|
|
89
|
+
* to this server". Errors propagate; nothing is swallowed, so callers
|
|
90
|
+
* can report the outcome.
|
|
91
|
+
*
|
|
92
|
+
* @param context - The manager-supplied inputs for the request.
|
|
93
|
+
* @param refreshToken - The refresh token to present.
|
|
94
|
+
* @returns The refreshed tokens, or undefined when no refresh could be
|
|
95
|
+
* attempted (no server URL, no server metadata, or no client
|
|
96
|
+
* registration).
|
|
97
|
+
* @throws When Protected Resource Metadata discovery failed
|
|
98
|
+
* transiently, or when the token request itself fails.
|
|
99
|
+
*/
|
|
100
|
+
export async function requestTokenRefresh(context, refreshToken) {
|
|
101
|
+
if (!context.serverUrl) {
|
|
102
|
+
return undefined;
|
|
103
|
+
}
|
|
104
|
+
const serverUrl = new URL(context.serverUrl);
|
|
105
|
+
const discovered = await discoverAuth(serverUrl);
|
|
106
|
+
if (discovered.resourceMetadataDiscoveryFailed) {
|
|
107
|
+
throw new Error('OAuth token refresh aborted: Protected Resource Metadata discovery failed transiently.');
|
|
108
|
+
}
|
|
109
|
+
if (!discovered.serverMetadata) {
|
|
110
|
+
return undefined;
|
|
111
|
+
}
|
|
112
|
+
// Record the issuer before reading the client registration: an
|
|
113
|
+
// entry obtained from a different authorization server must not
|
|
114
|
+
// be used for the refresh.
|
|
115
|
+
context.setIssuer(discovered.serverMetadata.issuer);
|
|
116
|
+
const clientInformation = await context.provider.clientInformation();
|
|
117
|
+
if (!clientInformation) {
|
|
118
|
+
return undefined;
|
|
119
|
+
}
|
|
120
|
+
const resource = await selectResourceURL(serverUrl, context.provider, discovered.resourceMetadata);
|
|
121
|
+
const newTokens = await refreshAuthorization(discovered.authorizationServerUrl, {
|
|
122
|
+
metadata: discovered.serverMetadata,
|
|
123
|
+
clientInformation,
|
|
124
|
+
refreshToken,
|
|
125
|
+
resource,
|
|
126
|
+
// Bound the token request like the connect-time token exchange:
|
|
127
|
+
// a hung token endpoint must not hold the cross-process refresh
|
|
128
|
+
// lock (or the invoking tool call) indefinitely.
|
|
129
|
+
fetchFn: createTimeoutFetch(getDownstreamTimeoutMs()),
|
|
130
|
+
});
|
|
131
|
+
await context.saveTokens(newTokens);
|
|
132
|
+
return newTokens;
|
|
133
|
+
}
|