@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 @@
|
|
|
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,gBAAgB,EAGhB,4BAA4B,EAC5B,sBAAsB,EACtB,kBAAkB,GAClB,MAAM,sBAAsB,CAAC;AAE9B,OAAO,EACN,WAAW,EAEX,uBAAuB,GAEvB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AAC,YAAY,CAAC,GAAG,CAAC,OAAO,CAAC,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\tloopbackSettings,\n\ttype McpClientMetadataDocuments,\n\ttype McpOAuthSettings,\n\toffersClientMetadataDocument,\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. Pass the sign-in's `clientMetadataDocuments`, so the callback server also serves the\n * server-specific redirect URI. Close the callback server when the sign-in ends.\n */\nexport async function listenForLoopbackSignIn(options: {\n\tserverUrl: string;\n\tstore: McpOAuthStateStore;\n\tsettings: McpOAuthSettings;\n\tclientMetadataDocuments?: McpClientMetadataDocuments;\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 loopback = loopbackSettings(settings);\n\tconst registered = registeredRedirectUrls((await options.store.load())?.clientInformation)[0];\n\tconst port = loopback.port ?? (registered ? Number(new URL(registered).port) || undefined : undefined);\n\tconst offersDocument = offersClientMetadataDocument(settings, options.clientMetadataDocuments, loopback.url);\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: offersDocument ? [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`.\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"]}
|
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
import type { OAuthClientMetadataDocument, OAuthClientProvider } from "./flow.ts";
|
|
2
|
+
import type { AuthorizationServerMetadata, OAuthClientInformationMixed, OAuthClientMetadata, OAuthDiscoveryState, OAuthTokens } from "./types.ts";
|
|
3
|
+
export interface McpOAuthState {
|
|
4
|
+
serverUrl: string;
|
|
5
|
+
clientInformation?: OAuthClientInformationMixed;
|
|
6
|
+
tokens?: OAuthTokens;
|
|
7
|
+
/** When the access token expires, in milliseconds since the epoch, from `expires_in` at the time it was saved. */
|
|
8
|
+
tokensExpireAt?: number;
|
|
9
|
+
codeVerifier?: string;
|
|
10
|
+
oauthState?: string;
|
|
11
|
+
discovery?: OAuthDiscoveryState;
|
|
12
|
+
}
|
|
13
|
+
export interface McpOAuthStateStore {
|
|
14
|
+
load(): McpOAuthState | undefined | Promise<McpOAuthState | undefined>;
|
|
15
|
+
save(state: McpOAuthState): void | Promise<void>;
|
|
16
|
+
}
|
|
17
|
+
export interface McpOAuthProviderOptions {
|
|
18
|
+
serverUrl: string | URL;
|
|
19
|
+
redirectUrl: string | URL;
|
|
20
|
+
clientMetadata: Omit<OAuthClientMetadata, "redirect_uris"> & {
|
|
21
|
+
redirect_uris?: string[];
|
|
22
|
+
};
|
|
23
|
+
/** See `OAuthClientProvider.clientMetadataDocument`. */
|
|
24
|
+
clientMetadataDocument?: (metadata: AuthorizationServerMetadata | undefined) => OAuthClientMetadataDocument | undefined;
|
|
25
|
+
clientId?: string;
|
|
26
|
+
clientSecret?: string;
|
|
27
|
+
store?: McpOAuthStateStore;
|
|
28
|
+
onRedirect(url: URL): void | Promise<void>;
|
|
29
|
+
}
|
|
30
|
+
export declare class MemoryOAuthStateStore implements McpOAuthStateStore {
|
|
31
|
+
private value;
|
|
32
|
+
load(): McpOAuthState | undefined;
|
|
33
|
+
save(state: McpOAuthState): void;
|
|
34
|
+
}
|
|
35
|
+
/** Default stateful provider for one exact MCP server URL. Applications inject durable storage if needed. */
|
|
36
|
+
export declare class McpOAuthProvider implements OAuthClientProvider {
|
|
37
|
+
readonly redirectUrl: string;
|
|
38
|
+
readonly clientMetadata: OAuthClientMetadata;
|
|
39
|
+
readonly clientMetadataDocument?: (metadata: AuthorizationServerMetadata | undefined) => OAuthClientMetadataDocument | undefined;
|
|
40
|
+
private serverUrl;
|
|
41
|
+
private configuredClient;
|
|
42
|
+
private store;
|
|
43
|
+
private onRedirect;
|
|
44
|
+
private writes;
|
|
45
|
+
constructor(options: McpOAuthProviderOptions);
|
|
46
|
+
state(): Promise<string>;
|
|
47
|
+
clientInformation(): Promise<OAuthClientInformationMixed | undefined>;
|
|
48
|
+
saveClientInformation(information: OAuthClientInformationMixed): Promise<void>;
|
|
49
|
+
tokens(): Promise<OAuthTokens | undefined>;
|
|
50
|
+
saveTokens(tokens: OAuthTokens): Promise<void>;
|
|
51
|
+
redirectToAuthorization(url: URL): Promise<void>;
|
|
52
|
+
saveCodeVerifier(verifier: string): Promise<void>;
|
|
53
|
+
codeVerifier(): Promise<string>;
|
|
54
|
+
invalidateCredentials(kind: "all" | "client" | "tokens" | "verifier" | "discovery"): Promise<void>;
|
|
55
|
+
saveDiscoveryState(discovery: OAuthDiscoveryState): Promise<void>;
|
|
56
|
+
discoveryState(): Promise<OAuthDiscoveryState | undefined>;
|
|
57
|
+
private load;
|
|
58
|
+
private update;
|
|
59
|
+
/** Stored state for another server URL is ignored so credentials never leak across servers. */
|
|
60
|
+
private own;
|
|
61
|
+
}
|
|
62
|
+
//# sourceMappingURL=provider.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"provider.d.ts","sourceRoot":"","sources":["../../src/oauth/provider.ts"],"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,GAAG,UAAU,GAAG,WAAW,GAAG,OAAO,CAAC,IAAI,CAAC,CAavG;IAEK,kBAAkB,CAAC,SAAS,EAAE,mBAAmB,GAAG,OAAO,CAAC,IAAI,CAAC,CAEtE;IAEK,cAAc,IAAI,OAAO,CAAC,mBAAmB,GAAG,SAAS,CAAC,CAE/D;YAEa,IAAI;YAKJ,MAAM;IAOpB,+FAA+F;IAC/F,OAAO,CAAC,GAAG;CAGX"}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
export class MemoryOAuthStateStore {
|
|
2
|
+
value;
|
|
3
|
+
load() {
|
|
4
|
+
return this.value === undefined ? undefined : structuredClone(this.value);
|
|
5
|
+
}
|
|
6
|
+
save(state) {
|
|
7
|
+
this.value = structuredClone(state);
|
|
8
|
+
}
|
|
9
|
+
}
|
|
10
|
+
/** Default stateful provider for one exact MCP server URL. Applications inject durable storage if needed. */
|
|
11
|
+
export class McpOAuthProvider {
|
|
12
|
+
redirectUrl;
|
|
13
|
+
clientMetadata;
|
|
14
|
+
clientMetadataDocument;
|
|
15
|
+
serverUrl;
|
|
16
|
+
configuredClient;
|
|
17
|
+
store;
|
|
18
|
+
onRedirect;
|
|
19
|
+
writes = Promise.resolve();
|
|
20
|
+
constructor(options) {
|
|
21
|
+
this.serverUrl = String(new URL(options.serverUrl));
|
|
22
|
+
this.redirectUrl = String(options.redirectUrl);
|
|
23
|
+
this.clientMetadata = {
|
|
24
|
+
...options.clientMetadata,
|
|
25
|
+
redirect_uris: options.clientMetadata.redirect_uris ?? [this.redirectUrl],
|
|
26
|
+
grant_types: options.clientMetadata.grant_types ?? ["authorization_code", "refresh_token"],
|
|
27
|
+
response_types: options.clientMetadata.response_types ?? ["code"],
|
|
28
|
+
token_endpoint_auth_method: options.clientMetadata.token_endpoint_auth_method ?? (options.clientSecret ? "client_secret_post" : "none"),
|
|
29
|
+
};
|
|
30
|
+
this.clientMetadataDocument = options.clientMetadataDocument;
|
|
31
|
+
this.configuredClient = options.clientId
|
|
32
|
+
? { client_id: options.clientId, ...(options.clientSecret ? { client_secret: options.clientSecret } : {}) }
|
|
33
|
+
: undefined;
|
|
34
|
+
this.store = options.store ?? new MemoryOAuthStateStore();
|
|
35
|
+
this.onRedirect = options.onRedirect;
|
|
36
|
+
}
|
|
37
|
+
async state() {
|
|
38
|
+
const existing = (await this.load()).oauthState;
|
|
39
|
+
if (existing)
|
|
40
|
+
return existing;
|
|
41
|
+
const state = Buffer.from(crypto.getRandomValues(new Uint8Array(32))).toString("hex");
|
|
42
|
+
await this.update((value) => ({ ...value, oauthState: state }));
|
|
43
|
+
return state;
|
|
44
|
+
}
|
|
45
|
+
async clientInformation() {
|
|
46
|
+
return this.configuredClient ?? (await this.load()).clientInformation;
|
|
47
|
+
}
|
|
48
|
+
async saveClientInformation(information) {
|
|
49
|
+
if (this.configuredClient)
|
|
50
|
+
return;
|
|
51
|
+
await this.update((value) => ({ ...value, clientInformation: information }));
|
|
52
|
+
}
|
|
53
|
+
async tokens() {
|
|
54
|
+
return (await this.load()).tokens;
|
|
55
|
+
}
|
|
56
|
+
async saveTokens(tokens) {
|
|
57
|
+
const expiresAt = tokens.expires_in === undefined ? undefined : Date.now() + tokens.expires_in * 1000;
|
|
58
|
+
await this.update((value) => {
|
|
59
|
+
const next = { ...value, tokens };
|
|
60
|
+
if (expiresAt === undefined)
|
|
61
|
+
delete next.tokensExpireAt;
|
|
62
|
+
else
|
|
63
|
+
next.tokensExpireAt = expiresAt;
|
|
64
|
+
return next;
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
async redirectToAuthorization(url) {
|
|
68
|
+
await this.onRedirect(url);
|
|
69
|
+
}
|
|
70
|
+
async saveCodeVerifier(verifier) {
|
|
71
|
+
await this.update((value) => ({ ...value, codeVerifier: verifier }));
|
|
72
|
+
}
|
|
73
|
+
async codeVerifier() {
|
|
74
|
+
const verifier = (await this.load()).codeVerifier;
|
|
75
|
+
if (!verifier)
|
|
76
|
+
throw new Error("No OAuth PKCE code verifier is stored");
|
|
77
|
+
return verifier;
|
|
78
|
+
}
|
|
79
|
+
async invalidateCredentials(kind) {
|
|
80
|
+
await this.update((value) => {
|
|
81
|
+
const next = { ...value };
|
|
82
|
+
if (kind === "all" || kind === "client")
|
|
83
|
+
delete next.clientInformation;
|
|
84
|
+
if (kind === "all" || kind === "tokens") {
|
|
85
|
+
delete next.tokens;
|
|
86
|
+
delete next.tokensExpireAt;
|
|
87
|
+
}
|
|
88
|
+
if (kind === "all" || kind === "verifier")
|
|
89
|
+
delete next.codeVerifier;
|
|
90
|
+
if (kind === "all" || kind === "discovery")
|
|
91
|
+
delete next.discovery;
|
|
92
|
+
if (kind === "all")
|
|
93
|
+
delete next.oauthState;
|
|
94
|
+
return next;
|
|
95
|
+
});
|
|
96
|
+
}
|
|
97
|
+
async saveDiscoveryState(discovery) {
|
|
98
|
+
await this.update((value) => ({ ...value, discovery }));
|
|
99
|
+
}
|
|
100
|
+
async discoveryState() {
|
|
101
|
+
return (await this.load()).discovery;
|
|
102
|
+
}
|
|
103
|
+
async load() {
|
|
104
|
+
await this.writes;
|
|
105
|
+
return this.own(await this.store.load());
|
|
106
|
+
}
|
|
107
|
+
async update(update) {
|
|
108
|
+
this.writes = this.writes.then(async () => {
|
|
109
|
+
await this.store.save(update(this.own(await this.store.load())));
|
|
110
|
+
});
|
|
111
|
+
await this.writes;
|
|
112
|
+
}
|
|
113
|
+
/** Stored state for another server URL is ignored so credentials never leak across servers. */
|
|
114
|
+
own(state) {
|
|
115
|
+
return state?.serverUrl === this.serverUrl ? state : { serverUrl: this.serverUrl };
|
|
116
|
+
}
|
|
117
|
+
}
|
|
118
|
+
//# sourceMappingURL=provider.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"provider.js","sourceRoot":"","sources":["../../src/oauth/provider.ts"],"names":[],"mappings":"AAuCA,MAAM,OAAO,qBAAqB;IACzB,KAAK,CAA4B;IAEzC,IAAI;QACH,OAAO,IAAI,CAAC,KAAK,KAA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AAC,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\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\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\tthis.clientMetadataDocument = options.clientMetadataDocument;\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\treturn this.configuredClient ?? (await this.load()).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\treturn (await this.load()).tokens;\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 (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}\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"]}
|
|
@@ -0,0 +1,73 @@
|
|
|
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
|
+
/** The scope requested, if any. Saved with the tokens when the token response names none. */
|
|
37
|
+
scope?: string;
|
|
38
|
+
}
|
|
39
|
+
/** Result of `startMcpSignIn`: signed in by refreshing the stored tokens, or the browser step. */
|
|
40
|
+
export type McpSignInStart = {
|
|
41
|
+
kind: "authorized";
|
|
42
|
+
} | McpSignInRedirect;
|
|
43
|
+
/** An authorization response: from a callback server, a callback route, or `responseFromRedirectUrl`. */
|
|
44
|
+
export type McpAuthorizationResponse = OAuthCallback;
|
|
45
|
+
/** The user or the application cancelled a sign-in (its `signal` was aborted, or the user gave up). */
|
|
46
|
+
export declare class McpSignInCancelledError extends Error {
|
|
47
|
+
constructor();
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* First half of a sign-in. Without a step-up (`insufficient_scope`), it first tries to refresh the stored
|
|
51
|
+
* tokens with the stored client, whatever `redirectUrl` is (`authorized`). The refresh takes the store's
|
|
52
|
+
* refresh lock, so never call this while holding it; when another process holds the lock for the whole
|
|
53
|
+
* wait (`McpRefreshLockBusyError`), the refresh is skipped, and any other failure of the lock fails the
|
|
54
|
+
* sign-in. Otherwise it prepares the browser step (`redirect`): a fresh `state`, and a stored client that
|
|
55
|
+
* cannot use `redirectUrl` is dropped with its tokens. Requests to the authorization server are
|
|
56
|
+
* time-limited.
|
|
57
|
+
*/
|
|
58
|
+
export declare function startMcpSignIn(options: McpSignInOptions): Promise<McpSignInStart>;
|
|
59
|
+
/**
|
|
60
|
+
* Second half of a sign-in: exchanges the authorization code of `response` and saves the tokens. Pass
|
|
61
|
+
* the options given to `startMcpSignIn`, including its `redirectUrl` (not `authorization.redirectUrl`).
|
|
62
|
+
* Fails when the response carries another `state`, when another sign-in started with the store since, or
|
|
63
|
+
* when the exchange would use another redirect URI than the authorization request (the options changed).
|
|
64
|
+
* A redirect URL the user pasted goes through `responseFromRedirectUrl` first, which checks its path.
|
|
65
|
+
*/
|
|
66
|
+
export declare function completeMcpSignIn(options: McpSignInOptions & {
|
|
67
|
+
/** The `redirect` result of `startMcpSignIn`. */
|
|
68
|
+
authorization: McpSignInRedirect;
|
|
69
|
+
response: McpAuthorizationResponse;
|
|
70
|
+
}): Promise<void>;
|
|
71
|
+
/** Run `fn`, reporting an abort of `signal` as `McpSignInCancelledError`. */
|
|
72
|
+
export declare function cancellable<T>(signal: AbortSignal | undefined, fn: () => Promise<T>): Promise<T>;
|
|
73
|
+
//# 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,EAEN,KAAK,qBAAqB,EAI1B,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,6FAA6F;IAC7F,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;;;;;;;;GAQG;AACH,wBAAsB,cAAc,CAAC,OAAO,EAAE,gBAAgB,GAAG,OAAO,CAAC,cAAc,CAAC,CAMvF;AAgGD;;;;;;GAMG;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,CAoBf;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,182 @@
|
|
|
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 { createOAuthClientProvider, 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
|
+
export async function startMcpSignIn(options) {
|
|
29
|
+
if (options.signal?.aborted)
|
|
30
|
+
throw new McpSignInCancelledError();
|
|
31
|
+
// A refresh keeps the granted scope; a server asking for more needs the browser step.
|
|
32
|
+
const stepUp = options.challenge?.error === "insufficient_scope";
|
|
33
|
+
if (!stepUp && (await refreshBeforeSignIn(options)) === "AUTHORIZED")
|
|
34
|
+
return { kind: "authorized" };
|
|
35
|
+
return cancellable(options.signal, () => startBrowserStep(options, stepUp));
|
|
36
|
+
}
|
|
37
|
+
/**
|
|
38
|
+
* Refresh the stored tokens, unless `cimd` is to replace a registered client. The refresh uses
|
|
39
|
+
* `redirectUrl` when the tokens came from a Client ID Metadata Document whose documents list it.
|
|
40
|
+
*/
|
|
41
|
+
async function refreshBeforeSignIn(options) {
|
|
42
|
+
const { store, settings, challenge, redirectUrl, signal } = options;
|
|
43
|
+
const refreshed = store.withRefreshLock(async () => {
|
|
44
|
+
// The lock may arrive after the sign-in was cancelled: return at once, so it is released.
|
|
45
|
+
if (signal?.aborted)
|
|
46
|
+
return "REDIRECT";
|
|
47
|
+
const state = await store.load();
|
|
48
|
+
if (!state?.tokens?.refresh_token)
|
|
49
|
+
return "REDIRECT";
|
|
50
|
+
if (settings.clientRegistration === "cimd" && state.clientInformation && !settings.clientId)
|
|
51
|
+
return "REDIRECT";
|
|
52
|
+
return refreshStoredTokens(options, state, { challenge, redirectUrl });
|
|
53
|
+
});
|
|
54
|
+
try {
|
|
55
|
+
return await untilAborted(signal, refreshed);
|
|
56
|
+
}
|
|
57
|
+
catch (error) {
|
|
58
|
+
// Another process is refreshing and took too long. The user signs in instead.
|
|
59
|
+
if (error instanceof McpRefreshLockBusyError)
|
|
60
|
+
return "REDIRECT";
|
|
61
|
+
throw error;
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
/**
|
|
65
|
+
* `promise`, or `McpSignInCancelledError` as soon as `signal` aborts. `promise` keeps running: a refresh
|
|
66
|
+
* the server answered must save its tokens.
|
|
67
|
+
*/
|
|
68
|
+
function untilAborted(signal, promise) {
|
|
69
|
+
if (!signal)
|
|
70
|
+
return promise;
|
|
71
|
+
return new Promise((resolve, reject) => {
|
|
72
|
+
const abort = () => reject(new McpSignInCancelledError());
|
|
73
|
+
signal.addEventListener("abort", abort, { once: true });
|
|
74
|
+
promise.then(resolve, reject).finally(() => signal.removeEventListener("abort", abort));
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
async function startBrowserStep(options, stepUp) {
|
|
78
|
+
const { store, settings, redirectUrl, challenge } = options;
|
|
79
|
+
const stored = await store.load();
|
|
80
|
+
if (stored)
|
|
81
|
+
await store.save(stateForSignIn(stored, options));
|
|
82
|
+
let authorizationUrl;
|
|
83
|
+
const provider = createOAuthClientProvider(options, redirectUrl, (url) => {
|
|
84
|
+
authorizationUrl = url;
|
|
85
|
+
});
|
|
86
|
+
// A server asking for more scope gets it on top of the configured scope and, since the challenge
|
|
87
|
+
// may list only the missing scopes, on top of the scope granted so far.
|
|
88
|
+
const scope = mergeScopes(settings.scope, stepUp ? stepUpScope(stored?.tokens?.scope, challenge?.scope) : challenge?.scope);
|
|
89
|
+
await authorizeMcp(provider, { ...flowOptions(options), scope, skipRefresh: true });
|
|
90
|
+
if (!authorizationUrl)
|
|
91
|
+
throw new Error("OAuth flow did not produce an authorization URL");
|
|
92
|
+
const requestedScope = authorizationUrl.searchParams.get("scope");
|
|
93
|
+
return {
|
|
94
|
+
kind: "redirect",
|
|
95
|
+
authorizationUrl: authorizationUrl.href,
|
|
96
|
+
// The flow picks the redirect URI, which may be specific to the MCP server.
|
|
97
|
+
redirectUrl: authorizationUrl.searchParams.get("redirect_uri") ?? redirectUrl,
|
|
98
|
+
state: await provider.state(),
|
|
99
|
+
...(requestedScope ? { scope: requestedScope } : {}),
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
/**
|
|
103
|
+
* The stored state for a browser step: without the last sign-in's `state`, and without a client that
|
|
104
|
+
* cannot use `redirectUrl`, along with its tokens.
|
|
105
|
+
*/
|
|
106
|
+
function stateForSignIn(stored, options) {
|
|
107
|
+
const { settings, redirectUrl } = options;
|
|
108
|
+
const next = { ...stored };
|
|
109
|
+
delete next.oauthState;
|
|
110
|
+
// A registered client cannot use another redirect URI, and its tokens belong to it. `cimd` replaces a
|
|
111
|
+
// registered client; `auto` keeps it. A Client ID Metadata Document is not stored, so tokens without
|
|
112
|
+
// a stored client belong to the document.
|
|
113
|
+
const keepClient = settings.clientId ||
|
|
114
|
+
(stored.clientInformation
|
|
115
|
+
? settings.clientRegistration !== "cimd" &&
|
|
116
|
+
registeredRedirectUrls(stored.clientInformation).includes(redirectUrl)
|
|
117
|
+
: offersClientMetadataDocument(settings, options.clientMetadataDocuments, redirectUrl));
|
|
118
|
+
if (!keepClient) {
|
|
119
|
+
delete next.clientInformation;
|
|
120
|
+
delete next.tokens;
|
|
121
|
+
delete next.tokensExpireAt;
|
|
122
|
+
}
|
|
123
|
+
return next;
|
|
124
|
+
}
|
|
125
|
+
/** Scopes of both lists, each once. */
|
|
126
|
+
function mergeScopes(...scopes) {
|
|
127
|
+
const merged = [...new Set(scopes.flatMap((scope) => scope?.split(/\s+/).filter(Boolean) ?? []))];
|
|
128
|
+
return merged.length > 0 ? merged.join(" ") : undefined;
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
131
|
+
* Second half of a sign-in: exchanges the authorization code of `response` and saves the tokens. Pass
|
|
132
|
+
* the options given to `startMcpSignIn`, including its `redirectUrl` (not `authorization.redirectUrl`).
|
|
133
|
+
* Fails when the response carries another `state`, when another sign-in started with the store since, or
|
|
134
|
+
* when the exchange would use another redirect URI than the authorization request (the options changed).
|
|
135
|
+
* A redirect URL the user pasted goes through `responseFromRedirectUrl` first, which checks its path.
|
|
136
|
+
*/
|
|
137
|
+
export async function completeMcpSignIn(options) {
|
|
138
|
+
await cancellable(options.signal, async () => {
|
|
139
|
+
const { authorization, response } = options;
|
|
140
|
+
if (response.state !== authorization.state) {
|
|
141
|
+
throw new Error("The authorization response belongs to a different sign-in");
|
|
142
|
+
}
|
|
143
|
+
// The stored PKCE verifier belongs to the latest sign-in; exchanging with it would fail with
|
|
144
|
+
// `invalid_grant`, which discards the stored tokens.
|
|
145
|
+
if ((await options.store.load())?.oauthState !== authorization.state) {
|
|
146
|
+
throw new Error("Another sign-in to this MCP server started since; sign in again");
|
|
147
|
+
}
|
|
148
|
+
await authorizeMcp(createOAuthClientProvider(options, options.redirectUrl), {
|
|
149
|
+
...flowOptions(options),
|
|
150
|
+
// Saved with the tokens when the token response names no scope, so it must be the requested one.
|
|
151
|
+
scope: authorization.scope,
|
|
152
|
+
authorizationRedirectUrl: authorization.redirectUrl,
|
|
153
|
+
authorizationCode: response.code,
|
|
154
|
+
iss: response.iss,
|
|
155
|
+
});
|
|
156
|
+
});
|
|
157
|
+
}
|
|
158
|
+
/** `authorizeMcp` options of a sign-in, without the scope. */
|
|
159
|
+
function flowOptions(options) {
|
|
160
|
+
return {
|
|
161
|
+
serverUrl: options.serverUrl,
|
|
162
|
+
fetch: timedFetch(),
|
|
163
|
+
signal: options.signal,
|
|
164
|
+
resourceMetadataUrl: options.challenge?.resourceMetadataUrl,
|
|
165
|
+
authorizationServerMetadataUrl: options.settings.authServerMetadataUrl,
|
|
166
|
+
};
|
|
167
|
+
}
|
|
168
|
+
/** Run `fn`, reporting an abort of `signal` as `McpSignInCancelledError`. */
|
|
169
|
+
export async function cancellable(signal, fn) {
|
|
170
|
+
if (signal?.aborted)
|
|
171
|
+
throw new McpSignInCancelledError();
|
|
172
|
+
try {
|
|
173
|
+
return await fn();
|
|
174
|
+
}
|
|
175
|
+
catch (error) {
|
|
176
|
+
// Aborted requests fail with the signal's reason; report them as the cancellation they are.
|
|
177
|
+
if (signal?.aborted)
|
|
178
|
+
throw new McpSignInCancelledError();
|
|
179
|
+
throw error;
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
//# sourceMappingURL=sign-in.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sign-in.js","sourceRoot":"","sources":["../../src/oauth/sign-in.ts"],"names":[],"mappings":"AAAA;;;;;;GAMG;AAEH,OAAO,EAAE,mBAAmB,EAAE,MAAM,oBAAoB,CAAC;AAEzD,OAAO,EACN,yBAAyB,EAEzB,4BAA4B,EAC5B,sBAAsB,EACtB,UAAU,GACV,MAAM,sBAAsB,CAAC;AAC9B,OAAO,EAAE,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,MAAM,IAAI,uBAAuB,EAAE,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\tcreateOAuthClientProvider,\n\ttype McpOAuthClientOptions,\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/** The scope requested, if any. Saved with the tokens when the token response names none. */\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 */\nexport async function startMcpSignIn(options: McpSignInOptions): Promise<McpSignInStart> {\n\tif (options.signal?.aborted) throw new McpSignInCancelledError();\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 `cimd` is to replace a registered client. The refresh uses\n * `redirectUrl` when the tokens came from a Client ID Metadata Document whose documents list it.\n */\nasync function refreshBeforeSignIn(options: McpSignInOptions): Promise<\"AUTHORIZED\" | \"REDIRECT\"> {\n\tconst { store, settings, challenge, redirectUrl, signal } = options;\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) return \"REDIRECT\";\n\t\tif (settings.clientRegistration === \"cimd\" && state.clientInformation && !settings.clientId) 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, redirectUrl, challenge } = options;\n\tconst stored = await store.load();\n\tif (stored) await store.save(stateForSignIn(stored, options));\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 = authorizationUrl.searchParams.get(\"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\t// A registered client cannot use another redirect URI, and its tokens belong to it. `cimd` replaces a\n\t// registered client; `auto` keeps it. A Client ID Metadata Document is not stored, so tokens without\n\t// a stored client belong to the document.\n\tconst keepClient =\n\t\tsettings.clientId ||\n\t\t(stored.clientInformation\n\t\t\t? settings.clientRegistration !== \"cimd\" &&\n\t\t\t\tregisteredRedirectUrls(stored.clientInformation).includes(redirectUrl)\n\t\t\t: offersClientMetadataDocument(settings, options.clientMetadataDocuments, redirectUrl));\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 * when the exchange would use another redirect URI than the authorization request (the options changed).\n * A redirect URL the user pasted goes through `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\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 ((await options.store.load())?.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\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: authorization.scope,\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"]}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
export interface OAuthProtectedResourceMetadata {
|
|
2
|
+
resource: string;
|
|
3
|
+
authorization_servers?: string[];
|
|
4
|
+
scopes_supported?: string[];
|
|
5
|
+
[key: string]: unknown;
|
|
6
|
+
}
|
|
7
|
+
export interface AuthorizationServerMetadata {
|
|
8
|
+
issuer: string;
|
|
9
|
+
authorization_endpoint: string;
|
|
10
|
+
token_endpoint: string;
|
|
11
|
+
registration_endpoint?: string;
|
|
12
|
+
scopes_supported?: string[];
|
|
13
|
+
response_types_supported: string[];
|
|
14
|
+
grant_types_supported?: string[];
|
|
15
|
+
token_endpoint_auth_methods_supported?: string[];
|
|
16
|
+
code_challenge_methods_supported?: string[];
|
|
17
|
+
client_id_metadata_document_supported?: boolean;
|
|
18
|
+
/** Whether authorization responses carry an `iss` parameter (RFC 9207). */
|
|
19
|
+
authorization_response_iss_parameter_supported?: boolean;
|
|
20
|
+
[key: string]: unknown;
|
|
21
|
+
}
|
|
22
|
+
export interface OAuthTokens {
|
|
23
|
+
access_token: string;
|
|
24
|
+
token_type: string;
|
|
25
|
+
expires_in?: number;
|
|
26
|
+
scope?: string;
|
|
27
|
+
refresh_token?: string;
|
|
28
|
+
id_token?: string;
|
|
29
|
+
}
|
|
30
|
+
export interface OAuthClientMetadata {
|
|
31
|
+
redirect_uris: string[];
|
|
32
|
+
token_endpoint_auth_method?: string;
|
|
33
|
+
grant_types?: string[];
|
|
34
|
+
response_types?: string[];
|
|
35
|
+
/**
|
|
36
|
+
* OpenID Connect client type, `native` or `web`. Dynamic client registration derives it from
|
|
37
|
+
* `redirect_uris` when absent (MCP SEP-837).
|
|
38
|
+
*/
|
|
39
|
+
application_type?: string;
|
|
40
|
+
client_name?: string;
|
|
41
|
+
client_uri?: string;
|
|
42
|
+
logo_uri?: string;
|
|
43
|
+
scope?: string;
|
|
44
|
+
contacts?: string[];
|
|
45
|
+
tos_uri?: string;
|
|
46
|
+
policy_uri?: string;
|
|
47
|
+
jwks_uri?: string;
|
|
48
|
+
jwks?: unknown;
|
|
49
|
+
software_id?: string;
|
|
50
|
+
software_version?: string;
|
|
51
|
+
software_statement?: string;
|
|
52
|
+
}
|
|
53
|
+
export interface OAuthClientInformation {
|
|
54
|
+
client_id: string;
|
|
55
|
+
client_secret?: string;
|
|
56
|
+
client_id_issued_at?: number;
|
|
57
|
+
client_secret_expires_at?: number;
|
|
58
|
+
}
|
|
59
|
+
export type OAuthClientInformationFull = OAuthClientInformation & OAuthClientMetadata;
|
|
60
|
+
export type OAuthClientInformationMixed = OAuthClientInformation | OAuthClientInformationFull;
|
|
61
|
+
export interface OAuthDiscoveryState {
|
|
62
|
+
authorizationServerUrl: string;
|
|
63
|
+
authorizationServerMetadata?: AuthorizationServerMetadata;
|
|
64
|
+
resourceMetadata?: OAuthProtectedResourceMetadata;
|
|
65
|
+
resourceMetadataUrl?: string;
|
|
66
|
+
}
|
|
67
|
+
export interface OAuthServerInfo {
|
|
68
|
+
authorizationServerUrl: string;
|
|
69
|
+
authorizationServerMetadata?: AuthorizationServerMetadata;
|
|
70
|
+
resourceMetadata?: OAuthProtectedResourceMetadata;
|
|
71
|
+
}
|
|
72
|
+
export interface OAuthChallenge {
|
|
73
|
+
resourceMetadataUrl?: URL;
|
|
74
|
+
scope?: string;
|
|
75
|
+
error?: string;
|
|
76
|
+
errorDescription?: string;
|
|
77
|
+
}
|
|
78
|
+
export declare function isHttpUrl(url: URL): boolean;
|
|
79
|
+
export declare function parseProtectedResourceMetadata(value: unknown): OAuthProtectedResourceMetadata;
|
|
80
|
+
export declare function parseAuthorizationServerMetadata(value: unknown): AuthorizationServerMetadata;
|
|
81
|
+
export declare function parseOAuthTokens(value: unknown): OAuthTokens;
|
|
82
|
+
export declare function parseClientInformation(value: unknown): OAuthClientInformationFull;
|
|
83
|
+
//# sourceMappingURL=types.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../../src/oauth/types.ts"],"names":[],"mappings":"AAQA,MAAM,WAAW,8BAA8B;IAC9C,QAA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