@ny4n/mcp 0.0.0-stage → 1.0.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/LICENSE +21 -0
- package/LICENSES/modelcontextprotocol-typescript-sdk.txt +21 -0
- package/README.md +135 -2
- package/dist/auth-provider.d.ts +19 -0
- package/dist/auth-provider.d.ts.map +1 -0
- package/dist/auth-provider.js +2 -0
- package/dist/auth-provider.js.map +1 -0
- package/dist/client.d.ts +89 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +457 -0
- package/dist/client.js.map +1 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +7 -0
- package/dist/index.js.map +1 -0
- package/dist/oauth/callback.d.ts +48 -0
- package/dist/oauth/callback.d.ts.map +1 -0
- package/dist/oauth/callback.js +115 -0
- package/dist/oauth/callback.js.map +1 -0
- package/dist/oauth/discovery.d.ts +30 -0
- package/dist/oauth/discovery.d.ts.map +1 -0
- package/dist/oauth/discovery.js +156 -0
- package/dist/oauth/discovery.js.map +1 -0
- package/dist/oauth/errors.d.ts +25 -0
- package/dist/oauth/errors.d.ts.map +1 -0
- package/dist/oauth/errors.js +48 -0
- package/dist/oauth/errors.js.map +1 -0
- package/dist/oauth/flow.d.ts +102 -0
- package/dist/oauth/flow.d.ts.map +1 -0
- package/dist/oauth/flow.js +334 -0
- package/dist/oauth/flow.js.map +1 -0
- package/dist/oauth/index.d.ts +7 -0
- package/dist/oauth/index.d.ts.map +1 -0
- package/dist/oauth/index.js +6 -0
- package/dist/oauth/index.js.map +1 -0
- package/dist/oauth/provider.d.ts +62 -0
- package/dist/oauth/provider.d.ts.map +1 -0
- package/dist/oauth/provider.js +118 -0
- package/dist/oauth/provider.js.map +1 -0
- package/dist/oauth/types.d.ts +82 -0
- package/dist/oauth/types.d.ts.map +1 -0
- package/dist/oauth/types.js +109 -0
- package/dist/oauth/types.js.map +1 -0
- package/dist/protocol/content.d.ts +82 -0
- package/dist/protocol/content.d.ts.map +1 -0
- package/dist/protocol/content.js +41 -0
- package/dist/protocol/content.js.map +1 -0
- package/dist/protocol/jsonrpc.d.ts +59 -0
- package/dist/protocol/jsonrpc.d.ts.map +1 -0
- package/dist/protocol/jsonrpc.js +67 -0
- package/dist/protocol/jsonrpc.js.map +1 -0
- package/dist/protocol/types.d.ts +123 -0
- package/dist/protocol/types.d.ts.map +1 -0
- package/dist/protocol/types.js +7 -0
- package/dist/protocol/types.js.map +1 -0
- package/dist/testing/index.d.ts +2 -0
- package/dist/testing/index.d.ts.map +1 -0
- package/dist/testing/index.js +2 -0
- package/dist/testing/index.js.map +1 -0
- package/dist/transports/in-memory.d.ts +19 -0
- package/dist/transports/in-memory.d.ts.map +1 -0
- package/dist/transports/in-memory.js +50 -0
- package/dist/transports/in-memory.js.map +1 -0
- package/dist/transports/stdio.d.ts +32 -0
- package/dist/transports/stdio.d.ts.map +1 -0
- package/dist/transports/stdio.js +201 -0
- package/dist/transports/stdio.js.map +1 -0
- package/dist/transports/streamable-http.d.ts +99 -0
- package/dist/transports/streamable-http.d.ts.map +1 -0
- package/dist/transports/streamable-http.js +459 -0
- package/dist/transports/streamable-http.js.map +1 -0
- package/dist/transports/transport.d.ts +28 -0
- package/dist/transports/transport.d.ts.map +1 -0
- package/dist/transports/transport.js +38 -0
- package/dist/transports/transport.js.map +1 -0
- package/package.json +59 -5
|
@@ -0,0 +1,334 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Adapted from modelcontextprotocol/typescript-sdk v1.29.0 src/client/auth.ts.
|
|
3
|
+
* Copyright (c) 2024 Anthropic, PBC. Licensed under MIT; see LICENSES/.
|
|
4
|
+
* Modified to remove SDK/Zod dependencies and use WebCrypto for PKCE.
|
|
5
|
+
*/
|
|
6
|
+
import { isObject } from "../protocol/jsonrpc.js";
|
|
7
|
+
import { discoverAuthorizationServerMetadata, discoverOAuthServerInfo, parseWwwAuthenticate, selectResource, } from "./discovery.js";
|
|
8
|
+
import { McpOAuthAuthorizationRequiredError, OAuthError, OAuthInsecureEndpointError, OAuthIssuerMismatchError, OAuthRegistrationError, } from "./errors.js";
|
|
9
|
+
import { parseClientInformation, parseOAuthTokens, } from "./types.js";
|
|
10
|
+
function loopback(hostname) {
|
|
11
|
+
return hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]" || hostname === "::1";
|
|
12
|
+
}
|
|
13
|
+
/**
|
|
14
|
+
* The OpenID Connect `application_type` for `redirect_uris` (MCP SEP-837). Without one, OpenID Connect servers
|
|
15
|
+
* assume `web`, which rejects http loopback redirect URIs. Loopback hosts and custom schemes are native (RFC 8252).
|
|
16
|
+
*/
|
|
17
|
+
function applicationType(redirectUris) {
|
|
18
|
+
const native = redirectUris.some((uri) => {
|
|
19
|
+
if (!URL.canParse(uri))
|
|
20
|
+
return false;
|
|
21
|
+
const url = new URL(uri);
|
|
22
|
+
return (url.protocol !== "http:" && url.protocol !== "https:") || loopback(url.hostname);
|
|
23
|
+
});
|
|
24
|
+
return native ? "native" : "web";
|
|
25
|
+
}
|
|
26
|
+
function secureEndpoint(value) {
|
|
27
|
+
const url = new URL(value);
|
|
28
|
+
if (url.protocol !== "https:" && !loopback(url.hostname))
|
|
29
|
+
throw new OAuthInsecureEndpointError(url.href);
|
|
30
|
+
return url;
|
|
31
|
+
}
|
|
32
|
+
function selectClientAuthMethod(information, supported) {
|
|
33
|
+
const hinted = "token_endpoint_auth_method" in information ? information.token_endpoint_auth_method : undefined;
|
|
34
|
+
if (hinted &&
|
|
35
|
+
["client_secret_basic", "client_secret_post", "none"].includes(hinted) &&
|
|
36
|
+
(supported.length === 0 || supported.includes(hinted))) {
|
|
37
|
+
return hinted;
|
|
38
|
+
}
|
|
39
|
+
if (supported.length === 0)
|
|
40
|
+
return information.client_secret ? "client_secret_basic" : "none";
|
|
41
|
+
if (information.client_secret && supported.includes("client_secret_basic"))
|
|
42
|
+
return "client_secret_basic";
|
|
43
|
+
if (information.client_secret && supported.includes("client_secret_post"))
|
|
44
|
+
return "client_secret_post";
|
|
45
|
+
if (supported.includes("none"))
|
|
46
|
+
return "none";
|
|
47
|
+
return information.client_secret ? "client_secret_post" : "none";
|
|
48
|
+
}
|
|
49
|
+
function applyClientAuthentication(method, information, headers, params) {
|
|
50
|
+
if (method === "client_secret_basic") {
|
|
51
|
+
if (!information.client_secret)
|
|
52
|
+
throw new Error("client_secret_basic requires a client secret");
|
|
53
|
+
headers.set("Authorization", `Basic ${Buffer.from(`${information.client_id}:${information.client_secret}`).toString("base64")}`);
|
|
54
|
+
}
|
|
55
|
+
else {
|
|
56
|
+
params.set("client_id", information.client_id);
|
|
57
|
+
if (method === "client_secret_post" && information.client_secret)
|
|
58
|
+
params.set("client_secret", information.client_secret);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
async function pkce() {
|
|
62
|
+
const bytes = crypto.getRandomValues(new Uint8Array(32));
|
|
63
|
+
const verifier = Buffer.from(bytes).toString("base64url");
|
|
64
|
+
const digest = await crypto.subtle.digest("SHA-256", new TextEncoder().encode(verifier));
|
|
65
|
+
return { verifier, challenge: Buffer.from(digest).toString("base64url") };
|
|
66
|
+
}
|
|
67
|
+
export async function startAuthorization(authorizationServerUrl, options) {
|
|
68
|
+
const metadata = options.metadata;
|
|
69
|
+
if (metadata && !metadata.response_types_supported.includes("code")) {
|
|
70
|
+
throw new Error("Authorization server does not support authorization codes");
|
|
71
|
+
}
|
|
72
|
+
if (metadata?.code_challenge_methods_supported && !metadata.code_challenge_methods_supported.includes("S256")) {
|
|
73
|
+
throw new Error("Authorization server does not support PKCE S256");
|
|
74
|
+
}
|
|
75
|
+
const url = new URL(metadata?.authorization_endpoint ?? new URL("/authorize", authorizationServerUrl));
|
|
76
|
+
const { verifier, challenge } = await pkce();
|
|
77
|
+
url.searchParams.set("response_type", "code");
|
|
78
|
+
url.searchParams.set("client_id", options.clientInformation.client_id);
|
|
79
|
+
url.searchParams.set("code_challenge", challenge);
|
|
80
|
+
url.searchParams.set("code_challenge_method", "S256");
|
|
81
|
+
url.searchParams.set("redirect_uri", String(options.redirectUrl));
|
|
82
|
+
if (options.state)
|
|
83
|
+
url.searchParams.set("state", options.state);
|
|
84
|
+
if (options.scope)
|
|
85
|
+
url.searchParams.set("scope", options.scope);
|
|
86
|
+
if (options.scope?.split(/\s+/).includes("offline_access"))
|
|
87
|
+
url.searchParams.set("prompt", "consent");
|
|
88
|
+
if (options.resource)
|
|
89
|
+
url.searchParams.set("resource", options.resource);
|
|
90
|
+
return { authorizationUrl: url, codeVerifier: verifier };
|
|
91
|
+
}
|
|
92
|
+
async function tokenRequest(authorizationServerUrl, options, params) {
|
|
93
|
+
const url = secureEndpoint(options.metadata?.token_endpoint ?? new URL("/token", authorizationServerUrl));
|
|
94
|
+
const headers = new Headers({ Accept: "application/json", "content-type": "application/x-www-form-urlencoded" });
|
|
95
|
+
if (options.resource)
|
|
96
|
+
params.set("resource", options.resource);
|
|
97
|
+
if (options.addClientAuthentication) {
|
|
98
|
+
await options.addClientAuthentication(headers, params, url, options.metadata);
|
|
99
|
+
}
|
|
100
|
+
else {
|
|
101
|
+
applyClientAuthentication(selectClientAuthMethod(options.clientInformation, options.metadata?.token_endpoint_auth_methods_supported ?? []), options.clientInformation, headers, params);
|
|
102
|
+
}
|
|
103
|
+
const response = await (options.fetch ?? globalThis.fetch)(url, {
|
|
104
|
+
method: "POST",
|
|
105
|
+
headers,
|
|
106
|
+
body: params,
|
|
107
|
+
signal: options.signal,
|
|
108
|
+
});
|
|
109
|
+
const text = await response.text();
|
|
110
|
+
let value;
|
|
111
|
+
try {
|
|
112
|
+
value = JSON.parse(text);
|
|
113
|
+
}
|
|
114
|
+
catch { }
|
|
115
|
+
// Servers may report OAuth errors with any status, so check the body before the status.
|
|
116
|
+
if (isObject(value) && typeof value.error === "string") {
|
|
117
|
+
throw new OAuthError(value.error, typeof value.error_description === "string" ? value.error_description : value.error, typeof value.error_uri === "string" ? value.error_uri : undefined);
|
|
118
|
+
}
|
|
119
|
+
if (!response.ok)
|
|
120
|
+
throw new OAuthError("server_error", `HTTP ${response.status}: ${text}`);
|
|
121
|
+
return parseOAuthTokens(value);
|
|
122
|
+
}
|
|
123
|
+
export async function registerClient(authorizationServerUrl, options) {
|
|
124
|
+
const endpoint = options.metadata?.registration_endpoint;
|
|
125
|
+
if (options.metadata && !endpoint)
|
|
126
|
+
throw new Error("Authorization server does not support dynamic client registration");
|
|
127
|
+
const response = await (options.fetch ?? globalThis.fetch)(new URL(endpoint ?? new URL("/register", authorizationServerUrl)), {
|
|
128
|
+
method: "POST",
|
|
129
|
+
headers: { Accept: "application/json", "content-type": "application/json" },
|
|
130
|
+
body: JSON.stringify({
|
|
131
|
+
...options.clientMetadata,
|
|
132
|
+
application_type: options.clientMetadata.application_type ?? applicationType(options.clientMetadata.redirect_uris),
|
|
133
|
+
...(options.scope ? { scope: options.scope } : {}),
|
|
134
|
+
}),
|
|
135
|
+
signal: options.signal,
|
|
136
|
+
});
|
|
137
|
+
if (!response.ok)
|
|
138
|
+
throw new OAuthRegistrationError(response.status, await response.text());
|
|
139
|
+
return parseClientInformation(await response.json());
|
|
140
|
+
}
|
|
141
|
+
export async function exchangeAuthorizationCode(authorizationServerUrl, options) {
|
|
142
|
+
return tokenRequest(authorizationServerUrl, options, new URLSearchParams({
|
|
143
|
+
grant_type: "authorization_code",
|
|
144
|
+
code: options.code,
|
|
145
|
+
code_verifier: options.codeVerifier,
|
|
146
|
+
redirect_uri: String(options.redirectUrl),
|
|
147
|
+
}));
|
|
148
|
+
}
|
|
149
|
+
export async function refreshAuthorization(authorizationServerUrl, options) {
|
|
150
|
+
const tokens = await tokenRequest(authorizationServerUrl, options, new URLSearchParams({ grant_type: "refresh_token", refresh_token: options.refreshToken }));
|
|
151
|
+
return { refresh_token: options.refreshToken, ...tokens };
|
|
152
|
+
}
|
|
153
|
+
function withScope(tokens, scope) {
|
|
154
|
+
return tokens.scope === undefined && scope ? { ...tokens, scope } : tokens;
|
|
155
|
+
}
|
|
156
|
+
/**
|
|
157
|
+
* Scopes for a step-up authorization: the challenged scopes plus the ones granted so far, since a
|
|
158
|
+
* challenge may list only the missing scopes and a token with just those would lose access the old
|
|
159
|
+
* one had (SEP-2350). Without challenged scopes, `undefined` lets the flow pick its default.
|
|
160
|
+
*/
|
|
161
|
+
export function stepUpScope(granted, challenged) {
|
|
162
|
+
if (!challenged)
|
|
163
|
+
return undefined;
|
|
164
|
+
const scopes = [granted, challenged].flatMap((scope) => scope?.split(/\s+/).filter(Boolean) ?? []);
|
|
165
|
+
return [...new Set(scopes)].join(" ");
|
|
166
|
+
}
|
|
167
|
+
async function runFlow(provider, options) {
|
|
168
|
+
const metadataUrl = options.authorizationServerMetadataUrl && secureEndpoint(options.authorizationServerMetadataUrl);
|
|
169
|
+
// With a configured metadata URL, discovery is not cached, so changing the URL applies at once.
|
|
170
|
+
const cached = metadataUrl ? undefined : await provider.discoveryState?.();
|
|
171
|
+
const discovered = cached?.authorizationServerUrl
|
|
172
|
+
? {
|
|
173
|
+
authorizationServerUrl: cached.authorizationServerUrl,
|
|
174
|
+
authorizationServerMetadata: cached.authorizationServerMetadata ??
|
|
175
|
+
(await discoverAuthorizationServerMetadata(cached.authorizationServerUrl, {
|
|
176
|
+
fetch: options.fetch,
|
|
177
|
+
skipIssuerValidation: options.skipIssuerValidation,
|
|
178
|
+
signal: options.signal,
|
|
179
|
+
})),
|
|
180
|
+
resourceMetadata: cached.resourceMetadata,
|
|
181
|
+
}
|
|
182
|
+
: await discoverOAuthServerInfo(options.serverUrl, {
|
|
183
|
+
resourceMetadataUrl: options.resourceMetadataUrl,
|
|
184
|
+
authorizationServerMetadataUrl: metadataUrl,
|
|
185
|
+
fetch: options.fetch,
|
|
186
|
+
skipIssuerValidation: options.skipIssuerValidation,
|
|
187
|
+
signal: options.signal,
|
|
188
|
+
});
|
|
189
|
+
if (!metadataUrl) {
|
|
190
|
+
await provider.saveDiscoveryState?.({
|
|
191
|
+
...discovered,
|
|
192
|
+
...(options.resourceMetadataUrl ? { resourceMetadataUrl: options.resourceMetadataUrl.href } : {}),
|
|
193
|
+
});
|
|
194
|
+
}
|
|
195
|
+
const metadata = discovered.authorizationServerMetadata;
|
|
196
|
+
const resource = selectResource(options.serverUrl, discovered.resourceMetadata);
|
|
197
|
+
// `||`, not `??`: an empty scope (for example from `scopes_supported: []`) falls through to the next source.
|
|
198
|
+
const scope = options.scope || discovered.resourceMetadata?.scopes_supported?.join(" ") || provider.clientMetadata.scope;
|
|
199
|
+
const stored = await provider.clientInformation();
|
|
200
|
+
const clientDocument = stored ? undefined : provider.clientMetadataDocument?.(metadata);
|
|
201
|
+
if (clientDocument) {
|
|
202
|
+
const url = new URL(clientDocument.url);
|
|
203
|
+
if (url.protocol !== "https:" || url.pathname === "/")
|
|
204
|
+
throw new Error("Invalid OAuth client metadata URL");
|
|
205
|
+
}
|
|
206
|
+
let client = stored ?? (clientDocument && { client_id: clientDocument.url });
|
|
207
|
+
if (!client) {
|
|
208
|
+
if (options.authorizationCode)
|
|
209
|
+
throw new Error("OAuth client information is missing during code exchange");
|
|
210
|
+
if (!provider.saveClientInformation)
|
|
211
|
+
throw new Error("OAuth client information cannot be persisted");
|
|
212
|
+
client = await registerClient(discovered.authorizationServerUrl, {
|
|
213
|
+
metadata,
|
|
214
|
+
clientMetadata: provider.clientMetadata,
|
|
215
|
+
scope,
|
|
216
|
+
fetch: options.fetch,
|
|
217
|
+
signal: options.signal,
|
|
218
|
+
});
|
|
219
|
+
await provider.saveClientInformation(client);
|
|
220
|
+
}
|
|
221
|
+
// The document's redirect URI may differ from the provider's, for example by a server-specific path.
|
|
222
|
+
const redirectUrl = clientDocument?.redirectUrl ?? provider.redirectUrl;
|
|
223
|
+
const tokenOptions = {
|
|
224
|
+
metadata,
|
|
225
|
+
clientInformation: client,
|
|
226
|
+
resource,
|
|
227
|
+
addClientAuthentication: provider.addClientAuthentication,
|
|
228
|
+
fetch: options.fetch,
|
|
229
|
+
signal: options.signal,
|
|
230
|
+
};
|
|
231
|
+
if (options.authorizationCode) {
|
|
232
|
+
// RFC 9207: never send a code from another authorization server to this one. Without metadata there
|
|
233
|
+
// is no issuer to compare with, so any `iss` is rejected.
|
|
234
|
+
const iss = options.iss;
|
|
235
|
+
if (iss !== undefined || metadata?.authorization_response_iss_parameter_supported) {
|
|
236
|
+
if (iss !== metadata?.issuer)
|
|
237
|
+
throw new OAuthIssuerMismatchError(metadata?.issuer, iss);
|
|
238
|
+
}
|
|
239
|
+
const tokens = await exchangeAuthorizationCode(discovered.authorizationServerUrl, {
|
|
240
|
+
...tokenOptions,
|
|
241
|
+
code: options.authorizationCode,
|
|
242
|
+
codeVerifier: await provider.codeVerifier(),
|
|
243
|
+
redirectUrl,
|
|
244
|
+
});
|
|
245
|
+
// A response without `scope` grants the requested scope (RFC 6749 §5.1). Recorded so a step-up can
|
|
246
|
+
// keep it. Callers pass the options of the authorization request, so `scope` is what was requested.
|
|
247
|
+
await provider.saveTokens(withScope(tokens, scope));
|
|
248
|
+
return "AUTHORIZED";
|
|
249
|
+
}
|
|
250
|
+
const existing = options.skipRefresh ? undefined : await provider.tokens();
|
|
251
|
+
if (existing?.refresh_token) {
|
|
252
|
+
try {
|
|
253
|
+
const tokens = await refreshAuthorization(discovered.authorizationServerUrl, {
|
|
254
|
+
...tokenOptions,
|
|
255
|
+
refreshToken: existing.refresh_token,
|
|
256
|
+
});
|
|
257
|
+
// A refresh without `scope` keeps the scope of the grant (RFC 6749 §6).
|
|
258
|
+
await provider.saveTokens(withScope(tokens, existing.scope));
|
|
259
|
+
return "AUTHORIZED";
|
|
260
|
+
}
|
|
261
|
+
catch (error) {
|
|
262
|
+
if (options.signal?.aborted || error instanceof OAuthInsecureEndpointError)
|
|
263
|
+
throw error;
|
|
264
|
+
if (error instanceof OAuthError && error.code !== "server_error")
|
|
265
|
+
throw error;
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
const state = await provider.state?.();
|
|
269
|
+
const authorization = await startAuthorization(discovered.authorizationServerUrl, {
|
|
270
|
+
metadata,
|
|
271
|
+
clientInformation: client,
|
|
272
|
+
redirectUrl,
|
|
273
|
+
scope,
|
|
274
|
+
state,
|
|
275
|
+
resource,
|
|
276
|
+
});
|
|
277
|
+
await provider.saveCodeVerifier(authorization.codeVerifier);
|
|
278
|
+
await provider.redirectToAuthorization(authorization.authorizationUrl);
|
|
279
|
+
return "REDIRECT";
|
|
280
|
+
}
|
|
281
|
+
export async function authorizeMcp(provider, options) {
|
|
282
|
+
try {
|
|
283
|
+
return await runFlow(provider, options);
|
|
284
|
+
}
|
|
285
|
+
catch (error) {
|
|
286
|
+
if (error instanceof OAuthError && ["invalid_client", "unauthorized_client"].includes(error.code)) {
|
|
287
|
+
await provider.invalidateCredentials?.("all");
|
|
288
|
+
return runFlow(provider, options);
|
|
289
|
+
}
|
|
290
|
+
if (error instanceof OAuthError && error.code === "invalid_grant") {
|
|
291
|
+
await provider.invalidateCredentials?.("tokens");
|
|
292
|
+
return runFlow(provider, options);
|
|
293
|
+
}
|
|
294
|
+
throw error;
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
/**
|
|
298
|
+
* Auth provider for `StreamableHttpTransport`. After a 401 it refreshes the tokens, or throws
|
|
299
|
+
* `McpOAuthAuthorizationRequiredError` when the user has to authorize (again). Concurrent 401s share
|
|
300
|
+
* one refresh, and a request whose token was already replaced is just retried: with rotating refresh
|
|
301
|
+
* tokens, a second refresh with the old refresh token would fail and discard the new grant.
|
|
302
|
+
*/
|
|
303
|
+
export function adaptOAuthProvider(provider) {
|
|
304
|
+
let inFlight;
|
|
305
|
+
return {
|
|
306
|
+
token: async () => (await provider.tokens())?.access_token,
|
|
307
|
+
onUnauthorized: async (context) => {
|
|
308
|
+
const challenge = parseWwwAuthenticate(context.response.headers.get("www-authenticate"));
|
|
309
|
+
const insufficientScope = challenge.error === "insufficient_scope";
|
|
310
|
+
if (!insufficientScope && !inFlight && context.token !== undefined) {
|
|
311
|
+
const current = (await provider.tokens())?.access_token;
|
|
312
|
+
if (current !== undefined && current !== context.token)
|
|
313
|
+
return;
|
|
314
|
+
}
|
|
315
|
+
inFlight ??= Promise.resolve(insufficientScope ? provider.tokens() : undefined)
|
|
316
|
+
.then((granted) => authorizeMcp(provider, {
|
|
317
|
+
serverUrl: context.serverUrl,
|
|
318
|
+
resourceMetadataUrl: challenge.resourceMetadataUrl,
|
|
319
|
+
scope: insufficientScope ? stepUpScope(granted?.scope, challenge.scope) : challenge.scope,
|
|
320
|
+
fetch: context.fetch,
|
|
321
|
+
skipRefresh: insufficientScope,
|
|
322
|
+
}))
|
|
323
|
+
.then((result) => {
|
|
324
|
+
if (result === "REDIRECT")
|
|
325
|
+
throw new McpOAuthAuthorizationRequiredError();
|
|
326
|
+
})
|
|
327
|
+
.finally(() => {
|
|
328
|
+
inFlight = undefined;
|
|
329
|
+
});
|
|
330
|
+
await inFlight;
|
|
331
|
+
},
|
|
332
|
+
};
|
|
333
|
+
}
|
|
334
|
+
//# sourceMappingURL=flow.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"flow.js","sourceRoot":"","sources":["../../src/oauth/flow.ts"],"names":[],"mappings":"AAAA;;;;GAIG;AAGH,OAAO,EAAE,QAAQ,EAAE,MAAM,wBAAwB,CAAC;AAClD,OAAO,EACN,mCAAmC,EACnC,uBAAuB,EACvB,oBAAoB,EACpB,cAAc,GACd,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACN,kCAAkC,EAClC,UAAU,EACV,0BAA0B,EAC1B,wBAAwB,EACxB,sBAAsB,GACtB,MAAM,aAAa,CAAC;AACrB,OAAO,EAQN,sBAAsB,EACtB,gBAAgB,GAChB,MAAM,YAAY,CAAC;AAyEpB,SAAS,QAAQ,CAAC,QAAgB;IACjC,OAAO,QAAQ,KAAK,WAAW,IAAI,QAAQ,KAAK,WAAW,IAAI,QAAQ,KAAK,OAAO,IAAI,QAAQ,KAAK,KAAK,CAAC;AAC3G,CAAC;AAED;;;GAGG;AACH,SAAS,eAA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AAI,CAAC,CAAC,OAAO,EAAE,EAAE,CACjB,YAAY,CAAC,QAAQ,EAAE;gBACtB,SAAS,EAAE,OAAO,CAAC,SAAS;gBAC5B,mBAAmB,EAAE,SAAS,CAAC,mBAAmB;gBAClD,KAAK,EAAE,iBAAiB,CAAC,CAAC,CAAC,WAAW,CAAC,OAAO,EAAE,KAAK,EAAE,SAAS,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,SAAS,CAAC,KAAK;gBACzF,KAAK,EAAE,OAAO,CAAC,KAAK;gBACpB,WAAW,EAAE,iBAAiB;aAC9B,CAAC,CACF;iBACA,IAAI,CAAC,CAAC,MAAM,EAAE,EAAE;gBAChB,IAAI,MAAM,KAAK,UAAU;oBAAE,MAAM,IAAI,kCAAkC,EAAE,CAAC;YAC3E,CAAC,CAAC;iBACD,OAAO,CAAC,GAAG,EAAE;gBACb,QAAQ,GAAG,SAAS,CAAC;YACtB,CAAC,CAAC,CAAC;YACJ,MAAM,QAAQ,CAAC;QAChB,CAAC;KACD,CAAC;AACH,CAAC","sourcesContent":["/*\n * Adapted from modelcontextprotocol/typescript-sdk v1.29.0 src/client/auth.ts.\n * Copyright (c) 2024 Anthropic, PBC. Licensed under MIT; see LICENSES/.\n * Modified to remove SDK/Zod dependencies and use WebCrypto for PKCE.\n */\n\nimport type { AuthProvider, McpFetch, UnauthorizedContext } from \"../auth-provider.ts\";\nimport { isObject } from \"../protocol/jsonrpc.ts\";\nimport {\n\tdiscoverAuthorizationServerMetadata,\n\tdiscoverOAuthServerInfo,\n\tparseWwwAuthenticate,\n\tselectResource,\n} from \"./discovery.ts\";\nimport {\n\tMcpOAuthAuthorizationRequiredError,\n\tOAuthError,\n\tOAuthInsecureEndpointError,\n\tOAuthIssuerMismatchError,\n\tOAuthRegistrationError,\n} from \"./errors.ts\";\nimport {\n\ttype AuthorizationServerMetadata,\n\ttype OAuthClientInformation,\n\ttype OAuthClientInformationFull,\n\ttype OAuthClientInformationMixed,\n\ttype OAuthClientMetadata,\n\ttype OAuthDiscoveryState,\n\ttype OAuthTokens,\n\tparseClientInformation,\n\tparseOAuthTokens,\n} from \"./types.ts\";\n\nexport type AddClientAuthentication = (\n\theaders: Headers,\n\tparams: URLSearchParams,\n\turl: string | URL,\n\tmetadata?: AuthorizationServerMetadata,\n) => void | Promise<void>;\n\n/** A Client ID Metadata Document: an https URL used as `client_id`, and a redirect URI it lists. */\nexport interface OAuthClientMetadataDocument {\n\turl: string;\n\tredirectUrl: string;\n}\n\nexport interface OAuthClientProvider {\n\treadonly redirectUrl: string | URL;\n\treadonly clientMetadata: OAuthClientMetadata;\n\t/**\n\t * Client ID Metadata Document to identify as instead of registering dynamically, or `undefined` to\n\t * register. Called when no client information is stored; the document is not stored. `metadata` is\n\t * `undefined` when the authorization server has none; check `client_id_metadata_document_supported`.\n\t */\n\tclientMetadataDocument?(metadata: AuthorizationServerMetadata | undefined): OAuthClientMetadataDocument | undefined;\n\tstate?(): string | Promise<string>;\n\tclientInformation(): OAuthClientInformationMixed | undefined | Promise<OAuthClientInformationMixed | undefined>;\n\tsaveClientInformation?(information: OAuthClientInformationMixed): void | Promise<void>;\n\ttokens(): OAuthTokens | undefined | Promise<OAuthTokens | undefined>;\n\tsaveTokens(tokens: OAuthTokens): void | Promise<void>;\n\tredirectToAuthorization(url: URL): void | Promise<void>;\n\tsaveCodeVerifier(verifier: string): void | Promise<void>;\n\tcodeVerifier(): string | Promise<string>;\n\taddClientAuthentication?: AddClientAuthentication;\n\tinvalidateCredentials?(kind: \"all\" | \"client\" | \"tokens\" | \"verifier\" | \"discovery\"): void | Promise<void>;\n\tsaveDiscoveryState?(state: OAuthDiscoveryState): void | Promise<void>;\n\tdiscoveryState?(): OAuthDiscoveryState | undefined | Promise<OAuthDiscoveryState | undefined>;\n}\n\nexport interface OAuthFlowOptions {\n\tserverUrl: string | URL;\n\tauthorizationCode?: string;\n\t/** `iss` parameter of the authorization response that delivered `authorizationCode` (RFC 9207). */\n\tiss?: string;\n\tscope?: string;\n\tresourceMetadataUrl?: URL;\n\t/**\n\t * Authorization server metadata document to use instead of discovery, for servers that advertise a\n\t * wrong authorization server or none. It is trusted as configured. Must use https, except on loopback.\n\t */\n\tauthorizationServerMetadataUrl?: URL;\n\tfetch?: McpFetch;\n\t/** Aborts every request of the flow. Requests have no time limit of their own; combine with a timeout as needed. */\n\tsignal?: AbortSignal;\n\tskipIssuerValidation?: boolean;\n\t/**\n\t * Go straight to the authorization redirect instead of refreshing stored tokens, for example when the\n\t * server asks for scopes the current grant lacks (a refresh keeps the old scope).\n\t */\n\tskipRefresh?: boolean;\n}\n\nexport type OAuthFlowResult = \"AUTHORIZED\" | \"REDIRECT\";\ntype ClientAuthMethod = \"client_secret_basic\" | \"client_secret_post\" | \"none\";\n\nexport interface TokenRequestOptions {\n\tmetadata?: AuthorizationServerMetadata;\n\tclientInformation: OAuthClientInformationMixed;\n\tresource?: string;\n\taddClientAuthentication?: AddClientAuthentication;\n\tfetch?: McpFetch;\n\tsignal?: AbortSignal;\n}\n\nfunction loopback(hostname: string): boolean {\n\treturn hostname === \"localhost\" || hostname === \"127.0.0.1\" || hostname === \"[::1]\" || hostname === \"::1\";\n}\n\n/**\n * The OpenID Connect `application_type` for `redirect_uris` (MCP SEP-837). Without one, OpenID Connect servers\n * assume `web`, which rejects http loopback redirect URIs. Loopback hosts and custom schemes are native (RFC 8252).\n */\nfunction applicationType(redirectUris: readonly string[]): \"native\" | \"web\" {\n\tconst native = redirectUris.some((uri) => {\n\t\tif (!URL.canParse(uri)) return false;\n\t\tconst url = new URL(uri);\n\t\treturn (url.protocol !== \"http:\" && url.protocol !== \"https:\") || loopback(url.hostname);\n\t});\n\treturn native ? \"native\" : \"web\";\n}\n\nfunction secureEndpoint(value: string | URL): URL {\n\tconst url = new URL(value);\n\tif (url.protocol !== \"https:\" && !loopback(url.hostname)) throw new OAuthInsecureEndpointError(url.href);\n\treturn url;\n}\n\nfunction selectClientAuthMethod(information: OAuthClientInformationMixed, supported: string[]): ClientAuthMethod {\n\tconst hinted = \"token_endpoint_auth_method\" in information ? information.token_endpoint_auth_method : undefined;\n\tif (\n\t\thinted &&\n\t\t[\"client_secret_basic\", \"client_secret_post\", \"none\"].includes(hinted) &&\n\t\t(supported.length === 0 || supported.includes(hinted))\n\t) {\n\t\treturn hinted as ClientAuthMethod;\n\t}\n\tif (supported.length === 0) return information.client_secret ? \"client_secret_basic\" : \"none\";\n\tif (information.client_secret && supported.includes(\"client_secret_basic\")) return \"client_secret_basic\";\n\tif (information.client_secret && supported.includes(\"client_secret_post\")) return \"client_secret_post\";\n\tif (supported.includes(\"none\")) return \"none\";\n\treturn information.client_secret ? \"client_secret_post\" : \"none\";\n}\n\nfunction applyClientAuthentication(\n\tmethod: ClientAuthMethod,\n\tinformation: OAuthClientInformation,\n\theaders: Headers,\n\tparams: URLSearchParams,\n): void {\n\tif (method === \"client_secret_basic\") {\n\t\tif (!information.client_secret) throw new Error(\"client_secret_basic requires a client secret\");\n\t\theaders.set(\n\t\t\t\"Authorization\",\n\t\t\t`Basic ${Buffer.from(`${information.client_id}:${information.client_secret}`).toString(\"base64\")}`,\n\t\t);\n\t} else {\n\t\tparams.set(\"client_id\", information.client_id);\n\t\tif (method === \"client_secret_post\" && information.client_secret)\n\t\t\tparams.set(\"client_secret\", information.client_secret);\n\t}\n}\n\nasync function pkce(): Promise<{ verifier: string; challenge: string }> {\n\tconst bytes = crypto.getRandomValues(new Uint8Array(32));\n\tconst verifier = Buffer.from(bytes).toString(\"base64url\");\n\tconst digest = await crypto.subtle.digest(\"SHA-256\", new TextEncoder().encode(verifier));\n\treturn { verifier, challenge: Buffer.from(digest).toString(\"base64url\") };\n}\n\nexport async function startAuthorization(\n\tauthorizationServerUrl: string | URL,\n\toptions: {\n\t\tmetadata?: AuthorizationServerMetadata;\n\t\tclientInformation: OAuthClientInformationMixed;\n\t\tredirectUrl: string | URL;\n\t\tscope?: string;\n\t\tstate?: string;\n\t\tresource?: string;\n\t},\n): Promise<{ authorizationUrl: URL; codeVerifier: string }> {\n\tconst metadata = options.metadata;\n\tif (metadata && !metadata.response_types_supported.includes(\"code\")) {\n\t\tthrow new Error(\"Authorization server does not support authorization codes\");\n\t}\n\tif (metadata?.code_challenge_methods_supported && !metadata.code_challenge_methods_supported.includes(\"S256\")) {\n\t\tthrow new Error(\"Authorization server does not support PKCE S256\");\n\t}\n\tconst url = new URL(metadata?.authorization_endpoint ?? new URL(\"/authorize\", authorizationServerUrl));\n\tconst { verifier, challenge } = await pkce();\n\turl.searchParams.set(\"response_type\", \"code\");\n\turl.searchParams.set(\"client_id\", options.clientInformation.client_id);\n\turl.searchParams.set(\"code_challenge\", challenge);\n\turl.searchParams.set(\"code_challenge_method\", \"S256\");\n\turl.searchParams.set(\"redirect_uri\", String(options.redirectUrl));\n\tif (options.state) url.searchParams.set(\"state\", options.state);\n\tif (options.scope) url.searchParams.set(\"scope\", options.scope);\n\tif (options.scope?.split(/\\s+/).includes(\"offline_access\")) url.searchParams.set(\"prompt\", \"consent\");\n\tif (options.resource) url.searchParams.set(\"resource\", options.resource);\n\treturn { authorizationUrl: url, codeVerifier: verifier };\n}\n\nasync function tokenRequest(\n\tauthorizationServerUrl: string | URL,\n\toptions: TokenRequestOptions,\n\tparams: URLSearchParams,\n): Promise<OAuthTokens> {\n\tconst url = secureEndpoint(options.metadata?.token_endpoint ?? new URL(\"/token\", authorizationServerUrl));\n\tconst headers = new Headers({ Accept: \"application/json\", \"content-type\": \"application/x-www-form-urlencoded\" });\n\tif (options.resource) params.set(\"resource\", options.resource);\n\tif (options.addClientAuthentication) {\n\t\tawait options.addClientAuthentication(headers, params, url, options.metadata);\n\t} else {\n\t\tapplyClientAuthentication(\n\t\t\tselectClientAuthMethod(\n\t\t\t\toptions.clientInformation,\n\t\t\t\toptions.metadata?.token_endpoint_auth_methods_supported ?? [],\n\t\t\t),\n\t\t\toptions.clientInformation,\n\t\t\theaders,\n\t\t\tparams,\n\t\t);\n\t}\n\tconst response = await (options.fetch ?? globalThis.fetch)(url, {\n\t\tmethod: \"POST\",\n\t\theaders,\n\t\tbody: params,\n\t\tsignal: options.signal,\n\t});\n\tconst text = await response.text();\n\tlet value: unknown;\n\ttry {\n\t\tvalue = JSON.parse(text);\n\t} catch {}\n\t// Servers may report OAuth errors with any status, so check the body before the status.\n\tif (isObject(value) && typeof value.error === \"string\") {\n\t\tthrow new OAuthError(\n\t\t\tvalue.error,\n\t\t\ttypeof value.error_description === \"string\" ? value.error_description : value.error,\n\t\t\ttypeof value.error_uri === \"string\" ? value.error_uri : undefined,\n\t\t);\n\t}\n\tif (!response.ok) throw new OAuthError(\"server_error\", `HTTP ${response.status}: ${text}`);\n\treturn parseOAuthTokens(value);\n}\n\nexport async function registerClient(\n\tauthorizationServerUrl: string | URL,\n\toptions: {\n\t\tmetadata?: AuthorizationServerMetadata;\n\t\tclientMetadata: OAuthClientMetadata;\n\t\tscope?: string;\n\t\tfetch?: McpFetch;\n\t\tsignal?: AbortSignal;\n\t},\n): Promise<OAuthClientInformationFull> {\n\tconst endpoint = options.metadata?.registration_endpoint;\n\tif (options.metadata && !endpoint)\n\t\tthrow new Error(\"Authorization server does not support dynamic client registration\");\n\tconst response = await (options.fetch ?? globalThis.fetch)(\n\t\tnew URL(endpoint ?? new URL(\"/register\", authorizationServerUrl)),\n\t\t{\n\t\t\tmethod: \"POST\",\n\t\t\theaders: { Accept: \"application/json\", \"content-type\": \"application/json\" },\n\t\t\tbody: JSON.stringify({\n\t\t\t\t...options.clientMetadata,\n\t\t\t\tapplication_type:\n\t\t\t\t\toptions.clientMetadata.application_type ?? applicationType(options.clientMetadata.redirect_uris),\n\t\t\t\t...(options.scope ? { scope: options.scope } : {}),\n\t\t\t}),\n\t\t\tsignal: options.signal,\n\t\t},\n\t);\n\tif (!response.ok) throw new OAuthRegistrationError(response.status, await response.text());\n\treturn parseClientInformation(await response.json());\n}\n\nexport async function exchangeAuthorizationCode(\n\tauthorizationServerUrl: string | URL,\n\toptions: TokenRequestOptions & { code: string; codeVerifier: string; redirectUrl: string | URL },\n): Promise<OAuthTokens> {\n\treturn tokenRequest(\n\t\tauthorizationServerUrl,\n\t\toptions,\n\t\tnew URLSearchParams({\n\t\t\tgrant_type: \"authorization_code\",\n\t\t\tcode: options.code,\n\t\t\tcode_verifier: options.codeVerifier,\n\t\t\tredirect_uri: String(options.redirectUrl),\n\t\t}),\n\t);\n}\n\nexport async function refreshAuthorization(\n\tauthorizationServerUrl: string | URL,\n\toptions: TokenRequestOptions & { refreshToken: string },\n): Promise<OAuthTokens> {\n\tconst tokens = await tokenRequest(\n\t\tauthorizationServerUrl,\n\t\toptions,\n\t\tnew URLSearchParams({ grant_type: \"refresh_token\", refresh_token: options.refreshToken }),\n\t);\n\treturn { refresh_token: options.refreshToken, ...tokens };\n}\n\nfunction withScope(tokens: OAuthTokens, scope: string | undefined): OAuthTokens {\n\treturn tokens.scope === undefined && scope ? { ...tokens, scope } : tokens;\n}\n\n/**\n * Scopes for a step-up authorization: the challenged scopes plus the ones granted so far, since a\n * challenge may list only the missing scopes and a token with just those would lose access the old\n * one had (SEP-2350). Without challenged scopes, `undefined` lets the flow pick its default.\n */\nexport function stepUpScope(granted: string | undefined, challenged: string | undefined): string | undefined {\n\tif (!challenged) return undefined;\n\tconst scopes = [granted, challenged].flatMap((scope) => scope?.split(/\\s+/).filter(Boolean) ?? []);\n\treturn [...new Set(scopes)].join(\" \");\n}\n\nasync function runFlow(provider: OAuthClientProvider, options: OAuthFlowOptions): Promise<OAuthFlowResult> {\n\tconst metadataUrl = options.authorizationServerMetadataUrl && secureEndpoint(options.authorizationServerMetadataUrl);\n\t// With a configured metadata URL, discovery is not cached, so changing the URL applies at once.\n\tconst cached = metadataUrl ? undefined : await provider.discoveryState?.();\n\tconst discovered = cached?.authorizationServerUrl\n\t\t? {\n\t\t\t\tauthorizationServerUrl: cached.authorizationServerUrl,\n\t\t\t\tauthorizationServerMetadata:\n\t\t\t\t\tcached.authorizationServerMetadata ??\n\t\t\t\t\t(await discoverAuthorizationServerMetadata(cached.authorizationServerUrl, {\n\t\t\t\t\t\tfetch: options.fetch,\n\t\t\t\t\t\tskipIssuerValidation: options.skipIssuerValidation,\n\t\t\t\t\t\tsignal: options.signal,\n\t\t\t\t\t})),\n\t\t\t\tresourceMetadata: cached.resourceMetadata,\n\t\t\t}\n\t\t: await discoverOAuthServerInfo(options.serverUrl, {\n\t\t\t\tresourceMetadataUrl: options.resourceMetadataUrl,\n\t\t\t\tauthorizationServerMetadataUrl: metadataUrl,\n\t\t\t\tfetch: options.fetch,\n\t\t\t\tskipIssuerValidation: options.skipIssuerValidation,\n\t\t\t\tsignal: options.signal,\n\t\t\t});\n\tif (!metadataUrl) {\n\t\tawait provider.saveDiscoveryState?.({\n\t\t\t...discovered,\n\t\t\t...(options.resourceMetadataUrl ? { resourceMetadataUrl: options.resourceMetadataUrl.href } : {}),\n\t\t});\n\t}\n\tconst metadata = discovered.authorizationServerMetadata;\n\tconst resource = selectResource(options.serverUrl, discovered.resourceMetadata);\n\t// `||`, not `??`: an empty scope (for example from `scopes_supported: []`) falls through to the next source.\n\tconst scope =\n\t\toptions.scope || discovered.resourceMetadata?.scopes_supported?.join(\" \") || provider.clientMetadata.scope;\n\tconst stored = await provider.clientInformation();\n\tconst clientDocument = stored ? undefined : provider.clientMetadataDocument?.(metadata);\n\tif (clientDocument) {\n\t\tconst url = new URL(clientDocument.url);\n\t\tif (url.protocol !== \"https:\" || url.pathname === \"/\") throw new Error(\"Invalid OAuth client metadata URL\");\n\t}\n\tlet client = stored ?? (clientDocument && { client_id: clientDocument.url });\n\tif (!client) {\n\t\tif (options.authorizationCode) throw new Error(\"OAuth client information is missing during code exchange\");\n\t\tif (!provider.saveClientInformation) throw new Error(\"OAuth client information cannot be persisted\");\n\t\tclient = await registerClient(discovered.authorizationServerUrl, {\n\t\t\tmetadata,\n\t\t\tclientMetadata: provider.clientMetadata,\n\t\t\tscope,\n\t\t\tfetch: options.fetch,\n\t\t\tsignal: options.signal,\n\t\t});\n\t\tawait provider.saveClientInformation(client);\n\t}\n\t// The document's redirect URI may differ from the provider's, for example by a server-specific path.\n\tconst redirectUrl = clientDocument?.redirectUrl ?? provider.redirectUrl;\n\tconst tokenOptions: TokenRequestOptions = {\n\t\tmetadata,\n\t\tclientInformation: client,\n\t\tresource,\n\t\taddClientAuthentication: provider.addClientAuthentication,\n\t\tfetch: options.fetch,\n\t\tsignal: options.signal,\n\t};\n\tif (options.authorizationCode) {\n\t\t// RFC 9207: never send a code from another authorization server to this one. Without metadata there\n\t\t// is no issuer to compare with, so any `iss` is rejected.\n\t\tconst iss = options.iss;\n\t\tif (iss !== undefined || metadata?.authorization_response_iss_parameter_supported) {\n\t\t\tif (iss !== metadata?.issuer) throw new OAuthIssuerMismatchError(metadata?.issuer, iss);\n\t\t}\n\t\tconst tokens = await exchangeAuthorizationCode(discovered.authorizationServerUrl, {\n\t\t\t...tokenOptions,\n\t\t\tcode: options.authorizationCode,\n\t\t\tcodeVerifier: await provider.codeVerifier(),\n\t\t\tredirectUrl,\n\t\t});\n\t\t// A response without `scope` grants the requested scope (RFC 6749 §5.1). Recorded so a step-up can\n\t\t// keep it. Callers pass the options of the authorization request, so `scope` is what was requested.\n\t\tawait provider.saveTokens(withScope(tokens, scope));\n\t\treturn \"AUTHORIZED\";\n\t}\n\tconst existing = options.skipRefresh ? undefined : await provider.tokens();\n\tif (existing?.refresh_token) {\n\t\ttry {\n\t\t\tconst tokens = await refreshAuthorization(discovered.authorizationServerUrl, {\n\t\t\t\t...tokenOptions,\n\t\t\t\trefreshToken: existing.refresh_token,\n\t\t\t});\n\t\t\t// A refresh without `scope` keeps the scope of the grant (RFC 6749 §6).\n\t\t\tawait provider.saveTokens(withScope(tokens, existing.scope));\n\t\t\treturn \"AUTHORIZED\";\n\t\t} catch (error) {\n\t\t\tif (options.signal?.aborted || error instanceof OAuthInsecureEndpointError) throw error;\n\t\t\tif (error instanceof OAuthError && error.code !== \"server_error\") throw error;\n\t\t}\n\t}\n\tconst state = await provider.state?.();\n\tconst authorization = await startAuthorization(discovered.authorizationServerUrl, {\n\t\tmetadata,\n\t\tclientInformation: client,\n\t\tredirectUrl,\n\t\tscope,\n\t\tstate,\n\t\tresource,\n\t});\n\tawait provider.saveCodeVerifier(authorization.codeVerifier);\n\tawait provider.redirectToAuthorization(authorization.authorizationUrl);\n\treturn \"REDIRECT\";\n}\n\nexport async function authorizeMcp(provider: OAuthClientProvider, options: OAuthFlowOptions): Promise<OAuthFlowResult> {\n\ttry {\n\t\treturn await runFlow(provider, options);\n\t} catch (error) {\n\t\tif (error instanceof OAuthError && [\"invalid_client\", \"unauthorized_client\"].includes(error.code)) {\n\t\t\tawait provider.invalidateCredentials?.(\"all\");\n\t\t\treturn runFlow(provider, options);\n\t\t}\n\t\tif (error instanceof OAuthError && error.code === \"invalid_grant\") {\n\t\t\tawait provider.invalidateCredentials?.(\"tokens\");\n\t\t\treturn runFlow(provider, options);\n\t\t}\n\t\tthrow error;\n\t}\n}\n\n/**\n * Auth provider for `StreamableHttpTransport`. After a 401 it refreshes the tokens, or throws\n * `McpOAuthAuthorizationRequiredError` when the user has to authorize (again). Concurrent 401s share\n * one refresh, and a request whose token was already replaced is just retried: with rotating refresh\n * tokens, a second refresh with the old refresh token would fail and discard the new grant.\n */\nexport function adaptOAuthProvider(provider: OAuthClientProvider): AuthProvider {\n\tlet inFlight: Promise<void> | undefined;\n\treturn {\n\t\ttoken: async () => (await provider.tokens())?.access_token,\n\t\tonUnauthorized: async (context: UnauthorizedContext) => {\n\t\t\tconst challenge = parseWwwAuthenticate(context.response.headers.get(\"www-authenticate\"));\n\t\t\tconst insufficientScope = challenge.error === \"insufficient_scope\";\n\t\t\tif (!insufficientScope && !inFlight && context.token !== undefined) {\n\t\t\t\tconst current = (await provider.tokens())?.access_token;\n\t\t\t\tif (current !== undefined && current !== context.token) return;\n\t\t\t}\n\t\t\tinFlight ??= Promise.resolve(insufficientScope ? provider.tokens() : undefined)\n\t\t\t\t.then((granted) =>\n\t\t\t\t\tauthorizeMcp(provider, {\n\t\t\t\t\t\tserverUrl: context.serverUrl,\n\t\t\t\t\t\tresourceMetadataUrl: challenge.resourceMetadataUrl,\n\t\t\t\t\t\tscope: insufficientScope ? stepUpScope(granted?.scope, challenge.scope) : challenge.scope,\n\t\t\t\t\t\tfetch: context.fetch,\n\t\t\t\t\t\tskipRefresh: insufficientScope,\n\t\t\t\t\t}),\n\t\t\t\t)\n\t\t\t\t.then((result) => {\n\t\t\t\t\tif (result === \"REDIRECT\") throw new McpOAuthAuthorizationRequiredError();\n\t\t\t\t})\n\t\t\t\t.finally(() => {\n\t\t\t\t\tinFlight = undefined;\n\t\t\t\t});\n\t\t\tawait inFlight;\n\t\t},\n\t};\n}\n"]}
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
export { type OAuthCallback, type OAuthCallbackPage, OAuthCallbackServer, type OAuthCallbackServerOptions, } from "./callback.ts";
|
|
2
|
+
export { buildAuthorizationServerDiscoveryUrls, discoverAuthorizationServerMetadata, discoverOAuthServerInfo, discoverProtectedResourceMetadata, parseWwwAuthenticate, resourceUrlFromServerUrl, selectResource, } from "./discovery.ts";
|
|
3
|
+
export { McpOAuthAuthorizationRequiredError, OAuthError, OAuthInsecureEndpointError, OAuthIssuerMismatchError, OAuthRegistrationError, } from "./errors.ts";
|
|
4
|
+
export { type AddClientAuthentication, adaptOAuthProvider, authorizeMcp, exchangeAuthorizationCode, type OAuthClientMetadataDocument, type OAuthClientProvider, type OAuthFlowOptions, type OAuthFlowResult, refreshAuthorization, registerClient, startAuthorization, stepUpScope, type TokenRequestOptions, } from "./flow.ts";
|
|
5
|
+
export { McpOAuthProvider, type McpOAuthProviderOptions, type McpOAuthState, type McpOAuthStateStore, MemoryOAuthStateStore, } from "./provider.ts";
|
|
6
|
+
export type { AuthorizationServerMetadata, OAuthChallenge, OAuthClientInformation, OAuthClientInformationFull, OAuthClientInformationMixed, OAuthClientMetadata, OAuthDiscoveryState, OAuthProtectedResourceMetadata, OAuthServerInfo, OAuthTokens, } from "./types.ts";
|
|
7
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../../src/oauth/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACN,KAAK,aAAa,EAClB,KAAK,iBAAiB,EACtB,mBAAmB,EACnB,KAAK,0BAA0B,GAC/B,MAAM,eAAe,CAAC;AACvB,OAAO,EACN,qCAAqC,EACrC,mCAAmC,EACnC,uBAAuB,EACvB,iCAAiC,EACjC,oBAAoB,EACpB,wBAAwB,EACxB,cAAc,GACd,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACN,kCAAkC,EAClC,UAAU,EACV,0BAA0B,EAC1B,wBAAwB,EACxB,sBAAsB,GACtB,MAAM,aAAa,CAAC;AACrB,OAAO,EACN,KAAK,uBAAuB,EAC5B,kBAAkB,EAClB,YAAY,EACZ,yBAAyB,EACzB,KAAK,2BAA2B,EAChC,KAAK,mBAAmB,EACxB,KAAK,gBAAgB,EACrB,KAAK,eAAe,EACpB,oBAAoB,EACpB,cAAc,EACd,kBAAkB,EAClB,WAAW,EACX,KAAK,mBAAmB,GACxB,MAAM,WAAW,CAAC;AACnB,OAAO,EACN,gBAAgB,EAChB,KAAK,uBAAuB,EAC5B,KAAK,aAAa,EAClB,KAAK,kBAAkB,EACvB,qBAAqB,GACrB,MAAM,eAAe,CAAC;AACvB,YAAY,EACX,2BAA2B,EAC3B,cAAc,EACd,sBAAsB,EACtB,0BAA0B,EAC1B,2BAA2B,EAC3B,mBAAmB,EACnB,mBAAmB,EACnB,8BAA8B,EAC9B,eAAe,EACf,WAAW,GACX,MAAM,YAAY,CAAC"}
|
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
export { OAuthCallbackServer, } from "./callback.js";
|
|
2
|
+
export { buildAuthorizationServerDiscoveryUrls, discoverAuthorizationServerMetadata, discoverOAuthServerInfo, discoverProtectedResourceMetadata, parseWwwAuthenticate, resourceUrlFromServerUrl, selectResource, } from "./discovery.js";
|
|
3
|
+
export { McpOAuthAuthorizationRequiredError, OAuthError, OAuthInsecureEndpointError, OAuthIssuerMismatchError, OAuthRegistrationError, } from "./errors.js";
|
|
4
|
+
export { adaptOAuthProvider, authorizeMcp, exchangeAuthorizationCode, refreshAuthorization, registerClient, startAuthorization, stepUpScope, } from "./flow.js";
|
|
5
|
+
export { McpOAuthProvider, MemoryOAuthStateStore, } from "./provider.js";
|
|
6
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/oauth/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAGN,mBAAmB,GAEnB,MAAM,eAAe,CAAC;AACvB,OAAO,EACN,qCAAqC,EACrC,mCAAmC,EACnC,uBAAuB,EACvB,iCAAiC,EACjC,oBAAoB,EACpB,wBAAwB,EACxB,cAAc,GACd,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACN,kCAAkC,EAClC,UAAU,EACV,0BAA0B,EAC1B,wBAAwB,EACxB,sBAAsB,GACtB,MAAM,aAAa,CAAC;AACrB,OAAO,EAEN,kBAAkB,EAClB,YAAY,EACZ,yBAAyB,EAKzB,oBAAoB,EACpB,cAAc,EACd,kBAAkB,EAClB,WAAW,GAEX,MAAM,WAAW,CAAC;AACnB,OAAO,EACN,gBAAgB,EAIhB,qBAAqB,GACrB,MAAM,eAAe,CAAC","sourcesContent":["export {\n\ttype OAuthCallback,\n\ttype OAuthCallbackPage,\n\tOAuthCallbackServer,\n\ttype OAuthCallbackServerOptions,\n} from \"./callback.ts\";\nexport {\n\tbuildAuthorizationServerDiscoveryUrls,\n\tdiscoverAuthorizationServerMetadata,\n\tdiscoverOAuthServerInfo,\n\tdiscoverProtectedResourceMetadata,\n\tparseWwwAuthenticate,\n\tresourceUrlFromServerUrl,\n\tselectResource,\n} from \"./discovery.ts\";\nexport {\n\tMcpOAuthAuthorizationRequiredError,\n\tOAuthError,\n\tOAuthInsecureEndpointError,\n\tOAuthIssuerMismatchError,\n\tOAuthRegistrationError,\n} from \"./errors.ts\";\nexport {\n\ttype AddClientAuthentication,\n\tadaptOAuthProvider,\n\tauthorizeMcp,\n\texchangeAuthorizationCode,\n\ttype OAuthClientMetadataDocument,\n\ttype OAuthClientProvider,\n\ttype OAuthFlowOptions,\n\ttype OAuthFlowResult,\n\trefreshAuthorization,\n\tregisterClient,\n\tstartAuthorization,\n\tstepUpScope,\n\ttype TokenRequestOptions,\n} from \"./flow.ts\";\nexport {\n\tMcpOAuthProvider,\n\ttype McpOAuthProviderOptions,\n\ttype McpOAuthState,\n\ttype McpOAuthStateStore,\n\tMemoryOAuthStateStore,\n} from \"./provider.ts\";\nexport type {\n\tAuthorizationServerMetadata,\n\tOAuthChallenge,\n\tOAuthClientInformation,\n\tOAuthClientInformationFull,\n\tOAuthClientInformationMixed,\n\tOAuthClientMetadata,\n\tOAuthDiscoveryState,\n\tOAuthProtectedResourceMetadata,\n\tOAuthServerInfo,\n\tOAuthTokens,\n} from \"./types.ts\";\n"]}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import type { OAuthClientMetadataDocument, OAuthClientProvider } from "./flow.ts";
|
|
2
|
+
import type { AuthorizationServerMetadata, OAuthClientInformationMixed, OAuthClientMetadata, OAuthDiscoveryState, OAuthTokens } from "./types.ts";
|
|
3
|
+
export interface McpOAuthState {
|
|
4
|
+
serverUrl: string;
|
|
5
|
+
clientInformation?: OAuthClientInformationMixed;
|
|
6
|
+
tokens?: OAuthTokens;
|
|
7
|
+
/** When the access token expires, in milliseconds since the epoch, from `expires_in` at the time it was saved. */
|
|
8
|
+
tokensExpireAt?: number;
|
|
9
|
+
codeVerifier?: string;
|
|
10
|
+
oauthState?: string;
|
|
11
|
+
discovery?: OAuthDiscoveryState;
|
|
12
|
+
}
|
|
13
|
+
export interface McpOAuthStateStore {
|
|
14
|
+
load(): McpOAuthState | undefined | Promise<McpOAuthState | undefined>;
|
|
15
|
+
save(state: McpOAuthState): void | Promise<void>;
|
|
16
|
+
}
|
|
17
|
+
export interface McpOAuthProviderOptions {
|
|
18
|
+
serverUrl: string | URL;
|
|
19
|
+
redirectUrl: string | URL;
|
|
20
|
+
clientMetadata: Omit<OAuthClientMetadata, "redirect_uris"> & {
|
|
21
|
+
redirect_uris?: string[];
|
|
22
|
+
};
|
|
23
|
+
/** See `OAuthClientProvider.clientMetadataDocument`. */
|
|
24
|
+
clientMetadataDocument?: (metadata: AuthorizationServerMetadata | undefined) => OAuthClientMetadataDocument | undefined;
|
|
25
|
+
clientId?: string;
|
|
26
|
+
clientSecret?: string;
|
|
27
|
+
store?: McpOAuthStateStore;
|
|
28
|
+
onRedirect(url: URL): void | Promise<void>;
|
|
29
|
+
}
|
|
30
|
+
export declare class MemoryOAuthStateStore implements McpOAuthStateStore {
|
|
31
|
+
private value;
|
|
32
|
+
load(): McpOAuthState | undefined;
|
|
33
|
+
save(state: McpOAuthState): void;
|
|
34
|
+
}
|
|
35
|
+
/** Default stateful provider for one exact MCP server URL. Applications inject durable storage if needed. */
|
|
36
|
+
export declare class McpOAuthProvider implements OAuthClientProvider {
|
|
37
|
+
readonly redirectUrl: string;
|
|
38
|
+
readonly clientMetadata: OAuthClientMetadata;
|
|
39
|
+
readonly clientMetadataDocument?: (metadata: AuthorizationServerMetadata | undefined) => OAuthClientMetadataDocument | undefined;
|
|
40
|
+
private serverUrl;
|
|
41
|
+
private configuredClient;
|
|
42
|
+
private store;
|
|
43
|
+
private onRedirect;
|
|
44
|
+
private writes;
|
|
45
|
+
constructor(options: McpOAuthProviderOptions);
|
|
46
|
+
state(): Promise<string>;
|
|
47
|
+
clientInformation(): Promise<OAuthClientInformationMixed | undefined>;
|
|
48
|
+
saveClientInformation(information: OAuthClientInformationMixed): Promise<void>;
|
|
49
|
+
tokens(): Promise<OAuthTokens | undefined>;
|
|
50
|
+
saveTokens(tokens: OAuthTokens): Promise<void>;
|
|
51
|
+
redirectToAuthorization(url: URL): Promise<void>;
|
|
52
|
+
saveCodeVerifier(verifier: string): Promise<void>;
|
|
53
|
+
codeVerifier(): Promise<string>;
|
|
54
|
+
invalidateCredentials(kind: "all" | "client" | "tokens" | "verifier" | "discovery"): Promise<void>;
|
|
55
|
+
saveDiscoveryState(discovery: OAuthDiscoveryState): Promise<void>;
|
|
56
|
+
discoveryState(): Promise<OAuthDiscoveryState | undefined>;
|
|
57
|
+
private load;
|
|
58
|
+
private update;
|
|
59
|
+
/** Stored state for another server URL is ignored so credentials never leak across servers. */
|
|
60
|
+
private own;
|
|
61
|
+
}
|
|
62
|
+
//# sourceMappingURL=provider.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../../src/oauth/provider.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,2BAA2B,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAClF,OAAO,KAAK,EACX,2BAA2B,EAC3B,2BAA2B,EAC3B,mBAAmB,EACnB,mBAAmB,EACnB,WAAW,EACX,MAAM,YAAY,CAAC;AAEpB,MAAM,WAAW,aAAa;IAC7B,SAAS,EAAE,MAAM,CAAC;IAClB,iBAAiB,CAAC,EAAE,2BAA2B,CAAC;IAChD,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,kHAAkH;IAClH,cAAc,CAAC,EAAE,MAAM,CAAC;IACxB,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,SAAS,CAAC,EAAE,mBAAmB,CAAC;CAChC;AAED,MAAM,WAAW,kBAAkB;IAClC,IAAI,IAAI,aAAa,GAAG,SAAS,GAAG,OAAO,CAAC,aAAa,GAAG,SAAS,CAAC,CAAC;IACvE,IAAI,CAAC,KAAK,EAAE,aAAa,GAAG,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC;CACjD;AAED,MAAM,WAAW,uBAAuB;IACvC,SAAS,EAAE,MAAM,G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C,CAE1E;IAEK,qBAAqB,CAAC,WAAW,EAAE,2BAA2B,GAAG,OAAO,CAAC,IAAI,CAAC,CAGnF;IAEK,MAAM,IAAI,OAAO,CAAC,WAAW,GAAG,SAAS,CAAC,CAE/C;IAEK,UAAU,CAAC,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CAQnD;IAEK,uBAAuB,CAAC,GAAG,EAAE,GAAG,GAAG,OAAO,CAAC,IAAI,CAAC,CAErD;IAEK,gBAAgB,CAAC,QAAQ,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAEtD;IAEK,YAAY,IAAI,OAAO,CAAC,MAAM,CAAC,CAIpC;IAEK,qBAAqB,CAAC,IAAI,EAAE,KAAK,GAAG,QAAQ,GAAG,QAAQ,GAAG,UAAU,GAAG,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CAavG;IAEK,kBAAkB,CAAC,SAAS,EAAE,mBAAmB,GAAG,OAAO,CAAC,IAAI,CAAC,CAEtE;IAEK,cAAc,IAAI,OAAO,CAAC,mBAAmB,GAAG,SAAS,CAAC,CAE/D;YAEa,IAAI;YAKJ,MAAM;IAOpB,+FAA+F;IAC/F,OAAO,CAAC,GAAG;CAGX"}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
export class MemoryOAuthStateStore {
|
|
2
|
+
value;
|
|
3
|
+
load() {
|
|
4
|
+
return this.value === undefined ? undefined : structuredClone(this.value);
|
|
5
|
+
}
|
|
6
|
+
save(state) {
|
|
7
|
+
this.value = structuredClone(state);
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
/** Default stateful provider for one exact MCP server URL. Applications inject durable storage if needed. */
|
|
11
|
+
export class McpOAuthProvider {
|
|
12
|
+
redirectUrl;
|
|
13
|
+
clientMetadata;
|
|
14
|
+
clientMetadataDocument;
|
|
15
|
+
serverUrl;
|
|
16
|
+
configuredClient;
|
|
17
|
+
store;
|
|
18
|
+
onRedirect;
|
|
19
|
+
writes = Promise.resolve();
|
|
20
|
+
constructor(options) {
|
|
21
|
+
this.serverUrl = String(new URL(options.serverUrl));
|
|
22
|
+
this.redirectUrl = String(options.redirectUrl);
|
|
23
|
+
this.clientMetadata = {
|
|
24
|
+
...options.clientMetadata,
|
|
25
|
+
redirect_uris: options.clientMetadata.redirect_uris ?? [this.redirectUrl],
|
|
26
|
+
grant_types: options.clientMetadata.grant_types ?? ["authorization_code", "refresh_token"],
|
|
27
|
+
response_types: options.clientMetadata.response_types ?? ["code"],
|
|
28
|
+
token_endpoint_auth_method: options.clientMetadata.token_endpoint_auth_method ?? (options.clientSecret ? "client_secret_post" : "none"),
|
|
29
|
+
};
|
|
30
|
+
this.clientMetadataDocument = options.clientMetadataDocument;
|
|
31
|
+
this.configuredClient = options.clientId
|
|
32
|
+
? { client_id: options.clientId, ...(options.clientSecret ? { client_secret: options.clientSecret } : {}) }
|
|
33
|
+
: undefined;
|
|
34
|
+
this.store = options.store ?? new MemoryOAuthStateStore();
|
|
35
|
+
this.onRedirect = options.onRedirect;
|
|
36
|
+
}
|
|
37
|
+
async state() {
|
|
38
|
+
const existing = (await this.load()).oauthState;
|
|
39
|
+
if (existing)
|
|
40
|
+
return existing;
|
|
41
|
+
const state = Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("hex");
|
|
42
|
+
await this.update((value) => ({ ...value, oauthState: state }));
|
|
43
|
+
return state;
|
|
44
|
+
}
|
|
45
|
+
async clientInformation() {
|
|
46
|
+
return this.configuredClient ?? (await this.load()).clientInformation;
|
|
47
|
+
}
|
|
48
|
+
async saveClientInformation(information) {
|
|
49
|
+
if (this.configuredClient)
|
|
50
|
+
return;
|
|
51
|
+
await this.update((value) => ({ ...value, clientInformation: information }));
|
|
52
|
+
}
|
|
53
|
+
async tokens() {
|
|
54
|
+
return (await this.load()).tokens;
|
|
55
|
+
}
|
|
56
|
+
async saveTokens(tokens) {
|
|
57
|
+
const expiresAt = tokens.expires_in === undefined ? undefined : Date.now() + tokens.expires_in * 1000;
|
|
58
|
+
await this.update((value) => {
|
|
59
|
+
const next = { ...value, tokens };
|
|
60
|
+
if (expiresAt === undefined)
|
|
61
|
+
delete next.tokensExpireAt;
|
|
62
|
+
else
|
|
63
|
+
next.tokensExpireAt = expiresAt;
|
|
64
|
+
return next;
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
async redirectToAuthorization(url) {
|
|
68
|
+
await this.onRedirect(url);
|
|
69
|
+
}
|
|
70
|
+
async saveCodeVerifier(verifier) {
|
|
71
|
+
await this.update((value) => ({ ...value, codeVerifier: verifier }));
|
|
72
|
+
}
|
|
73
|
+
async codeVerifier() {
|
|
74
|
+
const verifier = (await this.load()).codeVerifier;
|
|
75
|
+
if (!verifier)
|
|
76
|
+
throw new Error("No OAuth PKCE code verifier is stored");
|
|
77
|
+
return verifier;
|
|
78
|
+
}
|
|
79
|
+
async invalidateCredentials(kind) {
|
|
80
|
+
await this.update((value) => {
|
|
81
|
+
const next = { ...value };
|
|
82
|
+
if (kind === "all" || kind === "client")
|
|
83
|
+
delete next.clientInformation;
|
|
84
|
+
if (kind === "all" || kind === "tokens") {
|
|
85
|
+
delete next.tokens;
|
|
86
|
+
delete next.tokensExpireAt;
|
|
87
|
+
}
|
|
88
|
+
if (kind === "all" || kind === "verifier")
|
|
89
|
+
delete next.codeVerifier;
|
|
90
|
+
if (kind === "all" || kind === "discovery")
|
|
91
|
+
delete next.discovery;
|
|
92
|
+
if (kind === "all")
|
|
93
|
+
delete next.oauthState;
|
|
94
|
+
return next;
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
async saveDiscoveryState(discovery) {
|
|
98
|
+
await this.update((value) => ({ ...value, discovery }));
|
|
99
|
+
}
|
|
100
|
+
async discoveryState() {
|
|
101
|
+
return (await this.load()).discovery;
|
|
102
|
+
}
|
|
103
|
+
async load() {
|
|
104
|
+
await this.writes;
|
|
105
|
+
return this.own(await this.store.load());
|
|
106
|
+
}
|
|
107
|
+
async update(update) {
|
|
108
|
+
this.writes = this.writes.then(async () => {
|
|
109
|
+
await this.store.save(update(this.own(await this.store.load())));
|
|
110
|
+
});
|
|
111
|
+
await this.writes;
|
|
112
|
+
}
|
|
113
|
+
/** Stored state for another server URL is ignored so credentials never leak across servers. */
|
|
114
|
+
own(state) {
|
|
115
|
+
return state?.serverUrl === this.serverUrl ? state : { serverUrl: this.serverUrl };
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
//# sourceMappingURL=provider.js.map
|