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.
@@ -1,6 +1,6 @@
1
- import { ensureConfigDir, readConfigFile, writeConfigFile, readCredentials, writeCredentials, } from './config-io.js';
1
+ import { ensureConfigDir, readConfigFile, writeConfigFile, mutateCredentials, } from './config-io.js';
2
2
  import { normalizeDescription, SERVER_DESCRIPTION_GUIDANCE, validateGlobPattern, validateOAuthClientName, validateOAuthClientUri, } from '../utils/index.js';
3
- import { discoverAuth } from '../services/index.js';
3
+ import { discoverAuth, resolveBindingUrl } from '../services/index.js';
4
4
  import { handleLogin } from './login-command.js';
5
5
  /**
6
6
  * Validates every glob pattern in an optional tool list, throwing with
@@ -206,11 +206,11 @@ async function tryAutoLogin(configPath, name, url, noBrowser) {
206
206
  }
207
207
  catch {
208
208
  // Probe failed — cache 'unknown' and don't block the add.
209
- await persistAuthRequirement(configPath, name, 'unknown');
209
+ await persistAuthRequirement(configPath, name, url, 'unknown');
210
210
  return undefined;
211
211
  }
212
212
  // Cache the requirement regardless of the login outcome.
213
- await persistAuthRequirement(configPath, name, requirement);
213
+ await persistAuthRequirement(configPath, name, url, requirement);
214
214
  if (!hasOAuth) {
215
215
  return undefined;
216
216
  }
@@ -220,15 +220,23 @@ async function tryAutoLogin(configPath, name, url, noBrowser) {
220
220
  * Caches the probed auth requirement for a server in credentials.json,
221
221
  * preserving any previously stored tokens or client registration.
222
222
  *
223
+ * The entry's server-URL binding is backfilled from the probed URL when
224
+ * it has none yet; an existing binding is preserved so a URL change
225
+ * never re-binds old credentials to the new server.
226
+ *
223
227
  * @param configPath - Absolute path to the mcp.json file.
224
228
  * @param name - Server name.
229
+ * @param url - The server URL the probe ran against.
225
230
  * @param requirement - The probed auth requirement to cache.
226
231
  */
227
- async function persistAuthRequirement(configPath, name, requirement) {
228
- const existing = await readCredentials(configPath);
229
- await writeCredentials(configPath, name, {
230
- ...existing[name],
231
- authRequirement: requirement,
232
- checkedAt: new Date().toISOString(),
232
+ async function persistAuthRequirement(configPath, name, url, requirement) {
233
+ await mutateCredentials(configPath, name, (current) => {
234
+ const serverUrl = resolveBindingUrl(current, url);
235
+ return {
236
+ ...current,
237
+ ...(serverUrl !== undefined ? { serverUrl } : {}),
238
+ authRequirement: requirement,
239
+ checkedAt: new Date().toISOString(),
240
+ };
233
241
  });
234
242
  }
@@ -1,6 +1,6 @@
1
1
  import * as fs from 'node:fs/promises';
2
2
  import * as path from 'node:path';
3
- import { atomicWriteFile, parseJsonc } from '../utils/index.js';
3
+ import { atomicWriteFile, parseJsonc, withFileLock } from '../utils/index.js';
4
4
  /**
5
5
  * Type guard for Node.js system errors that carry a `code` property.
6
6
  *
@@ -19,6 +19,61 @@ function isNodeError(err) {
19
19
  function getCredentialsPath(configPath) {
20
20
  return path.join(path.dirname(configPath), 'credentials.json');
21
21
  }
22
+ /**
23
+ * Lock options for credentials.json mutations. A critical section is a
24
+ * few file operations long, so a short stale window is safe: a crashed
25
+ * holder is reclaimed quickly and a live one is never stolen (the holder
26
+ * renews the lock file's mtime while it works). The timeout exceeds the
27
+ * stale window so a crashed holder's lock is reclaimed before waiters
28
+ * give up.
29
+ */
30
+ const CREDENTIALS_LOCK_OPTIONS = {
31
+ timeoutMs: 15_000,
32
+ staleMs: 5_000,
33
+ retryDelayMs: 25,
34
+ };
35
+ /**
36
+ * Lock options for the cross-process OAuth refresh lock. Its critical
37
+ * section includes authorization-server discovery and the token request,
38
+ * both bounded by the downstream timeout, so waiters get a larger window
39
+ * than for plain file mutations.
40
+ */
41
+ const REFRESH_LOCK_OPTIONS = {
42
+ timeoutMs: 30_000,
43
+ staleMs: 15_000,
44
+ retryDelayMs: 25,
45
+ };
46
+ /**
47
+ * Runs `task` while holding the cross-process lock that serializes
48
+ * mutations of this config's credentials.json. Every writer of the shared
49
+ * file goes through this lock so concurrent router instances, CLI
50
+ * commands, and login flows cannot lose each other's updates.
51
+ *
52
+ * @param configPath - Absolute path to the mcp.json file.
53
+ * @param task - The mutation to run while holding the lock.
54
+ * @returns The task's result.
55
+ * @throws When the lock cannot be acquired before its timeout.
56
+ */
57
+ async function withCredentialsLock(configPath, task) {
58
+ const credPath = getCredentialsPath(configPath);
59
+ return withFileLock(`${credPath}.lock`, task, CREDENTIALS_LOCK_OPTIONS);
60
+ }
61
+ /**
62
+ * Runs `task` while holding the cross-process OAuth refresh lock for this
63
+ * config's credentials.json. Token refreshes take this lock before
64
+ * re-reading the stored tokens, so concurrent router instances refresh a
65
+ * rotating refresh token exactly once instead of racing each other into
66
+ * `invalid_grant`.
67
+ *
68
+ * @param configPath - Absolute path to the mcp.json file.
69
+ * @param task - The refresh operation to run while holding the lock.
70
+ * @returns The task's result.
71
+ * @throws When the lock cannot be acquired before its timeout.
72
+ */
73
+ export async function withRefreshLock(configPath, task) {
74
+ const credPath = getCredentialsPath(configPath);
75
+ return withFileLock(`${credPath}.refresh.lock`, task, REFRESH_LOCK_OPTIONS);
76
+ }
22
77
  /**
23
78
  * Ensures the parent directory and config file exist.
24
79
  * If the file does not exist, creates it with an empty mcpServers object.
@@ -121,17 +176,88 @@ export async function readCredentials(configPath) {
121
176
  return parsed;
122
177
  }
123
178
  /**
124
- * Writes (or overwrites) credentials for a single server.
125
- * Preserves existing mcpServers and credentials for other servers.
179
+ * Mutates a single server's credentials entry through a fresh
180
+ * read-modify-write executed under the cross-process credentials lock.
181
+ *
182
+ * `mutate` receives the entry currently on disk (or `undefined` when the
183
+ * server has none) and returns:
184
+ * - a replacement entry, written to the store;
185
+ * - `undefined` to delete the entry (and the file when it becomes empty);
186
+ * - the same reference it received to leave the store untouched.
187
+ *
188
+ * Reading inside the lock is what makes concurrent writers safe: a token
189
+ * refresh or auth-requirement update that lands between the caller's
190
+ * earlier read and this call is seen by `mutate` instead of being
191
+ * overwritten by a stale snapshot.
192
+ *
193
+ * @param configPath - Absolute path to the mcp.json file.
194
+ * @param name - Server name.
195
+ * @param mutate - Computes the next entry from the current on-disk one.
196
+ * @param logger - Optional logger for permission warnings.
197
+ * @throws If the lock cannot be acquired, the store is unreadable or
198
+ * invalid, or the write fails.
199
+ */
200
+ export async function mutateCredentials(configPath, name, mutate, logger) {
201
+ await withCredentialsLock(configPath, async () => {
202
+ const credPath = getCredentialsPath(configPath);
203
+ const store = (await readCredentialsStore(credPath)) ?? {};
204
+ const current = store[name];
205
+ const next = mutate(current);
206
+ if (next === current) {
207
+ // No change requested: skip the write entirely.
208
+ return;
209
+ }
210
+ if (next === undefined) {
211
+ delete store[name];
212
+ }
213
+ else {
214
+ store[name] = next;
215
+ }
216
+ await writeCredentialsStore(credPath, store, logger);
217
+ });
218
+ }
219
+ /**
220
+ * Writes (or overwrites) credentials for a single server under the
221
+ * cross-process credentials lock. Preserves credentials for other
222
+ * servers.
223
+ *
224
+ * @internal Exported for tests and the cross-process concurrency
225
+ * fixture only; production code writes through
226
+ * {@link mutateCredentials} so it merges against the latest on-disk
227
+ * entry.
126
228
  *
127
229
  * @param configPath - Absolute path to the mcp.json file.
128
230
  * @param name - Server name.
129
231
  * @param credentials - The credentials to store.
232
+ * @param logger - Optional logger for permission warnings.
130
233
  */
131
234
  export async function writeCredentials(configPath, name, credentials, logger) {
132
- const credPath = getCredentialsPath(configPath);
133
- const store = (await readCredentialsStore(credPath, 'writing')) ?? {};
134
- store[name] = credentials;
235
+ await mutateCredentials(configPath, name, () => credentials, logger);
236
+ }
237
+ /**
238
+ * Replaces the whole credentials store atomically. Deletes the file when
239
+ * the store becomes empty. An existing file keeps its permissions; a new
240
+ * file is restricted to the owner.
241
+ *
242
+ * @param credPath - Absolute path to credentials.json.
243
+ * @param store - The complete store to persist.
244
+ * @param logger - Optional logger for permission warnings.
245
+ */
246
+ async function writeCredentialsStore(credPath, store, logger) {
247
+ if (Object.keys(store).length === 0) {
248
+ // No entries remain — delete the file entirely. A real failure
249
+ // (e.g. permission denied) must surface: silently leaving removed
250
+ // credentials on disk would defeat logout and `remove`.
251
+ try {
252
+ await fs.unlink(credPath);
253
+ }
254
+ catch (err) {
255
+ if (!isNodeError(err) || err.code !== 'ENOENT') {
256
+ throw err;
257
+ }
258
+ }
259
+ return;
260
+ }
135
261
  const { isNewFile, mode } = await resolveCredentialsMode(credPath);
136
262
  // Write atomically (unique temporary sibling + rename): a crash or
137
263
  // forced exit can never leave credentials.json truncated, and
@@ -148,23 +274,22 @@ export async function writeCredentials(configPath, name, credentials, logger) {
148
274
  * JSON) is fatal so a damaged store is never silently overwritten.
149
275
  *
150
276
  * @param credPath - Absolute path to credentials.json.
151
- * @param action - Action named in the error message.
152
277
  * @returns The stored credentials, or undefined when no file exists.
153
278
  */
154
- async function readCredentialsStore(credPath, action) {
279
+ async function readCredentialsStore(credPath) {
155
280
  try {
156
281
  const raw = await fs.readFile(credPath, 'utf-8');
157
282
  const parsed = JSON.parse(raw);
158
- if (typeof parsed === 'object' && parsed !== null) {
159
- return parsed;
283
+ if (typeof parsed !== 'object' || parsed === null || Array.isArray(parsed)) {
284
+ throw new Error(`Credentials file must contain a JSON object: ${credPath}`);
160
285
  }
161
- return {};
286
+ return parsed;
162
287
  }
163
288
  catch (err) {
164
289
  if (isNodeError(err) && err.code === 'ENOENT') {
165
290
  return undefined;
166
291
  }
167
- throw new Error(`Failed to read credentials file for ${action}: ${credPath}`, { cause: err });
292
+ throw new Error(`Failed to read credentials file for update: ${credPath}`, { cause: err });
168
293
  }
169
294
  }
170
295
  /**
@@ -207,27 +332,13 @@ async function restrictNewCredentialsFile(credPath, logger) {
207
332
  }
208
333
  }
209
334
  /**
210
- * Removes credentials for a server from the config file.
211
- * No-op if the server has no stored credentials.
212
- * Deletes the credentials file when the last entry is removed.
335
+ * Removes credentials for a server under the cross-process credentials
336
+ * lock. No-op if the server has no stored credentials. Deletes the
337
+ * credentials file when the last entry is removed.
213
338
  *
214
339
  * @param configPath - Absolute path to the mcp.json file.
215
340
  * @param name - Server name.
216
341
  */
217
342
  export async function removeCredentials(configPath, name) {
218
- const credPath = getCredentialsPath(configPath);
219
- const store = await readCredentialsStore(credPath, 'removal');
220
- if (store === undefined) {
221
- // File does not exist — nothing to remove
222
- return;
223
- }
224
- delete store[name];
225
- if (Object.keys(store).length === 0) {
226
- // No remaining entries — delete the file entirely
227
- await fs.unlink(credPath);
228
- }
229
- else {
230
- const { mode } = await resolveCredentialsMode(credPath);
231
- await atomicWriteFile(credPath, JSON.stringify(store, null, 2) + '\n', mode);
232
- }
343
+ await mutateCredentials(configPath, name, () => undefined);
233
344
  }
@@ -310,6 +310,10 @@ export async function handleLogin(configPath, name, options) {
310
310
  const callbackPort = _resolveCallbackPort(_validatePortOverride(options?.portOverride), effectiveServer);
311
311
  const mgr = new OAuthCredentialManager(configPath, effectiveServer);
312
312
  const { metadata, requireIssuer, resourceMetadata } = await discoverOAuthMetadata(effectiveServer, name);
313
+ // Bind any stored credentials to the authorization server that
314
+ // actually serves this login: a registration or token obtained from a
315
+ // different issuer must not be reused.
316
+ mgr.setIssuer(metadata.issuer);
313
317
  const { selectResourceURL, exchangeAuthorization } = await _getSdkAuth();
314
318
  // RFC 8707 resource indicator, selected from the server's Protected
315
319
  // Resource Metadata the same way the SDK's auth() flow selects it.
@@ -3,10 +3,16 @@ import { ensureConfigDir, readConfigFile, writeConfigFile, removeCredentials, }
3
3
  * Handles the `remove <name>` subcommand: deletes a server entry
4
4
  * and cleans up any stored OAuth credentials for that server.
5
5
  *
6
+ * Credentials are removed before the config is rewritten. If cleanup
7
+ * fails, the server stays configured and the command can be retried;
8
+ * the reverse order would drop the server from `mcp.json` while its
9
+ * credentials survive on disk.
10
+ *
6
11
  * @param configPath - Absolute path to the mcp.json file.
7
12
  * @param name - Server name to remove.
8
13
  * @returns Human-readable confirmation message to print to stdout.
9
- * @throws If the server name is not found.
14
+ * @throws If the server name is not found, or if credentials cleanup
15
+ * fails (the config is left untouched in that case).
10
16
  */
11
17
  export async function handleRemove(configPath, name) {
12
18
  await ensureConfigDir(configPath);
@@ -18,9 +24,9 @@ export async function handleRemove(configPath, name) {
18
24
  : ' No servers configured.';
19
25
  throw new Error(`Server "${name}" not found.${hint}`);
20
26
  }
27
+ // Clean up any stored OAuth credentials for the removed server first.
28
+ await removeCredentials(configPath, name);
21
29
  delete servers[name];
22
30
  await writeConfigFile(configPath, servers);
23
- // Clean up any stored OAuth credentials for the removed server.
24
- await removeCredentials(configPath, name);
25
31
  return `Removed server "${name}".`;
26
32
  }
@@ -97,8 +97,8 @@ export async function handleTools(configPath, name) {
97
97
  throw new Error(`Server "${name}" not found.${hint}`);
98
98
  }
99
99
  const logger = new Logger(process.env.MCP_COMPRESS_ROUTER_VERBOSE === 'true' ? 'debug' : 'info');
100
- // Refresh cached auth requirement for HTTP servers (Open Question 1:
101
- // yes, for consistency with `add`). stdio servers short-circuit inside
100
+ // Refresh cached auth requirement for HTTP servers, for consistency
101
+ // with `add`. stdio servers short-circuit inside
102
102
  // persistAuthRequirements and do no network access.
103
103
  if (target.type !== 'stdio') {
104
104
  await persistAuthRequirements(configPath, [target], logger);
@@ -0,0 +1,116 @@
1
+ /**
2
+ * Extracts the access token a request carries in its `Authorization`
3
+ * header. A missing header, a non-Bearer scheme, or an empty token all
4
+ * yield `undefined`, so the caller leaves the response untouched.
5
+ *
6
+ * @param headers - The request's headers, if any.
7
+ * @returns The bearer token, or undefined when the request carries none.
8
+ */
9
+ function bearerToken(headers) {
10
+ const authorization = new Headers(headers).get('authorization');
11
+ if (authorization === null) {
12
+ return undefined;
13
+ }
14
+ const match = /^Bearer\s+(.+)$/i.exec(authorization.trim());
15
+ return match?.[1];
16
+ }
17
+ /**
18
+ * Returns a copy of the request init whose `Authorization` header
19
+ * carries the given access token. Every other header and the body are
20
+ * preserved as-is, so a JSON-RPC body can be replayed verbatim.
21
+ *
22
+ * @param init - The original request init.
23
+ * @param accessToken - The replacement access token.
24
+ * @returns The request init for the retried request.
25
+ */
26
+ function withBearerToken(init, accessToken) {
27
+ const headers = new Headers(init?.headers);
28
+ headers.set('authorization', `Bearer ${accessToken}`);
29
+ return { ...init, headers };
30
+ }
31
+ /**
32
+ * Wraps a fetch implementation so a 401 that carried a bearer token is
33
+ * retried once through the credential manager's coordinated
34
+ * adopt-or-refresh path.
35
+ *
36
+ * The wrapper sees the outgoing `Authorization: Bearer <T>` header, so
37
+ * it knows exactly which token the rejected request carried. On a 401
38
+ * it asks the manager for a replacement: another process's freshly
39
+ * stored token is adopted without a refresh, and only a still-current
40
+ * token drives one coordinated refresh under the cross-process lock.
41
+ * When the manager yields a token, the 401 body is cancelled and the
42
+ * request is replayed once with the replacement token — the same init,
43
+ * including the same body (JSON-RPC bodies are strings, so reuse is
44
+ * safe). A retried non-401 response clears the auth-failure backoff; a
45
+ * retried 401 records the failure and is returned, so the SDK's
46
+ * `auth()` flow terminates instead of looping.
47
+ *
48
+ * Only 401 responses are handled: non-401 responses, requests without a
49
+ * bearer token, and a rejecting `baseFetch` pass through or propagate
50
+ * untouched. When the manager cannot attempt an adoption or refresh,
51
+ * the original 401 is returned with its body intact. A thrown
52
+ * coordinated attempt — after the manager's own failure-path re-read
53
+ * found no concurrently stored winner — also records the auth failure
54
+ * before the original 401 is returned, so `tokens()` omits
55
+ * `refresh_token` and the SDK's `auth()` terminates instead of
56
+ * refreshing outside the cross-process lock.
57
+ *
58
+ * @param baseFetch - The underlying fetch to wrap.
59
+ * @param manager - The credential manager for the downstream server, or
60
+ * undefined when the server has no OAuth credentials (the base fetch
61
+ * is returned unchanged).
62
+ * @param logger - Optional structured logger for adopt/refresh/backoff
63
+ * diagnostics. Token values are never logged.
64
+ * @returns A fetch-compatible function with the auth retry applied.
65
+ */
66
+ export function createAuthRetryFetch(baseFetch, manager, logger) {
67
+ if (!manager) {
68
+ return baseFetch;
69
+ }
70
+ return async (url, init) => {
71
+ const response = await baseFetch(url, init);
72
+ if (response.status !== 401) {
73
+ return response;
74
+ }
75
+ const usedToken = bearerToken(init?.headers);
76
+ if (usedToken === undefined) {
77
+ return response;
78
+ }
79
+ let tokens;
80
+ try {
81
+ tokens = await manager.refreshAfterUnauthorized(usedToken);
82
+ }
83
+ catch (err) {
84
+ logger?.warn('Coordinated OAuth token refresh failed', {
85
+ server: manager.serverName,
86
+ error: err instanceof Error ? err.message : String(err),
87
+ });
88
+ // The manager throws only when the failed attempt found no
89
+ // concurrently stored token to adopt. Record the auth failure so
90
+ // tokens() hides refresh_token and the SDK's auth() flow
91
+ // terminates instead of refreshing uncoordinated.
92
+ manager.noteAuthFailure();
93
+ return response;
94
+ }
95
+ if (tokens === undefined) {
96
+ // No adoption or refresh could be attempted; the SDK's own
97
+ // auth() flow handles the 401 with the body left intact.
98
+ return response;
99
+ }
100
+ logger?.debug('Adopted or refreshed OAuth token; retrying request', {
101
+ server: manager.serverName,
102
+ });
103
+ await response.body?.cancel();
104
+ const retried = await baseFetch(url, withBearerToken(init, tokens.access_token));
105
+ if (retried.status !== 401) {
106
+ manager.noteAuthSuccess();
107
+ return retried;
108
+ }
109
+ await retried.body?.cancel();
110
+ manager.noteAuthFailure();
111
+ logger?.warn('OAuth token still rejected; entering auth-failure backoff', {
112
+ server: manager.serverName,
113
+ });
114
+ return retried;
115
+ };
116
+ }
@@ -1,4 +1,5 @@
1
- import { readCredentials, writeCredentials } from '../cli/config-io.js';
1
+ import { mutateCredentials } from '../cli/config-io.js';
2
+ import { credentialsUsableFor, resolveBindingUrl } from './credential-binding.js';
2
3
  import { discoverAuth } from './oauth-discovery.js';
3
4
  /**
4
5
  * Probes a downstream HTTP server to determine whether it advertises OAuth
@@ -54,7 +55,9 @@ export function computeAuthStatus(server, stored) {
54
55
  return 'header';
55
56
  }
56
57
  const requirement = stored?.authRequirement ?? 'unknown';
57
- const hasTokens = Boolean(stored?.tokens?.access_token);
58
+ // Tokens bound to a different server URL do not count: the server
59
+ // needs a fresh login before it can be used.
60
+ const hasTokens = Boolean(stored?.tokens?.access_token) && credentialsUsableFor(stored, server.url);
58
61
  switch (requirement) {
59
62
  case 'oauth':
60
63
  return hasTokens ? 'authenticated' : 'requires login';
@@ -83,31 +86,39 @@ function hasAuthorizationHeader(headers) {
83
86
  * never support OAuth). Probe errors are recorded as `'unknown'` so a
84
87
  * single flaky server never blocks startup.
85
88
  *
86
- * The network probes run in parallel for speed, but the credential file
87
- * writes are serialized to avoid concurrent read-modify-write races.
89
+ * The network probes run in parallel for speed; each credential entry is
90
+ * then updated through a cross-process-locked read-modify-write, so a
91
+ * token refresh that lands while the probes are in flight is merged into
92
+ * the entry instead of being overwritten by a stale snapshot. Each
93
+ * entry's server-URL binding is backfilled from the probed server when it
94
+ * has none yet; an existing binding is preserved so a URL change never
95
+ * re-binds old credentials to the new server.
88
96
  *
89
97
  * @param configPath - Absolute path to the mcp.json file.
90
98
  * @param servers - Typed downstream server configs.
91
99
  * @param logger - Logger for diagnostic output.
92
100
  */
93
101
  export async function persistAuthRequirements(configPath, servers, logger) {
94
- // Read the existing store once so per-server tokens and client
95
- // registration survive the auth-requirement update.
96
- const existing = await readCredentials(configPath);
97
102
  const httpServers = servers.filter((server) => server.type !== 'stdio');
98
103
  // Network-bound: probe in parallel for speed.
99
104
  const results = await Promise.all(httpServers.map(async (server) => ({
100
105
  name: server.name,
101
106
  requirement: await probeAuthRequirement(server, logger),
107
+ serverUrl: server.url,
102
108
  })));
103
109
  const checkedAt = new Date().toISOString();
104
- // Serialize writes to avoid concurrent file read-modify-write races.
105
- for (const { name, requirement } of results) {
106
- await writeCredentials(configPath, name, {
107
- ...existing[name],
108
- authRequirement: requirement,
109
- checkedAt,
110
- });
110
+ // Each entry is updated from its current on-disk state under the
111
+ // credentials lock, preserving anything written in the meantime.
112
+ for (const { name, requirement, serverUrl } of results) {
113
+ await mutateCredentials(configPath, name, (current) => {
114
+ const boundUrl = resolveBindingUrl(current, serverUrl);
115
+ return {
116
+ ...current,
117
+ ...(boundUrl !== undefined ? { serverUrl: boundUrl } : {}),
118
+ authRequirement: requirement,
119
+ checkedAt,
120
+ };
121
+ }, logger);
111
122
  }
112
123
  logger.debug('Cached auth requirements', {
113
124
  servers: Object.fromEntries(results.map((r) => [r.name, r.requirement])),
@@ -0,0 +1,112 @@
1
+ /**
2
+ * Normalizes a server URL for credential-binding comparison. The
3
+ * canonical `URL.href` form lowercases the host, drops a default port,
4
+ * and adds the trailing slash of an origin URL, so equivalent spellings
5
+ * compare equal. A trailing slash on a non-origin path stays
6
+ * significant: `https://example.com/mcp` and
7
+ * `https://example.com/mcp/` are different endpoints.
8
+ *
9
+ * @param url - The server URL to normalize.
10
+ * @returns The normalized URL, or undefined when the input is absent or
11
+ * not a valid absolute URL.
12
+ */
13
+ function normalizeServerUrl(url) {
14
+ if (url === undefined) {
15
+ return undefined;
16
+ }
17
+ try {
18
+ return new URL(url).href;
19
+ }
20
+ catch {
21
+ return undefined;
22
+ }
23
+ }
24
+ /**
25
+ * Whether a credentials entry holds OAuth client registration or
26
+ * tokens, as opposed to probe-only auth-requirement metadata.
27
+ *
28
+ * @param creds - The stored credentials entry, if any.
29
+ * @returns True when the entry carries credential material.
30
+ */
31
+ function hasCredentialMaterial(creds) {
32
+ return (creds !== undefined && (creds.clientRegistration !== undefined || creds.tokens !== undefined));
33
+ }
34
+ /**
35
+ * Whether stored credentials may be used for a downstream server.
36
+ *
37
+ * An entry is bound to the server it was created for: credentials are
38
+ * only usable while the configured URL matches the recorded
39
+ * `serverUrl`, and, when both the entry and the caller know the
40
+ * authorization server issuer, only while the issuers match. This
41
+ * keeps a leftover entry from a removed or renamed server from being
42
+ * presented to a different domain.
43
+ *
44
+ * Entries without a recorded `serverUrl` (written before the binding
45
+ * existed) are adopted: they stay usable and are bound on the next
46
+ * write. Probe-only entries (no client registration, no tokens) carry
47
+ * no credential material and are always usable.
48
+ *
49
+ * @param creds - The stored credentials entry, if any.
50
+ * @param serverUrl - The configured URL of the downstream server.
51
+ * @param issuer - The discovered authorization server issuer, when
52
+ * known. Omitted when the caller has not discovered metadata.
53
+ * @returns True when the credentials may be used for this server.
54
+ */
55
+ export function credentialsUsableFor(creds, serverUrl, issuer) {
56
+ if (!hasCredentialMaterial(creds)) {
57
+ return true;
58
+ }
59
+ const currentUrl = normalizeServerUrl(serverUrl);
60
+ if (currentUrl === undefined) {
61
+ return false;
62
+ }
63
+ if (creds.serverUrl !== undefined) {
64
+ const storedUrl = normalizeServerUrl(creds.serverUrl);
65
+ if (storedUrl === undefined || storedUrl !== currentUrl) {
66
+ return false;
67
+ }
68
+ }
69
+ if (issuer !== undefined && creds.issuer !== undefined && creds.issuer !== issuer) {
70
+ return false;
71
+ }
72
+ return true;
73
+ }
74
+ /**
75
+ * Resolves the `serverUrl` to record on a credentials write. An
76
+ * existing binding on an entry with credential material wins — a URL
77
+ * change must not re-bind credentials to the new server. A probe-only
78
+ * entry keeps no binding: its URL describes where a probe ran, and
79
+ * inheriting it would stamp fresh credentials with a stale server URL.
80
+ * Either way an unbound entry is bound to the current server URL.
81
+ *
82
+ * @param existing - The entry being replaced, if any.
83
+ * @param serverUrl - The configured URL of the downstream server.
84
+ * @returns The URL to record, or undefined when neither source yields a
85
+ * valid URL.
86
+ */
87
+ export function resolveBindingUrl(existing, serverUrl) {
88
+ const boundUrl = hasCredentialMaterial(existing) ? existing.serverUrl : undefined;
89
+ return boundUrl ?? normalizeServerUrl(serverUrl);
90
+ }
91
+ /**
92
+ * Resolves the binding fields (`serverUrl`, `issuer`) recorded on
93
+ * every credentials write: the URL of the server the entry belongs to,
94
+ * and the authorization server issuer when it is known. A probe-only
95
+ * entry carries no credential material, so its binding is not
96
+ * inherited; otherwise existing values are preserved when the caller
97
+ * cannot determine them, so a write never strips a binding.
98
+ *
99
+ * @param existing - The entry being replaced, if any.
100
+ * @param serverUrl - The configured URL of the downstream server.
101
+ * @param issuer - The authorization server issuer for the current
102
+ * flow, when discovered.
103
+ * @returns The binding fields to spread into the written entry.
104
+ */
105
+ export function bindingFieldsFor(existing, serverUrl, issuer) {
106
+ const boundUrl = resolveBindingUrl(existing, serverUrl);
107
+ const resolvedIssuer = issuer ?? (hasCredentialMaterial(existing) ? existing.issuer : undefined);
108
+ return {
109
+ ...(boundUrl !== undefined ? { serverUrl: boundUrl } : {}),
110
+ ...(resolvedIssuer !== undefined ? { issuer: resolvedIssuer } : {}),
111
+ };
112
+ }