@diffra-ai/mcp 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +7 -0
- package/LICENSE +22 -0
- package/README.md +190 -2
- package/THIRD_PARTY_NOTICES/modelcontextprotocol-typescript-sdk.txt +21 -0
- 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 +461 -0
- package/dist/client.js.map +1 -0
- package/dist/config.d.ts +117 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/config.js +153 -0
- package/dist/config.js.map +1 -0
- package/dist/index.d.ts +16 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +14 -0
- package/dist/index.js.map +1 -0
- package/dist/input-schema.d.ts +7 -0
- package/dist/input-schema.d.ts.map +1 -0
- package/dist/input-schema.js +13 -0
- package/dist/input-schema.js.map +1 -0
- package/dist/model-content.d.ts +19 -0
- package/dist/model-content.d.ts.map +1 -0
- package/dist/model-content.js +67 -0
- package/dist/model-content.js.map +1 -0
- package/dist/naming.d.ts +23 -0
- package/dist/naming.d.ts.map +1 -0
- package/dist/naming.js +37 -0
- package/dist/naming.js.map +1 -0
- package/dist/oauth/auth-provider.d.ts +52 -0
- package/dist/oauth/auth-provider.d.ts.map +1 -0
- package/dist/oauth/auth-provider.js +97 -0
- package/dist/oauth/auth-provider.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 +119 -0
- package/dist/oauth/callback.js.map +1 -0
- package/dist/oauth/client-settings.d.ts +107 -0
- package/dist/oauth/client-settings.d.ts.map +1 -0
- package/dist/oauth/client-settings.js +114 -0
- package/dist/oauth/client-settings.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 +32 -0
- package/dist/oauth/errors.d.ts.map +1 -0
- package/dist/oauth/errors.js +58 -0
- package/dist/oauth/errors.js.map +1 -0
- package/dist/oauth/flow.d.ts +112 -0
- package/dist/oauth/flow.d.ts.map +1 -0
- package/dist/oauth/flow.js +360 -0
- package/dist/oauth/flow.js.map +1 -0
- package/dist/oauth/index.d.ts +11 -0
- package/dist/oauth/index.d.ts.map +1 -0
- package/dist/oauth/index.js +9 -0
- package/dist/oauth/index.js.map +1 -0
- package/dist/oauth/loopback.d.ts +51 -0
- package/dist/oauth/loopback.d.ts.map +1 -0
- package/dist/oauth/loopback.js +98 -0
- package/dist/oauth/loopback.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/sign-in.d.ts +73 -0
- package/dist/oauth/sign-in.d.ts.map +1 -0
- package/dist/oauth/sign-in.js +182 -0
- package/dist/oauth/sign-in.js.map +1 -0
- package/dist/oauth/types.d.ts +83 -0
- package/dist/oauth/types.d.ts.map +1 -0
- package/dist/oauth/types.js +113 -0
- package/dist/oauth/types.js.map +1 -0
- package/dist/output-limit.d.ts +24 -0
- package/dist/output-limit.d.ts.map +1 -0
- package/dist/output-limit.js +58 -0
- package/dist/output-limit.js.map +1 -0
- package/dist/protocol/content.d.ts +83 -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/result-schema.d.ts +10 -0
- package/dist/result-schema.d.ts.map +1 -0
- package/dist/result-schema.js +78 -0
- package/dist/result-schema.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/lines.d.ts +34 -0
- package/dist/transports/lines.d.ts.map +1 -0
- package/dist/transports/lines.js +85 -0
- package/dist/transports/lines.js.map +1 -0
- package/dist/transports/pipe.d.ts +49 -0
- package/dist/transports/pipe.d.ts.map +1 -0
- package/dist/transports/pipe.js +96 -0
- package/dist/transports/pipe.js.map +1 -0
- package/dist/transports/stdio.d.ts +29 -0
- package/dist/transports/stdio.d.ts.map +1 -0
- package/dist/transports/stdio.js +170 -0
- package/dist/transports/stdio.js.map +1 -0
- package/dist/transports/streamable-http.d.ts +103 -0
- package/dist/transports/streamable-http.d.ts.map +1 -0
- package/dist/transports/streamable-http.js +531 -0
- package/dist/transports/streamable-http.js.map +1 -0
- package/dist/transports/transport.d.ts +36 -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,360 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* Adapted from modelcontextprotocol/typescript-sdk v1.29.0 src/client/auth.ts.
|
|
3
|
+
* Copyright (c) 2024 Anthropic, PBC. Licensed under MIT; see THIRD_PARTY_NOTICES/.
|
|
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 { isHttpUrl, 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
|
+
// Callers open this URL with the platform URL handler, which also launches files and custom protocols.
|
|
77
|
+
if (!isHttpUrl(url))
|
|
78
|
+
throw new Error(`Invalid authorization endpoint ${url.href}`);
|
|
79
|
+
const { verifier, challenge } = await pkce();
|
|
80
|
+
url.searchParams.set("response_type", "code");
|
|
81
|
+
url.searchParams.set("client_id", options.clientInformation.client_id);
|
|
82
|
+
url.searchParams.set("code_challenge", challenge);
|
|
83
|
+
url.searchParams.set("code_challenge_method", "S256");
|
|
84
|
+
url.searchParams.set("redirect_uri", String(options.redirectUrl));
|
|
85
|
+
if (options.state)
|
|
86
|
+
url.searchParams.set("state", options.state);
|
|
87
|
+
if (options.scope)
|
|
88
|
+
url.searchParams.set("scope", options.scope);
|
|
89
|
+
if (options.scope?.split(/\s+/).includes("offline_access"))
|
|
90
|
+
url.searchParams.set("prompt", "consent");
|
|
91
|
+
if (options.resource)
|
|
92
|
+
url.searchParams.set("resource", options.resource);
|
|
93
|
+
return { authorizationUrl: url, codeVerifier: verifier };
|
|
94
|
+
}
|
|
95
|
+
async function tokenRequest(authorizationServerUrl, options, params) {
|
|
96
|
+
const url = secureEndpoint(options.metadata?.token_endpoint ?? new URL("/token", authorizationServerUrl));
|
|
97
|
+
const headers = new Headers({ Accept: "application/json", "content-type": "application/x-www-form-urlencoded" });
|
|
98
|
+
if (options.resource)
|
|
99
|
+
params.set("resource", options.resource);
|
|
100
|
+
if (options.addClientAuthentication) {
|
|
101
|
+
await options.addClientAuthentication(headers, params, url, options.metadata);
|
|
102
|
+
}
|
|
103
|
+
else {
|
|
104
|
+
applyClientAuthentication(selectClientAuthMethod(options.clientInformation, options.metadata?.token_endpoint_auth_methods_supported ?? []), options.clientInformation, headers, params);
|
|
105
|
+
}
|
|
106
|
+
const response = await (options.fetch ?? globalThis.fetch)(url, {
|
|
107
|
+
method: "POST",
|
|
108
|
+
headers,
|
|
109
|
+
body: params,
|
|
110
|
+
signal: options.signal,
|
|
111
|
+
});
|
|
112
|
+
const text = await response.text();
|
|
113
|
+
let value;
|
|
114
|
+
try {
|
|
115
|
+
value = JSON.parse(text);
|
|
116
|
+
}
|
|
117
|
+
catch { }
|
|
118
|
+
// Servers may report OAuth errors with any status, so check the body before the status.
|
|
119
|
+
if (isObject(value) && typeof value.error === "string") {
|
|
120
|
+
throw new OAuthError(value.error, typeof value.error_description === "string" ? value.error_description : value.error, typeof value.error_uri === "string" ? value.error_uri : undefined);
|
|
121
|
+
}
|
|
122
|
+
if (!response.ok)
|
|
123
|
+
throw new OAuthError("server_error", `HTTP ${response.status}: ${text}`);
|
|
124
|
+
return parseOAuthTokens(value);
|
|
125
|
+
}
|
|
126
|
+
export async function registerClient(authorizationServerUrl, options) {
|
|
127
|
+
const endpoint = options.metadata?.registration_endpoint;
|
|
128
|
+
if (options.metadata && !endpoint)
|
|
129
|
+
throw new Error("Authorization server does not support dynamic client registration");
|
|
130
|
+
const response = await (options.fetch ?? globalThis.fetch)(new URL(endpoint ?? new URL("/register", authorizationServerUrl)), {
|
|
131
|
+
method: "POST",
|
|
132
|
+
headers: { Accept: "application/json", "content-type": "application/json" },
|
|
133
|
+
body: JSON.stringify({
|
|
134
|
+
...options.clientMetadata,
|
|
135
|
+
application_type: options.clientMetadata.application_type ?? applicationType(options.clientMetadata.redirect_uris),
|
|
136
|
+
...(options.scope ? { scope: options.scope } : {}),
|
|
137
|
+
}),
|
|
138
|
+
signal: options.signal,
|
|
139
|
+
});
|
|
140
|
+
if (!response.ok)
|
|
141
|
+
throw new OAuthRegistrationError(response.status, await response.text());
|
|
142
|
+
return parseClientInformation(await response.json());
|
|
143
|
+
}
|
|
144
|
+
export async function exchangeAuthorizationCode(authorizationServerUrl, options) {
|
|
145
|
+
return tokenRequest(authorizationServerUrl, options, new URLSearchParams({
|
|
146
|
+
grant_type: "authorization_code",
|
|
147
|
+
code: options.code,
|
|
148
|
+
code_verifier: options.codeVerifier,
|
|
149
|
+
redirect_uri: String(options.redirectUrl),
|
|
150
|
+
}));
|
|
151
|
+
}
|
|
152
|
+
export async function refreshAuthorization(authorizationServerUrl, options) {
|
|
153
|
+
const tokens = await tokenRequest(authorizationServerUrl, options, new URLSearchParams({ grant_type: "refresh_token", refresh_token: options.refreshToken }));
|
|
154
|
+
return { refresh_token: options.refreshToken, ...tokens };
|
|
155
|
+
}
|
|
156
|
+
function withScope(tokens, scope) {
|
|
157
|
+
return tokens.scope === undefined && scope ? { ...tokens, scope } : tokens;
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Scopes for a step-up authorization: the challenged scopes plus the ones granted so far, since a
|
|
161
|
+
* challenge may list only the missing scopes and a token with just those would lose access the old
|
|
162
|
+
* one had (SEP-2350). Without challenged scopes, `undefined` lets the flow pick its default.
|
|
163
|
+
*/
|
|
164
|
+
export function stepUpScope(granted, challenged) {
|
|
165
|
+
if (!challenged)
|
|
166
|
+
return undefined;
|
|
167
|
+
const scopes = [granted, challenged].flatMap((scope) => scope?.split(/\s+/).filter(Boolean) ?? []);
|
|
168
|
+
return [...new Set(scopes)].join(" ");
|
|
169
|
+
}
|
|
170
|
+
async function runFlow(provider, options, use = {}) {
|
|
171
|
+
const metadataUrl = options.authorizationServerMetadataUrl && secureEndpoint(options.authorizationServerMetadataUrl);
|
|
172
|
+
// With a configured metadata URL, discovery is not cached, so changing the URL applies at once.
|
|
173
|
+
const cached = metadataUrl ? undefined : await provider.discoveryState?.();
|
|
174
|
+
const discovered = cached?.authorizationServerUrl
|
|
175
|
+
? {
|
|
176
|
+
authorizationServerUrl: cached.authorizationServerUrl,
|
|
177
|
+
authorizationServerMetadata: cached.authorizationServerMetadata ??
|
|
178
|
+
(await discoverAuthorizationServerMetadata(cached.authorizationServerUrl, {
|
|
179
|
+
fetch: options.fetch,
|
|
180
|
+
skipIssuerValidation: options.skipIssuerValidation,
|
|
181
|
+
signal: options.signal,
|
|
182
|
+
})),
|
|
183
|
+
resourceMetadata: cached.resourceMetadata,
|
|
184
|
+
}
|
|
185
|
+
: await discoverOAuthServerInfo(options.serverUrl, {
|
|
186
|
+
resourceMetadataUrl: options.resourceMetadataUrl,
|
|
187
|
+
authorizationServerMetadataUrl: metadataUrl,
|
|
188
|
+
fetch: options.fetch,
|
|
189
|
+
skipIssuerValidation: options.skipIssuerValidation,
|
|
190
|
+
signal: options.signal,
|
|
191
|
+
});
|
|
192
|
+
if (!metadataUrl) {
|
|
193
|
+
await provider.saveDiscoveryState?.({
|
|
194
|
+
...discovered,
|
|
195
|
+
...(options.resourceMetadataUrl ? { resourceMetadataUrl: options.resourceMetadataUrl.href } : {}),
|
|
196
|
+
});
|
|
197
|
+
}
|
|
198
|
+
const metadata = discovered.authorizationServerMetadata;
|
|
199
|
+
const resource = selectResource(options.serverUrl, discovered.resourceMetadata);
|
|
200
|
+
// `||`, not `??`: an empty scope (for example from `scopes_supported: []`) falls through to the next source.
|
|
201
|
+
const scope = options.scope || discovered.resourceMetadata?.scopes_supported?.join(" ") || provider.clientMetadata.scope;
|
|
202
|
+
const stored = await provider.clientInformation();
|
|
203
|
+
use.storedClientId = stored?.client_id;
|
|
204
|
+
const clientDocument = stored ? undefined : provider.clientMetadataDocument?.(metadata);
|
|
205
|
+
if (clientDocument) {
|
|
206
|
+
const url = new URL(clientDocument.url);
|
|
207
|
+
if (url.protocol !== "https:" || url.pathname === "/")
|
|
208
|
+
throw new Error("Invalid OAuth client metadata URL");
|
|
209
|
+
}
|
|
210
|
+
// The document's redirect URI may differ from the provider's, for example by a server-specific path.
|
|
211
|
+
const redirectUrl = clientDocument?.redirectUrl ?? String(provider.redirectUrl);
|
|
212
|
+
// Checked first: another redirect URI also explains a client that is missing for the exchange.
|
|
213
|
+
if (options.authorizationCode && options.authorizationRedirectUrl !== undefined) {
|
|
214
|
+
if (redirectUrl !== options.authorizationRedirectUrl) {
|
|
215
|
+
throw new Error(`The code exchange would use the redirect URI ${redirectUrl}, but the authorization request used ${options.authorizationRedirectUrl}`);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
let client = stored ?? (clientDocument && { client_id: clientDocument.url });
|
|
219
|
+
if (!client) {
|
|
220
|
+
if (options.refreshOnly)
|
|
221
|
+
return "REDIRECT";
|
|
222
|
+
if (options.authorizationCode) {
|
|
223
|
+
throw new Error("OAuth client information is missing during code exchange: the authorization request's client was removed, or the client settings changed");
|
|
224
|
+
}
|
|
225
|
+
if (!provider.saveClientInformation)
|
|
226
|
+
throw new Error("OAuth client information cannot be persisted");
|
|
227
|
+
client = await registerClient(discovered.authorizationServerUrl, {
|
|
228
|
+
metadata,
|
|
229
|
+
clientMetadata: provider.clientMetadata,
|
|
230
|
+
scope,
|
|
231
|
+
fetch: options.fetch,
|
|
232
|
+
signal: options.signal,
|
|
233
|
+
});
|
|
234
|
+
await provider.saveClientInformation(client);
|
|
235
|
+
}
|
|
236
|
+
const tokenOptions = {
|
|
237
|
+
metadata,
|
|
238
|
+
clientInformation: client,
|
|
239
|
+
resource,
|
|
240
|
+
addClientAuthentication: provider.addClientAuthentication,
|
|
241
|
+
fetch: options.fetch,
|
|
242
|
+
signal: options.signal,
|
|
243
|
+
};
|
|
244
|
+
if (options.authorizationCode) {
|
|
245
|
+
// RFC 9207: never send a code from another authorization server to this one. Without metadata there
|
|
246
|
+
// is no issuer to compare with, so any `iss` is rejected.
|
|
247
|
+
const iss = options.iss;
|
|
248
|
+
if (iss !== undefined || metadata?.authorization_response_iss_parameter_supported) {
|
|
249
|
+
if (iss !== metadata?.issuer)
|
|
250
|
+
throw new OAuthIssuerMismatchError(metadata?.issuer, iss);
|
|
251
|
+
}
|
|
252
|
+
const tokens = await exchangeAuthorizationCode(discovered.authorizationServerUrl, {
|
|
253
|
+
...tokenOptions,
|
|
254
|
+
code: options.authorizationCode,
|
|
255
|
+
codeVerifier: await provider.codeVerifier(),
|
|
256
|
+
redirectUrl,
|
|
257
|
+
});
|
|
258
|
+
// A response without `scope` grants the requested scope (RFC 6749 §5.1). Recorded so a step-up can
|
|
259
|
+
// keep it. Callers pass the options of the authorization request, so `scope` is what was requested.
|
|
260
|
+
await provider.saveTokens(withScope(tokens, scope));
|
|
261
|
+
return "AUTHORIZED";
|
|
262
|
+
}
|
|
263
|
+
const existing = options.skipRefresh ? undefined : await provider.tokens();
|
|
264
|
+
if (existing?.refresh_token) {
|
|
265
|
+
try {
|
|
266
|
+
const tokens = await refreshAuthorization(discovered.authorizationServerUrl, {
|
|
267
|
+
...tokenOptions,
|
|
268
|
+
refreshToken: existing.refresh_token,
|
|
269
|
+
});
|
|
270
|
+
// A refresh without `scope` keeps the scope of the grant (RFC 6749 §6).
|
|
271
|
+
await provider.saveTokens(withScope(tokens, existing.scope));
|
|
272
|
+
return "AUTHORIZED";
|
|
273
|
+
}
|
|
274
|
+
catch (error) {
|
|
275
|
+
if (options.signal?.aborted || error instanceof OAuthInsecureEndpointError)
|
|
276
|
+
throw error;
|
|
277
|
+
if (error instanceof OAuthError && error.code !== "server_error")
|
|
278
|
+
throw error;
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
if (options.refreshOnly)
|
|
282
|
+
return "REDIRECT";
|
|
283
|
+
const state = await provider.state?.();
|
|
284
|
+
const authorization = await startAuthorization(discovered.authorizationServerUrl, {
|
|
285
|
+
metadata,
|
|
286
|
+
clientInformation: client,
|
|
287
|
+
redirectUrl,
|
|
288
|
+
scope,
|
|
289
|
+
state,
|
|
290
|
+
resource,
|
|
291
|
+
});
|
|
292
|
+
await provider.saveCodeVerifier(authorization.codeVerifier);
|
|
293
|
+
await provider.redirectToAuthorization(authorization.authorizationUrl);
|
|
294
|
+
return "REDIRECT";
|
|
295
|
+
}
|
|
296
|
+
export async function authorizeMcp(provider, options) {
|
|
297
|
+
const use = {};
|
|
298
|
+
try {
|
|
299
|
+
return await runFlow(provider, options, use);
|
|
300
|
+
}
|
|
301
|
+
catch (error) {
|
|
302
|
+
if (error instanceof OAuthError && ["invalid_client", "unauthorized_client"].includes(error.code)) {
|
|
303
|
+
// A refresh keeps a pending authorization's `state` and verifier: they are the user's sign-in. A client
|
|
304
|
+
// stored meanwhile (by a sign-in that completed) is not the one the server rejected, so it stays.
|
|
305
|
+
if (options.refreshOnly) {
|
|
306
|
+
if ((await provider.clientInformation())?.client_id === use.storedClientId) {
|
|
307
|
+
for (const kind of ["client", "tokens", "discovery"])
|
|
308
|
+
await provider.invalidateCredentials?.(kind);
|
|
309
|
+
}
|
|
310
|
+
}
|
|
311
|
+
else {
|
|
312
|
+
await provider.invalidateCredentials?.("all");
|
|
313
|
+
}
|
|
314
|
+
return runFlow(provider, options);
|
|
315
|
+
}
|
|
316
|
+
if (error instanceof OAuthError && error.code === "invalid_grant") {
|
|
317
|
+
await provider.invalidateCredentials?.("tokens");
|
|
318
|
+
return runFlow(provider, options);
|
|
319
|
+
}
|
|
320
|
+
throw error;
|
|
321
|
+
}
|
|
322
|
+
}
|
|
323
|
+
/**
|
|
324
|
+
* Auth provider for `StreamableHttpTransport`. After a 401 it refreshes the tokens, or throws
|
|
325
|
+
* `McpOAuthAuthorizationRequiredError` when the user has to authorize (again). Concurrent 401s share
|
|
326
|
+
* one refresh, and a request whose token was already replaced is just retried: with rotating refresh
|
|
327
|
+
* tokens, a second refresh with the old refresh token would fail and discard the new grant.
|
|
328
|
+
*/
|
|
329
|
+
export function adaptOAuthProvider(provider) {
|
|
330
|
+
let inFlight;
|
|
331
|
+
return {
|
|
332
|
+
token: async () => (await provider.tokens())?.access_token,
|
|
333
|
+
onUnauthorized: async (context) => {
|
|
334
|
+
const challenge = parseWwwAuthenticate(context.response.headers.get("www-authenticate"));
|
|
335
|
+
const insufficientScope = challenge.error === "insufficient_scope";
|
|
336
|
+
if (!insufficientScope && !inFlight && context.token !== undefined) {
|
|
337
|
+
const current = (await provider.tokens())?.access_token;
|
|
338
|
+
if (current !== undefined && current !== context.token)
|
|
339
|
+
return;
|
|
340
|
+
}
|
|
341
|
+
inFlight ??= Promise.resolve(insufficientScope ? provider.tokens() : undefined)
|
|
342
|
+
.then((granted) => authorizeMcp(provider, {
|
|
343
|
+
serverUrl: context.serverUrl,
|
|
344
|
+
resourceMetadataUrl: challenge.resourceMetadataUrl,
|
|
345
|
+
scope: insufficientScope ? stepUpScope(granted?.scope, challenge.scope) : challenge.scope,
|
|
346
|
+
fetch: context.fetch,
|
|
347
|
+
skipRefresh: insufficientScope,
|
|
348
|
+
}))
|
|
349
|
+
.then((result) => {
|
|
350
|
+
if (result === "REDIRECT")
|
|
351
|
+
throw new McpOAuthAuthorizationRequiredError();
|
|
352
|
+
})
|
|
353
|
+
.finally(() => {
|
|
354
|
+
inFlight = undefined;
|
|
355
|
+
});
|
|
356
|
+
await inFlight;
|
|
357
|
+
},
|
|
358
|
+
};
|
|
359
|
+
}
|
|
360
|
+
//# 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,EAEN,SAAS,EAOT,sBAAsB,EACtB,gBAAgB,GAChB,MAAM,YAAY,CAAC;AAmFpB,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,eAAe,CAAC,YAA+B;IACvD,MAAM,MAAM,GAAG,YAAY,CAAC,IAAI,CAAC,CAAC,GAAG,EAAE,EAAE;QACxC,IAAI,CAAC,GAAG,CAAC,QAAQ,CAAC,GAAG,CAAC;YAAE,OAAO,KAAK,CAAC;QACrC,MAAM,GAAG,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,CAAC;QACzB,OAAO,CAAC,GAAG,CAAC,QA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;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 THIRD_PARTY_NOTICES/.\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\tisHttpUrl,\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\t/**\n\t * Only refresh the stored tokens: return `REDIRECT` instead of registering a client or preparing an\n\t * authorization request, so a pending authorization (its `state` and PKCE verifier) stays usable.\n\t */\n\trefreshOnly?: boolean;\n\t/**\n\t * With `authorizationCode`: the redirect URI the authorization request used. The exchange fails before\n\t * sending the code when the flow would send another one (RFC 6749 section 4.1.3 requires the same).\n\t */\n\tauthorizationRedirectUrl?: string;\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\t// Callers open this URL with the platform URL handler, which also launches files and custom protocols.\n\tif (!isHttpUrl(url)) throw new Error(`Invalid authorization endpoint ${url.href}`);\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\n/** What a flow used, for deciding what to invalidate after it failed. */\ninterface FlowUse {\n\t/** `client_id` of the stored client the flow used; `undefined` when none was stored. */\n\tstoredClientId?: string;\n}\n\nasync function runFlow(\n\tprovider: OAuthClientProvider,\n\toptions: OAuthFlowOptions,\n\tuse: FlowUse = {},\n): 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\tuse.storedClientId = stored?.client_id;\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\t// The document's redirect URI may differ from the provider's, for example by a server-specific path.\n\tconst redirectUrl = clientDocument?.redirectUrl ?? String(provider.redirectUrl);\n\t// Checked first: another redirect URI also explains a client that is missing for the exchange.\n\tif (options.authorizationCode && options.authorizationRedirectUrl !== undefined) {\n\t\tif (redirectUrl !== options.authorizationRedirectUrl) {\n\t\t\tthrow new Error(\n\t\t\t\t`The code exchange would use the redirect URI ${redirectUrl}, but the authorization request used ${options.authorizationRedirectUrl}`,\n\t\t\t);\n\t\t}\n\t}\n\tlet client = stored ?? (clientDocument && { client_id: clientDocument.url });\n\tif (!client) {\n\t\tif (options.refreshOnly) return \"REDIRECT\";\n\t\tif (options.authorizationCode) {\n\t\t\tthrow new Error(\n\t\t\t\t\"OAuth client information is missing during code exchange: the authorization request's client was removed, or the client settings changed\",\n\t\t\t);\n\t\t}\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\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\tif (options.refreshOnly) return \"REDIRECT\";\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\tconst use: FlowUse = {};\n\ttry {\n\t\treturn await runFlow(provider, options, use);\n\t} catch (error) {\n\t\tif (error instanceof OAuthError && [\"invalid_client\", \"unauthorized_client\"].includes(error.code)) {\n\t\t\t// A refresh keeps a pending authorization's `state` and verifier: they are the user's sign-in. A client\n\t\t\t// stored meanwhile (by a sign-in that completed) is not the one the server rejected, so it stays.\n\t\t\tif (options.refreshOnly) {\n\t\t\t\tif ((await provider.clientInformation())?.client_id === use.storedClientId) {\n\t\t\t\t\tfor (const kind of [\"client\", \"tokens\", \"discovery\"] as const)\n\t\t\t\t\t\tawait provider.invalidateCredentials?.(kind);\n\t\t\t\t}\n\t\t\t} else {\n\t\t\t\tawait provider.invalidateCredentials?.(\"all\");\n\t\t\t}\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,11 @@
|
|
|
1
|
+
export { createMcpAuthProvider, type McpAuthProvider } from "./auth-provider.ts";
|
|
2
|
+
export { type OAuthCallback, type OAuthCallbackPage, OAuthCallbackServer, type OAuthCallbackServerOptions, } from "./callback.ts";
|
|
3
|
+
export type { McpClientMetadataDocuments, McpOAuthClientOptions, McpOAuthServerStore, McpOAuthSettings, } from "./client-settings.ts";
|
|
4
|
+
export { buildAuthorizationServerDiscoveryUrls, discoverAuthorizationServerMetadata, discoverOAuthServerInfo, discoverProtectedResourceMetadata, parseWwwAuthenticate, resourceUrlFromServerUrl, selectResource, } from "./discovery.ts";
|
|
5
|
+
export { McpOAuthAuthorizationRequiredError, McpRefreshLockBusyError, OAuthError, OAuthInsecureEndpointError, OAuthIssuerMismatchError, OAuthRegistrationError, } from "./errors.ts";
|
|
6
|
+
export { type AddClientAuthentication, adaptOAuthProvider, authorizeMcp, exchangeAuthorizationCode, type OAuthClientMetadataDocument, type OAuthClientProvider, type OAuthFlowOptions, type OAuthFlowResult, refreshAuthorization, registerClient, startAuthorization, stepUpScope, type TokenRequestOptions, } from "./flow.ts";
|
|
7
|
+
export { listenForLoopbackSignIn, type McpLoopbackCallback, responseFromRedirectUrl, waitForLoopbackSignIn, } from "./loopback.ts";
|
|
8
|
+
export { McpOAuthProvider, type McpOAuthProviderOptions, type McpOAuthState, type McpOAuthStateStore, MemoryOAuthStateStore, } from "./provider.ts";
|
|
9
|
+
export { completeMcpSignIn, type McpAuthorizationResponse, McpSignInCancelledError, type McpSignInOptions, type McpSignInRedirect, type McpSignInStart, startMcpSignIn, } from "./sign-in.ts";
|
|
10
|
+
export type { AuthorizationServerMetadata, OAuthChallenge, OAuthClientInformation, OAuthClientInformationFull, OAuthClientInformationMixed, OAuthClientMetadata, OAuthDiscoveryState, OAuthProtectedResourceMetadata, OAuthServerInfo, OAuthTokens, } from "./types.ts";
|
|
11
|
+
//# 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,EAAE,qBAAqB,EAAE,KAAK,eAAe,EAAE,MAAM,oBAAoB,CAAC;AACjF,OAAO,EACN,KAAK,aAAa,EAClB,KAAK,iBAAiB,EACtB,mBAAmB,EACnB,KAAK,0BAA0B,GAC/B,MAAM,eAAe,CAAC;AACvB,YAAY,EACX,0BAA0B,EAC1B,qBAAqB,EACrB,mBAAmB,EACnB,gBAAgB,GAChB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EACN,qCAAqC,EACrC,mCAAmC,EACnC,uBAAuB,EACvB,iCAAiC,EACjC,oBAAoB,EACpB,wBAAwB,EACxB,cAAc,GACd,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACN,kCAAkC,EAClC,uBAAuB,EACvB,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,uBAAuB,EACvB,KAAK,mBAAmB,EACxB,uBAAuB,EACvB,qBAAqB,GACrB,MAAM,eAAe,CAAC;AACvB,OAAO,EACN,gBAAgB,EAChB,KAAK,uBAAuB,EAC5B,KAAK,aAAa,EAClB,KAAK,kBAAkB,EACvB,qBAAqB,GACrB,MAAM,eAAe,CAAC;AACvB,OAAO,EACN,iBAAiB,EACjB,KAAK,wBAAwB,EAC7B,uBAAuB,EACvB,KAAK,gBAAgB,EACrB,KAAK,iBAAiB,EACtB,KAAK,cAAc,EACnB,cAAc,GACd,MAAM,cAAc,CAAC;AACtB,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,9 @@
|
|
|
1
|
+
export { createMcpAuthProvider } from "./auth-provider.js";
|
|
2
|
+
export { OAuthCallbackServer, } from "./callback.js";
|
|
3
|
+
export { buildAuthorizationServerDiscoveryUrls, discoverAuthorizationServerMetadata, discoverOAuthServerInfo, discoverProtectedResourceMetadata, parseWwwAuthenticate, resourceUrlFromServerUrl, selectResource, } from "./discovery.js";
|
|
4
|
+
export { McpOAuthAuthorizationRequiredError, McpRefreshLockBusyError, OAuthError, OAuthInsecureEndpointError, OAuthIssuerMismatchError, OAuthRegistrationError, } from "./errors.js";
|
|
5
|
+
export { adaptOAuthProvider, authorizeMcp, exchangeAuthorizationCode, refreshAuthorization, registerClient, startAuthorization, stepUpScope, } from "./flow.js";
|
|
6
|
+
export { listenForLoopbackSignIn, responseFromRedirectUrl, waitForLoopbackSignIn, } from "./loopback.js";
|
|
7
|
+
export { McpOAuthProvider, MemoryOAuthStateStore, } from "./provider.js";
|
|
8
|
+
export { completeMcpSignIn, McpSignInCancelledError, startMcpSignIn, } from "./sign-in.js";
|
|
9
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/oauth/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,qBAAqB,EAAwB,MAAM,oBAAoB,CAAC;AACjF,OAAO,EAGN,mBAAmB,GAEnB,MAAM,eAAe,CAAC;AAOvB,OAAO,EACN,qCAAqC,EACrC,mCAAmC,EACnC,uBAAuB,EACvB,iCAAiC,EACjC,oBAAoB,EACpB,wBAAwB,EACxB,cAAc,GACd,MAAM,gBAAgB,CAAC;AACxB,OAAO,EACN,kCAAkC,EAClC,uBAAuB,EACvB,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,uBAAuB,EAEvB,uBAAuB,EACvB,qBAAqB,GACrB,MAAM,eAAe,CAAC;AACvB,OAAO,EACN,gBAAgB,EAIhB,qBAAqB,GACrB,MAAM,eAAe,CAAC;AACvB,OAAO,EACN,iBAAiB,EAEjB,uBAAuB,EAIvB,cAAc,GACd,MAAM,cAAc,CAAC","sourcesContent":["export { createMcpAuthProvider, type McpAuthProvider } from \"./auth-provider.ts\";\nexport {\n\ttype OAuthCallback,\n\ttype OAuthCallbackPage,\n\tOAuthCallbackServer,\n\ttype OAuthCallbackServerOptions,\n} from \"./callback.ts\";\nexport type {\n\tMcpClientMetadataDocuments,\n\tMcpOAuthClientOptions,\n\tMcpOAuthServerStore,\n\tMcpOAuthSettings,\n} from \"./client-settings.ts\";\nexport {\n\tbuildAuthorizationServerDiscoveryUrls,\n\tdiscoverAuthorizationServerMetadata,\n\tdiscoverOAuthServerInfo,\n\tdiscoverProtectedResourceMetadata,\n\tparseWwwAuthenticate,\n\tresourceUrlFromServerUrl,\n\tselectResource,\n} from \"./discovery.ts\";\nexport {\n\tMcpOAuthAuthorizationRequiredError,\n\tMcpRefreshLockBusyError,\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\tlistenForLoopbackSignIn,\n\ttype McpLoopbackCallback,\n\tresponseFromRedirectUrl,\n\twaitForLoopbackSignIn,\n} from \"./loopback.ts\";\nexport {\n\tMcpOAuthProvider,\n\ttype McpOAuthProviderOptions,\n\ttype McpOAuthState,\n\ttype McpOAuthStateStore,\n\tMemoryOAuthStateStore,\n} from \"./provider.ts\";\nexport {\n\tcompleteMcpSignIn,\n\ttype McpAuthorizationResponse,\n\tMcpSignInCancelledError,\n\ttype McpSignInOptions,\n\ttype McpSignInRedirect,\n\ttype McpSignInStart,\n\tstartMcpSignIn,\n} from \"./sign-in.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,51 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How the authorization response of a sign-in reaches a local application: a loopback callback server
|
|
3
|
+
* the browser redirects to, or a redirect URL the user pastes from the browser address bar.
|
|
4
|
+
*/
|
|
5
|
+
import { type OAuthCallbackPage, OAuthCallbackServer } from "./callback.ts";
|
|
6
|
+
import { type McpClientMetadataDocuments, type McpOAuthSettings } from "./client-settings.ts";
|
|
7
|
+
import type { McpOAuthStateStore } from "./provider.ts";
|
|
8
|
+
import { type McpAuthorizationResponse, type McpSignInRedirect } from "./sign-in.ts";
|
|
9
|
+
/** A loopback callback server and the redirect URI it serves. */
|
|
10
|
+
export interface McpLoopbackCallback {
|
|
11
|
+
callback: OAuthCallbackServer;
|
|
12
|
+
/** Pass to `startMcpSignIn` and `completeMcpSignIn`. */
|
|
13
|
+
redirectUrl: string;
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Listen for the authorization response of a sign-in on loopback, where `settings` say: `callbackUrl`
|
|
17
|
+
* and `callbackPort`, else the port of the stored client's redirect URI (so that client stays valid) or
|
|
18
|
+
* a free one. Pass the sign-in's `clientMetadataDocuments`, so the callback server also serves the
|
|
19
|
+
* server-specific redirect URI. Close the callback server when the sign-in ends.
|
|
20
|
+
*/
|
|
21
|
+
export declare function listenForLoopbackSignIn(options: {
|
|
22
|
+
serverUrl: string;
|
|
23
|
+
store: McpOAuthStateStore;
|
|
24
|
+
settings: McpOAuthSettings;
|
|
25
|
+
clientMetadataDocuments?: McpClientMetadataDocuments;
|
|
26
|
+
/** Renders the browser page after the redirect. Default: plain text. */
|
|
27
|
+
renderPage?: (page: OAuthCallbackPage) => string;
|
|
28
|
+
}): Promise<McpLoopbackCallback>;
|
|
29
|
+
/**
|
|
30
|
+
* Wait for the authorization response on a loopback callback server, or for a redirect URL the user
|
|
31
|
+
* pastes from the browser address bar, whichever comes first. Aborting `signal` stops the wait with
|
|
32
|
+
* `McpSignInCancelledError`.
|
|
33
|
+
*/
|
|
34
|
+
export declare function waitForLoopbackSignIn(options: {
|
|
35
|
+
callback: OAuthCallbackServer;
|
|
36
|
+
/** The `redirect` result of `startMcpSignIn`. */
|
|
37
|
+
authorization: McpSignInRedirect;
|
|
38
|
+
/**
|
|
39
|
+
* Ask for the redirect URL, for when the browser cannot reach the loopback callback (for example over
|
|
40
|
+
* SSH). Aborted once the callback arrives or the sign-in is cancelled. Resolving to `undefined` or an
|
|
41
|
+
* empty string cancels the sign-in.
|
|
42
|
+
*/
|
|
43
|
+
promptForRedirectUrl?: (signal: AbortSignal) => Promise<string | undefined>;
|
|
44
|
+
signal?: AbortSignal;
|
|
45
|
+
}): Promise<McpAuthorizationResponse>;
|
|
46
|
+
/**
|
|
47
|
+
* The authorization response in a redirect URL the user pasted from the browser address bar. Fails when
|
|
48
|
+
* the URL is not on the sign-in's redirect URI, carries another `state`, or reports an error.
|
|
49
|
+
*/
|
|
50
|
+
export declare function responseFromRedirectUrl(input: string, authorization: Pick<McpSignInRedirect, "state" | "redirectUrl">): McpAuthorizationResponse;
|
|
51
|
+
//# sourceMappingURL=loopback.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"loopback.d.ts","sourceRoot":"","sources":["../../src/oauth/loopback.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAAE,KAAK,iBAAiB,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAC;AAC5E,OAAO,EAEN,KAAK,0BAA0B,EAC/B,KAAK,gBAAgB,EAIrB,MAAM,sBAAsB,CAAC;AAC9B,OAAO,KAAK,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAC;AACxD,OAAO,EAEN,KAAK,wBAAwB,EAE7B,KAAK,iBAAiB,EACtB,MAAM,cAAc,CAAC;AAEtB,iEAAiE;AACjE,MAAM,WAAW,mBAAmB;IACnC,QAAQ,EAAE,mBAAmB,CAAC;IAC9B,wDAAwD;IACxD,WAAW,EAAE,MAAM,CAAC;CACpB;AAED;;;;;GAKG;AACH,wBAAsB,uBAAuB,CAAC,OAAO,EAAE;IACtD,SAAS,EAAE,MAAM,CAAC;IAClB,KAAK,EAAE,kBAAkB,CAAC;IAC1B,QAAQ,EAAE,gBAAgB,CAAC;IAC3B,uBAAuB,CAAC,EAAE,0BAA0B,CAAC;IACrD,wEAAwE;IACxE,UAAU,CAAC,EAAE,CAAC,IAAI,EAAE,iBAAiB,KAAK,MAAM,CAAC;CACjD,GAAG,OAAO,CAAC,mBAAmB,CAAC,CAuB/B;AAED;;;;GAIG;AACH,wBAAsB,qBAAqB,CAAC,OAAO,EAAE;IACpD,QAAQ,EAAE,mBAAmB,CAAC;IAC9B,iDAAiD;IACjD,aAAa,EAAE,iBAAiB,CAAC;IACjC;;;;OAIG;IACH,oBAAoB,CAAC,EAAE,CAAC,MAAM,EAAE,WAAW,KAAK,OAAO,CAAC,MAAM,GAAG,SAAS,CAAC,CAAC;IAC5E,MAAM,CAAC,EAAE,WAAW,CAAC;CACrB,GAAG,OAAO,CAAC,wBAAwB,CAAC,CAwBpC;AAED;;;GAGG;AACH,wBAAgB,uBAAuB,CACtC,KAAK,EAAE,MAAM,EACb,aAAa,EAAE,IAAI,CAAC,iBAAiB,EAAE,OAAO,GAAG,aAAa,CAAC,GAC7D,wBAAwB,CAoB1B"}
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* How the authorization response of a sign-in reaches a local application: a loopback callback server
|
|
3
|
+
* the browser redirects to, or a redirect URL the user pastes from the browser address bar.
|
|
4
|
+
*/
|
|
5
|
+
import { OAuthCallbackServer } from "./callback.js";
|
|
6
|
+
import { loopbackSettings, offersClientMetadataDocument, registeredRedirectUrls, serverSpecificPath, } from "./client-settings.js";
|
|
7
|
+
import { cancellable, McpSignInCancelledError, } from "./sign-in.js";
|
|
8
|
+
/**
|
|
9
|
+
* Listen for the authorization response of a sign-in on loopback, where `settings` say: `callbackUrl`
|
|
10
|
+
* and `callbackPort`, else the port of the stored client's redirect URI (so that client stays valid) or
|
|
11
|
+
* a free one. Pass the sign-in's `clientMetadataDocuments`, so the callback server also serves the
|
|
12
|
+
* server-specific redirect URI. Close the callback server when the sign-in ends.
|
|
13
|
+
*/
|
|
14
|
+
export async function listenForLoopbackSignIn(options) {
|
|
15
|
+
const { settings } = options;
|
|
16
|
+
const loopback = loopbackSettings(settings);
|
|
17
|
+
const registered = registeredRedirectUrls((await options.store.load())?.clientInformation)[0];
|
|
18
|
+
const port = loopback.port ?? (registered ? Number(new URL(registered).port) || undefined : undefined);
|
|
19
|
+
const offersDocument = offersClientMetadataDocument(settings, options.clientMetadataDocuments, loopback.url);
|
|
20
|
+
const listenOptions = {
|
|
21
|
+
host: loopback.host,
|
|
22
|
+
redirectHost: loopback.redirectHost,
|
|
23
|
+
path: loopback.path,
|
|
24
|
+
// The redirect URI of a server-specific Client ID Metadata Document.
|
|
25
|
+
extraPaths: offersDocument ? [serverSpecificPath(loopback.path, options.serverUrl)] : [],
|
|
26
|
+
renderPage: options.renderPage,
|
|
27
|
+
};
|
|
28
|
+
let callback;
|
|
29
|
+
try {
|
|
30
|
+
callback = await OAuthCallbackServer.listen({ ...listenOptions, port: port ?? 0 });
|
|
31
|
+
}
|
|
32
|
+
catch (error) {
|
|
33
|
+
// A configured port is required; the stored client's port is only preferred.
|
|
34
|
+
if (loopback.port !== undefined || port === undefined)
|
|
35
|
+
throw error;
|
|
36
|
+
callback = await OAuthCallbackServer.listen(listenOptions);
|
|
37
|
+
}
|
|
38
|
+
return { callback, redirectUrl: loopback.fixedRedirectUrl ?? callback.redirectUrl };
|
|
39
|
+
}
|
|
40
|
+
/**
|
|
41
|
+
* Wait for the authorization response on a loopback callback server, or for a redirect URL the user
|
|
42
|
+
* pastes from the browser address bar, whichever comes first. Aborting `signal` stops the wait with
|
|
43
|
+
* `McpSignInCancelledError`.
|
|
44
|
+
*/
|
|
45
|
+
export async function waitForLoopbackSignIn(options) {
|
|
46
|
+
const { authorization } = options;
|
|
47
|
+
const controller = new AbortController();
|
|
48
|
+
const signal = options.signal ? AbortSignal.any([controller.signal, options.signal]) : controller.signal;
|
|
49
|
+
const fromBrowser = options.callback.waitForCallback(authorization.state, new URL(authorization.redirectUrl).pathname);
|
|
50
|
+
const fromUser = options.promptForRedirectUrl
|
|
51
|
+
? options.promptForRedirectUrl(signal).then((input) => {
|
|
52
|
+
if (!input?.trim())
|
|
53
|
+
throw new McpSignInCancelledError();
|
|
54
|
+
return responseFromRedirectUrl(input, authorization);
|
|
55
|
+
})
|
|
56
|
+
: new Promise((_, reject) => {
|
|
57
|
+
signal.addEventListener("abort", () => reject(new McpSignInCancelledError()), { once: true });
|
|
58
|
+
});
|
|
59
|
+
try {
|
|
60
|
+
return await cancellable(options.signal, () => Promise.race([fromBrowser, fromUser]));
|
|
61
|
+
}
|
|
62
|
+
finally {
|
|
63
|
+
// The losing side rejects once the prompt is aborted or the callback server closes.
|
|
64
|
+
controller.abort();
|
|
65
|
+
fromBrowser.catch(() => undefined);
|
|
66
|
+
fromUser.catch(() => undefined);
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
/**
|
|
70
|
+
* The authorization response in a redirect URL the user pasted from the browser address bar. Fails when
|
|
71
|
+
* the URL is not on the sign-in's redirect URI, carries another `state`, or reports an error.
|
|
72
|
+
*/
|
|
73
|
+
export function responseFromRedirectUrl(input, authorization) {
|
|
74
|
+
let url;
|
|
75
|
+
try {
|
|
76
|
+
url = new URL(input.trim());
|
|
77
|
+
}
|
|
78
|
+
catch {
|
|
79
|
+
throw new Error("Expected the full redirect URL from the browser address bar");
|
|
80
|
+
}
|
|
81
|
+
const redirectUrl = new URL(authorization.redirectUrl);
|
|
82
|
+
// A server-specific redirect URI tells authorization servers apart, so it must match exactly.
|
|
83
|
+
if (url.origin !== redirectUrl.origin || url.pathname !== redirectUrl.pathname) {
|
|
84
|
+
throw new Error("The redirect URL does not match this sign-in's redirect URI");
|
|
85
|
+
}
|
|
86
|
+
const error = url.searchParams.get("error");
|
|
87
|
+
if (error)
|
|
88
|
+
throw new Error(url.searchParams.get("error_description") ?? error);
|
|
89
|
+
const state = url.searchParams.get("state");
|
|
90
|
+
if (state !== authorization.state)
|
|
91
|
+
throw new Error("The redirect URL belongs to a different sign-in");
|
|
92
|
+
const code = url.searchParams.get("code");
|
|
93
|
+
if (!code)
|
|
94
|
+
throw new Error("The redirect URL does not contain an authorization code");
|
|
95
|
+
const iss = url.searchParams.get("iss");
|
|
96
|
+
return { code, state, ...(iss ? { iss } : {}) };
|
|
97
|
+
}
|
|
98
|
+
//# sourceMappingURL=loopback.js.map
|