@duckmind/dm-windows-x64 0.63.6 → 0.63.9
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/dm.exe +0 -0
- package/extensions/.dm-extensions.json +174 -11
- package/extensions/dm-mcp-adapter/OAUTH.md +3 -0
- package/extensions/dm-mcp-adapter/THIRD_PARTY_NOTICES.md +4 -0
- package/extensions/dm-mcp-adapter/abort.js +35 -0
- package/extensions/dm-mcp-adapter/agent-dir.js +45 -0
- package/extensions/dm-mcp-adapter/agent-plugin-loader.js +349 -0
- package/extensions/dm-mcp-adapter/app-bridge.bundle.js +5843 -0
- package/extensions/dm-mcp-adapter/cli.js +354 -0
- package/extensions/dm-mcp-adapter/commands.js +619 -0
- package/extensions/dm-mcp-adapter/config.js +1060 -0
- package/extensions/dm-mcp-adapter/consent-manager.js +60 -0
- package/extensions/dm-mcp-adapter/direct-tools.js +544 -0
- package/extensions/dm-mcp-adapter/dist/agent-dir.js +45 -0
- package/extensions/dm-mcp-adapter/dist/agent-plugin-loader.js +349 -0
- package/extensions/dm-mcp-adapter/dist/config.js +1060 -0
- package/extensions/dm-mcp-adapter/dist/mcp-bearer-store.js +311 -0
- package/extensions/dm-mcp-adapter/dist/metadata-cache.js +285 -0
- package/extensions/dm-mcp-adapter/dist/package-mcp-loader.js +144 -0
- package/extensions/dm-mcp-adapter/dist/resource-tools.js +7 -0
- package/extensions/dm-mcp-adapter/dist/types.js +247 -0
- package/extensions/dm-mcp-adapter/dist/ui-app-bridge-helpers.js +36 -0
- package/extensions/dm-mcp-adapter/dist/ui-stream-types.js +58 -0
- package/extensions/dm-mcp-adapter/dist/ui-tool-visibility.js +26 -0
- package/extensions/dm-mcp-adapter/dist/utils.js +307 -0
- package/extensions/dm-mcp-adapter/elicitation-handler.js +306 -0
- package/extensions/dm-mcp-adapter/error-signal.js +16 -0
- package/extensions/dm-mcp-adapter/errors.js +225 -0
- package/extensions/dm-mcp-adapter/failure-backoff.js +19 -0
- package/extensions/dm-mcp-adapter/glimpse-ui.js +61 -0
- package/extensions/dm-mcp-adapter/host-html-template.js +464 -0
- package/extensions/dm-mcp-adapter/index.js +1079 -0
- package/extensions/dm-mcp-adapter/init.js +624 -0
- package/extensions/dm-mcp-adapter/json-schema-validator.js +53 -0
- package/extensions/dm-mcp-adapter/lifecycle.js +385 -0
- package/extensions/dm-mcp-adapter/logger.js +115 -0
- package/extensions/dm-mcp-adapter/mcp-auth-flow.js +824 -0
- package/extensions/dm-mcp-adapter/mcp-auth.js +732 -0
- package/extensions/dm-mcp-adapter/mcp-bearer-store.js +311 -0
- package/extensions/dm-mcp-adapter/mcp-callback-server.js +388 -0
- package/extensions/dm-mcp-adapter/mcp-code.js +291 -0
- package/extensions/dm-mcp-adapter/mcp-keyring-helper.cjs +88 -0
- package/extensions/dm-mcp-adapter/mcp-oauth-provider.js +490 -0
- package/extensions/dm-mcp-adapter/mcp-output-guard.js +386 -0
- package/extensions/dm-mcp-adapter/mcp-panel.js +951 -0
- package/extensions/dm-mcp-adapter/mcp-probe.js +151 -0
- package/extensions/dm-mcp-adapter/mcp-references.js +263 -0
- package/extensions/dm-mcp-adapter/mcp-script-worker.mjs +126 -0
- package/extensions/dm-mcp-adapter/mcp-setup-panel.js +578 -0
- package/extensions/dm-mcp-adapter/mcp-status.js +80 -0
- package/extensions/dm-mcp-adapter/mcp-trace.js +215 -0
- package/extensions/dm-mcp-adapter/metadata-cache.js +292 -0
- package/extensions/dm-mcp-adapter/namespace-tools.js +155 -0
- package/extensions/dm-mcp-adapter/npx-resolver.js +465 -0
- package/extensions/dm-mcp-adapter/oauth-handler.js +17 -0
- package/extensions/dm-mcp-adapter/oauth.js +17 -0
- package/extensions/dm-mcp-adapter/onboarding-state.js +62 -0
- package/extensions/dm-mcp-adapter/package-mcp-loader.js +144 -0
- package/extensions/dm-mcp-adapter/package.json +68 -0
- package/extensions/dm-mcp-adapter/panel-keys.js +26 -0
- package/extensions/dm-mcp-adapter/prompts.js +258 -0
- package/extensions/dm-mcp-adapter/proxy-modes.js +1336 -0
- package/extensions/dm-mcp-adapter/request-headers-command.js +293 -0
- package/extensions/dm-mcp-adapter/resource-tools.js +7 -0
- package/extensions/dm-mcp-adapter/runtime-owner.js +79 -0
- package/extensions/dm-mcp-adapter/sampling-handler.js +222 -0
- package/extensions/dm-mcp-adapter/sandbox-proxy-template.js +190 -0
- package/extensions/dm-mcp-adapter/search-ranking.js +198 -0
- package/extensions/dm-mcp-adapter/server-manager.js +1258 -0
- package/extensions/dm-mcp-adapter/session-recovery.js +82 -0
- package/extensions/dm-mcp-adapter/skills/mcp-scripting/SKILL.md +39 -0
- package/extensions/dm-mcp-adapter/state.js +0 -0
- package/extensions/dm-mcp-adapter/test-runner.mjs +18 -0
- package/extensions/dm-mcp-adapter/tool-approval.js +151 -0
- package/extensions/dm-mcp-adapter/tool-metadata.js +247 -0
- package/extensions/dm-mcp-adapter/tool-registrar.js +212 -0
- package/extensions/dm-mcp-adapter/tool-result-renderer.js +355 -0
- package/extensions/dm-mcp-adapter/ts-shape.js +157 -0
- package/extensions/dm-mcp-adapter/types.js +264 -0
- package/extensions/dm-mcp-adapter/ui-app-bridge-helpers.js +36 -0
- package/extensions/dm-mcp-adapter/ui-resource-handler.js +209 -0
- package/extensions/dm-mcp-adapter/ui-server.js +815 -0
- package/extensions/dm-mcp-adapter/ui-session.js +455 -0
- package/extensions/dm-mcp-adapter/ui-stream-types.js +58 -0
- package/extensions/dm-mcp-adapter/ui-tool-visibility.js +26 -0
- package/extensions/dm-mcp-adapter/unix-socket-transport.js +83 -0
- package/extensions/dm-mcp-adapter/utils.js +307 -0
- package/package.json +13 -1
- package/extensions/dm-localllm-provider/detect.test.js +0 -1051
- package/extensions/dm-localllm-provider/index.test.js +0 -149
- package/extensions/dm-localllm-provider/keychain.test.js +0 -61
|
@@ -0,0 +1,824 @@
|
|
|
1
|
+
import {
|
|
2
|
+
auth as runSdkAuth,
|
|
3
|
+
extractWWWAuthenticateParams,
|
|
4
|
+
LATEST_PROTOCOL_VERSION,
|
|
5
|
+
UnauthorizedError
|
|
6
|
+
} from "@modelcontextprotocol/client";
|
|
7
|
+
import open from "open";
|
|
8
|
+
import { McpOAuthProvider } from "./mcp-oauth-provider.js";
|
|
9
|
+
import {
|
|
10
|
+
ensureCallbackServer,
|
|
11
|
+
waitForCallback,
|
|
12
|
+
cancelPendingCallback,
|
|
13
|
+
stopCallbackServer,
|
|
14
|
+
stopCallbackServerIfIdle,
|
|
15
|
+
releaseCallbackServer
|
|
16
|
+
} from "./mcp-callback-server.js";
|
|
17
|
+
import {
|
|
18
|
+
getAuthForUrl,
|
|
19
|
+
isTokenExpired,
|
|
20
|
+
hasStoredTokens,
|
|
21
|
+
clearAllCredentials,
|
|
22
|
+
clearClientInfo,
|
|
23
|
+
clearTokens,
|
|
24
|
+
clearCodeVerifier,
|
|
25
|
+
getOAuthState,
|
|
26
|
+
clearOAuthState,
|
|
27
|
+
getAuthBaseDir,
|
|
28
|
+
OAuthCredentialStoreError
|
|
29
|
+
} from "./mcp-auth.js";
|
|
30
|
+
import { isServerDisabled } from "./types.js";
|
|
31
|
+
import { formatTerminalError, interpolateEnvRecord, interpolateEnvVars } from "./utils.js";
|
|
32
|
+
import { abortable, throwIfAborted } from "./abort.js";
|
|
33
|
+
import { combineAbortSignals, isAbortError } from "./runtime-owner.js";
|
|
34
|
+
function applyOAuthConfig(discovery, config) {
|
|
35
|
+
return {
|
|
36
|
+
...discovery,
|
|
37
|
+
...config.scope !== undefined ? { scope: config.scope } : {},
|
|
38
|
+
...config.skipIssuerMetadataValidation === true ? { skipIssuerMetadataValidation: true } : {}
|
|
39
|
+
};
|
|
40
|
+
}
|
|
41
|
+
const runtimeStates = new WeakMap;
|
|
42
|
+
const activeRuntimes = new Set;
|
|
43
|
+
export function createOAuthRuntime(signal) {
|
|
44
|
+
const controller = new AbortController;
|
|
45
|
+
const runtime = { signal: combineAbortSignals(signal, controller.signal) };
|
|
46
|
+
runtimeStates.set(runtime, {
|
|
47
|
+
controller,
|
|
48
|
+
generation: 0,
|
|
49
|
+
pendingAuths: new Map,
|
|
50
|
+
pendingAuthStates: new Map,
|
|
51
|
+
pendingAuthCleanupTimers: new Map,
|
|
52
|
+
pendingAuthentications: new Map
|
|
53
|
+
});
|
|
54
|
+
activeRuntimes.add(runtime);
|
|
55
|
+
return runtime;
|
|
56
|
+
}
|
|
57
|
+
let legacyRuntime = createOAuthRuntime();
|
|
58
|
+
activeRuntimes.delete(legacyRuntime);
|
|
59
|
+
function getRuntime(options) {
|
|
60
|
+
if (options?.runtime) {
|
|
61
|
+
options.runtime.signal.throwIfAborted();
|
|
62
|
+
activeRuntimes.add(options.runtime);
|
|
63
|
+
return options.runtime;
|
|
64
|
+
}
|
|
65
|
+
if (legacyRuntime.signal.aborted)
|
|
66
|
+
legacyRuntime = createOAuthRuntime();
|
|
67
|
+
activeRuntimes.add(legacyRuntime);
|
|
68
|
+
return legacyRuntime;
|
|
69
|
+
}
|
|
70
|
+
function getRuntimeState(runtime) {
|
|
71
|
+
const state = runtimeStates.get(runtime);
|
|
72
|
+
if (!state)
|
|
73
|
+
throw new Error("Unknown OAuth runtime");
|
|
74
|
+
return state;
|
|
75
|
+
}
|
|
76
|
+
function getPendingAuthKey(serverName, options) {
|
|
77
|
+
return `${serverName}|${getAuthBaseDir(options)}`;
|
|
78
|
+
}
|
|
79
|
+
export function hasPendingAuth(serverName, options, runtime) {
|
|
80
|
+
const state = getRuntimeState(runtime ?? legacyRuntime);
|
|
81
|
+
if (options) {
|
|
82
|
+
return state.pendingAuths.has(getPendingAuthKey(serverName, options));
|
|
83
|
+
}
|
|
84
|
+
return Array.from(state.pendingAuths.values()).some((pendingAuth) => pendingAuth.serverName === serverName);
|
|
85
|
+
}
|
|
86
|
+
const MANUAL_AUTH_TIMEOUT_MS = 5 * 60 * 1000;
|
|
87
|
+
function generateState() {
|
|
88
|
+
return Array.from(crypto.getRandomValues(new Uint8Array(32))).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
89
|
+
}
|
|
90
|
+
export function extractOAuthConfig(definition) {
|
|
91
|
+
if (definition.oauth === false) {
|
|
92
|
+
return {};
|
|
93
|
+
}
|
|
94
|
+
const config = {};
|
|
95
|
+
if (definition.oauth?.grantType !== undefined)
|
|
96
|
+
config.grantType = definition.oauth.grantType;
|
|
97
|
+
if (definition.oauth?.clientId !== undefined) {
|
|
98
|
+
if (typeof definition.oauth.clientId !== "string")
|
|
99
|
+
throw new Error("OAuth clientId must be a string");
|
|
100
|
+
config.clientId = interpolateEnvVars(definition.oauth.clientId);
|
|
101
|
+
}
|
|
102
|
+
if (definition.oauth?.clientSecret !== undefined) {
|
|
103
|
+
if (typeof definition.oauth.clientSecret !== "string")
|
|
104
|
+
throw new Error("OAuth clientSecret must be a string");
|
|
105
|
+
config.clientSecret = definition.oauth.clientSecret.startsWith("!") ? definition.oauth.clientSecret : interpolateEnvVars(definition.oauth.clientSecret);
|
|
106
|
+
}
|
|
107
|
+
if (definition.oauth?.scope !== undefined) {
|
|
108
|
+
if (typeof definition.oauth.scope !== "string")
|
|
109
|
+
throw new Error("OAuth scope must be a string");
|
|
110
|
+
config.scope = interpolateEnvVars(definition.oauth.scope);
|
|
111
|
+
}
|
|
112
|
+
if (definition.oauth?.authorizationParams !== undefined) {
|
|
113
|
+
const params = definition.oauth.authorizationParams;
|
|
114
|
+
if (!params || typeof params !== "object" || Array.isArray(params)) {
|
|
115
|
+
throw new Error("OAuth authorizationParams must be an object");
|
|
116
|
+
}
|
|
117
|
+
config.authorizationParams = {};
|
|
118
|
+
for (const [key, value] of Object.entries(params)) {
|
|
119
|
+
if (!key)
|
|
120
|
+
throw new Error("OAuth authorizationParams keys must not be empty");
|
|
121
|
+
if (typeof value !== "string")
|
|
122
|
+
throw new Error(`OAuth authorizationParams.${key} must be a string`);
|
|
123
|
+
config.authorizationParams[key] = interpolateEnvVars(value);
|
|
124
|
+
}
|
|
125
|
+
}
|
|
126
|
+
if (definition.oauth?.redirectUri !== undefined) {
|
|
127
|
+
if (typeof definition.oauth.redirectUri !== "string") {
|
|
128
|
+
throw new Error("OAuth redirectUri must be a string");
|
|
129
|
+
}
|
|
130
|
+
const redirectUri = interpolateEnvVars(definition.oauth.redirectUri).trim();
|
|
131
|
+
if (!redirectUri) {
|
|
132
|
+
throw new Error("OAuth redirectUri must not be empty");
|
|
133
|
+
}
|
|
134
|
+
config.redirectUri = redirectUri;
|
|
135
|
+
}
|
|
136
|
+
if (definition.oauth?.clientName !== undefined) {
|
|
137
|
+
if (typeof definition.oauth.clientName !== "string") {
|
|
138
|
+
throw new Error("OAuth clientName must be a string");
|
|
139
|
+
}
|
|
140
|
+
const clientName = interpolateEnvVars(definition.oauth.clientName).trim();
|
|
141
|
+
if (!clientName) {
|
|
142
|
+
throw new Error("OAuth clientName must not be empty");
|
|
143
|
+
}
|
|
144
|
+
config.clientName = clientName;
|
|
145
|
+
}
|
|
146
|
+
if (definition.oauth?.clientUri !== undefined) {
|
|
147
|
+
if (typeof definition.oauth.clientUri !== "string") {
|
|
148
|
+
throw new Error("OAuth clientUri must be a string");
|
|
149
|
+
}
|
|
150
|
+
const clientUri = interpolateEnvVars(definition.oauth.clientUri).trim();
|
|
151
|
+
if (!clientUri) {
|
|
152
|
+
throw new Error("OAuth clientUri must not be empty");
|
|
153
|
+
}
|
|
154
|
+
config.clientUri = clientUri;
|
|
155
|
+
}
|
|
156
|
+
if (definition.oauth?.logoUri !== undefined) {
|
|
157
|
+
if (typeof definition.oauth.logoUri !== "string") {
|
|
158
|
+
throw new Error("OAuth logoUri must be a string");
|
|
159
|
+
}
|
|
160
|
+
const logoUri = interpolateEnvVars(definition.oauth.logoUri).trim();
|
|
161
|
+
if (!logoUri) {
|
|
162
|
+
throw new Error("OAuth logoUri must not be empty");
|
|
163
|
+
}
|
|
164
|
+
let parsed;
|
|
165
|
+
try {
|
|
166
|
+
parsed = new URL(logoUri);
|
|
167
|
+
} catch {
|
|
168
|
+
throw new Error("OAuth logoUri must be an absolute http(s) URL");
|
|
169
|
+
}
|
|
170
|
+
if (parsed.protocol !== "https:" && parsed.protocol !== "http:") {
|
|
171
|
+
throw new Error("OAuth logoUri must be an absolute http(s) URL");
|
|
172
|
+
}
|
|
173
|
+
config.logoUri = logoUri;
|
|
174
|
+
}
|
|
175
|
+
if (definition.oauth?.authServerMetadataUrl !== undefined) {
|
|
176
|
+
if (typeof definition.oauth.authServerMetadataUrl !== "string") {
|
|
177
|
+
throw new Error("OAuth authServerMetadataUrl must be a string");
|
|
178
|
+
}
|
|
179
|
+
const authServerMetadataUrl = interpolateEnvVars(definition.oauth.authServerMetadataUrl).trim();
|
|
180
|
+
if (!authServerMetadataUrl) {
|
|
181
|
+
throw new Error("OAuth authServerMetadataUrl must not be empty");
|
|
182
|
+
}
|
|
183
|
+
let parsed;
|
|
184
|
+
try {
|
|
185
|
+
parsed = new URL(authServerMetadataUrl);
|
|
186
|
+
} catch {
|
|
187
|
+
throw new Error("OAuth authServerMetadataUrl must be an absolute https:// URL");
|
|
188
|
+
}
|
|
189
|
+
if (parsed.protocol !== "https:") {
|
|
190
|
+
throw new Error("OAuth authServerMetadataUrl must be an absolute https:// URL");
|
|
191
|
+
}
|
|
192
|
+
config.authServerMetadataUrl = authServerMetadataUrl;
|
|
193
|
+
}
|
|
194
|
+
if (definition.oauth?.skipIssuerMetadataValidation !== undefined) {
|
|
195
|
+
if (typeof definition.oauth.skipIssuerMetadataValidation !== "boolean") {
|
|
196
|
+
throw new Error("OAuth skipIssuerMetadataValidation must be a boolean");
|
|
197
|
+
}
|
|
198
|
+
config.skipIssuerMetadataValidation = definition.oauth.skipIssuerMetadataValidation;
|
|
199
|
+
}
|
|
200
|
+
return config;
|
|
201
|
+
}
|
|
202
|
+
async function probeAuthDiscovery(serverUrl, definition, signal) {
|
|
203
|
+
const discoveryHeaders = definition?.headers ? Object.fromEntries(Object.entries(definition.headers).filter(([, value]) => !value.startsWith("!") || value.startsWith("!!"))) : undefined;
|
|
204
|
+
const headers = new Headers(interpolateEnvRecord(discoveryHeaders));
|
|
205
|
+
headers.set("content-type", "application/json");
|
|
206
|
+
const controller = new AbortController;
|
|
207
|
+
const discoverySignal = combineAbortSignals(signal, controller.signal);
|
|
208
|
+
const timer = setTimeout(() => controller.abort(), 5000);
|
|
209
|
+
try {
|
|
210
|
+
headers.set("accept", "application/json, text/event-stream");
|
|
211
|
+
const response = await fetch(new URL(serverUrl), {
|
|
212
|
+
method: "POST",
|
|
213
|
+
headers,
|
|
214
|
+
body: JSON.stringify({
|
|
215
|
+
jsonrpc: "2.0",
|
|
216
|
+
id: 0,
|
|
217
|
+
method: "initialize",
|
|
218
|
+
params: {
|
|
219
|
+
protocolVersion: LATEST_PROTOCOL_VERSION,
|
|
220
|
+
capabilities: {},
|
|
221
|
+
clientInfo: { name: "dm-mcp-adapter", version: "2.11.0" }
|
|
222
|
+
}
|
|
223
|
+
}),
|
|
224
|
+
...discoverySignal ? { signal: discoverySignal } : {}
|
|
225
|
+
});
|
|
226
|
+
const { resourceMetadataUrl, scope } = extractWWWAuthenticateParams(response);
|
|
227
|
+
await response.body?.cancel().catch(() => {});
|
|
228
|
+
return { ...resourceMetadataUrl ? { resourceMetadataUrl } : {}, ...scope ? { scope } : {} };
|
|
229
|
+
} catch (error) {
|
|
230
|
+
if (signal?.aborted)
|
|
231
|
+
throwIfAborted(signal);
|
|
232
|
+
return {};
|
|
233
|
+
} finally {
|
|
234
|
+
clearTimeout(timer);
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
function parseOAuthRedirectUri(redirectUri) {
|
|
238
|
+
let url;
|
|
239
|
+
try {
|
|
240
|
+
url = new URL(redirectUri);
|
|
241
|
+
} catch (error) {
|
|
242
|
+
throw new Error(`Invalid OAuth redirectUri: ${redirectUri}`, { cause: error });
|
|
243
|
+
}
|
|
244
|
+
if (url.username || url.password) {
|
|
245
|
+
throw new Error("OAuth redirectUri must not include username or password");
|
|
246
|
+
}
|
|
247
|
+
if (url.hash) {
|
|
248
|
+
throw new Error("OAuth redirectUri must not include a fragment");
|
|
249
|
+
}
|
|
250
|
+
const hostname = url.hostname.toLowerCase();
|
|
251
|
+
const isLocalhost = hostname === "localhost" || hostname === "127.0.0.1" || hostname === "[::1]" || hostname === "::1";
|
|
252
|
+
if (url.port) {
|
|
253
|
+
const parsedPort = Number.parseInt(url.port, 10);
|
|
254
|
+
if (!Number.isInteger(parsedPort) || parsedPort <= 0 || parsedPort > 65535) {
|
|
255
|
+
throw new Error("OAuth redirectUri port must be a positive numeric port");
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
if (url.protocol === "https:" && !isLocalhost) {
|
|
259
|
+
return { mode: "manual" };
|
|
260
|
+
}
|
|
261
|
+
if (url.protocol !== "http:" || !isLocalhost) {
|
|
262
|
+
throw new Error("OAuth redirectUri must be an https:// URI or an http:// localhost or loopback URI");
|
|
263
|
+
}
|
|
264
|
+
if (!url.port) {
|
|
265
|
+
throw new Error("OAuth localhost redirectUri must include an explicit numeric port");
|
|
266
|
+
}
|
|
267
|
+
const port = Number.parseInt(url.port, 10);
|
|
268
|
+
if (!Number.isInteger(port) || port <= 0 || port > 65535) {
|
|
269
|
+
throw new Error("OAuth localhost redirectUri must include an explicit numeric port");
|
|
270
|
+
}
|
|
271
|
+
const callbackHost = hostname === "[::1]" ? "::1" : hostname;
|
|
272
|
+
return { mode: "local", port, callbackHost, callbackPath: url.pathname };
|
|
273
|
+
}
|
|
274
|
+
export async function startAuth(serverName, serverUrl, definition, options = {}) {
|
|
275
|
+
if (isServerDisabled(definition))
|
|
276
|
+
throw new Error(`MCP server "${serverName}" is disabled`);
|
|
277
|
+
const runtime = getRuntime(options);
|
|
278
|
+
const runtimeState = getRuntimeState(runtime);
|
|
279
|
+
const config = definition ? extractOAuthConfig(definition) : {};
|
|
280
|
+
const authStorageOptions = options.authStorageOptions ?? {};
|
|
281
|
+
const signal = combineAbortSignals(runtime.signal, options.signal);
|
|
282
|
+
const generation = runtimeState.generation;
|
|
283
|
+
throwIfAborted(signal);
|
|
284
|
+
if (config.grantType === "client_credentials") {
|
|
285
|
+
const storedAuth = await getAuthForUrl(serverName, serverUrl, authStorageOptions);
|
|
286
|
+
if (storedAuth?.clientInfo && !storedAuth.tokens && !config.clientId) {
|
|
287
|
+
clearClientInfo(serverName, authStorageOptions);
|
|
288
|
+
clearCodeVerifier(serverName, authStorageOptions);
|
|
289
|
+
await clearOAuthState(serverName, authStorageOptions);
|
|
290
|
+
}
|
|
291
|
+
const authProvider = new McpOAuthProvider(serverName, serverUrl, config, {
|
|
292
|
+
onRedirect: async () => {
|
|
293
|
+
throw new Error("Browser redirect is not used for client_credentials flow");
|
|
294
|
+
}
|
|
295
|
+
}, authStorageOptions, runtime.signal);
|
|
296
|
+
try {
|
|
297
|
+
const discovery = applyOAuthConfig(await probeAuthDiscovery(serverUrl, definition, signal), config);
|
|
298
|
+
throwIfAborted(signal);
|
|
299
|
+
const result = await abortable(runSdkAuth(authProvider, { serverUrl, ...discovery }), signal);
|
|
300
|
+
throwIfAborted(signal);
|
|
301
|
+
if (result !== "AUTHORIZED") {
|
|
302
|
+
throw new UnauthorizedError("Failed to authorize");
|
|
303
|
+
}
|
|
304
|
+
return { authorizationUrl: "" };
|
|
305
|
+
} finally {
|
|
306
|
+
authProvider.deactivate();
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
const existingPendingAuth = runtimeState.pendingAuths.get(getPendingAuthKey(serverName, authStorageOptions));
|
|
310
|
+
if (existingPendingAuth?.serverUrl === serverUrl) {
|
|
311
|
+
return { authorizationUrl: existingPendingAuth.authorizationUrl };
|
|
312
|
+
}
|
|
313
|
+
const redirectTarget = config.redirectUri !== undefined ? parseOAuthRedirectUri(config.redirectUri) : undefined;
|
|
314
|
+
const manualRedirect = redirectTarget?.mode === "manual";
|
|
315
|
+
const oauthState = generateState();
|
|
316
|
+
if (!manualRedirect) {
|
|
317
|
+
try {
|
|
318
|
+
await ensureCallbackServer({
|
|
319
|
+
strictPort: Boolean(config.clientId) || config.redirectUri !== undefined,
|
|
320
|
+
oauthState,
|
|
321
|
+
reserveState: true,
|
|
322
|
+
...redirectTarget?.mode === "local" ? { port: redirectTarget.port, callbackHost: redirectTarget.callbackHost, callbackPath: redirectTarget.callbackPath } : {}
|
|
323
|
+
});
|
|
324
|
+
throwIfAborted(signal);
|
|
325
|
+
} catch (error) {
|
|
326
|
+
releaseCallbackServer(oauthState);
|
|
327
|
+
try {
|
|
328
|
+
await cleanupAndReleaseCallbackServerIfIdle(() => clearOAuthState(serverName, authStorageOptions));
|
|
329
|
+
} catch (cleanupError) {
|
|
330
|
+
throw new AggregateError([error, cleanupError], "OAuth startup cleanup failed");
|
|
331
|
+
}
|
|
332
|
+
throw error;
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
let capturedUrl;
|
|
336
|
+
const authProvider = new McpOAuthProvider(serverName, serverUrl, config, {
|
|
337
|
+
onRedirect: async (url) => {
|
|
338
|
+
capturedUrl = url;
|
|
339
|
+
}
|
|
340
|
+
}, authStorageOptions, runtime.signal, oauthState);
|
|
341
|
+
try {
|
|
342
|
+
const storedAuth = await getAuthForUrl(serverName, serverUrl, authStorageOptions);
|
|
343
|
+
if (storedAuth?.clientInfo && !config.clientId) {
|
|
344
|
+
if (!storedAuth.tokens) {
|
|
345
|
+
clearClientInfo(serverName, authStorageOptions);
|
|
346
|
+
clearCodeVerifier(serverName, authStorageOptions);
|
|
347
|
+
await clearOAuthState(serverName, authStorageOptions);
|
|
348
|
+
} else {
|
|
349
|
+
const redirectUris = storedAuth.clientInfo.redirectUris;
|
|
350
|
+
if (!Array.isArray(redirectUris) || !redirectUris.includes(authProvider.redirectUrl ?? "")) {
|
|
351
|
+
clearClientInfo(serverName, authStorageOptions);
|
|
352
|
+
clearTokens(serverName, authStorageOptions);
|
|
353
|
+
clearCodeVerifier(serverName, authStorageOptions);
|
|
354
|
+
await clearOAuthState(serverName, authStorageOptions);
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
}
|
|
358
|
+
throwIfAborted(signal);
|
|
359
|
+
const discovery = applyOAuthConfig(await probeAuthDiscovery(serverUrl, definition, signal), config);
|
|
360
|
+
throwIfAborted(signal);
|
|
361
|
+
const result = await abortable(runSdkAuth(authProvider, { serverUrl, ...discovery }), signal);
|
|
362
|
+
throwIfAborted(signal);
|
|
363
|
+
if (result === "AUTHORIZED") {
|
|
364
|
+
authProvider.deactivate();
|
|
365
|
+
releaseCallbackServer(oauthState);
|
|
366
|
+
await clearOAuthState(serverName, authStorageOptions);
|
|
367
|
+
await stopCallbackServerIfIdle();
|
|
368
|
+
return { authorizationUrl: "" };
|
|
369
|
+
}
|
|
370
|
+
if (!capturedUrl) {
|
|
371
|
+
throw new UnauthorizedError("OAuth authorization URL was not provided");
|
|
372
|
+
}
|
|
373
|
+
await setPendingAuth(runtime, serverName, {
|
|
374
|
+
serverName,
|
|
375
|
+
authProvider,
|
|
376
|
+
serverUrl,
|
|
377
|
+
authorizationUrl: capturedUrl.toString(),
|
|
378
|
+
manualRedirect,
|
|
379
|
+
...manualRedirect ? { manualCompletionController: new AbortController } : {},
|
|
380
|
+
discovery,
|
|
381
|
+
authStorageOptions
|
|
382
|
+
}, oauthState, signal, generation);
|
|
383
|
+
return { authorizationUrl: capturedUrl.toString() };
|
|
384
|
+
} catch (error) {
|
|
385
|
+
authProvider.deactivate();
|
|
386
|
+
try {
|
|
387
|
+
await clearPendingAuthAndReleaseIfIdle(runtime, serverName, oauthState, authStorageOptions);
|
|
388
|
+
} catch (cleanupError) {
|
|
389
|
+
throw new AggregateError([error, cleanupError], "OAuth startup cleanup failed");
|
|
390
|
+
}
|
|
391
|
+
throw error;
|
|
392
|
+
}
|
|
393
|
+
}
|
|
394
|
+
async function setPendingAuth(runtime, serverName, pendingAuth, oauthState, signal, generation = getRuntimeState(runtime).generation) {
|
|
395
|
+
const state = getRuntimeState(runtime);
|
|
396
|
+
const key = getPendingAuthKey(serverName, pendingAuth.authStorageOptions);
|
|
397
|
+
await clearPendingAuth(runtime, serverName, undefined, pendingAuth.authStorageOptions);
|
|
398
|
+
throwIfAborted(signal);
|
|
399
|
+
if (generation !== state.generation)
|
|
400
|
+
throw new Error("OAuth runtime stopped");
|
|
401
|
+
state.pendingAuths.set(key, pendingAuth);
|
|
402
|
+
state.pendingAuthStates.set(key, oauthState);
|
|
403
|
+
const cleanupTimer = setTimeout(() => {
|
|
404
|
+
clearPendingAuthAndReleaseIfIdle(runtime, serverName, oauthState, pendingAuth.authStorageOptions, new Error("OAuth authorization timeout - authorization took too long")).catch((error) => {
|
|
405
|
+
console.error(`MCP Auth: Timed-out flow cleanup failed: ${formatTerminalError(error)}`);
|
|
406
|
+
});
|
|
407
|
+
}, MANUAL_AUTH_TIMEOUT_MS);
|
|
408
|
+
cleanupTimer.unref?.();
|
|
409
|
+
state.pendingAuthCleanupTimers.set(key, cleanupTimer);
|
|
410
|
+
}
|
|
411
|
+
async function clearPendingAuth(runtime, serverName, oauthState, fallbackStorageOptions = {}, reason = new Error("Authorization cancelled")) {
|
|
412
|
+
const state = getRuntimeState(runtime);
|
|
413
|
+
const key = getPendingAuthKey(serverName, fallbackStorageOptions);
|
|
414
|
+
const pendingAuth = state.pendingAuths.get(key);
|
|
415
|
+
const authStorageOptions = pendingAuth?.authStorageOptions ?? fallbackStorageOptions;
|
|
416
|
+
const pendingState = state.pendingAuthStates.get(key);
|
|
417
|
+
if (oauthState && pendingState && pendingState !== oauthState)
|
|
418
|
+
return;
|
|
419
|
+
const timer = state.pendingAuthCleanupTimers.get(key);
|
|
420
|
+
if (timer) {
|
|
421
|
+
clearTimeout(timer);
|
|
422
|
+
state.pendingAuthCleanupTimers.delete(key);
|
|
423
|
+
}
|
|
424
|
+
pendingAuth?.manualCompletionController?.abort(reason);
|
|
425
|
+
pendingAuth?.authProvider.deactivate();
|
|
426
|
+
state.pendingAuths.delete(key);
|
|
427
|
+
state.pendingAuthStates.delete(key);
|
|
428
|
+
const stateToRelease = pendingState ?? oauthState;
|
|
429
|
+
if (stateToRelease) {
|
|
430
|
+
cancelPendingCallback(stateToRelease);
|
|
431
|
+
const storedState = await getOAuthState(serverName, authStorageOptions);
|
|
432
|
+
if (storedState === stateToRelease) {
|
|
433
|
+
await clearOAuthState(serverName, authStorageOptions);
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
}
|
|
437
|
+
async function clearPendingAuthAndReleaseIfIdle(runtime, serverName, oauthState, fallbackStorageOptions = {}, reason) {
|
|
438
|
+
await cleanupAndReleaseCallbackServerIfIdle(() => clearPendingAuth(runtime, serverName, oauthState, fallbackStorageOptions, reason));
|
|
439
|
+
}
|
|
440
|
+
async function cleanupAndReleaseCallbackServerIfIdle(cleanup) {
|
|
441
|
+
let cleanupFailure;
|
|
442
|
+
try {
|
|
443
|
+
await cleanup();
|
|
444
|
+
} catch (error) {
|
|
445
|
+
cleanupFailure = { error };
|
|
446
|
+
}
|
|
447
|
+
try {
|
|
448
|
+
await stopCallbackServerIfIdle();
|
|
449
|
+
} catch (releaseError) {
|
|
450
|
+
if (cleanupFailure) {
|
|
451
|
+
throw new AggregateError([cleanupFailure.error, releaseError], "OAuth callback cleanup failed");
|
|
452
|
+
}
|
|
453
|
+
throw releaseError;
|
|
454
|
+
}
|
|
455
|
+
if (cleanupFailure)
|
|
456
|
+
throw cleanupFailure.error;
|
|
457
|
+
}
|
|
458
|
+
function getSearchParamsFromInput(input) {
|
|
459
|
+
try {
|
|
460
|
+
const url = new URL(input);
|
|
461
|
+
const params = new URLSearchParams(url.search);
|
|
462
|
+
if (url.hash) {
|
|
463
|
+
const hash = url.hash.startsWith("#") ? url.hash.slice(1) : url.hash;
|
|
464
|
+
const hashParams = new URLSearchParams(hash);
|
|
465
|
+
for (const [key, value] of hashParams) {
|
|
466
|
+
if (!params.has(key))
|
|
467
|
+
params.set(key, value);
|
|
468
|
+
}
|
|
469
|
+
}
|
|
470
|
+
return params;
|
|
471
|
+
} catch {
|
|
472
|
+
const query = input.includes("?") ? input.slice(input.indexOf("?") + 1) : input;
|
|
473
|
+
const params = new URLSearchParams(query.startsWith("#") ? query.slice(1) : query);
|
|
474
|
+
return params.has("code") || params.has("state") || params.has("error") ? params : undefined;
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
export function parseAuthorizationRedirectInput(input, expectedState) {
|
|
478
|
+
const trimmed = input.trim();
|
|
479
|
+
if (!trimmed) {
|
|
480
|
+
throw new Error("Authorization code or redirect URL is required");
|
|
481
|
+
}
|
|
482
|
+
const params = getSearchParamsFromInput(trimmed);
|
|
483
|
+
if (params) {
|
|
484
|
+
const error = params.get("error");
|
|
485
|
+
if (error) {
|
|
486
|
+
const description = params.get("error_description");
|
|
487
|
+
throw new Error(description ? `${error}: ${description}` : error);
|
|
488
|
+
}
|
|
489
|
+
const state = params.get("state");
|
|
490
|
+
if (expectedState && !state) {
|
|
491
|
+
throw new Error("OAuth state missing from redirect URL");
|
|
492
|
+
}
|
|
493
|
+
if (expectedState && state !== expectedState) {
|
|
494
|
+
throw new Error("OAuth state mismatch - potential CSRF attack");
|
|
495
|
+
}
|
|
496
|
+
const code = params.get("code");
|
|
497
|
+
if (code) {
|
|
498
|
+
const iss = params.get("iss");
|
|
499
|
+
return { code, ...iss !== null ? { iss } : {} };
|
|
500
|
+
}
|
|
501
|
+
}
|
|
502
|
+
if (/^[A-Za-z0-9._~+/=-]+$/.test(trimmed)) {
|
|
503
|
+
return { code: trimmed };
|
|
504
|
+
}
|
|
505
|
+
throw new Error("Could not find an OAuth authorization code in the provided input");
|
|
506
|
+
}
|
|
507
|
+
export function parseAuthorizationCodeInput(input, expectedState) {
|
|
508
|
+
return parseAuthorizationRedirectInput(input, expectedState).code;
|
|
509
|
+
}
|
|
510
|
+
function waitForManualCompletionCancellation(signal) {
|
|
511
|
+
return new Promise((_, reject) => {
|
|
512
|
+
const rejectFromSignal = () => {
|
|
513
|
+
reject(signal.reason instanceof Error ? signal.reason : new Error("Authorization cancelled"));
|
|
514
|
+
};
|
|
515
|
+
if (signal.aborted) {
|
|
516
|
+
rejectFromSignal();
|
|
517
|
+
return;
|
|
518
|
+
}
|
|
519
|
+
signal.addEventListener("abort", rejectFromSignal, { once: true });
|
|
520
|
+
});
|
|
521
|
+
}
|
|
522
|
+
export async function waitForAuthorizationResponse(callbackPromise, authorizationUrl, expectedState, onAuthorizationInput, signal) {
|
|
523
|
+
if (!onAuthorizationInput) {
|
|
524
|
+
return {
|
|
525
|
+
input: await abortable(callbackPromise, signal),
|
|
526
|
+
source: "callback"
|
|
527
|
+
};
|
|
528
|
+
}
|
|
529
|
+
const inputController = new AbortController;
|
|
530
|
+
try {
|
|
531
|
+
const response = await abortable(Promise.race([
|
|
532
|
+
callbackPromise.then((input) => ({ input, source: "callback" })),
|
|
533
|
+
onAuthorizationInput(authorizationUrl, inputController.signal).then((input) => ({
|
|
534
|
+
input,
|
|
535
|
+
source: "manual"
|
|
536
|
+
}))
|
|
537
|
+
]), signal);
|
|
538
|
+
if (response.source === "callback")
|
|
539
|
+
return response;
|
|
540
|
+
if (!response.input?.trim())
|
|
541
|
+
throw new Error("OAuth authentication cancelled");
|
|
542
|
+
if (!getSearchParamsFromInput(response.input.trim())) {
|
|
543
|
+
throw new Error("Paste the full OAuth callback URL, including its code and state parameters");
|
|
544
|
+
}
|
|
545
|
+
return {
|
|
546
|
+
input: parseAuthorizationRedirectInput(response.input, expectedState),
|
|
547
|
+
source: "manual"
|
|
548
|
+
};
|
|
549
|
+
} finally {
|
|
550
|
+
inputController.abort();
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
export async function completeAuthFromInput(serverName, input, options = {}) {
|
|
554
|
+
const runtime = getRuntime(options);
|
|
555
|
+
const runtimeState = getRuntimeState(runtime);
|
|
556
|
+
const fallbackAuthStorageOptions = options.authStorageOptions ?? {};
|
|
557
|
+
const signal = combineAbortSignals(runtime.signal, options.signal);
|
|
558
|
+
throwIfAborted(signal);
|
|
559
|
+
const key = getPendingAuthKey(serverName, fallbackAuthStorageOptions);
|
|
560
|
+
const oauthState = runtimeState.pendingAuthStates.get(key);
|
|
561
|
+
const pendingAuth = runtimeState.pendingAuths.get(key);
|
|
562
|
+
throwIfAborted(signal);
|
|
563
|
+
if (pendingAuth?.manualRedirect && !getSearchParamsFromInput(input.trim())) {
|
|
564
|
+
throw new Error("Paste the full OAuth callback URL, including its code and state parameters");
|
|
565
|
+
}
|
|
566
|
+
const parsed = parseAuthorizationRedirectInput(input, oauthState);
|
|
567
|
+
return completeAuth(serverName, parsed, options);
|
|
568
|
+
}
|
|
569
|
+
export async function completeAuth(serverName, authorizationCode, options = {}) {
|
|
570
|
+
const runtime = getRuntime(options);
|
|
571
|
+
const runtimeState = getRuntimeState(runtime);
|
|
572
|
+
const { code, iss } = typeof authorizationCode === "string" ? { code: authorizationCode, iss: undefined } : authorizationCode;
|
|
573
|
+
const fallbackAuthStorageOptions = options.authStorageOptions ?? {};
|
|
574
|
+
const signal = combineAbortSignals(runtime.signal, options.signal);
|
|
575
|
+
throwIfAborted(signal);
|
|
576
|
+
const key = getPendingAuthKey(serverName, fallbackAuthStorageOptions);
|
|
577
|
+
const pendingAuth = runtimeState.pendingAuths.get(key);
|
|
578
|
+
const authStorageOptions = pendingAuth?.authStorageOptions ?? fallbackAuthStorageOptions;
|
|
579
|
+
if (!pendingAuth) {
|
|
580
|
+
throw new Error(`No pending OAuth flow for server: ${serverName}`);
|
|
581
|
+
}
|
|
582
|
+
const oauthState = runtimeState.pendingAuthStates.get(key);
|
|
583
|
+
throwIfAborted(signal);
|
|
584
|
+
let keepPendingForRetry = false;
|
|
585
|
+
let caughtError;
|
|
586
|
+
try {
|
|
587
|
+
const discoveryState = await pendingAuth.authProvider.discoveryState();
|
|
588
|
+
const metadata = discoveryState?.authorizationServerMetadata;
|
|
589
|
+
const expectedIssuer = metadata?.issuer ?? discoveryState?.authorizationServerUrl;
|
|
590
|
+
const requiresIssuer = metadata?.authorization_response_iss_parameter_supported === true;
|
|
591
|
+
if (expectedIssuer !== undefined && iss === undefined && requiresIssuer) {
|
|
592
|
+
keepPendingForRetry = true;
|
|
593
|
+
throw new Error(`The authorization server for ${serverName} requires the RFC 9207 "iss" parameter. ` + "Paste the full redirect URL from the browser address bar (not just the authorization code).");
|
|
594
|
+
}
|
|
595
|
+
if (expectedIssuer !== undefined && iss !== undefined && iss !== expectedIssuer) {
|
|
596
|
+
throw new Error(`The OAuth authorization response issuer does not match the discovered issuer for ${serverName}.`);
|
|
597
|
+
}
|
|
598
|
+
const result = await abortable(runSdkAuth(pendingAuth.authProvider, {
|
|
599
|
+
serverUrl: pendingAuth.serverUrl,
|
|
600
|
+
authorizationCode: code,
|
|
601
|
+
...iss !== undefined ? { iss } : {},
|
|
602
|
+
...pendingAuth.discovery
|
|
603
|
+
}), signal);
|
|
604
|
+
throwIfAborted(signal);
|
|
605
|
+
if (result !== "AUTHORIZED") {
|
|
606
|
+
throw new UnauthorizedError("Failed to authorize");
|
|
607
|
+
}
|
|
608
|
+
return "authenticated";
|
|
609
|
+
} catch (error) {
|
|
610
|
+
caughtError = error;
|
|
611
|
+
throw error;
|
|
612
|
+
} finally {
|
|
613
|
+
if (!keepPendingForRetry) {
|
|
614
|
+
try {
|
|
615
|
+
await clearPendingAuthAndReleaseIfIdle(runtime, serverName, oauthState, authStorageOptions);
|
|
616
|
+
} catch (cleanupError) {
|
|
617
|
+
if (caughtError !== undefined) {
|
|
618
|
+
throw new AggregateError([caughtError, cleanupError], "OAuth completion cleanup failed");
|
|
619
|
+
}
|
|
620
|
+
throw cleanupError;
|
|
621
|
+
}
|
|
622
|
+
}
|
|
623
|
+
}
|
|
624
|
+
}
|
|
625
|
+
export async function authenticate(serverName, serverUrl, definition, options = {}) {
|
|
626
|
+
if (isServerDisabled(definition))
|
|
627
|
+
throw new Error(`MCP server "${serverName}" is disabled`);
|
|
628
|
+
const runtime = getRuntime(options);
|
|
629
|
+
const runtimeState = getRuntimeState(runtime);
|
|
630
|
+
const authStorageOptions = options.authStorageOptions ?? {};
|
|
631
|
+
const signal = combineAbortSignals(runtime.signal, options.signal);
|
|
632
|
+
throwIfAborted(signal);
|
|
633
|
+
const authKey = `${serverName}|${serverUrl}|${getAuthBaseDir(authStorageOptions)}`;
|
|
634
|
+
const inFlight = runtimeState.pendingAuthentications.get(authKey);
|
|
635
|
+
if (inFlight) {
|
|
636
|
+
return inFlight;
|
|
637
|
+
}
|
|
638
|
+
const operation = (async () => {
|
|
639
|
+
const { authorizationUrl } = await startAuth(serverName, serverUrl, definition, {
|
|
640
|
+
...options,
|
|
641
|
+
...signal ? { signal } : {},
|
|
642
|
+
runtime
|
|
643
|
+
});
|
|
644
|
+
if (!authorizationUrl) {
|
|
645
|
+
return "authenticated";
|
|
646
|
+
}
|
|
647
|
+
let oauthState;
|
|
648
|
+
try {
|
|
649
|
+
oauthState = runtimeState.pendingAuthStates.get(getPendingAuthKey(serverName, authStorageOptions));
|
|
650
|
+
throwIfAborted(signal);
|
|
651
|
+
if (!oauthState) {
|
|
652
|
+
throw new Error("OAuth state not found - this should not happen");
|
|
653
|
+
}
|
|
654
|
+
const pendingAuth = runtimeState.pendingAuths.get(getPendingAuthKey(serverName, authStorageOptions));
|
|
655
|
+
if (!pendingAuth) {
|
|
656
|
+
throw new Error(`No pending OAuth flow for server: ${serverName}`);
|
|
657
|
+
}
|
|
658
|
+
if (pendingAuth.manualRedirect && !options.onAuthorizationInput) {
|
|
659
|
+
throw new Error(`OAuth for ${serverName} uses a remote redirect URI. Complete it with auth-start/auth-complete or /mcp-auth.`);
|
|
660
|
+
}
|
|
661
|
+
const callbackPromise = pendingAuth.manualRedirect ? waitForManualCompletionCancellation(pendingAuth.manualCompletionController.signal) : waitForCallback(oauthState);
|
|
662
|
+
callbackPromise.catch(() => {});
|
|
663
|
+
if (options.onAuthorizationUrl) {
|
|
664
|
+
await abortable(Promise.resolve(options.onAuthorizationUrl(authorizationUrl)), signal);
|
|
665
|
+
} else {
|
|
666
|
+
console.log(`MCP Auth: Open this URL to authenticate ${serverName}:
|
|
667
|
+
${authorizationUrl}`);
|
|
668
|
+
}
|
|
669
|
+
try {
|
|
670
|
+
await abortable(open(authorizationUrl), signal);
|
|
671
|
+
} catch (error) {
|
|
672
|
+
if (isAbortError(error, signal))
|
|
673
|
+
throw error;
|
|
674
|
+
console.warn(`MCP Auth: Failed to open browser for ${serverName}; waiting for manual callback`, { error });
|
|
675
|
+
}
|
|
676
|
+
const authorizationResponse = await waitForAuthorizationResponse(callbackPromise, authorizationUrl, oauthState, options.onAuthorizationInput, signal);
|
|
677
|
+
if (authorizationResponse.source === "manual") {
|
|
678
|
+
cancelPendingCallback(oauthState);
|
|
679
|
+
}
|
|
680
|
+
throwIfAborted(signal);
|
|
681
|
+
return await completeAuth(serverName, authorizationResponse.input, {
|
|
682
|
+
...options,
|
|
683
|
+
...signal ? { signal } : {},
|
|
684
|
+
runtime
|
|
685
|
+
});
|
|
686
|
+
} catch (error) {
|
|
687
|
+
if (oauthState)
|
|
688
|
+
cancelPendingCallback(oauthState);
|
|
689
|
+
try {
|
|
690
|
+
await clearPendingAuthAndReleaseIfIdle(runtime, serverName, oauthState, authStorageOptions);
|
|
691
|
+
} catch (cleanupError) {
|
|
692
|
+
throw new AggregateError([error, cleanupError], "OAuth cancellation cleanup failed");
|
|
693
|
+
}
|
|
694
|
+
throw error;
|
|
695
|
+
}
|
|
696
|
+
})();
|
|
697
|
+
runtimeState.pendingAuthentications.set(authKey, operation);
|
|
698
|
+
try {
|
|
699
|
+
return await operation;
|
|
700
|
+
} finally {
|
|
701
|
+
if (runtimeState.pendingAuthentications.get(authKey) === operation) {
|
|
702
|
+
runtimeState.pendingAuthentications.delete(authKey);
|
|
703
|
+
}
|
|
704
|
+
}
|
|
705
|
+
}
|
|
706
|
+
export async function getValidToken(serverName, serverUrl, options = {}) {
|
|
707
|
+
const runtime = getRuntime(options);
|
|
708
|
+
const authStorageOptions = options.authStorageOptions ?? {};
|
|
709
|
+
const signal = combineAbortSignals(runtime.signal, options.signal);
|
|
710
|
+
throwIfAborted(signal);
|
|
711
|
+
const entry = await getAuthForUrl(serverName, serverUrl, authStorageOptions);
|
|
712
|
+
throwIfAborted(signal);
|
|
713
|
+
if (!entry?.tokens) {
|
|
714
|
+
return null;
|
|
715
|
+
}
|
|
716
|
+
const expired = await isTokenExpired(serverName, authStorageOptions);
|
|
717
|
+
if (expired === false) {
|
|
718
|
+
return entry.tokens;
|
|
719
|
+
}
|
|
720
|
+
if (expired === true && entry.tokens.refreshToken) {
|
|
721
|
+
console.log(`MCP Auth: Token expired for ${serverName}, attempting refresh`);
|
|
722
|
+
try {
|
|
723
|
+
const authProvider = new McpOAuthProvider(serverName, serverUrl, {}, {
|
|
724
|
+
onRedirect: async () => {}
|
|
725
|
+
}, authStorageOptions, runtime.signal);
|
|
726
|
+
try {
|
|
727
|
+
const clientInfo = await authProvider.clientInformation();
|
|
728
|
+
throwIfAborted(signal);
|
|
729
|
+
if (!clientInfo) {
|
|
730
|
+
console.log(`MCP Auth: No client info for refresh for ${serverName}`);
|
|
731
|
+
return null;
|
|
732
|
+
}
|
|
733
|
+
const discovery = await probeAuthDiscovery(serverUrl, undefined, signal);
|
|
734
|
+
throwIfAborted(signal);
|
|
735
|
+
const result = await abortable(runSdkAuth(authProvider, {
|
|
736
|
+
serverUrl,
|
|
737
|
+
...discovery,
|
|
738
|
+
...options.skipIssuerMetadataValidation === true ? { skipIssuerMetadataValidation: true } : {}
|
|
739
|
+
}), signal);
|
|
740
|
+
throwIfAborted(signal);
|
|
741
|
+
if (result !== "AUTHORIZED") {
|
|
742
|
+
return null;
|
|
743
|
+
}
|
|
744
|
+
const refreshed = await getAuthForUrl(serverName, serverUrl, authStorageOptions);
|
|
745
|
+
throwIfAborted(signal);
|
|
746
|
+
return refreshed?.tokens ?? null;
|
|
747
|
+
} finally {
|
|
748
|
+
authProvider.deactivate();
|
|
749
|
+
}
|
|
750
|
+
} catch (error) {
|
|
751
|
+
if (isAbortError(error, signal) || error instanceof OAuthCredentialStoreError)
|
|
752
|
+
throw error;
|
|
753
|
+
console.error(`MCP Auth: Token refresh failed for ${serverName}`, { error });
|
|
754
|
+
return null;
|
|
755
|
+
}
|
|
756
|
+
}
|
|
757
|
+
return entry.tokens;
|
|
758
|
+
}
|
|
759
|
+
export async function getAuthStatus(serverName, options = {}) {
|
|
760
|
+
getRuntime(options);
|
|
761
|
+
const authStorageOptions = options.authStorageOptions ?? {};
|
|
762
|
+
const hasTokens = await hasStoredTokens(serverName, authStorageOptions);
|
|
763
|
+
if (!hasTokens)
|
|
764
|
+
return "not_authenticated";
|
|
765
|
+
const expired = await isTokenExpired(serverName, authStorageOptions);
|
|
766
|
+
return expired ? "expired" : "authenticated";
|
|
767
|
+
}
|
|
768
|
+
export async function removeAuth(serverName, options = {}) {
|
|
769
|
+
const runtime = getRuntime(options);
|
|
770
|
+
const signal = combineAbortSignals(runtime.signal, options.signal);
|
|
771
|
+
throwIfAborted(signal);
|
|
772
|
+
const authStorageOptions = options.authStorageOptions ?? {};
|
|
773
|
+
const oauthState = await getOAuthState(serverName, authStorageOptions);
|
|
774
|
+
throwIfAborted(signal);
|
|
775
|
+
if (oauthState) {
|
|
776
|
+
cancelPendingCallback(oauthState);
|
|
777
|
+
}
|
|
778
|
+
await clearPendingAuthAndReleaseIfIdle(runtime, serverName, oauthState, authStorageOptions);
|
|
779
|
+
throwIfAborted(signal);
|
|
780
|
+
clearAllCredentials(serverName, authStorageOptions);
|
|
781
|
+
await clearOAuthState(serverName, authStorageOptions);
|
|
782
|
+
throwIfAborted(signal);
|
|
783
|
+
console.log(`MCP Auth: Removed credentials for ${serverName}`);
|
|
784
|
+
}
|
|
785
|
+
export function supportsOAuth(definition) {
|
|
786
|
+
if (!definition.url)
|
|
787
|
+
return false;
|
|
788
|
+
if (definition.auth === false)
|
|
789
|
+
return false;
|
|
790
|
+
if (definition.oauth === false)
|
|
791
|
+
return false;
|
|
792
|
+
if (definition.auth === "oauth")
|
|
793
|
+
return true;
|
|
794
|
+
if (definition.headers && Object.keys(definition.headers).length > 0)
|
|
795
|
+
return false;
|
|
796
|
+
return definition.auth === undefined;
|
|
797
|
+
}
|
|
798
|
+
export async function initializeOAuth(runtimeOrSignal) {
|
|
799
|
+
if (runtimeOrSignal && "signal" in runtimeOrSignal) {
|
|
800
|
+
runtimeOrSignal.signal.throwIfAborted();
|
|
801
|
+
activeRuntimes.add(runtimeOrSignal);
|
|
802
|
+
return runtimeOrSignal;
|
|
803
|
+
}
|
|
804
|
+
await shutdownOAuth(legacyRuntime);
|
|
805
|
+
legacyRuntime = createOAuthRuntime(runtimeOrSignal);
|
|
806
|
+
return legacyRuntime;
|
|
807
|
+
}
|
|
808
|
+
export async function shutdownOAuth(runtime = legacyRuntime) {
|
|
809
|
+
const state = getRuntimeState(runtime);
|
|
810
|
+
if (state.controller.signal.aborted)
|
|
811
|
+
return;
|
|
812
|
+
state.generation += 1;
|
|
813
|
+
state.controller.abort(new Error("OAuth runtime stopped"));
|
|
814
|
+
for (const callbackState of Array.from(state.pendingAuthStates.values()))
|
|
815
|
+
cancelPendingCallback(callbackState);
|
|
816
|
+
for (const pendingAuth of Array.from(state.pendingAuths.values())) {
|
|
817
|
+
await clearPendingAuth(runtime, pendingAuth.serverName, undefined, pendingAuth.authStorageOptions);
|
|
818
|
+
}
|
|
819
|
+
state.pendingAuthentications.clear();
|
|
820
|
+
activeRuntimes.delete(runtime);
|
|
821
|
+
if (activeRuntimes.size === 0) {
|
|
822
|
+
await stopCallbackServer();
|
|
823
|
+
}
|
|
824
|
+
}
|