UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

690 lines (689 loc) • 25.2 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { o as racePromiseWithAbortSignal } from "./src-BPmQBLJp.mjs"; import { r as captureOpenClawStateWorkerContext } from "./openclaw-state-worker-context-DAKL_dnZ.mjs"; import { n as withOpenClawStateLeaseAsync } from "./openclaw-state-lease-Cn13CM0c.mjs"; import { i as readOAuthRefreshErrorReason, n as createOAuthRefreshResponseError, t as createOAuthRefreshError } from "./oauth-refresh-outcome-DGKa-Dzy.mjs"; import { i as readResponseWithLimit } from "./http-response-body-B-i_0116.mjs"; import { l as isProvenDeliveryNotSentError } from "./delivery-recovery.shared-3Nb7FEaL.mjs"; import { n as buildMcpOAuthAuthorizationFetch, r as buildMcpOAuthHttpFetch } from "./mcp-http-fetch-BUTs6xsJ.mjs"; import { n as mcpOAuthSignInHint, o as requesterMcpOAuthStoreKeyPrefix } from "./mcp-oauth-identity-B4O1ccto.mjs"; import { a as deleteMcpOAuthPendingAuthorizationsByPrefix, d as readMcpOAuthStoreStatuses, f as writeMcpOAuthPendingAuthorization, i as deleteMcpOAuthPendingAuthorization, l as readMcpOAuthStore, m as mcpOAuthAuthorizationRequiredError, n as consumeOAuthState, o as listMcpOAuthStoreKeysByPrefix, p as projectMcpOAuthCredentialsStatus, r as countMcpOAuthStorePrincipals, s as mutateMcpOAuthStore, t as clearMcpOAuthStore, u as readMcpOAuthStoreReadOnly } from "./mcp-oauth-store-Cp55xn8F.mjs"; import { t as MCP_OAUTH_DEFAULT_REDIRECT_URL } from "./mcp-oauth-store.mutations-DT8WHglw.mjs"; import { randomUUID } from "node:crypto"; //#region src/agents/mcp-oauth-provider.ts /** MCP SDK OAuth provider backed by canonical OpenClaw state. */ var McpOAuthCredentialsRetainedError = class extends Error { constructor() { super("Existing authentication was retained. Use the CLI sign-in flow."); this.name = "McpOAuthCredentialsRetainedError"; } }; function resolveTokenExpiresAt(e) { const t = e.expires_in; return typeof t === "number" && Number.isFinite(t) ? Date.now() + t * 1e3 : void 0; } function canReuseStoredTokens(e) { const t = e.discoveryState?.authorizationServerUrl; return !e.tokens?.refresh_token || t === void 0 || e.tokensAuthorizationServerUrl !== void 0 && t === e.tokensAuthorizationServerUrl; } function resolveOAuthRedirectUrl(e, t = {}) { return normalizeOptionalString(e.redirectUrl) ?? normalizeOptionalString(t.redirectUrl) ?? "http://127.0.0.1:8989/oauth/callback"; } function hasRegisteredOAuthRedirect(e, t) { if (e.includes(t)) return true; const n = URL.parse(t); if (!n || n.protocol !== "http:" || ![ "127.0.0.1", "[::1]", "localhost" ].includes(n.hostname)) return false; return e.includes(t.replace(/^(http:\/\/[^/?#]+):\d+(?=[/?#]|$)/iu, "$1")); } /** Bind OAuth network work to the lease that fences its persisted side effects. */ function withMcpOAuthLeaseSignal(e, t, n) { const r = e ?? ((e, t) => fetch(e, t)); return async (e, i) => { n?.(); const a = i?.signal; const o = a ? AbortSignal.any([a, t]) : t; const s = await r(e, { ...i, signal: o }); n?.(); return s; }; } /** Creates the MCP SDK OAuth provider backed by canonical shared SQLite state. */ async function createMcpOAuthClientProvider(e) { const t = e.config ?? {}; const n = e.identity.storeKey; const r = e.storeContext; let i; let a = {}; const readStore = async () => { e.login?.assertCurrent(); const t = await readMcpOAuthStore(n, r); e.login?.assertCurrent(); await e.lease.assertOwned(); e.login?.assertCurrent(); a = { redirectUrl: t.redirectUrl }; return t; }; await readStore(); e.login?.assertCurrent(); const updateStore = async (t, i = {}) => { e.login?.assertCurrent(); const o = e.login ? { assertCurrent: e.login.assertCurrent, beforeCommit: i.beforeCommit } : void 0; try { const { store: s } = await mutateMcpOAuthStore({ storeKey: n, lease: e.lease, context: r }, t, o); i.onAcknowledged?.(); e.login?.assertCurrent(); a = { redirectUrl: s.redirectUrl }; return s; } catch (e) { a = { error: e }; throw e; } }; const preparedStore = () => { if ("error" in a) throw a.error; return a; }; const assertAuthorizationRedirectAllowed = () => { e.login?.assertCurrent(); if (e.allowAuthorizationRedirect !== true) throw mcpOAuthAuthorizationRequiredError(e.identity, r.admission); }; return { get redirectUrl() { return resolveOAuthRedirectUrl(t, preparedStore()); }, clientMetadataUrl: normalizeOptionalString(t.clientMetadataUrl), get clientMetadata() { const e = resolveOAuthRedirectUrl(t, preparedStore()); const n = normalizeOptionalString(t.scope); return { client_name: "OpenClaw MCP", redirect_uris: [e], grant_types: ["authorization_code", "refresh_token"], response_types: ["code"], token_endpoint_auth_method: "none", ...n ? { scope: n } : {} }; }, async state() { assertAuthorizationRedirectAllowed(); if (e.login) { const t = await readStore(); e.login.assertCurrent(); if (t.tokens?.access_token && (!t.refreshClaim || t.refreshClaim === e.refreshBoundary?.claim) && t.pendingAuthorizationChallenge?.requiresAuthorization !== true && (t.tokenExpiresAt === void 0 || t.tokenExpiresAt > Date.now())) throw new Error("Existing authentication could not be refreshed. Use the CLI sign-in flow."); } return randomUUID(); }, async clientInformation() { const n = await readStore(); e.login?.assertCurrent(); if (!canReuseStoredTokens(n)) assertAuthorizationRedirectAllowed(); const r = n.clientInformation; if (!n.tokens && r && "redirect_uris" in r && Array.isArray(r.redirect_uris) && !hasRegisteredOAuthRedirect(r.redirect_uris, resolveOAuthRedirectUrl(t, n))) return; return r; }, async saveClientInformation(t) { await updateStore({ kind: "clientInformation", clientInformation: t }); e.login?.assertCurrent(); }, async tokens() { if (e.suppressStoredTokens) { e.login?.assertCurrent(); await e.lease.assertOwned(); e.login?.assertCurrent(); return; } const t = await readStore(); e.login?.assertCurrent(); if (t.refreshClaim && t.refreshClaim !== e.refreshBoundary?.claim) { if (e.allowAuthorizationRedirect) return; throw new Error("MCP OAuth refresh outcome is uncertain; sign in again."); } return canReuseStoredTokens(t) ? t.tokens : void 0; }, async saveTokens(t) { e.refreshBoundary?.assertTokens(t); await updateStore({ kind: "tokens", tokens: t, tokenExpiresAt: resolveTokenExpiresAt(t), ...e.replaceAuthorization ? { replaceAuthorization: true } : {}, ...e.refreshBoundary?.claim ? { refreshClaim: e.refreshBoundary.claim } : {} }, { beforeCommit: e.login?.beforeTokensSaved, onAcknowledged: e.login?.onTokensSaved }); e.login?.assertCurrent(); }, async redirectToAuthorization(n) { assertAuthorizationRedirectAllowed(); const r = n.searchParams.get("state"); if (e.login && (!r || !i)) throw new Error("MCP OAuth authorization preparation is incomplete."); await updateStore({ kind: "authorizationRedirect", authorizationUrl: n.toString(), redirectUrl: normalizeOptionalString(t.redirectUrl), codeVerifier: i }, { onAcknowledged: () => { i = void 0; if (r) e.login?.onAuthorizationPublished(r); } }); e.login?.assertCurrent(); }, saveCodeVerifier(e) { assertAuthorizationRedirectAllowed(); i = e; }, async codeVerifier() { e.login?.assertCurrent(); let t = i; if (t !== void 0) { await e.lease.assertOwned(); e.login?.assertCurrent(); } else { const n = await readStore(); e.login?.assertCurrent(); t = n.codeVerifier; } if (!t) throw new Error("Missing MCP OAuth code verifier. Run the login flow again."); return t; }, async invalidateCredentials(t) { e.login?.assertCurrent(); e.refreshBoundary?.assertCanInvalidate(); if (e.login) throw new McpOAuthCredentialsRetainedError(); await updateStore({ kind: "invalidate", scope: t, suppressStoredTokens: e.suppressStoredTokens === true }); }, async saveDiscoveryState(t) { await updateStore({ kind: "discoveryState", discoveryState: t }); e.login?.assertCurrent(); }, async discoveryState() { const t = await readStore(); e.login?.assertCurrent(); return t.discoveryState; } }; } //#endregion //#region src/agents/mcp-oauth-refresh-boundary.ts /** Adapt the SDK token POST to its existing SQLite lease, not a second OAuth owner. */ function createMcpOAuthRefreshBoundary(e, t) { const n = randomUUID(); let r = false; let i = false; let a; const unknown = (e) => createOAuthRefreshError("MCP OAuth refresh outcome is uncertain; sign in again.", { version: 1, phase: "after-token-response", outcome: "unknown" }, { cause: e }); const check = async () => { t?.(); await e.lease.assertOwned(); t?.(); }; return { get claim() { return r ? n : void 0; }, assertTokens(e) { if (!i) return; if (!e.access_token.trim() || e.refresh_token !== void 0 && !e.refresh_token.trim() || e.expires_in !== void 0 && (!Number.isFinite(e.expires_in) || e.expires_in <= 0)) throw unknown(); }, assertCanInvalidate() { if (r) throw a ?? unknown(); }, wrap(o) { return async (s, c) => { const l = c?.body instanceof URLSearchParams ? c.body : typeof c?.body === "string" ? new URLSearchParams(c.body) : void 0; if (c?.method?.toUpperCase() !== "POST" || l?.get("grant_type") !== "refresh_token") return await o(s, c); let u; try { if (r) throw unknown(); await check(); try { const i = await mutateMcpOAuthStore(e, { kind: "beginRefresh", claim: n, refreshToken: l.get("refresh_token") ?? "" }, t ? { assertCurrent: t } : void 0); r = i.applied && i.store.refreshClaim === n; if (!r) throw unknown(); } catch (t) { await check(); const i = await readMcpOAuthStore(e.storeKey, e.context); await check(); r = i.refreshClaim === n; throw t; } await check(); const a = AbortSignal.any([ e.lease.signal, AbortSignal.timeout(3e4), ...c?.signal ? [c.signal] : [] ]); a.throwIfAborted(); i = true; const d = await o(s, { ...c, signal: a }); const f = await readResponseWithLimit(d, 262144, { signal: a }); const p = new TextDecoder("utf-8", { fatal: true }).decode(f); const m = JSON.parse(p); if (!d.ok || readOAuthRefreshErrorReason(m)) { u = createOAuthRefreshResponseError("MCP OAuth refresh", d.status, m); throw u; } return new Response(p, { status: d.status, statusText: d.statusText, headers: d.headers }); } catch (e) { if (i && isProvenDeliveryNotSentError(e)) i = false; a = i ? u ?? unknown(e) : createOAuthRefreshError("MCP OAuth refresh did not start.", { version: 1, phase: "before-dispatch", outcome: "not-attempted", recovery: { kind: "later", evidence: "dispatch-not-started" } }, { cause: e }); throw a; } }; }, async finish({ redirected: o = false } = {}) { if (r && !i) await mutateMcpOAuthStore(e, { kind: "restoreRefresh", claim: n }, t ? { assertCurrent: t } : void 0); if (a && !o) throw a; } }; } //#endregion //#region src/agents/mcp-oauth.ts const LOCALHOST_REDIRECT_URL = "http://localhost:8989/oauth/callback"; const TOKEN_EXPIRY_SKEW_MS = 3e4; const MCP_OAUTH_LEASE_MS = 6e4; const MCP_OAUTH_LEASE_WAIT_MS = 3e4; function isMcpOAuthRedirectRegistrationError(e) { return /invalid_client_metadata|redirect_uri/i.test(String(e)); } async function withMcpOAuthLease(e, t, n, r = captureOpenClawStateWorkerContext()) { r.admission.assertCurrent(); return await withOpenClawStateLeaseAsync({ scope: "core:mcp-oauth", key: e, leaseMs: MCP_OAUTH_LEASE_MS, waitMs: MCP_OAUTH_LEASE_WAIT_MS, ...n ? { signal: n } : {} }, r, (e) => t(e, r)); } function isStoredMcpOAuthAccessTokenUsable(e, t) { const n = e.tokens; if (!n?.access_token || t.rejectedAccessToken === n.access_token) return false; return e.tokenExpiresAt !== void 0 && e.tokenExpiresAt > Date.now() + TOKEN_EXPIRY_SKEW_MS || e.tokenExpiresAt === void 0 && (t.acceptUnknownExpiry === true || !n.refresh_token); } async function resolveMcpOAuthAccessToken(e) { const t = e.identity.storeKey; const n = e.signal; n?.throwIfAborted(); if (e.authorizationChallenge !== true) { const r = await readMcpOAuthStoreReadOnly(t); n?.throwIfAborted(); if (r.pendingAuthorizationChallenge?.requiresAuthorization !== true && !r.refreshClaim && isStoredMcpOAuthAccessTokenUsable(r, e)) return r.tokens?.access_token; } const r = new AbortController(); const i = new AbortController(); let a = false; const onAbort = () => (a ? i : r).abort(n?.reason); n?.addEventListener("abort", onAbort, { once: true }); const o = withMcpOAuthLease(t, async (n, r) => { a = true; const i = await readMcpOAuthStore(t, r); await n.assertOwned(); const o = i.tokens; const s = e.rejectedAccessToken === o?.access_token; const c = !o?.access_token || s; if (e.authorizationChallenge === true && c) { const i = e.resourceMetadataUrl?.toString(); const a = normalizeOptionalString(e.scope); if (i || a || e.interactiveAuthorizationRequired === true) await mutateMcpOAuthStore({ storeKey: t, lease: n, context: r }, { kind: "authorizationChallenge", resourceMetadataUrl: i, scope: a, ...e.interactiveAuthorizationRequired === true ? { requiresAuthorization: true } : {} }); } if (e.authorizationChallenge === true && e.interactiveAuthorizationRequired === true && c) throw mcpOAuthAuthorizationRequiredError(e.identity, r.admission, true); if (i.pendingAuthorizationChallenge?.requiresAuthorization === true) throw mcpOAuthAuthorizationRequiredError(e.identity, r.admission, true); if (i.refreshClaim) throw new Error("MCP OAuth refresh outcome is uncertain; sign in again."); if (!o?.access_token) { if (e.allowMissingToken === true) return; throw mcpOAuthAuthorizationRequiredError(e.identity, r.admission); } if (isStoredMcpOAuthAccessTokenUsable(i, e)) return o.access_token; if (!o.refresh_token) throw new Error(`MCP server "${e.identity.serverName}" has expired OAuth credentials. ${mcpOAuthSignInHint(e.identity)}`); const { auth: l } = await import("@modelcontextprotocol/client"); await n.assertOwned(); const u = i.pendingAuthorizationChallenge; await mutateMcpOAuthStore({ storeKey: t, lease: n, context: r }, { kind: "bindTokensIssuer" }); const d = createMcpOAuthRefreshBoundary({ storeKey: t, lease: n, context: r }); const f = await createMcpOAuthClientProvider({ identity: e.identity, config: e.config, lease: n, storeContext: r, refreshBoundary: d }); const p = e.fetchFn ?? buildMcpOAuthHttpFetch({ resourceUrl: e.identity.serverUrl }); let m; try { m = await l(f, { serverUrl: e.identity.serverUrl, resourceMetadataUrl: e.resourceMetadataUrl ?? (u?.resourceMetadataUrl ? new URL(u.resourceMetadataUrl) : void 0), scope: e.scope ?? normalizeOptionalString(u?.scope) ?? normalizeOptionalString(e.config?.scope), fetchFn: d.wrap(withMcpOAuthLeaseSignal(p, n.signal)) }); } finally { await d.finish(); } await n.assertOwned(); const h = await f.tokens(); if (m !== "AUTHORIZED" || !h?.access_token) throw new Error(`MCP server "${e.identity.serverName}" could not refresh OAuth credentials. ${mcpOAuthSignInHint(e.identity)}`); return h.access_token; }, r.signal); try { return await racePromiseWithAbortSignal(o, i.signal); } finally { n?.removeEventListener("abort", onAbort); } } /** Persist a terminal resource rejection without overwriting newer credentials. */ async function recordMcpOAuthAuthorizationRequired(e) { const t = e.identity.storeKey; return await withMcpOAuthLease(t, async (n, r) => { const i = await readMcpOAuthStore(t, r); await n.assertOwned(); if (i.tokens?.access_token !== e.rejectedAccessToken) return false; return (await mutateMcpOAuthStore({ storeKey: t, lease: n, context: r }, { kind: "authorizationChallenge", rejectedAccessToken: e.rejectedAccessToken, resourceMetadataUrl: e.resourceMetadataUrl?.toString(), scope: normalizeOptionalString(e.scope), requiresAuthorization: true })).applied; }, e.signal); } /** Deletes one OAuth session without racing an in-flight refresh or login. */ async function clearMcpOAuthCredentials(e) { await clearMcpOAuthStoreKey(e.storeKey); } async function clearMcpOAuthStoreKey(e, t = captureOpenClawStateWorkerContext()) { await withMcpOAuthLease(e, async (n) => { await clearMcpOAuthStore({ storeKey: e, lease: n, context: t }); }, void 0, t); } /** Clear operator and requester credentials bound to one configured server URL. */ async function clearMcpOAuthServer(e) { const t = captureOpenClawStateWorkerContext(); await clearMcpOAuthStoreKey(e.storeKey, t); await clearMcpOAuthRequesters(e, t); } /** Clear requester credentials without changing the operator row for this server URL. */ async function clearMcpOAuthRequesters(e, t = captureOpenClawStateWorkerContext()) { const n = requesterMcpOAuthStoreKeyPrefix(e.serverName, e.serverUrl); const r = await listMcpOAuthStoreKeysByPrefix(n, t); for (const e of r) await clearMcpOAuthStoreKey(e, t); await deleteMcpOAuthPendingAuthorizationsByPrefix(n, t); } /** Count authorized requester principals for one configured server URL. */ async function countMcpOAuthPrincipals(e) { return countMcpOAuthStorePrincipals(requesterMcpOAuthStoreKeyPrefix(e.serverName, e.serverUrl)); } /** Read one ordered requester set within a single current storage lifetime. */ async function readMcpOAuthCredentialsStatuses(e) { return readMcpOAuthStoreStatuses(e.map((e) => e.storeKey)); } /** Reads stored OAuth credential presence without exposing values or creating state. */ async function readMcpOAuthCredentialsStatus(e, t) { const n = t ?? await readMcpOAuthStoreReadOnly(e.storeKey); return projectMcpOAuthCredentialsStatus(n); } async function runMcpOAuthAuthorizationAttempt(e, t, n) { const { auth: r } = await import("@modelcontextprotocol/client"); e.login?.assertCurrent(); const i = createMcpOAuthRefreshBoundary({ storeKey: e.identity.storeKey, lease: t, context: n }, e.login?.assertCurrent); const a = await createMcpOAuthClientProvider({ identity: e.identity, config: e.config, allowAuthorizationRedirect: true, suppressStoredTokens: e.suppressStoredTokens, replaceAuthorization: Boolean(e.authorizationCode) || e.suppressStoredTokens, lease: t, login: e.login, storeContext: n, refreshBoundary: i }); e.login?.assertCurrent(); let o; try { o = await r(a, { serverUrl: e.identity.serverUrl, authorizationCode: normalizeOptionalString(e.authorizationCode), iss: e.iss, resourceMetadataUrl: e.resourceMetadataUrl, scope: normalizeOptionalString(e.scope) ?? normalizeOptionalString(e.config?.scope), fetchFn: i.wrap(withMcpOAuthLeaseSignal(e.fetchFn, t.signal, e.login?.assertCurrent)) }); } finally { await i.finish({ redirected: o === "REDIRECT" }); } e.login?.assertCurrent(); await t.assertOwned(); e.login?.assertCurrent(); return o === "AUTHORIZED" ? "authorized" : "redirect"; } async function startMcpOAuthAuthorization(e, t, n) { const r = e.storeKey; return await withMcpOAuthLease(r, async (i, a) => { n.login?.assertCurrent(); const o = await readMcpOAuthStore(r, a); n.login?.assertCurrent(); await i.assertOwned(); n.login?.assertCurrent(); if (n.login && o.tokens?.access_token && !o.refreshClaim && o.pendingAuthorizationChallenge?.requiresAuthorization !== true && (o.tokenExpiresAt === void 0 || o.tokenExpiresAt > Date.now() + TOKEN_EXPIRY_SKEW_MS)) return { status: "authorized" }; const s = o.pendingAuthorizationChallenge; const c = normalizeOptionalString(n.redirectUrl) ?? normalizeOptionalString(t.oauth?.redirectUrl); const l = c ?? o.redirectUrl; const u = { identity: e, config: { ...t.oauth, ...l ? { redirectUrl: l } : {} }, fetchFn: buildMcpOAuthAuthorizationFetch(t, n.login?.assertCurrent), resourceMetadataUrl: s?.resourceMetadataUrl ? new URL(s.resourceMetadataUrl) : void 0, scope: normalizeOptionalString(s?.scope), suppressStoredTokens: s?.requiresAuthorization === true, login: n.login }; let d; try { d = await runMcpOAuthAuthorizationAttempt(u, i, a); } catch (e) { n.login?.assertCurrent(); if (!c && isMcpOAuthRedirectRegistrationError(e)) d = await runMcpOAuthAuthorizationAttempt({ ...u, config: { ...t.oauth, redirectUrl: LOCALHOST_REDIRECT_URL } }, i, a); else throw e; } n.login?.assertCurrent(); if (d === "authorized") return { status: "authorized" }; const f = await readMcpOAuthStore(r, a); n.login?.assertCurrent(); await i.assertOwned(); n.login?.assertCurrent(); const p = f.lastAuthorizationUrl; const m = p ? new URL(p).searchParams.get("state") : null; if (!p || !f.codeVerifier || !f.redirectUrl || !m) throw new Error("MCP OAuth authorization session was not persisted."); await writeMcpOAuthPendingAuthorization({ storeKey: r, lease: i, context: a }, m, n.login ? { assertCurrent: n.login.assertCurrent } : void 0); n.login?.assertCurrent(); return { status: "redirect", authorizationUrl: p, redirectUrl: f.redirectUrl, state: m }; }, n.login?.signal); } async function completeMcpOAuthAuthorization(e, t, n) { const r = e.storeKey; return await withMcpOAuthLease(r, async (r, i) => { return await completeMcpOAuthAuthorizationUnderLease(e, t, n, r, i); }); } function readMcpOAuthAuthorizationState(e) { if (!e) return; try { return normalizeOptionalString(new URL(e).searchParams.get("state")); } catch { return; } } async function completeMcpOAuthAuthorizationUnderLease(e, t, n, r, i, a) { const o = normalizeOptionalString(n.code); if (!o) throw new Error("Missing MCP OAuth authorization code. Run the login flow again."); const s = e.storeKey; a?.assertCurrent(); const c = await readMcpOAuthStore(s, i); a?.assertCurrent(); await r.assertOwned(); a?.assertCurrent(); if (!c.codeVerifier || !c.redirectUrl) throw new Error("Missing MCP OAuth authorization session. Run the login flow again."); const l = c.pendingAuthorizationChallenge; const u = await runMcpOAuthAuthorizationAttempt({ identity: e, config: { ...t.oauth, redirectUrl: c.redirectUrl }, fetchFn: buildMcpOAuthAuthorizationFetch(t, a?.assertCurrent), authorizationCode: o, iss: n.iss, resourceMetadataUrl: l?.resourceMetadataUrl ? new URL(l.resourceMetadataUrl) : void 0, scope: normalizeOptionalString(l?.scope), suppressStoredTokens: l?.requiresAuthorization === true, login: a }, r, i); a?.assertCurrent(); if (u !== "authorized") throw new Error("MCP OAuth authorization did not complete. Run the login flow again."); const d = { storeKey: s, lease: r, context: i }; const f = a ? { assertCurrent: a.assertCurrent } : void 0; await mutateMcpOAuthStore(d, { kind: "completeAuthorization" }, f); a?.assertCurrent(); await deleteMcpOAuthPendingAuthorization(d, f); a?.assertCurrent(); return "authorized"; } /** Claims one callback state and completes its exchange under the same store lease. */ async function completeOAuthCallback(e, t, n, r, i = captureOpenClawStateWorkerContext()) { return await withMcpOAuthLease(e.storeKey, async (a) => { r?.assertCurrent(); const o = await consumeOAuthState({ storeKey: e.storeKey, lease: a, context: i }, n.state, r ? { assertCurrent: r.assertCurrent } : void 0); r?.assertCurrent(); if (!o) return "expired"; const s = await readMcpOAuthStore(e.storeKey, i); r?.assertCurrent(); await a.assertOwned(); r?.assertCurrent(); if (readMcpOAuthAuthorizationState(s.lastAuthorizationUrl) !== n.state) return "expired"; const c = await completeMcpOAuthAuthorizationUnderLease(e, t, n, a, i, r); r?.assertCurrent(); return c; }, r?.signal, i); } async function cancelMcpOAuthAuthorization(e, t) { await withMcpOAuthLease(e.storeKey, async (n, r) => { const i = await readMcpOAuthStore(e.storeKey, r); await n.assertOwned(); if (readMcpOAuthAuthorizationState(i.lastAuthorizationUrl) !== t) return; const a = { storeKey: e.storeKey, lease: n, context: r }; await mutateMcpOAuthStore(a, { kind: "completeAuthorization" }); await deleteMcpOAuthPendingAuthorization(a); }); } //#endregion export { completeMcpOAuthAuthorization as a, readMcpOAuthCredentialsStatus as c, resolveMcpOAuthAccessToken as d, startMcpOAuthAuthorization as f, clearMcpOAuthServer as i, readMcpOAuthCredentialsStatuses as l, clearMcpOAuthCredentials as n, completeOAuthCallback as o, McpOAuthCredentialsRetainedError as p, clearMcpOAuthRequesters as r, countMcpOAuthPrincipals as s, cancelMcpOAuthAuthorization as t, recordMcpOAuthAuthorizationRequired as u };