@draht/mcp 2026.10.31 → 2026.11.5-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/dist/config.d.ts +126 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/config.js +167 -0
- package/dist/config.js.map +1 -0
- package/dist/index.d.ts +5 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5 -0
- package/dist/index.js.map +1 -1
- 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/naming.d.ts +18 -0
- package/dist/naming.d.ts.map +1 -0
- package/dist/naming.js +29 -0
- package/dist/naming.js.map +1 -0
- package/dist/oauth/auth-provider.d.ts +63 -0
- package/dist/oauth/auth-provider.d.ts.map +1 -0
- package/dist/oauth/auth-provider.js +116 -0
- package/dist/oauth/auth-provider.js.map +1 -0
- package/dist/oauth/callback.d.ts.map +1 -1
- package/dist/oauth/callback.js +4 -0
- package/dist/oauth/callback.js.map +1 -1
- package/dist/oauth/client-metadata-base.d.ts +16 -0
- package/dist/oauth/client-metadata-base.d.ts.map +1 -0
- package/dist/oauth/client-metadata-base.js +27 -0
- package/dist/oauth/client-metadata-base.js.map +1 -0
- package/dist/oauth/client-settings.d.ts +131 -0
- package/dist/oauth/client-settings.d.ts.map +1 -0
- package/dist/oauth/client-settings.js +158 -0
- package/dist/oauth/client-settings.js.map +1 -0
- package/dist/oauth/errors.d.ts +7 -0
- package/dist/oauth/errors.d.ts.map +1 -1
- package/dist/oauth/errors.js +10 -0
- package/dist/oauth/errors.js.map +1 -1
- package/dist/oauth/flow.d.ts +33 -0
- package/dist/oauth/flow.d.ts.map +1 -1
- package/dist/oauth/flow.js +64 -10
- package/dist/oauth/flow.js.map +1 -1
- package/dist/oauth/index.d.ts +7 -2
- package/dist/oauth/index.d.ts.map +1 -1
- package/dist/oauth/index.js +6 -1
- package/dist/oauth/index.js.map +1 -1
- package/dist/oauth/loopback.d.ts +55 -0
- package/dist/oauth/loopback.d.ts.map +1 -0
- package/dist/oauth/loopback.js +106 -0
- package/dist/oauth/loopback.js.map +1 -0
- package/dist/oauth/provider.d.ts +4 -1
- package/dist/oauth/provider.d.ts.map +1 -1
- package/dist/oauth/provider.js +9 -3
- package/dist/oauth/provider.js.map +1 -1
- package/dist/oauth/sign-in.d.ts +82 -0
- package/dist/oauth/sign-in.d.ts.map +1 -0
- package/dist/oauth/sign-in.js +209 -0
- package/dist/oauth/sign-in.js.map +1 -0
- package/dist/oauth/types.d.ts +1 -0
- package/dist/oauth/types.d.ts.map +1 -1
- package/dist/oauth/types.js +8 -4
- package/dist/oauth/types.js.map +1 -1
- 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/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 +1 -4
- package/dist/transports/stdio.d.ts.map +1 -1
- package/dist/transports/stdio.js +20 -51
- package/dist/transports/stdio.js.map +1 -1
- package/dist/transports/streamable-http.d.ts.map +1 -1
- package/dist/transports/streamable-http.js +77 -11
- package/dist/transports/streamable-http.js.map +1 -1
- package/package.json +3 -4
|
@@ -0,0 +1,106 @@
|
|
|
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 { clientMetadataBaseUrl, loopbackSettings, matchesClient, 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. With `cimd`, the callback server also serves the server-specific redirect URI. Close the
|
|
12
|
+
* callback server when the sign-in ends.
|
|
13
|
+
*
|
|
14
|
+
* draht: upstream also takes the application's `clientMetadataDocuments` to decide whether `auto` uses a
|
|
15
|
+
* document; without `auto`, only `settings` decide. Invalid client settings fail before anything listens,
|
|
16
|
+
* and only a stored client that still belongs to the configured client keeps its port.
|
|
17
|
+
*/
|
|
18
|
+
export async function listenForLoopbackSignIn(options) {
|
|
19
|
+
const { settings } = options;
|
|
20
|
+
const baseUrl = clientMetadataBaseUrl(settings);
|
|
21
|
+
const loopback = loopbackSettings(settings);
|
|
22
|
+
const state = await options.store.load();
|
|
23
|
+
const registered = matchesClient(state, options.serverUrl, baseUrl)
|
|
24
|
+
? registeredRedirectUrls(state?.clientInformation)[0]
|
|
25
|
+
: undefined;
|
|
26
|
+
const port = loopback.port ?? (registered ? Number(new URL(registered).port) || undefined : undefined);
|
|
27
|
+
const listenOptions = {
|
|
28
|
+
host: loopback.host,
|
|
29
|
+
redirectHost: loopback.redirectHost,
|
|
30
|
+
path: loopback.path,
|
|
31
|
+
// The redirect URI of a server-specific Client ID Metadata Document.
|
|
32
|
+
extraPaths: baseUrl ? [serverSpecificPath(loopback.path, options.serverUrl)] : [],
|
|
33
|
+
renderPage: options.renderPage,
|
|
34
|
+
};
|
|
35
|
+
let callback;
|
|
36
|
+
try {
|
|
37
|
+
callback = await OAuthCallbackServer.listen({ ...listenOptions, port: port ?? 0 });
|
|
38
|
+
}
|
|
39
|
+
catch (error) {
|
|
40
|
+
// A configured port is required; the stored client's port is only preferred.
|
|
41
|
+
if (loopback.port !== undefined || port === undefined)
|
|
42
|
+
throw error;
|
|
43
|
+
callback = await OAuthCallbackServer.listen(listenOptions);
|
|
44
|
+
}
|
|
45
|
+
return { callback, redirectUrl: loopback.fixedRedirectUrl ?? callback.redirectUrl };
|
|
46
|
+
}
|
|
47
|
+
/**
|
|
48
|
+
* Wait for the authorization response on a loopback callback server, or for a redirect URL the user
|
|
49
|
+
* pastes from the browser address bar, whichever comes first. Aborting `signal` stops the wait with
|
|
50
|
+
* `McpSignInCancelledError`. The callback server only accepts the response on the sign-in's redirect
|
|
51
|
+
* path, from a browser that addressed its own origin.
|
|
52
|
+
*/
|
|
53
|
+
export async function waitForLoopbackSignIn(options) {
|
|
54
|
+
const { authorization } = options;
|
|
55
|
+
const controller = new AbortController();
|
|
56
|
+
const signal = options.signal ? AbortSignal.any([controller.signal, options.signal]) : controller.signal;
|
|
57
|
+
const fromBrowser = options.callback.waitForCallback(authorization.state, new URL(authorization.redirectUrl).pathname);
|
|
58
|
+
const fromUser = options.promptForRedirectUrl
|
|
59
|
+
? options.promptForRedirectUrl(signal).then((input) => {
|
|
60
|
+
if (!input?.trim())
|
|
61
|
+
throw new McpSignInCancelledError();
|
|
62
|
+
return responseFromRedirectUrl(input, authorization);
|
|
63
|
+
})
|
|
64
|
+
: new Promise((_, reject) => {
|
|
65
|
+
signal.addEventListener("abort", () => reject(new McpSignInCancelledError()), { once: true });
|
|
66
|
+
});
|
|
67
|
+
try {
|
|
68
|
+
return await cancellable(options.signal, () => Promise.race([fromBrowser, fromUser]));
|
|
69
|
+
}
|
|
70
|
+
finally {
|
|
71
|
+
// The losing side rejects once the prompt is aborted or the callback server closes.
|
|
72
|
+
controller.abort();
|
|
73
|
+
fromBrowser.catch(() => undefined);
|
|
74
|
+
fromUser.catch(() => undefined);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
/**
|
|
78
|
+
* The authorization response in a redirect URL the user pasted from the browser address bar. Fails when
|
|
79
|
+
* the URL is not on the sign-in's redirect URI, carries another `state`, or reports an error.
|
|
80
|
+
*/
|
|
81
|
+
export function responseFromRedirectUrl(input, authorization) {
|
|
82
|
+
let url;
|
|
83
|
+
try {
|
|
84
|
+
url = new URL(input.trim());
|
|
85
|
+
}
|
|
86
|
+
catch {
|
|
87
|
+
throw new Error("Expected the full redirect URL from the browser address bar");
|
|
88
|
+
}
|
|
89
|
+
const redirectUrl = new URL(authorization.redirectUrl);
|
|
90
|
+
// A server-specific redirect URI tells authorization servers apart, so it must match exactly.
|
|
91
|
+
if (url.origin !== redirectUrl.origin || url.pathname !== redirectUrl.pathname) {
|
|
92
|
+
throw new Error("The redirect URL does not match this sign-in's redirect URI");
|
|
93
|
+
}
|
|
94
|
+
const error = url.searchParams.get("error");
|
|
95
|
+
if (error)
|
|
96
|
+
throw new Error(url.searchParams.get("error_description") ?? error);
|
|
97
|
+
const state = url.searchParams.get("state");
|
|
98
|
+
if (state !== authorization.state)
|
|
99
|
+
throw new Error("The redirect URL belongs to a different sign-in");
|
|
100
|
+
const code = url.searchParams.get("code");
|
|
101
|
+
if (!code)
|
|
102
|
+
throw new Error("The redirect URL does not contain an authorization code");
|
|
103
|
+
const iss = url.searchParams.get("iss");
|
|
104
|
+
return { code, state, ...(iss ? { iss } : {}) };
|
|
105
|
+
}
|
|
106
|
+
//# sourceMappingURL=loopback.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"loopback.js","sourceRoot":"","sources":["../../src/oauth/loopback.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH,OAAO,EAA0B,mBAAmB,EAAE,MAAM,eAAe,CAAC;AAC5E,OAAO,EACN,qBAAqB,EACrB,gBAAgB,EAEhB,aAAa,EACb,sBAAsB,EACtB,kBAAkB,GAClB,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EACN,WAAW,EAEX,uBAAuB,GAEvB,MAAM,cAAc,CAAC;AAStB;;;;;;;;;GASG;AACH,MAAM,CAAC,KAAK,UAAU,uBAAuB,CAAC,OAM7C;IACA,MAAM,EAAE,QAAQ,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C,CAAC;IAC5C,IAAI,KAAK,KAAK,aAAa,CAAC,KAAK;QAAE,MAAM,IAAI,KAAK,CAAC,iDAAiD,CAAC,CAAC;IACtG,MAAM,IAAI,GAAG,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC;IAC1C,IAAI,CAAC,IAAI;QAAE,MAAM,IAAI,KAAK,CAAC,yDAAyD,CAAC,CAAC;IACtF,MAAM,GAAG,GAAG,GAAG,CAAC,YAAY,CAAC,GAAG,CAAC,KAAK,CAAC,CAAC;IACxC,OAAO,EAAE,IAAI,EAAE,KAAK,EAAE,GAAG,CAAC,GAAG,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC;AACjD,CAAC","sourcesContent":["/**\n * How the authorization response of a sign-in reaches a local application: a loopback callback server\n * the browser redirects to, or a redirect URL the user pastes from the browser address bar.\n */\n\nimport { type OAuthCallbackPage, OAuthCallbackServer } from \"./callback.ts\";\nimport {\n\tclientMetadataBaseUrl,\n\tloopbackSettings,\n\ttype McpOAuthSettings,\n\tmatchesClient,\n\tregisteredRedirectUrls,\n\tserverSpecificPath,\n} from \"./client-settings.ts\";\nimport type { McpOAuthStateStore } from \"./provider.ts\";\nimport {\n\tcancellable,\n\ttype McpAuthorizationResponse,\n\tMcpSignInCancelledError,\n\ttype McpSignInRedirect,\n} from \"./sign-in.ts\";\n\n/** A loopback callback server and the redirect URI it serves. */\nexport interface McpLoopbackCallback {\n\tcallback: OAuthCallbackServer;\n\t/** Pass to `startMcpSignIn` and `completeMcpSignIn`. */\n\tredirectUrl: string;\n}\n\n/**\n * Listen for the authorization response of a sign-in on loopback, where `settings` say: `callbackUrl`\n * and `callbackPort`, else the port of the stored client's redirect URI (so that client stays valid) or\n * a free one. With `cimd`, the callback server also serves the server-specific redirect URI. Close the\n * callback server when the sign-in ends.\n *\n * draht: upstream also takes the application's `clientMetadataDocuments` to decide whether `auto` uses a\n * document; without `auto`, only `settings` decide. Invalid client settings fail before anything listens,\n * and only a stored client that still belongs to the configured client keeps its port.\n */\nexport async function listenForLoopbackSignIn(options: {\n\tserverUrl: string;\n\tstore: McpOAuthStateStore;\n\tsettings: McpOAuthSettings;\n\t/** Renders the browser page after the redirect. Default: plain text. */\n\trenderPage?: (page: OAuthCallbackPage) => string;\n}): Promise<McpLoopbackCallback> {\n\tconst { settings } = options;\n\tconst baseUrl = clientMetadataBaseUrl(settings);\n\tconst loopback = loopbackSettings(settings);\n\tconst state = await options.store.load();\n\tconst registered = matchesClient(state, options.serverUrl, baseUrl)\n\t\t? registeredRedirectUrls(state?.clientInformation)[0]\n\t\t: undefined;\n\tconst port = loopback.port ?? (registered ? Number(new URL(registered).port) || undefined : undefined);\n\tconst listenOptions = {\n\t\thost: loopback.host,\n\t\tredirectHost: loopback.redirectHost,\n\t\tpath: loopback.path,\n\t\t// The redirect URI of a server-specific Client ID Metadata Document.\n\t\textraPaths: baseUrl ? [serverSpecificPath(loopback.path, options.serverUrl)] : [],\n\t\trenderPage: options.renderPage,\n\t};\n\tlet callback: OAuthCallbackServer;\n\ttry {\n\t\tcallback = await OAuthCallbackServer.listen({ ...listenOptions, port: port ?? 0 });\n\t} catch (error) {\n\t\t// A configured port is required; the stored client's port is only preferred.\n\t\tif (loopback.port !== undefined || port === undefined) throw error;\n\t\tcallback = await OAuthCallbackServer.listen(listenOptions);\n\t}\n\treturn { callback, redirectUrl: loopback.fixedRedirectUrl ?? callback.redirectUrl };\n}\n\n/**\n * Wait for the authorization response on a loopback callback server, or for a redirect URL the user\n * pastes from the browser address bar, whichever comes first. Aborting `signal` stops the wait with\n * `McpSignInCancelledError`. The callback server only accepts the response on the sign-in's redirect\n * path, from a browser that addressed its own origin.\n */\nexport async function waitForLoopbackSignIn(options: {\n\tcallback: OAuthCallbackServer;\n\t/** The `redirect` result of `startMcpSignIn`. */\n\tauthorization: McpSignInRedirect;\n\t/**\n\t * Ask for the redirect URL, for when the browser cannot reach the loopback callback (for example over\n\t * SSH). Aborted once the callback arrives or the sign-in is cancelled. Resolving to `undefined` or an\n\t * empty string cancels the sign-in.\n\t */\n\tpromptForRedirectUrl?: (signal: AbortSignal) => Promise<string | undefined>;\n\tsignal?: AbortSignal;\n}): Promise<McpAuthorizationResponse> {\n\tconst { authorization } = options;\n\tconst controller = new AbortController();\n\tconst signal = options.signal ? AbortSignal.any([controller.signal, options.signal]) : controller.signal;\n\tconst fromBrowser = options.callback.waitForCallback(\n\t\tauthorization.state,\n\t\tnew URL(authorization.redirectUrl).pathname,\n\t);\n\tconst fromUser = options.promptForRedirectUrl\n\t\t? options.promptForRedirectUrl(signal).then((input) => {\n\t\t\t\tif (!input?.trim()) throw new McpSignInCancelledError();\n\t\t\t\treturn responseFromRedirectUrl(input, authorization);\n\t\t\t})\n\t\t: new Promise<never>((_, reject) => {\n\t\t\t\tsignal.addEventListener(\"abort\", () => reject(new McpSignInCancelledError()), { once: true });\n\t\t\t});\n\ttry {\n\t\treturn await cancellable(options.signal, () => Promise.race([fromBrowser, fromUser]));\n\t} finally {\n\t\t// The losing side rejects once the prompt is aborted or the callback server closes.\n\t\tcontroller.abort();\n\t\tfromBrowser.catch(() => undefined);\n\t\tfromUser.catch(() => undefined);\n\t}\n}\n\n/**\n * The authorization response in a redirect URL the user pasted from the browser address bar. Fails when\n * the URL is not on the sign-in's redirect URI, carries another `state`, or reports an error.\n */\nexport function responseFromRedirectUrl(\n\tinput: string,\n\tauthorization: Pick<McpSignInRedirect, \"state\" | \"redirectUrl\">,\n): McpAuthorizationResponse {\n\tlet url: URL;\n\ttry {\n\t\turl = new URL(input.trim());\n\t} catch {\n\t\tthrow new Error(\"Expected the full redirect URL from the browser address bar\");\n\t}\n\tconst redirectUrl = new URL(authorization.redirectUrl);\n\t// A server-specific redirect URI tells authorization servers apart, so it must match exactly.\n\tif (url.origin !== redirectUrl.origin || url.pathname !== redirectUrl.pathname) {\n\t\tthrow new Error(\"The redirect URL does not match this sign-in's redirect URI\");\n\t}\n\tconst error = url.searchParams.get(\"error\");\n\tif (error) throw new Error(url.searchParams.get(\"error_description\") ?? error);\n\tconst state = url.searchParams.get(\"state\");\n\tif (state !== authorization.state) throw new Error(\"The redirect URL belongs to a different sign-in\");\n\tconst code = url.searchParams.get(\"code\");\n\tif (!code) throw new Error(\"The redirect URL does not contain an authorization code\");\n\tconst iss = url.searchParams.get(\"iss\");\n\treturn { code, state, ...(iss ? { iss } : {}) };\n}\n"]}
|
package/dist/oauth/provider.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { OAuthClientMetadataDocument, OAuthClientProvider } from "./flow.ts";
|
|
1
|
+
import type { OAuthAuthorizationRequest, OAuthClientMetadataDocument, OAuthClientProvider } from "./flow.ts";
|
|
2
2
|
import type { AuthorizationServerMetadata, OAuthClientInformationMixed, OAuthClientMetadata, OAuthDiscoveryState, OAuthTokens } from "./types.ts";
|
|
3
3
|
export interface McpOAuthState {
|
|
4
4
|
serverUrl: string;
|
|
@@ -10,6 +10,8 @@ export interface McpOAuthState {
|
|
|
10
10
|
tokensExpireAt?: number;
|
|
11
11
|
codeVerifier?: string;
|
|
12
12
|
oauthState?: string;
|
|
13
|
+
/** The pending authorization request's client and authorization server, kept with `codeVerifier`. */
|
|
14
|
+
authorizationRequest?: OAuthAuthorizationRequest;
|
|
13
15
|
discovery?: OAuthDiscoveryState;
|
|
14
16
|
}
|
|
15
17
|
export interface McpOAuthStateStore {
|
|
@@ -55,6 +57,7 @@ export declare class McpOAuthProvider implements OAuthClientProvider {
|
|
|
55
57
|
saveTokens(tokens: OAuthTokens): Promise<void>;
|
|
56
58
|
redirectToAuthorization(url: URL): Promise<void>;
|
|
57
59
|
saveCodeVerifier(verifier: string): Promise<void>;
|
|
60
|
+
saveAuthorizationRequest(request: OAuthAuthorizationRequest): Promise<void>;
|
|
58
61
|
codeVerifier(): Promise<string>;
|
|
59
62
|
invalidateCredentials(kind: "all" | "client" | "tokens" | "verifier" | "discovery"): Promise<void>;
|
|
60
63
|
saveDiscoveryState(discovery: OAuthDiscoveryState): Promise<void>;
|
|
@@ -1 +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;
|
|
1
|
+
{"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../../src/oauth/provider.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,yBAAyB,EAAE,2BAA2B,EAAE,mBAAmB,EAAE,MAAM,WAAW,CAAC;AAC7G,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,gGAAgG;IAChG,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,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,qGAAqG;IACrG,oBAAoB,CAAC,EAAE,yBAAyB,CAAC;IACjD,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,GAAG,GAAG,CAAC;IACxB,WAAW,EAAE,MAAM,GAAG,GAAG,CAAC;IAC1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WAAW,EAAE,2BAA2B,GAAG,OAAO,CAAC,IAAI,CAAC,CAGnF;IAEK,MAAM,IAAI,OAAO,CAAC,WAAW,GAAG,SAAS,CAAC,CAM/C;IAED,8GAA8G;IAC9G,OAAO,CAAC,0BAA0B;IAQ5B,UAAU,CAAC,MAAM,EAAE,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CAcnD;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,wBAAwB,CAAC,OAAO,EAAE,yBAAyB,GAAG,OAAO,CAAC,IAAI,CAAC,CAEhF;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,CAmBvG;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"}
|
package/dist/oauth/provider.js
CHANGED
|
@@ -104,6 +104,9 @@ export class McpOAuthProvider {
|
|
|
104
104
|
async saveCodeVerifier(verifier) {
|
|
105
105
|
await this.update((value) => ({ ...value, codeVerifier: verifier }));
|
|
106
106
|
}
|
|
107
|
+
async saveAuthorizationRequest(request) {
|
|
108
|
+
await this.update((value) => ({ ...value, authorizationRequest: request }));
|
|
109
|
+
}
|
|
107
110
|
async codeVerifier() {
|
|
108
111
|
const verifier = (await this.load()).codeVerifier;
|
|
109
112
|
if (!verifier)
|
|
@@ -120,12 +123,15 @@ export class McpOAuthProvider {
|
|
|
120
123
|
delete next.tokensExpireAt;
|
|
121
124
|
delete next.clientMetadataUrl;
|
|
122
125
|
}
|
|
123
|
-
|
|
126
|
+
// The verifier, the request it belongs to, and its `state` go together: the flow drops them once
|
|
127
|
+
// the code is exchanged, so a completed sign-in cannot be completed again.
|
|
128
|
+
if (kind === "all" || kind === "verifier") {
|
|
124
129
|
delete next.codeVerifier;
|
|
130
|
+
delete next.authorizationRequest;
|
|
131
|
+
delete next.oauthState;
|
|
132
|
+
}
|
|
125
133
|
if (kind === "all" || kind === "discovery")
|
|
126
134
|
delete next.discovery;
|
|
127
|
-
if (kind === "all")
|
|
128
|
-
delete next.oauthState;
|
|
129
135
|
return next;
|
|
130
136
|
});
|
|
131
137
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"provider.js","sourceRoot":"","sources":["../../src/oauth/provider.ts"],"names":[],"mappings":"AAyCA,MAAM,OAAO,qBAAqB;IACzB,KAAK,CAA4B;IAEzC,IAAI;QACH,OAAO,IAAI,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,eAAe,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC3E,CAAC;IAED,IAAI,CAAC,KAAoB;QACxB,IAAI,CAAC,KAAK,GAAG,eAAe,CAAC,KAAK,CAAC,CAAC;IACrC,CAAC;CACD;AAED,6GAA6G;AAC7G,MAAM,OAAO,gBAAgB;IACnB,WAAW,CAAS;IACpB,cAAc,CAAsB;IACpC,sBAAsB,CAEc;IACrC,SAAS,CAAS;IAClB,gBAAgB,CAA0C;IAC1D,KAAK,CAAqB;IAC1B,UAAU,CAAqC;IAC/C,MAAM,GAAkB,OAAO,CAAC,OAAO,EAAE,CAAC;IAC1C,sBAAsB,CAA0C;IAExE,YAAY,OAAgC;QAC3C,IAAI,CAAC,SAAS,GAAG,MAAM,CAAC,IAAI,GAAG,CAAC,OAAO,CAAC,SAAS,CAAC,CAAC,CAAC;QACpD,IAA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AK;gBAAE,OAAO,IAAI,CAAC,UAAU,CAAC;YAC3C,OAAO,IAAI,CAAC;QACb,CAAC,CAAC,CAAC;IACJ,CAAC;IAED,KAAK,CAAC,kBAAkB,CAAC,SAA8B;QACtD,MAAM,IAAI,CAAC,MAAM,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC,CAAC,EAAE,GAAG,KAAK,EAAE,SAAS,EAAE,CAAC,CAAC,CAAC;IACzD,CAAC;IAED,KAAK,CAAC,cAAc;QACnB,OAAO,CAAC,MAAM,IAAI,CAAC,IAAI,EAAE,CAAC,CAAC,SAAS,CAAC;IACtC,CAAC;IAEO,KAAK,CAAC,IAAI;QACjB,MAAM,IAAI,CAAC,MAAM,CAAC;QAClB,OAAO,IAAI,CAAC,GAAG,CAAC,MAAM,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC;IAC1C,CAAC;IAEO,KAAK,CAAC,MAAM,CAAC,MAA+C;QACnE,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,IAAI,EAAE;YACzC,MAAM,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC;QAClE,CAAC,CAAC,CAAC;QACH,MAAM,IAAI,CAAC,MAAM,CAAC;IACnB,CAAC;IAED,+FAA+F;IACvF,GAAG,CAAC,KAAgC;QAC3C,OAAO,KAAK,EAAE,SAAS,KAAK,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,IAAI,CAAC,SAAS,EAAE,CAAC;IACpF,CAAC;CACD","sourcesContent":["import type { OAuthClientMetadataDocument, OAuthClientProvider } from \"./flow.ts\";\nimport type {\n\tAuthorizationServerMetadata,\n\tOAuthClientInformationMixed,\n\tOAuthClientMetadata,\n\tOAuthDiscoveryState,\n\tOAuthTokens,\n} from \"./types.ts\";\n\nexport interface McpOAuthState {\n\tserverUrl: string;\n\tclientInformation?: OAuthClientInformationMixed;\n\t/** Client ID Metadata Document that issued the stored tokens; absent for registered clients. */\n\tclientMetadataUrl?: string;\n\ttokens?: OAuthTokens;\n\t/** When the access token expires, in milliseconds since the epoch, from `expires_in` at the time it was saved. */\n\ttokensExpireAt?: number;\n\tcodeVerifier?: string;\n\toauthState?: string;\n\tdiscovery?: OAuthDiscoveryState;\n}\n\nexport interface McpOAuthStateStore {\n\tload(): McpOAuthState | undefined | Promise<McpOAuthState | undefined>;\n\tsave(state: McpOAuthState): void | Promise<void>;\n}\n\nexport interface McpOAuthProviderOptions {\n\tserverUrl: string | URL;\n\tredirectUrl: string | URL;\n\tclientMetadata: Omit<OAuthClientMetadata, \"redirect_uris\"> & { redirect_uris?: string[] };\n\t/** See `OAuthClientProvider.clientMetadataDocument`. */\n\tclientMetadataDocument?: (\n\t\tmetadata: AuthorizationServerMetadata | undefined,\n\t) => OAuthClientMetadataDocument | undefined;\n\tclientId?: string;\n\tclientSecret?: string;\n\tstore?: McpOAuthStateStore;\n\tonRedirect(url: URL): void | Promise<void>;\n}\n\nexport class MemoryOAuthStateStore implements McpOAuthStateStore {\n\tprivate value: McpOAuthState | undefined;\n\n\tload(): McpOAuthState | undefined {\n\t\treturn this.value === undefined ? undefined : structuredClone(this.value);\n\t}\n\n\tsave(state: McpOAuthState): void {\n\t\tthis.value = structuredClone(state);\n\t}\n}\n\n/** Default stateful provider for one exact MCP server URL. Applications inject durable storage if needed. */\nexport class McpOAuthProvider implements OAuthClientProvider {\n\treadonly redirectUrl: string;\n\treadonly clientMetadata: OAuthClientMetadata;\n\treadonly clientMetadataDocument?: (\n\t\tmetadata: AuthorizationServerMetadata | undefined,\n\t) => OAuthClientMetadataDocument | undefined;\n\tprivate serverUrl: string;\n\tprivate configuredClient: OAuthClientInformationMixed | undefined;\n\tprivate store: McpOAuthStateStore;\n\tprivate onRedirect: (url: URL) => void | Promise<void>;\n\tprivate writes: Promise<void> = Promise.resolve();\n\tprivate selectedClientMetadata: { url: string | undefined } | undefined;\n\n\tconstructor(options: McpOAuthProviderOptions) {\n\t\tthis.serverUrl = String(new URL(options.serverUrl));\n\t\tthis.redirectUrl = String(options.redirectUrl);\n\t\tthis.clientMetadata = {\n\t\t\t...options.clientMetadata,\n\t\t\tredirect_uris: options.clientMetadata.redirect_uris ?? [this.redirectUrl],\n\t\t\tgrant_types: options.clientMetadata.grant_types ?? [\"authorization_code\", \"refresh_token\"],\n\t\t\tresponse_types: options.clientMetadata.response_types ?? [\"code\"],\n\t\t\ttoken_endpoint_auth_method:\n\t\t\t\toptions.clientMetadata.token_endpoint_auth_method ?? (options.clientSecret ? \"client_secret_post\" : \"none\"),\n\t\t};\n\t\tif (options.clientMetadataDocument) {\n\t\t\tconst selectDocument = options.clientMetadataDocument;\n\t\t\tthis.clientMetadataDocument = (metadata) => {\n\t\t\t\tconst document = selectDocument(metadata);\n\t\t\t\tthis.selectedClientMetadata = { url: document?.url };\n\t\t\t\treturn document;\n\t\t\t};\n\t\t}\n\t\tthis.configuredClient = options.clientId\n\t\t\t? { client_id: options.clientId, ...(options.clientSecret ? { client_secret: options.clientSecret } : {}) }\n\t\t\t: undefined;\n\t\tthis.store = options.store ?? new MemoryOAuthStateStore();\n\t\tthis.onRedirect = options.onRedirect;\n\t}\n\n\tasync state(): Promise<string> {\n\t\tconst existing = (await this.load()).oauthState;\n\t\tif (existing) return existing;\n\t\tconst state = Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString(\"hex\");\n\t\tawait this.update((value) => ({ ...value, oauthState: state }));\n\t\treturn state;\n\t}\n\n\tasync clientInformation(): Promise<OAuthClientInformationMixed | undefined> {\n\t\tconst state = await this.load();\n\t\tif (!this.selectCachedClientDocument(state) || this.selectedClientMetadata?.url) return undefined;\n\t\treturn this.configuredClient ?? (state.clientMetadataUrl ? undefined : state.clientInformation);\n\t}\n\n\tasync saveClientInformation(information: OAuthClientInformationMixed): Promise<void> {\n\t\tif (this.configuredClient) return;\n\t\tawait this.update((value) => ({ ...value, clientInformation: information }));\n\t}\n\n\tasync tokens(): Promise<OAuthTokens | undefined> {\n\t\tconst state = await this.load();\n\t\tif (!this.selectCachedClientDocument(state)) return undefined;\n\t\t// Never refresh a grant with another document or a dynamically registered client.\n\t\tif (state.clientMetadataUrl !== this.selectedClientMetadata?.url) return undefined;\n\t\treturn state.tokens;\n\t}\n\n\t/** Resume through the current selector and validated discovery, never through the stored client URL alone. */\n\tprivate selectCachedClientDocument(state: McpOAuthState): boolean {\n\t\tif (!this.clientMetadataDocument || this.selectedClientMetadata) return true;\n\t\tconst metadata = state.discovery?.authorizationServerMetadata;\n\t\tif (!metadata) return false;\n\t\tthis.clientMetadataDocument(metadata);\n\t\treturn true;\n\t}\n\n\tasync saveTokens(tokens: OAuthTokens): Promise<void> {\n\t\tconst expiresAt = tokens.expires_in === undefined ? undefined : Date.now() + tokens.expires_in * 1000;\n\t\tawait this.update((value) => {\n\t\t\tconst next: McpOAuthState = { ...value, tokens };\n\t\t\tif (this.selectedClientMetadata?.url) {\n\t\t\t\tnext.clientMetadataUrl = this.selectedClientMetadata.url;\n\t\t\t\tdelete next.clientInformation;\n\t\t\t} else {\n\t\t\t\tdelete next.clientMetadataUrl;\n\t\t\t}\n\t\t\tif (expiresAt === undefined) delete next.tokensExpireAt;\n\t\t\telse next.tokensExpireAt = expiresAt;\n\t\t\treturn next;\n\t\t});\n\t}\n\n\tasync redirectToAuthorization(url: URL): Promise<void> {\n\t\tawait this.onRedirect(url);\n\t}\n\n\tasync saveCodeVerifier(verifier: string): Promise<void> {\n\t\tawait this.update((value) => ({ ...value, codeVerifier: verifier }));\n\t}\n\n\tasync codeVerifier(): Promise<string> {\n\t\tconst verifier = (await this.load()).codeVerifier;\n\t\tif (!verifier) throw new Error(\"No OAuth PKCE code verifier is stored\");\n\t\treturn verifier;\n\t}\n\n\tasync invalidateCredentials(kind: \"all\" | \"client\" | \"tokens\" | \"verifier\" | \"discovery\"): Promise<void> {\n\t\tawait this.update((value) => {\n\t\t\tconst next = { ...value };\n\t\t\tif (kind === \"all\" || kind === \"client\") delete next.clientInformation;\n\t\t\tif (kind === \"all\" || kind === \"tokens\") {\n\t\t\t\tdelete next.tokens;\n\t\t\t\tdelete next.tokensExpireAt;\n\t\t\t\tdelete next.clientMetadataUrl;\n\t\t\t}\n\t\t\tif (kind === \"all\" || kind === \"verifier\") delete next.codeVerifier;\n\t\t\tif (kind === \"all\" || kind === \"discovery\") delete next.discovery;\n\t\t\tif (kind === \"all\") delete next.oauthState;\n\t\t\treturn next;\n\t\t});\n\t}\n\n\tasync saveDiscoveryState(discovery: OAuthDiscoveryState): Promise<void> {\n\t\tawait this.update((value) => ({ ...value, discovery }));\n\t}\n\n\tasync discoveryState(): Promise<OAuthDiscoveryState | undefined> {\n\t\treturn (await this.load()).discovery;\n\t}\n\n\tprivate async load(): Promise<McpOAuthState> {\n\t\tawait this.writes;\n\t\treturn this.own(await this.store.load());\n\t}\n\n\tprivate async update(update: (state: McpOAuthState) => McpOAuthState): Promise<void> {\n\t\tthis.writes = this.writes.then(async () => {\n\t\t\tawait this.store.save(update(this.own(await this.store.load())));\n\t\t});\n\t\tawait this.writes;\n\t}\n\n\t/** Stored state for another server URL is ignored so credentials never leak across servers. */\n\tprivate own(state: McpOAuthState | undefined): McpOAuthState {\n\t\treturn state?.serverUrl === this.serverUrl ? state : { serverUrl: this.serverUrl };\n\t}\n}\n"]}
|
|
1
|
+
{"version":3,"file":"provider.js","sourceRoot":"","sources":["../../src/oauth/provider.ts"],"names":[],"mappings":"AA2CA,MAAM,OAAO,qBAAqB;IACzB,KAAK,CAA4B;IAEzC,IAAI;QACH,OAAO,IAAI,CAAC,KAAK,KAAK,SAAS,CAAC,CAAC,CAAC,SAAS,CAAC,CAAC,CAAC,eAAe,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC3E,CAAC;IAED,IAAI,CAAC,KAAoB;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E,CAAC,CAAC;IAC1C,CAAC;IAEO,KAAK,CAAC,MAAM,CAAC,MAA+C;QACnE,IAAI,CAAC,MAAM,GAAG,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,KAAK,IAAI,EAAE;YACzC,MAAM,IAAI,CAAC,KAAK,CAAC,IAAI,CAAC,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,MAAM,IAAI,CAAC,KAAK,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,CAAC;QAClE,CAAC,CAAC,CAAC;QACH,MAAM,IAAI,CAAC,MAAM,CAAC;IACnB,CAAC;IAED,+FAA+F;IACvF,GAAG,CAAC,KAAgC;QAC3C,OAAO,KAAK,EAAE,SAAS,KAAK,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC,KAAK,CAAC,CAAC,CAAC,EAAE,SAAS,EAAE,IAAI,CAAC,SAAS,EAAE,CAAC;IACpF,CAAC;CACD","sourcesContent":["import type { OAuthAuthorizationRequest, OAuthClientMetadataDocument, OAuthClientProvider } from \"./flow.ts\";\nimport type {\n\tAuthorizationServerMetadata,\n\tOAuthClientInformationMixed,\n\tOAuthClientMetadata,\n\tOAuthDiscoveryState,\n\tOAuthTokens,\n} from \"./types.ts\";\n\nexport interface McpOAuthState {\n\tserverUrl: string;\n\tclientInformation?: OAuthClientInformationMixed;\n\t/** Client ID Metadata Document that issued the stored tokens; absent for registered clients. */\n\tclientMetadataUrl?: string;\n\ttokens?: OAuthTokens;\n\t/** When the access token expires, in milliseconds since the epoch, from `expires_in` at the time it was saved. */\n\ttokensExpireAt?: number;\n\tcodeVerifier?: string;\n\toauthState?: string;\n\t/** The pending authorization request's client and authorization server, kept with `codeVerifier`. */\n\tauthorizationRequest?: OAuthAuthorizationRequest;\n\tdiscovery?: OAuthDiscoveryState;\n}\n\nexport interface McpOAuthStateStore {\n\tload(): McpOAuthState | undefined | Promise<McpOAuthState | undefined>;\n\tsave(state: McpOAuthState): void | Promise<void>;\n}\n\nexport interface McpOAuthProviderOptions {\n\tserverUrl: string | URL;\n\tredirectUrl: string | URL;\n\tclientMetadata: Omit<OAuthClientMetadata, \"redirect_uris\"> & { redirect_uris?: string[] };\n\t/** See `OAuthClientProvider.clientMetadataDocument`. */\n\tclientMetadataDocument?: (\n\t\tmetadata: AuthorizationServerMetadata | undefined,\n\t) => OAuthClientMetadataDocument | undefined;\n\tclientId?: string;\n\tclientSecret?: string;\n\tstore?: McpOAuthStateStore;\n\tonRedirect(url: URL): void | Promise<void>;\n}\n\nexport class MemoryOAuthStateStore implements McpOAuthStateStore {\n\tprivate value: McpOAuthState | undefined;\n\n\tload(): McpOAuthState | undefined {\n\t\treturn this.value === undefined ? undefined : structuredClone(this.value);\n\t}\n\n\tsave(state: McpOAuthState): void {\n\t\tthis.value = structuredClone(state);\n\t}\n}\n\n/** Default stateful provider for one exact MCP server URL. Applications inject durable storage if needed. */\nexport class McpOAuthProvider implements OAuthClientProvider {\n\treadonly redirectUrl: string;\n\treadonly clientMetadata: OAuthClientMetadata;\n\treadonly clientMetadataDocument?: (\n\t\tmetadata: AuthorizationServerMetadata | undefined,\n\t) => OAuthClientMetadataDocument | undefined;\n\tprivate serverUrl: string;\n\tprivate configuredClient: OAuthClientInformationMixed | undefined;\n\tprivate store: McpOAuthStateStore;\n\tprivate onRedirect: (url: URL) => void | Promise<void>;\n\tprivate writes: Promise<void> = Promise.resolve();\n\tprivate selectedClientMetadata: { url: string | undefined } | undefined;\n\n\tconstructor(options: McpOAuthProviderOptions) {\n\t\tthis.serverUrl = String(new URL(options.serverUrl));\n\t\tthis.redirectUrl = String(options.redirectUrl);\n\t\tthis.clientMetadata = {\n\t\t\t...options.clientMetadata,\n\t\t\tredirect_uris: options.clientMetadata.redirect_uris ?? [this.redirectUrl],\n\t\t\tgrant_types: options.clientMetadata.grant_types ?? [\"authorization_code\", \"refresh_token\"],\n\t\t\tresponse_types: options.clientMetadata.response_types ?? [\"code\"],\n\t\t\ttoken_endpoint_auth_method:\n\t\t\t\toptions.clientMetadata.token_endpoint_auth_method ?? (options.clientSecret ? \"client_secret_post\" : \"none\"),\n\t\t};\n\t\tif (options.clientMetadataDocument) {\n\t\t\tconst selectDocument = options.clientMetadataDocument;\n\t\t\tthis.clientMetadataDocument = (metadata) => {\n\t\t\t\tconst document = selectDocument(metadata);\n\t\t\t\tthis.selectedClientMetadata = { url: document?.url };\n\t\t\t\treturn document;\n\t\t\t};\n\t\t}\n\t\tthis.configuredClient = options.clientId\n\t\t\t? { client_id: options.clientId, ...(options.clientSecret ? { client_secret: options.clientSecret } : {}) }\n\t\t\t: undefined;\n\t\tthis.store = options.store ?? new MemoryOAuthStateStore();\n\t\tthis.onRedirect = options.onRedirect;\n\t}\n\n\tasync state(): Promise<string> {\n\t\tconst existing = (await this.load()).oauthState;\n\t\tif (existing) return existing;\n\t\tconst state = Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString(\"hex\");\n\t\tawait this.update((value) => ({ ...value, oauthState: state }));\n\t\treturn state;\n\t}\n\n\tasync clientInformation(): Promise<OAuthClientInformationMixed | undefined> {\n\t\tconst state = await this.load();\n\t\tif (!this.selectCachedClientDocument(state) || this.selectedClientMetadata?.url) return undefined;\n\t\treturn this.configuredClient ?? (state.clientMetadataUrl ? undefined : state.clientInformation);\n\t}\n\n\tasync saveClientInformation(information: OAuthClientInformationMixed): Promise<void> {\n\t\tif (this.configuredClient) return;\n\t\tawait this.update((value) => ({ ...value, clientInformation: information }));\n\t}\n\n\tasync tokens(): Promise<OAuthTokens | undefined> {\n\t\tconst state = await this.load();\n\t\tif (!this.selectCachedClientDocument(state)) return undefined;\n\t\t// Never refresh a grant with another document or a dynamically registered client.\n\t\tif (state.clientMetadataUrl !== this.selectedClientMetadata?.url) return undefined;\n\t\treturn state.tokens;\n\t}\n\n\t/** Resume through the current selector and validated discovery, never through the stored client URL alone. */\n\tprivate selectCachedClientDocument(state: McpOAuthState): boolean {\n\t\tif (!this.clientMetadataDocument || this.selectedClientMetadata) return true;\n\t\tconst metadata = state.discovery?.authorizationServerMetadata;\n\t\tif (!metadata) return false;\n\t\tthis.clientMetadataDocument(metadata);\n\t\treturn true;\n\t}\n\n\tasync saveTokens(tokens: OAuthTokens): Promise<void> {\n\t\tconst expiresAt = tokens.expires_in === undefined ? undefined : Date.now() + tokens.expires_in * 1000;\n\t\tawait this.update((value) => {\n\t\t\tconst next: McpOAuthState = { ...value, tokens };\n\t\t\tif (this.selectedClientMetadata?.url) {\n\t\t\t\tnext.clientMetadataUrl = this.selectedClientMetadata.url;\n\t\t\t\tdelete next.clientInformation;\n\t\t\t} else {\n\t\t\t\tdelete next.clientMetadataUrl;\n\t\t\t}\n\t\t\tif (expiresAt === undefined) delete next.tokensExpireAt;\n\t\t\telse next.tokensExpireAt = expiresAt;\n\t\t\treturn next;\n\t\t});\n\t}\n\n\tasync redirectToAuthorization(url: URL): Promise<void> {\n\t\tawait this.onRedirect(url);\n\t}\n\n\tasync saveCodeVerifier(verifier: string): Promise<void> {\n\t\tawait this.update((value) => ({ ...value, codeVerifier: verifier }));\n\t}\n\n\tasync saveAuthorizationRequest(request: OAuthAuthorizationRequest): Promise<void> {\n\t\tawait this.update((value) => ({ ...value, authorizationRequest: request }));\n\t}\n\n\tasync codeVerifier(): Promise<string> {\n\t\tconst verifier = (await this.load()).codeVerifier;\n\t\tif (!verifier) throw new Error(\"No OAuth PKCE code verifier is stored\");\n\t\treturn verifier;\n\t}\n\n\tasync invalidateCredentials(kind: \"all\" | \"client\" | \"tokens\" | \"verifier\" | \"discovery\"): Promise<void> {\n\t\tawait this.update((value) => {\n\t\t\tconst next = { ...value };\n\t\t\tif (kind === \"all\" || kind === \"client\") delete next.clientInformation;\n\t\t\tif (kind === \"all\" || kind === \"tokens\") {\n\t\t\t\tdelete next.tokens;\n\t\t\t\tdelete next.tokensExpireAt;\n\t\t\t\tdelete next.clientMetadataUrl;\n\t\t\t}\n\t\t\t// The verifier, the request it belongs to, and its `state` go together: the flow drops them once\n\t\t\t// the code is exchanged, so a completed sign-in cannot be completed again.\n\t\t\tif (kind === \"all\" || kind === \"verifier\") {\n\t\t\t\tdelete next.codeVerifier;\n\t\t\t\tdelete next.authorizationRequest;\n\t\t\t\tdelete next.oauthState;\n\t\t\t}\n\t\t\tif (kind === \"all\" || kind === \"discovery\") delete next.discovery;\n\t\t\treturn next;\n\t\t});\n\t}\n\n\tasync saveDiscoveryState(discovery: OAuthDiscoveryState): Promise<void> {\n\t\tawait this.update((value) => ({ ...value, discovery }));\n\t}\n\n\tasync discoveryState(): Promise<OAuthDiscoveryState | undefined> {\n\t\treturn (await this.load()).discovery;\n\t}\n\n\tprivate async load(): Promise<McpOAuthState> {\n\t\tawait this.writes;\n\t\treturn this.own(await this.store.load());\n\t}\n\n\tprivate async update(update: (state: McpOAuthState) => McpOAuthState): Promise<void> {\n\t\tthis.writes = this.writes.then(async () => {\n\t\t\tawait this.store.save(update(this.own(await this.store.load())));\n\t\t});\n\t\tawait this.writes;\n\t}\n\n\t/** Stored state for another server URL is ignored so credentials never leak across servers. */\n\tprivate own(state: McpOAuthState | undefined): McpOAuthState {\n\t\treturn state?.serverUrl === this.serverUrl ? state : { serverUrl: this.serverUrl };\n\t}\n}\n"]}
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sign-in to an OAuth-protected MCP server, in two halves so an application can complete it in another
|
|
3
|
+
* request with the same state store: `startMcpSignIn` refreshes the stored tokens when it can, or else
|
|
4
|
+
* prepares the browser step and returns the authorization URL; `completeMcpSignIn` exchanges the
|
|
5
|
+
* authorization code. The code arrives through a loopback callback server (`loopback.ts`), the
|
|
6
|
+
* application's own https callback route, or a redirect URL the user pastes.
|
|
7
|
+
*/
|
|
8
|
+
import type { OAuthCallback } from "./callback.ts";
|
|
9
|
+
import { type McpOAuthClientOptions } from "./client-settings.ts";
|
|
10
|
+
import type { OAuthChallenge } from "./types.ts";
|
|
11
|
+
/** Options of both halves of a sign-in. Pass the same values to `startMcpSignIn` and `completeMcpSignIn`. */
|
|
12
|
+
export interface McpSignInOptions extends McpOAuthClientOptions {
|
|
13
|
+
/**
|
|
14
|
+
* Redirect URI chosen by the caller: a loopback one (`listenForLoopbackSignIn`) or an https callback
|
|
15
|
+
* route of the application. Pass the same one to both halves: the authorization request may use a
|
|
16
|
+
* variant specific to the MCP server (`McpSignInRedirect.redirectUrl`), which the flow derives from it.
|
|
17
|
+
*/
|
|
18
|
+
redirectUrl: string;
|
|
19
|
+
/** The server's challenge that asked for the sign-in; its resource metadata URL and scope apply. */
|
|
20
|
+
challenge?: OAuthChallenge;
|
|
21
|
+
/**
|
|
22
|
+
* Aborting stops the sign-in at once with `McpSignInCancelledError`, also while `startMcpSignIn` waits
|
|
23
|
+
* for the store's refresh lock. A refresh already sent still completes and saves its tokens.
|
|
24
|
+
*/
|
|
25
|
+
signal?: AbortSignal;
|
|
26
|
+
}
|
|
27
|
+
/** The browser step of a sign-in, from `startMcpSignIn`. Plain data, so an application can persist it. */
|
|
28
|
+
export interface McpSignInRedirect {
|
|
29
|
+
kind: "redirect";
|
|
30
|
+
/** Open in the user's browser. */
|
|
31
|
+
authorizationUrl: string;
|
|
32
|
+
/** The redirect URI of the authorization request; the authorization response must arrive on it. */
|
|
33
|
+
redirectUrl: string;
|
|
34
|
+
/** The `state` parameter the authorization response must carry. */
|
|
35
|
+
state: string;
|
|
36
|
+
/**
|
|
37
|
+
* The scope the flow requested, if any (not a `scope` the authorization endpoint URL itself carries).
|
|
38
|
+
* Saved with the tokens when the token response names none.
|
|
39
|
+
*/
|
|
40
|
+
scope?: string;
|
|
41
|
+
}
|
|
42
|
+
/** Result of `startMcpSignIn`: signed in by refreshing the stored tokens, or the browser step. */
|
|
43
|
+
export type McpSignInStart = {
|
|
44
|
+
kind: "authorized";
|
|
45
|
+
} | McpSignInRedirect;
|
|
46
|
+
/** An authorization response: from a callback server, a callback route, or `responseFromRedirectUrl`. */
|
|
47
|
+
export type McpAuthorizationResponse = OAuthCallback;
|
|
48
|
+
/** The user or the application cancelled a sign-in (its `signal` was aborted, or the user gave up). */
|
|
49
|
+
export declare class McpSignInCancelledError extends Error {
|
|
50
|
+
constructor();
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* First half of a sign-in. Without a step-up (`insufficient_scope`), it first tries to refresh the stored
|
|
54
|
+
* tokens with the stored client, whatever `redirectUrl` is (`authorized`). The refresh takes the store's
|
|
55
|
+
* refresh lock, so never call this while holding it; when another process holds the lock for the whole
|
|
56
|
+
* wait (`McpRefreshLockBusyError`), the refresh is skipped, and any other failure of the lock fails the
|
|
57
|
+
* sign-in. Otherwise it prepares the browser step (`redirect`): a fresh `state`, and a stored client that
|
|
58
|
+
* cannot use `redirectUrl` is dropped with its tokens. Requests to the authorization server are
|
|
59
|
+
* time-limited.
|
|
60
|
+
*
|
|
61
|
+
* draht: invalid client settings (see `clientMetadataBaseUrl`) fail before the lock, discovery, or the
|
|
62
|
+
* browser step, and credentials of another client (a former registration mode or metadata base) are
|
|
63
|
+
* neither refreshed nor kept.
|
|
64
|
+
*/
|
|
65
|
+
export declare function startMcpSignIn(options: McpSignInOptions): Promise<McpSignInStart>;
|
|
66
|
+
/**
|
|
67
|
+
* Second half of a sign-in: exchanges the authorization code of `response` and saves the tokens. Pass
|
|
68
|
+
* the options given to `startMcpSignIn`, including its `redirectUrl` (not `authorization.redirectUrl`).
|
|
69
|
+
* Fails when the response carries another `state`, when another sign-in started with the store since or
|
|
70
|
+
* this one already completed, or when the exchange would use another redirect URI, client, authorization
|
|
71
|
+
* server, or token endpoint than the authorization request (the options or the discovery changed); these
|
|
72
|
+
* checks run before the stored PKCE verifier is read. A redirect URL the user pasted goes through
|
|
73
|
+
* `responseFromRedirectUrl` first, which checks its path.
|
|
74
|
+
*/
|
|
75
|
+
export declare function completeMcpSignIn(options: McpSignInOptions & {
|
|
76
|
+
/** The `redirect` result of `startMcpSignIn`. */
|
|
77
|
+
authorization: McpSignInRedirect;
|
|
78
|
+
response: McpAuthorizationResponse;
|
|
79
|
+
}): Promise<void>;
|
|
80
|
+
/** Run `fn`, reporting an abort of `signal` as `McpSignInCancelledError`. */
|
|
81
|
+
export declare function cancellable<T>(signal: AbortSignal | undefined, fn: () => Promise<T>): Promise<T>;
|
|
82
|
+
//# sourceMappingURL=sign-in.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sign-in.d.ts","sourceRoot":"","sources":["../../src/oauth/sign-in.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAGH,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,eAAe,CAAC;AACnD,OAAO,EAGN,KAAK,qBAAqB,EAK1B,MAAM,sBAAsB,CAAC;AAI9B,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,YAAY,CAAC;AAEjD,6GAA6G;AAC7G,MAAM,WAAW,gBAAiB,SAAQ,qBAAqB;IAC9D;;;;OAIG;IACH,WAAW,EAAE,MAAM,CAAC;IACpB,oGAAoG;IACpG,SAAS,CAAC,EAAE,cAAc,CAAC;IAC3B;;;OAGG;IACH,MAAM,CAAC,EAAE,WAAW,CAAC;CACrB;AAED,0GAA0G;AAC1G,MAAM,WAAW,iBAAiB;IACjC,IAAI,EAAE,UAAU,CAAC;IACjB,kCAAkC;IAClC,gBAAgB,EAAE,MAAM,CAAC;IACzB,mGAAmG;IACnG,WAAW,EAAE,MAAM,CAAC;IACpB,mEAAmE;IACnE,KAAK,EAAE,MAAM,CAAC;IACd;;;OAGG;IACH,KAAK,CAAC,EAAE,MAAM,CAAC;CACf;AAED,kGAAkG;AAClG,MAAM,MAAM,cAAc,GAAG;IAAE,IAAI,EAAE,YAAY,CAAA;CAAE,GAAG,iBAAiB,CAAC;AAExE,yGAAyG;AACzG,MAAM,MAAM,wBAAwB,GAAG,aAAa,CAAC;AAErD,uGAAuG;AACvG,qBAAa,uBAAwB,SAAQ,KAAK;IACjD,cAGC;CACD;AAED;;;;;;;;;;;;GAYG;AACH,wBAAsB,cAAc,CAAC,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAAC,cAAc,CAAC,CAOvF;AAyGD;;;;;;;;GAQG;AACH,wBAAsB,iBAAiB,CACtC,OAAO,EAAE,gBAAgB,GAAG;IAC3B,iDAAiD;IACjD,aAAa,EAAE,iBAAiB,CAAC;IACjC,QAAQ,EAAE,wBAAwB,CAAC;CACnC,GACC,OAAO,CAAC,IAAI,CAAC,CA6Bf;AAaD,6EAA6E;AAC7E,wBAAsB,WAAW,CAAC,CAAC,EAAE,MAAM,EAAE,WAAW,GAAG,SAAS,EAAE,EAAE,EAAE,MAAM,OAAO,CAAC,CAAC,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,CAStG"}
|
|
@@ -0,0 +1,209 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sign-in to an OAuth-protected MCP server, in two halves so an application can complete it in another
|
|
3
|
+
* request with the same state store: `startMcpSignIn` refreshes the stored tokens when it can, or else
|
|
4
|
+
* prepares the browser step and returns the authorization URL; `completeMcpSignIn` exchanges the
|
|
5
|
+
* authorization code. The code arrives through a loopback callback server (`loopback.ts`), the
|
|
6
|
+
* application's own https callback route, or a redirect URL the user pastes.
|
|
7
|
+
*/
|
|
8
|
+
import { refreshStoredTokens } from "./auth-provider.js";
|
|
9
|
+
import { clientMetadataBaseUrl, createOAuthClientProvider, matchesClient, offersClientMetadataDocument, registeredRedirectUrls, timedFetch, } from "./client-settings.js";
|
|
10
|
+
import { McpRefreshLockBusyError } from "./errors.js";
|
|
11
|
+
import { authorizeMcp, stepUpScope } from "./flow.js";
|
|
12
|
+
/** The user or the application cancelled a sign-in (its `signal` was aborted, or the user gave up). */
|
|
13
|
+
export class McpSignInCancelledError extends Error {
|
|
14
|
+
constructor() {
|
|
15
|
+
super("Sign-in cancelled");
|
|
16
|
+
this.name = "McpSignInCancelledError";
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* First half of a sign-in. Without a step-up (`insufficient_scope`), it first tries to refresh the stored
|
|
21
|
+
* tokens with the stored client, whatever `redirectUrl` is (`authorized`). The refresh takes the store's
|
|
22
|
+
* refresh lock, so never call this while holding it; when another process holds the lock for the whole
|
|
23
|
+
* wait (`McpRefreshLockBusyError`), the refresh is skipped, and any other failure of the lock fails the
|
|
24
|
+
* sign-in. Otherwise it prepares the browser step (`redirect`): a fresh `state`, and a stored client that
|
|
25
|
+
* cannot use `redirectUrl` is dropped with its tokens. Requests to the authorization server are
|
|
26
|
+
* time-limited.
|
|
27
|
+
*
|
|
28
|
+
* draht: invalid client settings (see `clientMetadataBaseUrl`) fail before the lock, discovery, or the
|
|
29
|
+
* browser step, and credentials of another client (a former registration mode or metadata base) are
|
|
30
|
+
* neither refreshed nor kept.
|
|
31
|
+
*/
|
|
32
|
+
export async function startMcpSignIn(options) {
|
|
33
|
+
if (options.signal?.aborted)
|
|
34
|
+
throw new McpSignInCancelledError();
|
|
35
|
+
clientMetadataBaseUrl(options.settings);
|
|
36
|
+
// A refresh keeps the granted scope; a server asking for more needs the browser step.
|
|
37
|
+
const stepUp = options.challenge?.error === "insufficient_scope";
|
|
38
|
+
if (!stepUp && (await refreshBeforeSignIn(options)) === "AUTHORIZED")
|
|
39
|
+
return { kind: "authorized" };
|
|
40
|
+
return cancellable(options.signal, () => startBrowserStep(options, stepUp));
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* Refresh the stored tokens, unless they belong to another client or `cimd` is to replace a registered
|
|
44
|
+
* client. The refresh uses `redirectUrl` when the tokens came from a Client ID Metadata Document whose
|
|
45
|
+
* documents list it.
|
|
46
|
+
*/
|
|
47
|
+
async function refreshBeforeSignIn(options) {
|
|
48
|
+
const { store, settings, serverUrl, challenge, redirectUrl, signal } = options;
|
|
49
|
+
const baseUrl = clientMetadataBaseUrl(settings);
|
|
50
|
+
const refreshed = store.withRefreshLock(async () => {
|
|
51
|
+
// The lock may arrive after the sign-in was cancelled: return at once, so it is released.
|
|
52
|
+
if (signal?.aborted)
|
|
53
|
+
return "REDIRECT";
|
|
54
|
+
const state = await store.load();
|
|
55
|
+
if (!state?.tokens?.refresh_token || !matchesClient(state, serverUrl, baseUrl))
|
|
56
|
+
return "REDIRECT";
|
|
57
|
+
// A Client ID Metadata Document never refreshes with a registered client.
|
|
58
|
+
if (baseUrl && state.clientInformation)
|
|
59
|
+
return "REDIRECT";
|
|
60
|
+
return refreshStoredTokens(options, state, { challenge, redirectUrl });
|
|
61
|
+
});
|
|
62
|
+
try {
|
|
63
|
+
return await untilAborted(signal, refreshed);
|
|
64
|
+
}
|
|
65
|
+
catch (error) {
|
|
66
|
+
// Another process is refreshing and took too long. The user signs in instead.
|
|
67
|
+
if (error instanceof McpRefreshLockBusyError)
|
|
68
|
+
return "REDIRECT";
|
|
69
|
+
throw error;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* `promise`, or `McpSignInCancelledError` as soon as `signal` aborts. `promise` keeps running: a refresh
|
|
74
|
+
* the server answered must save its tokens.
|
|
75
|
+
*/
|
|
76
|
+
function untilAborted(signal, promise) {
|
|
77
|
+
if (!signal)
|
|
78
|
+
return promise;
|
|
79
|
+
return new Promise((resolve, reject) => {
|
|
80
|
+
const abort = () => reject(new McpSignInCancelledError());
|
|
81
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
82
|
+
promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
|
|
83
|
+
});
|
|
84
|
+
}
|
|
85
|
+
async function startBrowserStep(options, stepUp) {
|
|
86
|
+
const { store, settings, serverUrl, redirectUrl, challenge } = options;
|
|
87
|
+
const previous = await store.load();
|
|
88
|
+
// draht: the credentials of another client (a former registration mode or metadata base) are dropped
|
|
89
|
+
// whole, client registration and discovery included, instead of being reused.
|
|
90
|
+
const stored = matchesClient(previous, serverUrl, clientMetadataBaseUrl(settings)) ? previous : undefined;
|
|
91
|
+
if (stored)
|
|
92
|
+
await store.save(stateForSignIn(stored, options));
|
|
93
|
+
else if (previous)
|
|
94
|
+
await store.save({ serverUrl: new URL(serverUrl).href });
|
|
95
|
+
let authorizationUrl;
|
|
96
|
+
const provider = createOAuthClientProvider(options, redirectUrl, (url) => {
|
|
97
|
+
authorizationUrl = url;
|
|
98
|
+
});
|
|
99
|
+
// A server asking for more scope gets it on top of the configured scope and, since the challenge
|
|
100
|
+
// may list only the missing scopes, on top of the scope granted so far.
|
|
101
|
+
const scope = mergeScopes(settings.scope, stepUp ? stepUpScope(stored?.tokens?.scope, challenge?.scope) : challenge?.scope);
|
|
102
|
+
await authorizeMcp(provider, { ...flowOptions(options), scope, skipRefresh: true });
|
|
103
|
+
if (!authorizationUrl)
|
|
104
|
+
throw new Error("OAuth flow did not produce an authorization URL");
|
|
105
|
+
const requestedScope = (await store.load())?.authorizationRequest?.scope;
|
|
106
|
+
return {
|
|
107
|
+
kind: "redirect",
|
|
108
|
+
authorizationUrl: authorizationUrl.href,
|
|
109
|
+
// The flow picks the redirect URI, which may be specific to the MCP server.
|
|
110
|
+
redirectUrl: authorizationUrl.searchParams.get("redirect_uri") ?? redirectUrl,
|
|
111
|
+
state: await provider.state(),
|
|
112
|
+
...(requestedScope ? { scope: requestedScope } : {}),
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
/**
|
|
116
|
+
* The stored state for a browser step: without the last sign-in's `state`, and without a client that
|
|
117
|
+
* cannot use `redirectUrl`, along with its tokens.
|
|
118
|
+
*/
|
|
119
|
+
function stateForSignIn(stored, options) {
|
|
120
|
+
const { settings, redirectUrl } = options;
|
|
121
|
+
const next = { ...stored };
|
|
122
|
+
delete next.oauthState;
|
|
123
|
+
delete next.codeVerifier;
|
|
124
|
+
delete next.authorizationRequest;
|
|
125
|
+
// A registered client cannot use another redirect URI, and its tokens belong to it. `cimd` replaces a
|
|
126
|
+
// registered client. A Client ID Metadata Document is not stored, so tokens without a stored client
|
|
127
|
+
// belong to the document, which `matchesClient` checked is the configured one.
|
|
128
|
+
const cimd = offersClientMetadataDocument(settings);
|
|
129
|
+
const keepClient = settings.clientId ||
|
|
130
|
+
(stored.clientInformation
|
|
131
|
+
? !cimd && registeredRedirectUrls(stored.clientInformation).includes(redirectUrl)
|
|
132
|
+
: cimd);
|
|
133
|
+
if (!keepClient) {
|
|
134
|
+
delete next.clientInformation;
|
|
135
|
+
delete next.tokens;
|
|
136
|
+
delete next.tokensExpireAt;
|
|
137
|
+
}
|
|
138
|
+
return next;
|
|
139
|
+
}
|
|
140
|
+
/** Scopes of both lists, each once. */
|
|
141
|
+
function mergeScopes(...scopes) {
|
|
142
|
+
const merged = [...new Set(scopes.flatMap((scope) => scope?.split(/\s+/).filter(Boolean) ?? []))];
|
|
143
|
+
return merged.length > 0 ? merged.join(" ") : undefined;
|
|
144
|
+
}
|
|
145
|
+
/**
|
|
146
|
+
* Second half of a sign-in: exchanges the authorization code of `response` and saves the tokens. Pass
|
|
147
|
+
* the options given to `startMcpSignIn`, including its `redirectUrl` (not `authorization.redirectUrl`).
|
|
148
|
+
* Fails when the response carries another `state`, when another sign-in started with the store since or
|
|
149
|
+
* this one already completed, or when the exchange would use another redirect URI, client, authorization
|
|
150
|
+
* server, or token endpoint than the authorization request (the options or the discovery changed); these
|
|
151
|
+
* checks run before the stored PKCE verifier is read. A redirect URL the user pasted goes through
|
|
152
|
+
* `responseFromRedirectUrl` first, which checks its path.
|
|
153
|
+
*/
|
|
154
|
+
export async function completeMcpSignIn(options) {
|
|
155
|
+
await cancellable(options.signal, async () => {
|
|
156
|
+
const { authorization, response } = options;
|
|
157
|
+
if (response.state !== authorization.state) {
|
|
158
|
+
throw new Error("The authorization response belongs to a different sign-in");
|
|
159
|
+
}
|
|
160
|
+
const stored = await options.store.load();
|
|
161
|
+
// A completed sign-in dropped its state and verifier; the code is spent.
|
|
162
|
+
if (!stored?.oauthState)
|
|
163
|
+
throw new Error("No sign-in to this MCP server is pending; sign in again");
|
|
164
|
+
// The stored PKCE verifier belongs to the latest sign-in; exchanging with it would fail with
|
|
165
|
+
// `invalid_grant`, which discards the stored tokens.
|
|
166
|
+
if (stored.oauthState !== authorization.state) {
|
|
167
|
+
throw new Error("Another sign-in to this MCP server started since; sign in again");
|
|
168
|
+
}
|
|
169
|
+
// Fail closed: without the request's client and authorization server, the exchange cannot be checked.
|
|
170
|
+
const request = stored.authorizationRequest;
|
|
171
|
+
if (!request || !stored.codeVerifier) {
|
|
172
|
+
throw new Error("The authorization request of this sign-in is not stored; sign in again");
|
|
173
|
+
}
|
|
174
|
+
await authorizeMcp(createOAuthClientProvider(options, options.redirectUrl), {
|
|
175
|
+
...flowOptions(options),
|
|
176
|
+
// Saved with the tokens when the token response names no scope, so it must be the requested one.
|
|
177
|
+
scope: request.scope,
|
|
178
|
+
authorizationRequest: request,
|
|
179
|
+
authorizationRedirectUrl: authorization.redirectUrl,
|
|
180
|
+
authorizationCode: response.code,
|
|
181
|
+
iss: response.iss,
|
|
182
|
+
});
|
|
183
|
+
});
|
|
184
|
+
}
|
|
185
|
+
/** `authorizeMcp` options of a sign-in, without the scope. */
|
|
186
|
+
function flowOptions(options) {
|
|
187
|
+
return {
|
|
188
|
+
serverUrl: options.serverUrl,
|
|
189
|
+
fetch: timedFetch(),
|
|
190
|
+
signal: options.signal,
|
|
191
|
+
resourceMetadataUrl: options.challenge?.resourceMetadataUrl,
|
|
192
|
+
authorizationServerMetadataUrl: options.settings.authServerMetadataUrl,
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
/** Run `fn`, reporting an abort of `signal` as `McpSignInCancelledError`. */
|
|
196
|
+
export async function cancellable(signal, fn) {
|
|
197
|
+
if (signal?.aborted)
|
|
198
|
+
throw new McpSignInCancelledError();
|
|
199
|
+
try {
|
|
200
|
+
return await fn();
|
|
201
|
+
}
|
|
202
|
+
catch (error) {
|
|
203
|
+
// Aborted requests fail with the signal's reason; report them as the cancellation they are.
|
|
204
|
+
if (signal?.aborted)
|
|
205
|
+
throw new McpSignInCancelledError();
|
|
206
|
+
throw error;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
//# sourceMappingURL=sign-in.js.map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,CAAC;QACzD,MAAM,KAAK,CAAC;IACb,CAAC;AACF,CAAC","sourcesContent":["/**\n * Sign-in to an OAuth-protected MCP server, in two halves so an application can complete it in another\n * request with the same state store: `startMcpSignIn` refreshes the stored tokens when it can, or else\n * prepares the browser step and returns the authorization URL; `completeMcpSignIn` exchanges the\n * authorization code. The code arrives through a loopback callback server (`loopback.ts`), the\n * application's own https callback route, or a redirect URL the user pastes.\n */\n\nimport { refreshStoredTokens } from \"./auth-provider.ts\";\nimport type { OAuthCallback } from \"./callback.ts\";\nimport {\n\tclientMetadataBaseUrl,\n\tcreateOAuthClientProvider,\n\ttype McpOAuthClientOptions,\n\tmatchesClient,\n\toffersClientMetadataDocument,\n\tregisteredRedirectUrls,\n\ttimedFetch,\n} from \"./client-settings.ts\";\nimport { McpRefreshLockBusyError } from \"./errors.ts\";\nimport { authorizeMcp, type OAuthFlowOptions, stepUpScope } from \"./flow.ts\";\nimport type { McpOAuthState } from \"./provider.ts\";\nimport type { OAuthChallenge } from \"./types.ts\";\n\n/** Options of both halves of a sign-in. Pass the same values to `startMcpSignIn` and `completeMcpSignIn`. */\nexport interface McpSignInOptions extends McpOAuthClientOptions {\n\t/**\n\t * Redirect URI chosen by the caller: a loopback one (`listenForLoopbackSignIn`) or an https callback\n\t * route of the application. Pass the same one to both halves: the authorization request may use a\n\t * variant specific to the MCP server (`McpSignInRedirect.redirectUrl`), which the flow derives from it.\n\t */\n\tredirectUrl: string;\n\t/** The server's challenge that asked for the sign-in; its resource metadata URL and scope apply. */\n\tchallenge?: OAuthChallenge;\n\t/**\n\t * Aborting stops the sign-in at once with `McpSignInCancelledError`, also while `startMcpSignIn` waits\n\t * for the store's refresh lock. A refresh already sent still completes and saves its tokens.\n\t */\n\tsignal?: AbortSignal;\n}\n\n/** The browser step of a sign-in, from `startMcpSignIn`. Plain data, so an application can persist it. */\nexport interface McpSignInRedirect {\n\tkind: \"redirect\";\n\t/** Open in the user's browser. */\n\tauthorizationUrl: string;\n\t/** The redirect URI of the authorization request; the authorization response must arrive on it. */\n\tredirectUrl: string;\n\t/** The `state` parameter the authorization response must carry. */\n\tstate: string;\n\t/**\n\t * The scope the flow requested, if any (not a `scope` the authorization endpoint URL itself carries).\n\t * Saved with the tokens when the token response names none.\n\t */\n\tscope?: string;\n}\n\n/** Result of `startMcpSignIn`: signed in by refreshing the stored tokens, or the browser step. */\nexport type McpSignInStart = { kind: \"authorized\" } | McpSignInRedirect;\n\n/** An authorization response: from a callback server, a callback route, or `responseFromRedirectUrl`. */\nexport type McpAuthorizationResponse = OAuthCallback;\n\n/** The user or the application cancelled a sign-in (its `signal` was aborted, or the user gave up). */\nexport class McpSignInCancelledError extends Error {\n\tconstructor() {\n\t\tsuper(\"Sign-in cancelled\");\n\t\tthis.name = \"McpSignInCancelledError\";\n\t}\n}\n\n/**\n * First half of a sign-in. Without a step-up (`insufficient_scope`), it first tries to refresh the stored\n * tokens with the stored client, whatever `redirectUrl` is (`authorized`). The refresh takes the store's\n * refresh lock, so never call this while holding it; when another process holds the lock for the whole\n * wait (`McpRefreshLockBusyError`), the refresh is skipped, and any other failure of the lock fails the\n * sign-in. Otherwise it prepares the browser step (`redirect`): a fresh `state`, and a stored client that\n * cannot use `redirectUrl` is dropped with its tokens. Requests to the authorization server are\n * time-limited.\n *\n * draht: invalid client settings (see `clientMetadataBaseUrl`) fail before the lock, discovery, or the\n * browser step, and credentials of another client (a former registration mode or metadata base) are\n * neither refreshed nor kept.\n */\nexport async function startMcpSignIn(options: McpSignInOptions): Promise<McpSignInStart> {\n\tif (options.signal?.aborted) throw new McpSignInCancelledError();\n\tclientMetadataBaseUrl(options.settings);\n\t// A refresh keeps the granted scope; a server asking for more needs the browser step.\n\tconst stepUp = options.challenge?.error === \"insufficient_scope\";\n\tif (!stepUp && (await refreshBeforeSignIn(options)) === \"AUTHORIZED\") return { kind: \"authorized\" };\n\treturn cancellable(options.signal, () => startBrowserStep(options, stepUp));\n}\n\n/**\n * Refresh the stored tokens, unless they belong to another client or `cimd` is to replace a registered\n * client. The refresh uses `redirectUrl` when the tokens came from a Client ID Metadata Document whose\n * documents list it.\n */\nasync function refreshBeforeSignIn(options: McpSignInOptions): Promise<\"AUTHORIZED\" | \"REDIRECT\"> {\n\tconst { store, settings, serverUrl, challenge, redirectUrl, signal } = options;\n\tconst baseUrl = clientMetadataBaseUrl(settings);\n\tconst refreshed = store.withRefreshLock(async () => {\n\t\t// The lock may arrive after the sign-in was cancelled: return at once, so it is released.\n\t\tif (signal?.aborted) return \"REDIRECT\";\n\t\tconst state = await store.load();\n\t\tif (!state?.tokens?.refresh_token || !matchesClient(state, serverUrl, baseUrl)) return \"REDIRECT\";\n\t\t// A Client ID Metadata Document never refreshes with a registered client.\n\t\tif (baseUrl && state.clientInformation) return \"REDIRECT\";\n\t\treturn refreshStoredTokens(options, state, { challenge, redirectUrl });\n\t});\n\ttry {\n\t\treturn await untilAborted(signal, refreshed);\n\t} catch (error) {\n\t\t// Another process is refreshing and took too long. The user signs in instead.\n\t\tif (error instanceof McpRefreshLockBusyError) return \"REDIRECT\";\n\t\tthrow error;\n\t}\n}\n\n/**\n * `promise`, or `McpSignInCancelledError` as soon as `signal` aborts. `promise` keeps running: a refresh\n * the server answered must save its tokens.\n */\nfunction untilAborted<T>(signal: AbortSignal | undefined, promise: Promise<T>): Promise<T> {\n\tif (!signal) return promise;\n\treturn new Promise<T>((resolve, reject) => {\n\t\tconst abort = () => reject(new McpSignInCancelledError());\n\t\tsignal.addEventListener(\"abort\", abort, { once: true });\n\t\tpromise.then(resolve, reject).finally(() => signal.removeEventListener(\"abort\", abort));\n\t});\n}\n\nasync function startBrowserStep(options: McpSignInOptions, stepUp: boolean): Promise<McpSignInRedirect> {\n\tconst { store, settings, serverUrl, redirectUrl, challenge } = options;\n\tconst previous = await store.load();\n\t// draht: the credentials of another client (a former registration mode or metadata base) are dropped\n\t// whole, client registration and discovery included, instead of being reused.\n\tconst stored = matchesClient(previous, serverUrl, clientMetadataBaseUrl(settings)) ? previous : undefined;\n\tif (stored) await store.save(stateForSignIn(stored, options));\n\telse if (previous) await store.save({ serverUrl: new URL(serverUrl).href });\n\tlet authorizationUrl: URL | undefined;\n\tconst provider = createOAuthClientProvider(options, redirectUrl, (url) => {\n\t\tauthorizationUrl = url;\n\t});\n\t// A server asking for more scope gets it on top of the configured scope and, since the challenge\n\t// may list only the missing scopes, on top of the scope granted so far.\n\tconst scope = mergeScopes(\n\t\tsettings.scope,\n\t\tstepUp ? stepUpScope(stored?.tokens?.scope, challenge?.scope) : challenge?.scope,\n\t);\n\tawait authorizeMcp(provider, { ...flowOptions(options), scope, skipRefresh: true });\n\tif (!authorizationUrl) throw new Error(\"OAuth flow did not produce an authorization URL\");\n\tconst requestedScope = (await store.load())?.authorizationRequest?.scope;\n\treturn {\n\t\tkind: \"redirect\",\n\t\tauthorizationUrl: authorizationUrl.href,\n\t\t// The flow picks the redirect URI, which may be specific to the MCP server.\n\t\tredirectUrl: authorizationUrl.searchParams.get(\"redirect_uri\") ?? redirectUrl,\n\t\tstate: await provider.state(),\n\t\t...(requestedScope ? { scope: requestedScope } : {}),\n\t};\n}\n\n/**\n * The stored state for a browser step: without the last sign-in's `state`, and without a client that\n * cannot use `redirectUrl`, along with its tokens.\n */\nfunction stateForSignIn(stored: McpOAuthState, options: McpSignInOptions): McpOAuthState {\n\tconst { settings, redirectUrl } = options;\n\tconst next: McpOAuthState = { ...stored };\n\tdelete next.oauthState;\n\tdelete next.codeVerifier;\n\tdelete next.authorizationRequest;\n\t// A registered client cannot use another redirect URI, and its tokens belong to it. `cimd` replaces a\n\t// registered client. A Client ID Metadata Document is not stored, so tokens without a stored client\n\t// belong to the document, which `matchesClient` checked is the configured one.\n\tconst cimd = offersClientMetadataDocument(settings);\n\tconst keepClient =\n\t\tsettings.clientId ||\n\t\t(stored.clientInformation\n\t\t\t? !cimd && registeredRedirectUrls(stored.clientInformation).includes(redirectUrl)\n\t\t\t: cimd);\n\tif (!keepClient) {\n\t\tdelete next.clientInformation;\n\t\tdelete next.tokens;\n\t\tdelete next.tokensExpireAt;\n\t}\n\treturn next;\n}\n\n/** Scopes of both lists, each once. */\nfunction mergeScopes(...scopes: (string | undefined)[]): string | undefined {\n\tconst merged = [...new Set(scopes.flatMap((scope) => scope?.split(/\\s+/).filter(Boolean) ?? []))];\n\treturn merged.length > 0 ? merged.join(\" \") : undefined;\n}\n\n/**\n * Second half of a sign-in: exchanges the authorization code of `response` and saves the tokens. Pass\n * the options given to `startMcpSignIn`, including its `redirectUrl` (not `authorization.redirectUrl`).\n * Fails when the response carries another `state`, when another sign-in started with the store since or\n * this one already completed, or when the exchange would use another redirect URI, client, authorization\n * server, or token endpoint than the authorization request (the options or the discovery changed); these\n * checks run before the stored PKCE verifier is read. A redirect URL the user pasted goes through\n * `responseFromRedirectUrl` first, which checks its path.\n */\nexport async function completeMcpSignIn(\n\toptions: McpSignInOptions & {\n\t\t/** The `redirect` result of `startMcpSignIn`. */\n\t\tauthorization: McpSignInRedirect;\n\t\tresponse: McpAuthorizationResponse;\n\t},\n): Promise<void> {\n\tawait cancellable(options.signal, async () => {\n\t\tconst { authorization, response } = options;\n\t\tif (response.state !== authorization.state) {\n\t\t\tthrow new Error(\"The authorization response belongs to a different sign-in\");\n\t\t}\n\t\tconst stored = await options.store.load();\n\t\t// A completed sign-in dropped its state and verifier; the code is spent.\n\t\tif (!stored?.oauthState) throw new Error(\"No sign-in to this MCP server is pending; sign in again\");\n\t\t// The stored PKCE verifier belongs to the latest sign-in; exchanging with it would fail with\n\t\t// `invalid_grant`, which discards the stored tokens.\n\t\tif (stored.oauthState !== authorization.state) {\n\t\t\tthrow new Error(\"Another sign-in to this MCP server started since; sign in again\");\n\t\t}\n\t\t// Fail closed: without the request's client and authorization server, the exchange cannot be checked.\n\t\tconst request = stored.authorizationRequest;\n\t\tif (!request || !stored.codeVerifier) {\n\t\t\tthrow new Error(\"The authorization request of this sign-in is not stored; sign in again\");\n\t\t}\n\t\tawait authorizeMcp(createOAuthClientProvider(options, options.redirectUrl), {\n\t\t\t...flowOptions(options),\n\t\t\t// Saved with the tokens when the token response names no scope, so it must be the requested one.\n\t\t\tscope: request.scope,\n\t\t\tauthorizationRequest: request,\n\t\t\tauthorizationRedirectUrl: authorization.redirectUrl,\n\t\t\tauthorizationCode: response.code,\n\t\t\tiss: response.iss,\n\t\t});\n\t});\n}\n\n/** `authorizeMcp` options of a sign-in, without the scope. */\nfunction flowOptions(options: McpSignInOptions): OAuthFlowOptions {\n\treturn {\n\t\tserverUrl: options.serverUrl,\n\t\tfetch: timedFetch(),\n\t\tsignal: options.signal,\n\t\tresourceMetadataUrl: options.challenge?.resourceMetadataUrl,\n\t\tauthorizationServerMetadataUrl: options.settings.authServerMetadataUrl,\n\t};\n}\n\n/** Run `fn`, reporting an abort of `signal` as `McpSignInCancelledError`. */\nexport async function cancellable<T>(signal: AbortSignal | undefined, fn: () => Promise<T>): Promise<T> {\n\tif (signal?.aborted) throw new McpSignInCancelledError();\n\ttry {\n\t\treturn await fn();\n\t} catch (error) {\n\t\t// Aborted requests fail with the signal's reason; report them as the cancellation they are.\n\t\tif (signal?.aborted) throw new McpSignInCancelledError();\n\t\tthrow error;\n\t}\n}\n"]}
|
package/dist/oauth/types.d.ts
CHANGED
|
@@ -75,6 +75,7 @@ export interface OAuthChallenge {
|
|
|
75
75
|
error?: string;
|
|
76
76
|
errorDescription?: string;
|
|
77
77
|
}
|
|
78
|
+
export declare function isHttpUrl(url: URL): boolean;
|
|
78
79
|
export declare function parseProtectedResourceMetadata(value: unknown): OAuthProtectedResourceMetadata;
|
|
79
80
|
export declare function parseAuthorizationServerMetadata(value: unknown): AuthorizationServerMetadata;
|
|
80
81
|
export declare function parseOAuthTokens(value: unknown): OAuthTokens;
|