UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

1,277 lines (1,276 loc) • 46.5 kB
import { o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs"; import { o as asDateTimestampMs } from "./number-coercion-D6u-4YD8.mjs"; import { p as toErrorObject } from "./error-coercion-hDrHOSGy.mjs"; import { _ as secretRefKey } from "./ref-contract-b8L-9DrQ.mjs"; import { g as parseSecretRef, p as normalizeSecretInputString } from "./types.secrets-BmNLLnHp.mjs"; import { o as racePromiseWithAbortSignal } from "./src-BPmQBLJp.mjs"; import "./abort-signal-D4Q6SEw7.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { r as normalizeProviderId } from "./provider-id-b5XGSf9C.mjs"; import { r as hasSqliteWorkerOutcomeUnknown } from "./sqlite-worker-error-DEIJgRIz.mjs"; import { s as retainCurrentWorkerNativeSection } from "./worker-task-native-sections-DlSNoZRe.mjs"; import "./sqlite-worker-contract--dxXkOty.mjs"; import { t as normalizeOptionalSecretInput } from "./normalize-secret-input-Cxkx67Fv.mjs"; import { G as getScopedAuthProfileEnv, I as OAUTH_REFRESH_CALL_TIMEOUT_MS, R as authProfilesLog, Y as resolveRuntimeAuthProfileAgentDir, d as isUserModelAuthProfileId } from "./user-model-account-authority-CRj924IP.mjs"; import { t as CLAUDE_CLI_PROFILE_ID } from "./profile-ids-B9fFWPvP.mjs"; import { t as continueAuthProfileAuthorization } from "./authorization-lifetime-qBbc4Xfj.mjs"; import { h as readRuntimeConfig } from "./runtime-snapshot-WbwbY5b7.mjs"; import { i as resolveProviderIdForAuth } from "./provider-auth-aliases-CgGlzANu.mjs"; import { t as KeyedAsyncQueue } from "./keyed-async-queue-DewLnYvW.mjs"; import { n as FILE_LOCK_TIMEOUT_ERROR_CODE } from "./file-lock-D9Tpq9ra.mjs"; import "./file-lock-B28znsON.mjs"; import { _ as observeCanonicalAuthProfileCredentials, a as isSafeToAdoptBootstrapOAuthIdentity, i as isSafeOAuthPostClaimSettlement, m as resolveOAuthMirrorDecision, n as hasMatchingOAuthIdentity, o as isSafeToAdoptMainStoreOAuthIdentity, r as isSafeOAuthOwnerRefreshResult } from "./oauth-shared-gvo_ItCc.mjs"; import { a as isPendingOAuthRefreshFence, i as isOAuthRefreshFence, n as createOAuthRefreshFence, o as isSameOAuthRefreshGeneration, t as createFailedOAuthRefreshFence } from "./oauth-refresh-marker-Bm1Qb0ET.mjs"; import { a as resolveTokenExpiryState, n as evaluateStoredCredentialEligibility, r as hasUsableOAuthCredential } from "./credential-state-BiAE74F8.mjs"; import { b as resolveAuthProfileDatabasePath } from "./sqlite-B2CoJ4Om.mjs"; import { c as resolveOAuthRefreshLockPath, d as resolveSharedAuthStorePath } from "./path-resolve-CpNl_n1M.mjs"; import { N as updateRuntimeAuthProfileStoreSnapshot, d as getRuntimeAuthProfileStoreSnapshotCore } from "./runtime-snapshots-1lyYKb7Y.mjs"; import { c as findActiveDegradedSecretOwner, n as SecretSurfaceUnavailableError } from "./runtime-degraded-state-BSnwk5PQ.mjs"; import { d as isTransientOAuthRefreshFailure, f as markOAuthRefreshFailureSettled, i as appendOAuthRefreshCleanupErrors, n as OAuthRefreshFailureError, r as OAuthRefreshOwnerError, t as OAuthManagerRefreshError, u as isSettledOAuthRefreshFailure } from "./oauth-refresh-failure-DxrQiYzV.mjs"; import "./config-CMA-J084.mjs"; import { c as isSetupCredentialAccessible, s as getSetupCredentialRuntimeProfile } from "./order-jOvee2J6.mjs"; import { _ as runAuthProfileUsage, b as withPersonalAuthProfileStore } from "./store-Bh2lUvOT.mjs"; import { i as readExternalCliBootstrapCredential, n as isPersistedExternalCliAuthProfile } from "./external-cli-sync-_MwEKD82.mjs"; import { C as updateAuthProfileStoreWithLock, _ as prepareAuthProfileCredentialRead, c as ensureAuthProfileStoreWithoutExternalProfilesAsync, f as loadAuthProfileStoreForRuntimeAsync, g as loadAuthProfileStoreWithoutExternalProfilesAsync, y as resolvePersistedAuthProfileOwnerAgentDirAsync } from "./store-runtime-dW0pXLJI.mjs"; import { i as OAuthProviderConfiguredUnavailableError, n as getOAuthApiKey, r as getOAuthProviders } from "./oauth-B28cNmEb.mjs"; import "./worker-DIQLdOUL.mjs"; import { c as observeOAuthRefreshFenceSettlement, l as observeOAuthRefreshSettlement, o as isExactOAuthCredential } from "./paths-BSElhsGi.mjs"; import { c as resolveProviderOAuthRefreshCapabilityWithPlugin, n as buildProviderAuthDoctorHintWithPlugin, r as formatProviderAuthProfileApiKeyWithPlugin, s as resolveProviderOAuthCredentialWithPlugin } from "./provider-runtime.runtime.js"; import { n as resolveEffectiveOAuthCredentialCore } from "./effective-oauth-BmGrO0m8.mjs"; import { n as resolveAuthProfileSecretOwnerId } from "./runtime-auth-profile-owner-BEs73a-p.mjs"; import { _ as settleOAuthRefreshPeerClaims, b as withOAuthProfileLock, f as OAuthRefreshPeerFenceError, g as rollbackOAuthRefreshPeerClaims, h as mergeOAuthRefreshPeerClaims, m as fenceOAuthRefreshPeers, p as failOAuthRefreshPeerClaims, t as clearLastGoodProfileWithLock } from "./profiles-DbLHYG1P.mjs"; import { t as assertNoOAuthSecretRefPolicyViolations } from "./policy-Rsd3YRyO.mjs"; import { n as suggestOAuthProfileIdForLegacyDefault } from "./repair-O0s3O0SG.mjs"; import { isDeepStrictEqual } from "node:util"; //#region src/agents/auth-profiles/doctor.ts /** * Provider-specific auth doctor hints. * Adds local migration guidance for known legacy profiles before falling back * to provider plugin doctor copy. */ const QWEN_PORTAL_OAUTH_MIGRATION_HINT = "Legacy Qwen Portal OAuth profiles are not refreshable. Re-authenticate with a current Qwen API key: openclaw onboard --auth-choice qwen-api-key."; function hasLegacyQwenPortalOAuthProfile(e, t) { return (t ? [e.profiles[t]] : Object.values(e.profiles)).some((e) => e?.type === "oauth" && normalizeProviderId(e.provider) === "qwen-portal"); } /** Formats provider-specific auth doctor guidance for a profile/store. */ async function formatAuthDoctorHint(e) { const t = normalizeProviderId(e.provider); if (t === "qwen-portal" && hasLegacyQwenPortalOAuthProfile(e.store, e.profileId)) return QWEN_PORTAL_OAUTH_MIGRATION_HINT; const n = await buildProviderAuthDoctorHintWithPlugin({ provider: t, context: { config: e.cfg, store: e.store, provider: t, profileId: e.profileId } }); return typeof n === "string" && n.trim() ? n : ""; } //#endregion //#region src/agents/auth-profiles/oauth-provider-operations.ts const OAUTH_PROVIDER_IDS = new Set(getOAuthProviders().map((e) => e.id)); async function refreshOAuthCredential(e, t = {}) { const n = await resolveProviderOAuthCredentialWithPlugin({ provider: e.provider, config: t.cfg, credential: e, refresh: true }); if (n.status === "available") return n.credential; if (n.status === "configured-unavailable") throw new OAuthProviderConfiguredUnavailableError(e.provider); if (!OAUTH_PROVIDER_IDS.has(e.provider)) return null; return (await getOAuthApiKey(e.provider, { [e.provider]: e }))?.newCredentials ?? null; } async function buildOAuthApiKey(e, t) { const n = await formatProviderAuthProfileApiKeyWithPlugin({ provider: e.provider, config: t, context: e }); return typeof n === "string" && n.length > 0 ? n : e.access; } async function canRefreshOAuthCredential(e, t) { const n = await resolveProviderOAuthRefreshCapabilityWithPlugin({ provider: e, config: t }); if (n.status === "available") return true; if (n.status === "configured-unavailable") throw new OAuthProviderConfiguredUnavailableError(e); return OAUTH_PROVIDER_IDS.has(e); } //#endregion //#region src/agents/auth-profiles/oauth-refresh-lock-errors.ts function isGlobalRefreshLockTimeoutError(e, t) { const n = typeof e === "object" && e !== null ? e : void 0; return n?.code === "file_lock_timeout" && n.lockPath === `${t}.lock`; } function buildRefreshContentionError(e) { return Object.assign(new Error(`OAuth refresh failed (refresh_contention): another process is already refreshing ${e.provider} for ${e.profileId}. Please wait for the in-flight refresh to finish and retry.`, { cause: e.cause }), { code: "refresh_contention", cause: e.cause }); } //#endregion //#region src/agents/auth-profiles/oauth-refresh-observation.ts /** Keep the refresh owner alive until its durable claim settles or rolls back. */ function beginOAuthRefreshObservation() { return { finish: retainCurrentWorkerNativeSection() }; } //#endregion //#region src/agents/auth-profiles/oauth-refresh-queue.ts /** Serialize refreshes while sharing a settled transient failure only with waiting admissions. */ function createOAuthRefreshQueue() { const e = new KeyedAsyncQueue(); const t = /* @__PURE__ */ new Map(); return { enqueue(n, r, i) { const a = `${n}\u0000${r}`; let o = t.get(a); if (!o) { const e = /* @__PURE__ */ new Map(); const n = { pending: 0, assertNoFailure(t, n) { const r = e.get(t); if (r && isExactOAuthCredential(n, r.credential)) throw r.error; }, fail(t, r, i) { e.set(t, { credential: r, error: i }); n.retire(); }, retire() { if (t.get(a) === n) t.delete(a); } }; t.set(a, n); o = n; } const s = o; s.pending++; return e.enqueue(a, () => i(s), { onSettle() { if (--s.pending === 0) s.retire(); } }); } }; } //#endregion //#region src/agents/auth-profiles/oauth-store.ts function canReuseOAuthCredentialAfterRefreshFailure(e) { return !e.forceRefresh || e.attempted.provider === e.candidate.provider && e.attempted.access !== e.candidate.access && hasMatchingOAuthIdentity(e.attempted, e.candidate); } async function adoptNewerMainOAuthCredential(e) { if (!e.agentDir || isUserModelAuthProfileId(e.profileId)) return null; try { const t = (await ensureAuthProfileStoreWithoutExternalProfilesAsync(void 0, { allowKeychainPrompt: false })).profiles[e.profileId]; if (t?.type !== "oauth") return null; const n = asDateTimestampMs(t.expires); const r = asDateTimestampMs(e.credential.expires); if (t.provider === e.credential.provider && hasUsableOAuthCredential(t) && n !== void 0 && (r === void 0 || n > r) && isSafeToAdoptMainStoreOAuthIdentity(e.credential, t)) return t; } catch (t) { authProfilesLog.debug("adoptNewerMainOAuthCredential failed", { profileId: e.profileId, error: formatErrorMessage(t) }); } return null; } /** Validate and mirror the current shared credential before peer settlement. */ async function resolveAuthoritativeSharedOAuthCredentialUnderLock(e) { let t = false; const acceptAuthoritative = (n) => { try { validateSettlementCredential(e.validateCredential, n); t = true; return true; } catch { authProfilesLog.warn("refused shared OAuth credential during settlement: credential validation failed", { profileId: e.profileId }); return false; } }; const n = await updateAuthProfileStoreWithLock({ agentDir: void 0, profileId: e.profileId, sharedStoreWrite: true, updater: (n) => { const r = n.profiles[e.profileId]; const i = resolveOAuthMirrorDecision({ existing: r, refreshed: e.candidate }); if (i !== "mirror") { if (i === "identity-mismatch-or-regression") authProfilesLog.warn("refused to mirror OAuth credential: identity mismatch or regression", { profileId: e.profileId }); if (i === "incoming-not-fresher" && r?.type === "oauth") acceptAuthoritative(r); return false; } if (r?.type === "oauth" && !acceptAuthoritative(r)) return false; n.profiles[e.profileId] = { ...e.candidate }; t = true; return true; } }); if (n === null) throw new Error("Failed to read authoritative shared OAuth credential"); if (!t) return; const r = n.profiles[e.profileId]; return r?.type === "oauth" ? r : void 0; } async function loadStoredOAuthRefreshStore(e, t, n) { if (n) return n.read(); return loadAuthProfileStoreWithoutExternalProfilesAsync(e, { allowKeychainPrompt: true, profileId: t }); } async function updateOAuthStore(e) { return e.personalStore ? e.personalStore.update(e.updater, e.assertCurrent) : updateAuthProfileStoreWithLock(e); } /** Claim against the persisted credential, which may differ from an adopted bootstrap token. */ async function persistOAuthRefreshClaim(e) { let t = false; return await updateOAuthStore({ personalStore: e.personalStore, agentDir: e.agentDir, profileId: e.profileId, assertCurrent: e.assertCurrent, updater: (n) => { e.assertAdmission?.(); if (!isExactOAuthCredential(n.profiles[e.profileId], e.expected)) return false; n.profiles[e.profileId] = continueAuthProfileAuthorization(e.expected, e.fence); t = true; return true; } }) !== null && t; } async function settleOAuthRefreshClaim(e) { const t = (await loadStoredOAuthRefreshStore(e.agentDir, e.profileId, e.personalStore)).profiles[e.profileId]; if (t?.type === "oauth" && !isExactOAuthCredential(t, e.fence) && isSafeOAuthPostClaimSettlement(e.generation, t)) return { credential: t, persisted: false }; let n = null; let r = false; return await updateOAuthStore({ personalStore: e.personalStore, assertCurrent: () => e.validateCredential?.(e.refreshed), agentDir: e.agentDir, profileId: e.profileId, updater: (t) => { const i = t.profiles[e.profileId]; if (i?.type !== "oauth") return false; if (isExactOAuthCredential(i, e.fence)) { t.profiles[e.profileId] = continueAuthProfileAuthorization(i, { ...e.refreshed }); n = e.refreshed; r = true; return true; } n = isSafeOAuthPostClaimSettlement(e.generation, i) ? i : null; return false; } }) === null || !n ? null : { credential: n, persisted: r }; } async function markOAuthRefreshClaimFailed(e) { if (await updateOAuthStore({ personalStore: e.personalStore, agentDir: e.agentDir, profileId: e.profileId, updater: (t) => { const n = t.profiles[e.profileId]; if (!isExactOAuthCredential(n, e.settledCredential ?? e.fence)) return false; t.profiles[e.profileId] = createFailedOAuthRefreshFence(e.fence); return true; } }) === null) throw new Error("Failed to persist terminal OAuth refresh fence"); } async function rollbackOAuthRefreshOwnerClaim(e) { let t = false; if (await updateOAuthStore({ personalStore: e.personalStore, agentDir: e.ownerAgentDir, profileId: e.profileId, assertCurrent: e.assertCurrent, updater: (n) => { const r = n.profiles[e.profileId]; if (!isExactOAuthCredential(r, e.fence)) return false; n.profiles[e.profileId] = continueAuthProfileAuthorization(e.fence, { ...e.original }); t = true; return true; } }) !== null && t) return; await markOAuthRefreshClaimFailed({ personalStore: e.personalStore, agentDir: e.ownerAgentDir, profileId: e.profileId, fence: e.fence }); } async function buildValidatedOAuthAccess(e, t) { t.validateCredential?.(e); return { apiKey: await buildOAuthApiKey(t.personalStore ? structuredClone(e) : e, t.cfg), credential: t.personalStore ? await t.personalStore.accept(e, (e) => t.validateCredential?.(e)) : e }; } async function settleOAuthRefreshPeerClaimsUnderLock(e) { validateSettlementCredential(e.validateCredential, e.replacement); if (e.claim.personalStore) return; const t = e.claim.authPath === resolveSharedAuthStorePath() ? e.replacement : await resolveAuthoritativeSharedOAuthCredentialUnderLock({ profileId: e.claim.profileId, candidate: e.replacement, validateCredential: e.validateCredential }); await settleOAuthRefreshPeerClaims({ profileId: e.claim.profileId, fence: e.claim.fence, claims: e.claims, authoritativeSharedCredential: t, replacement: e.replacement }); } /** * A running Gateway owns shared credentials and their refresh. Another process uses a still-valid * token as is and refuses before any write; it never refreshes beside the owner. */ async function resolveOAuthAccessBesideStateOwner(e, t) { const { readActiveGatewayLockIdentity: n } = await import("./gateway-lock-C8DzJkpV.mjs"); const r = await n({ env: getScopedAuthProfileEnv() ?? process.env, includeEmbedded: true }); if (!r || r.pid === process.pid) return; if (!t.forceRefresh && hasUsableOAuthCredential(e, { refreshMarginMs: 0 })) return await buildValidatedOAuthAccess(e, t); const i = r.port ? `the Gateway (pid ${r.pid}, port ${r.port})` : `OpenClaw process ${r.pid}`; throw new OAuthRefreshOwnerError({ provider: e.provider, profileId: t.profileId, reason: null, message: `The ${e.provider} sign-in "${t.profileId}" needs a refresh, but ${i} owns the shared credentials and only it may refresh them. No credential was changed. Run this through the Gateway, retry after its next turn refreshes the sign-in, or stop the Gateway through its service owner and rerun this command.` }); } /** Restore completed transient work; observer timeouts never enter this rollback. */ async function rollbackTransientOAuthRefreshClaim(e, t, n) { n(); const r = []; try { await rollbackOAuthRefreshPeerClaims({ profileId: e.profileId, fence: e.fence, claims: t, assertCurrent: n }); } catch (e) { r.push(e); } try { await rollbackOAuthRefreshOwnerClaim({ personalStore: e.personalStore, ownerAgentDir: e.ownerAgentDir, profileId: e.profileId, fence: e.fence, original: e.storedCredential, assertCurrent: n }); } catch (t) { r.push(t); try { await markOAuthRefreshClaimFailed({ personalStore: e.personalStore, agentDir: e.ownerAgentDir, profileId: e.profileId, fence: e.fence }); } catch (e) { r.push(e); } } return r; } var OAuthSettlementCredentialValidationError = class extends Error { constructor(e, t = []) { const n = toErrorObject(e, "OAuth credential validation failed"); super(n.message, { cause: appendOAuthRefreshCleanupErrors(n, t) }); this.name = "OAuthSettlementCredentialValidationError"; } }; function validateSettlementCredential(e, t) { try { e?.(t); } catch (e) { throw new OAuthSettlementCredentialValidationError(e); } } //#endregion //#region src/agents/auth-profiles/oauth-manager.ts const oauthRefreshRecoveryBuildFailures = /* @__PURE__ */ new WeakSet(); /** Create an independent OAuth refresh queue using the native provider operations. */ function createOAuthManager() { const e = createOAuthRefreshQueue(); async function claimOAuthRefresh(e) { const t = isUserModelAuthProfileId(e.profileId); const n = t ? void 0 : await resolvePersistedAuthProfileOwnerAgentDirAsync(e); const r = e.personalStore?.databasePath ?? (n ? resolveAuthProfileDatabasePath(n) : resolveSharedAuthStorePath()); const i = resolveOAuthRefreshLockPath(e.provider, e.profileId); const a = e.cfg ?? {}; const failTerminalPeers = async (n) => { const i = t ? [] : await fenceOAuthRefreshPeers({ cfg: a, ownerDatabasePath: r, profileId: e.profileId, generation: n, fence: n }); await failOAuthRefreshPeerClaims({ profileId: e.profileId, fence: n, claims: i }); }; let o; let s = false; try { const i = await withOAuthProfileLock({ provider: e.provider, profileId: e.profileId }, async () => { e.signal?.throwIfAborted(); const i = (await loadStoredOAuthRefreshStore(n, e.profileId, e.personalStore)).profiles[e.profileId]; if (!i || i.type !== "oauth" || i.provider !== e.provider) return { kind: "unavailable" }; const s = isOAuthRefreshFence(i); if (!s) e.validateCredential?.(i); let c = i; if (!s && !t && isPersistedExternalCliAuthProfile({ profileId: e.profileId, credential: i })) { authProfilesLog.warn("refused native OAuth refresh for an externally owned credential", { profileId: e.profileId, provider: i.provider }); return { kind: "unavailable" }; } if (e.forceRefresh && hasUsableOAuthCredential(i) && canReuseOAuthCredentialAfterRefreshFailure({ forceRefresh: true, attempted: e.attemptedCredential, candidate: i })) return { kind: "use", credential: i }; if (!s && !e.forceRefresh && hasUsableOAuthCredential(i)) return { kind: "use", credential: i }; if (!s && e.agentDir && !t) try { const t = (await loadStoredOAuthRefreshStore(void 0)).profiles[e.profileId]; if (n && t?.type === "oauth" && isSameOAuthRefreshGeneration({ profileId: e.profileId, left: i, right: t })) return { kind: "unavailable" }; if (t?.type === "oauth" && t.provider === i.provider && hasUsableOAuthCredential(t) && !e.forceRefresh && isSafeToAdoptMainStoreOAuthIdentity(i, t)) { e.validateCredential?.(t); authProfilesLog.info("adopted fresh OAuth credential from main store (under refresh lock)", { profileId: e.profileId, agentDir: e.agentDir, expires: new Date(t.expires).toISOString() }); return { kind: "use", credential: t }; } else if (t?.type === "oauth" && t.provider === i.provider && hasUsableOAuthCredential(t) && !isSafeToAdoptMainStoreOAuthIdentity(i, t)) authProfilesLog.warn("refused to adopt fresh main-store OAuth credential: identity mismatch", { profileId: e.profileId, agentDir: e.agentDir }); } catch (t) { authProfilesLog.debug("inside-lock main-store adoption failed; proceeding to refresh", { profileId: e.profileId, error: formatErrorMessage(t) }); } const l = !t && e.bootstrapCredential && e.bootstrapBaseCredential && isExactOAuthCredential(i, e.bootstrapBaseCredential) ? e.bootstrapCredential : null; if (l) { if (l.provider !== i.provider) authProfilesLog.warn("refused external oauth bootstrap credential: provider mismatch", { profileId: e.profileId, provider: i.provider }); else if (s || !isSafeToAdoptBootstrapOAuthIdentity(i, l)) authProfilesLog.warn("refused external oauth bootstrap credential: fenced or identity mismatch", { profileId: e.profileId, provider: i.provider }); else { c = l; e.validateCredential?.(c); if (!e.forceRefresh && hasUsableOAuthCredential(l)) return { kind: "use", credential: l }; } } if (s && c === i) { if (isPendingOAuthRefreshFence(i)) return { kind: "observe", ownerAgentDir: n, generation: i }; await failTerminalPeers(i); return { kind: "unavailable" }; } if (normalizeSecretInputString(c.refresh) === void 0) return { kind: "unavailable" }; if (!await canRefreshOAuthCredential(c.provider, e.cfg)) return { kind: "unavailable" }; const u = await e.personalStore?.captureRefreshAuthority(); e.signal?.throwIfAborted(); u?.(); e.cohort.assertNoFailure(r, c); const d = createOAuthRefreshFence({ profileId: e.profileId, credential: c }); o = beginOAuthRefreshObservation(); if (!await persistOAuthRefreshClaim({ personalStore: e.personalStore, assertAdmission: e.assertRefreshAdmission, assertCurrent: () => { e.signal?.throwIfAborted(); u?.(); e.validateCredential?.(c); }, agentDir: n, profileId: e.profileId, expected: i, fence: d })) { const t = (await loadStoredOAuthRefreshStore(n, e.profileId, e.personalStore)).profiles[e.profileId]; if (t?.type !== "oauth" || t.provider !== e.provider) return { kind: "unavailable" }; if (!isOAuthRefreshFence(t)) e.validateCredential?.(t); if (isPendingOAuthRefreshFence(t)) return { kind: "observe", ownerAgentDir: n, generation: t }; if (isOAuthRefreshFence(t)) { await failTerminalPeers(t); return { kind: "unavailable" }; } return hasUsableOAuthCredential(t) ? { kind: "use", credential: t } : { kind: "unavailable" }; } let f = []; const p = !t && c === i ? i : void 0; try { if (!t && p) f = await fenceOAuthRefreshPeers({ cfg: a, ownerDatabasePath: r, profileId: e.profileId, generation: p, fence: d, rollbackOnFailure: false }); } catch (t) { if (t instanceof OAuthRefreshPeerFenceError) f = mergeOAuthRefreshPeerClaims(f, t.claims); const r = []; try { await rollbackOAuthRefreshPeerClaims({ profileId: e.profileId, fence: d, claims: f }); } catch (e) { r.push(e); } try { await rollbackOAuthRefreshOwnerClaim({ personalStore: e.personalStore, ownerAgentDir: n, profileId: e.profileId, fence: d, original: i }); } catch (e) { r.push(e); } if (r.length > 0) throw new AggregateError([t, ...r], "Failed to claim OAuth refresh ownership and roll back partial claims.", { cause: t }); throw t; } return { kind: "claimed", personalStore: e.personalStore, profileId: e.profileId, credential: c, storedCredential: i, assertPersonalRefreshCurrent: u, fence: d, ownerAgentDir: n, authPath: r, peerClaims: f, ...p ? { peerGeneration: p } : {}, observation: o }; }); s = i.kind === "claimed"; return i; } catch (t) { if (isGlobalRefreshLockTimeoutError(t, i)) throw buildRefreshContentionError({ provider: e.provider, profileId: e.profileId, cause: t }); throw t; } finally { if (!s) o?.finish(); } } async function refreshOAuthTokenWithLock(e) { e.signal?.throwIfAborted(); const t = await claimOAuthRefresh(e); if (t.kind === "unavailable") return null; if (t.kind === "observe") return await observeOAuthRefreshFenceSettlement({ label: `refreshOAuthCredential(${e.provider})`, timeoutMs: OAUTH_REFRESH_CALL_TIMEOUT_MS, signal: e.signal, read: async () => (await loadStoredOAuthRefreshStore(t.ownerAgentDir, e.profileId, e.personalStore)).profiles[e.profileId], isPending: (e) => e?.type === "oauth" && e.provider === t.generation.provider && isPendingOAuthRefreshFence(e), resolve: async (n) => { if (n?.type !== "oauth" || !isSafeOAuthPostClaimSettlement(t.generation, n)) return null; return await buildValidatedOAuthAccess(n, e); } }); if (t.kind === "use") return await buildValidatedOAuthAccess(t.credential, e); e.attemptedCredentials?.push(t.credential); const n = e.cfg ?? {}; let r = t.peerClaims; const failPeers = async (n) => { try { await failOAuthRefreshPeerClaims({ profileId: e.profileId, fence: t.fence, claims: r }); } catch (e) { n(e); } }; const rediscoverPeerClaims = async (i) => { try { r = mergeOAuthRefreshPeerClaims(r, await fenceOAuthRefreshPeers({ cfg: n, ownerDatabasePath: t.authPath, profileId: e.profileId, generation: i, fence: t.fence, rollbackOnFailure: false })); } catch (e) { if (e instanceof OAuthRefreshPeerFenceError) r = mergeOAuthRefreshPeerClaims(r, e.claims); throw e; } }; const assertCurrent = () => validateSettlementCredential(() => { t.assertPersonalRefreshCurrent?.(); e.validateCredential?.(t.credential); }, t.credential); const failClaim = async (n, i) => { let a = { supersedingOwner: null, validationError: null, cleanupErrors: [] }; try { await withOAuthProfileLock({ provider: e.provider, profileId: e.profileId }, async () => { const o = []; let s = null; let c = null; try { const r = n ? (await loadStoredOAuthRefreshStore(t.ownerAgentDir, e.profileId, e.personalStore)).profiles[e.profileId] : void 0; if (i) assertCurrent(); s = r?.type === "oauth" && !isExactOAuthCredential(r, t.fence) && isSafeOAuthPostClaimSettlement(t.credential, r) && canReuseOAuthCredentialAfterRefreshFailure({ forceRefresh: e.forceRefresh, attempted: t.credential, candidate: r }) ? r : null; } catch (e) { o.push(e); } if (n && t.peerGeneration) try { await rediscoverPeerClaims(t.peerGeneration); } catch (e) { o.push(e); } if (s && o.length === 0) try { await settleOAuthRefreshPeerClaimsUnderLock({ claim: t, claims: r, replacement: s, validateCredential: e.validateCredential }); a = { supersedingOwner: s, validationError: c, cleanupErrors: o }; return; } catch (e) { if (e instanceof OAuthSettlementCredentialValidationError) c = e; else o.push(e); } if (i && !c) try { o.push(...await rollbackTransientOAuthRefreshClaim(t, r, assertCurrent)); a = { supersedingOwner: null, validationError: c, cleanupErrors: o }; return; } catch (e) { if (e instanceof OAuthSettlementCredentialValidationError) c = e; else o.push(e); } await failPeers((e) => o.push(e)); try { await markOAuthRefreshClaimFailed({ personalStore: e.personalStore, agentDir: t.ownerAgentDir, profileId: e.profileId, fence: t.fence }); } catch (e) { o.push(e); } a = { supersedingOwner: null, validationError: c, cleanupErrors: o }; }); return a; } catch (e) { return { supersedingOwner: null, validationError: a.validationError, cleanupErrors: [...a.cleanupErrors, e] }; } }; const settleFailure = async (n) => { const r = n ? toErrorObject(n.error, "OAuth refresh failed") : void 0; const i = n?.externalRefresh === true && isTransientOAuthRefreshFailure(n.error); const { supersedingOwner: a, validationError: o, cleanupErrors: s } = await failClaim(n?.rediscoverPeers !== false, i); if (o) throw new OAuthSettlementCredentialValidationError(o, s); if (a) try { return await buildValidatedOAuthAccess(a, e); } catch (e) { const t = r !== void 0 ? appendOAuthRefreshCleanupErrors(r, [...s, e]) : appendOAuthRefreshCleanupErrors(e, s); oauthRefreshRecoveryBuildFailures.add(t); throw t; } if (r !== void 0) { const a = appendOAuthRefreshCleanupErrors(r, s); if (n?.externalRefresh && s.length === 0) { const n = new OAuthRefreshFailureError({ provider: e.provider, profileId: e.profileId, message: a.message, cause: a, retryable: i }); markOAuthRefreshFailureSettled(n, a); if (i) e.cohort.fail(t.authPath, t.credential, n); throw n; } throw a; } if (s.length === 0) return null; throw appendOAuthRefreshCleanupErrors(s[0], s.slice(1)); }; const i = runAuthProfileUsage(async () => { let n; try { n = await refreshOAuthCredential(e.personalStore ? structuredClone(t.credential) : t.credential, { cfg: e.cfg }); } catch (e) { return await settleFailure({ error: e, externalRefresh: true }); } if (!n) return await settleFailure(); try { const i = { ...t.credential, ...e.personalStore ? structuredClone(n) : n, type: "oauth" }; if (!hasUsableOAuthCredential(i, { refreshMarginMs: 0 })) throw new Error("OAuth refresh returned an unusable credential"); if (!isSafeOAuthOwnerRefreshResult(t.credential, i)) throw new Error("OAuth refresh returned credentials for a different OAuth account"); e.validateCredential?.(i); const a = await withOAuthProfileLock({ provider: e.provider, profileId: e.profileId }, async () => { if (t.peerGeneration) await rediscoverPeerClaims(t.peerGeneration); const n = await settleOAuthRefreshClaim({ personalStore: e.personalStore, agentDir: t.ownerAgentDir, profileId: e.profileId, generation: t.credential, fence: t.fence, refreshed: i, validateCredential: e.validateCredential }); if (!n) return null; try { await settleOAuthRefreshPeerClaimsUnderLock({ claim: t, claims: r, replacement: n.credential, validateCredential: e.validateCredential }); } catch (r) { if (r instanceof OAuthSettlementCredentialValidationError) { const i = []; await failPeers((e) => i.push(e)); if (n.persisted) try { await markOAuthRefreshClaimFailed({ personalStore: e.personalStore, agentDir: t.ownerAgentDir, profileId: e.profileId, fence: t.fence, settledCredential: n.credential }); } catch (e) { i.push(e); } throw new OAuthSettlementCredentialValidationError(r, i); } await failPeers((t) => { authProfilesLog.warn("failed to terminally fence an OAuth refresh peer", { profileId: e.profileId, error: formatErrorMessage(t) }); }); authProfilesLog.warn("OAuth refresh peer settlement degraded", { profileId: e.profileId, error: formatErrorMessage(r) }); } return n; }); if (!a) throw new Error("Failed to persist refreshed OAuth credential"); if (!e.personalStore) observeCanonicalAuthProfileCredentials(t.authPath, { [e.profileId]: a.credential }); return await buildValidatedOAuthAccess(a.credential, e); } catch (e) { if (e instanceof OAuthRefreshPeerFenceError && hasSqliteWorkerOutcomeUnknown(e)) return await settleFailure({ error: e, rediscoverPeers: false }); if (e instanceof OAuthSettlementCredentialValidationError || hasSqliteWorkerOutcomeUnknown(e)) throw e; return await settleFailure({ error: e }); } }); i.then(t.observation.finish, t.observation.finish); return await observeOAuthRefreshSettlement(`refreshOAuthCredential(${t.credential.provider})`, OAUTH_REFRESH_CALL_TIMEOUT_MS, i, e.signal); } async function resolveOAuthAccess(e) { e.signal?.throwIfAborted(); if (!isUserModelAuthProfileId(e.profileId)) return resolveOwnedOAuthAccess(e); const t = e.validateCredential; const n = { ...e, validateCredential: t ? (e) => t(structuredClone(e)) : void 0 }; const resolve = (e) => resolveOwnedOAuthAccess({ ...n, personalStore: e }); return n.personalStore ? resolve(n.personalStore) : await withPersonalAuthProfileStore(n.profileId, async (e) => { await e.read(); return resolve(e); }) ?? null; } async function resolveOwnedOAuthAccess(t) { t.signal?.throwIfAborted(); const n = isUserModelAuthProfileId(t.profileId); let r = t.credential; if (t.personalStore) { const e = t.personalStore.readCurrentCredential(); if (e?.type !== "oauth") return null; r = e; } const i = await adoptNewerMainOAuthCredential({ profileId: t.profileId, agentDir: t.agentDir, credential: r }); if (i) { t.validateCredential?.(i); t.store.profiles[t.profileId] = { ...i }; authProfilesLog.info("adopted newer OAuth credentials from main agent", { profileId: t.profileId, agentDir: t.agentDir, expires: new Date(i.expires).toISOString() }); } const a = i ?? r; const o = n ? null : readExternalCliBootstrapCredential({ profileId: t.profileId, credential: a }); const s = resolveEffectiveOAuthCredentialCore({ profileId: t.profileId, credential: a, readBootstrapCredential: () => o }); const c = []; if (!t.forceRefresh && !isOAuthRefreshFence(a) && hasUsableOAuthCredential(s)) return await buildValidatedOAuthAccess(s, t); const l = await resolveOAuthAccessBesideStateOwner(s, t); if (l) return l; try { const n = runAuthProfileUsage(() => e.enqueue(r.provider, t.profileId, (e) => refreshOAuthTokenWithLock({ ...t, cohort: e, provider: r.provider, attemptedCredential: s, attemptedCredentials: c, bootstrapCredential: o, bootstrapBaseCredential: a }))); const i = await racePromiseWithAbortSignal(n, t.signal); t.signal?.throwIfAborted(); return i; } catch (e) { t.signal?.throwIfAborted(); if (hasSqliteWorkerOutcomeUnknown(e)) throw e; let i = e; let a = i instanceof OAuthSettlementCredentialValidationError || i instanceof Error && oauthRefreshRecoveryBuildFailures.has(i); let o = t.store; let l = false; const buildRecoveryAccess = async (e) => { try { return await buildValidatedOAuthAccess(e, t); } catch (e) { i = appendOAuthRefreshCleanupErrors(i, [e]); a = true; return null; } }; try { o = await loadStoredOAuthRefreshStore(t.agentDir, t.profileId, t.personalStore); l = true; } catch (e) { i = appendOAuthRefreshCleanupErrors(i, [e]); } const u = c.at(-1) ?? s; const canRecover = (e) => e?.type === "oauth" && isSafeOAuthPostClaimSettlement(u, e) && canReuseOAuthCredentialAfterRefreshFailure({ forceRefresh: t.forceRefresh, attempted: u, candidate: e }); const d = o.profiles[t.profileId]; if (l && !a && canRecover(d)) { const e = await buildRecoveryAccess(d); if (e) return e; } if (l && t.agentDir && !n && !a) try { const e = (await ensureAuthProfileStoreWithoutExternalProfilesAsync(void 0, { allowKeychainPrompt: false })).profiles[t.profileId]; if (canRecover(e)) { t.validateCredential?.(e); o.profiles[t.profileId] = { ...e }; authProfilesLog.info("inherited fresh OAuth credentials from main agent", { profileId: t.profileId, agentDir: t.agentDir, expires: new Date(e.expires).toISOString() }); const n = await buildRecoveryAccess(e); if (n) return n; } } catch (e) { i = appendOAuthRefreshCleanupErrors(i, [e]); } throw new OAuthManagerRefreshError({ credential: r, attemptedCredentials: [s, ...c], profileId: t.profileId, refreshedStore: o, retryable: d?.type === "oauth" && isPendingOAuthRefreshFence(d) || isTransientOAuthRefreshFailure(i) && d?.type === "oauth" && !isOAuthRefreshFence(d), cause: i }); } } return { resolveOAuthAccess }; } //#endregion //#region src/agents/auth-profiles/oauth.ts /** * Auth profile API-key/OAuth runtime resolver. * Converts selected auth profiles into provider API keys, refreshes OAuth * credentials, resolves SecretRefs, and maintains runtime store snapshots. */ function isProfileConfigCompatible(e) { const t = e.cfg?.auth?.profiles?.[e.profileId]; return !t || t.provider === e.provider && (t.mode === e.mode || (t.mode === "oauth" || t.mode === "token") && (e.mode === "oauth" || e.mode === "token")); } function buildApiKeyProfileResult(e) { const t = { apiKey: e.apiKey, provider: e.provider, email: e.email }; for (const n of [ "profileId", "profileType", "credential", "readCurrentCredential" ]) Object.defineProperty(t, n, { value: n === "readCurrentCredential" ? e[n] ?? null : e[n], enumerable: false }); return t; } /** Detect provider errors caused by single-use OAuth refresh token races. */ function isRefreshTokenReusedError(e) { const t = normalizeLowercaseStringOrEmpty(formatErrorMessage(e)); return t.includes("refresh_token_reused") || t.includes("refresh token has already been used") || t.includes("already been used to generate a new access token"); } /** Refresh one OAuth credential and merge provider-returned token fields. */ async function refreshOAuthCredentialForRuntime(e) { const t = await refreshOAuthCredential(e.credential, { cfg: e.cfg }); return t ? { ...e.credential, ...t, type: "oauth" } : null; } const oauthManager = createOAuthManager(); async function resolveOAuthProfileAccess(e, t, n) { const r = !n && t.authFlow === "chatgpt-token-sharing" ? await prepareAuthProfileCredentialRead(e) : null; const i = await oauthManager.resolveOAuthAccess({ personalStore: n, store: e.store, profileId: e.profileId, credential: t, agentDir: e.agentDir, cfg: e.cfg, forceRefresh: e.forceRefresh, validateCredential: e.validateOAuthCredential, assertRefreshAdmission: e.assertRefreshAdmission, signal: e.signal }); return i ? buildApiKeyProfileResult({ apiKey: i.apiKey, provider: i.credential.provider, email: i.credential.email ?? t.email, profileId: e.profileId, profileType: t.type, credential: i.credential, readCurrentCredential: n?.readCurrentCredential ?? r }) : null; } async function tryResolveOAuthProfile(e) { const { cfg: t, store: n, profileId: r } = e; if (r === "anthropic:claude-cli") return null; const i = n.profiles[r]; if (!i || i.type !== "oauth" || !isSetupCredentialAccessible({ profileId: r, credential: i, agentDir: e.agentDir })) return null; if (!isProfileConfigCompatible({ cfg: t, profileId: r, provider: i.provider, mode: i.type })) return null; const a = await resolveOAuthProfileAccess(e, i); e.signal?.throwIfAborted(); return a; } function authProfileSecretRefKey(e, t) { const n = e.type === "api_key" ? parseSecretRef(e.keyRef, t) ?? parseSecretRef(e.key, t) : e.type === "token" ? parseSecretRef(e.tokenRef, t) ?? parseSecretRef(e.token, t) : null; return n ? secretRefKey(n) : void 0; } /** Resolve a selected auth profile into the provider API key string. */ async function resolveApiKeyForProfile(e) { const t = { ...e, agentDir: resolveRuntimeAuthProfileAgentDir(e.agentDir) }; e.signal?.throwIfAborted(); const n = isUserModelAuthProfileId(e.profileId) ? await withPersonalAuthProfileStore(e.profileId, (e) => resolveApiKeyForProfileOwned(t, e)) ?? null : await resolveApiKeyForProfileOwned(t); e.signal?.throwIfAborted(); return n; } async function resolveApiKeyForProfileOwned(e, t) { e.signal?.throwIfAborted(); const { cfg: n, store: r, profileId: i } = e; const a = t ? (await t.read()).profiles[i] : r.profiles[i]; e.signal?.throwIfAborted(); if (!a || !isSetupCredentialAccessible({ profileId: i, credential: a, agentDir: e.agentDir })) return null; if (i === "anthropic:claude-cli") return null; const o = n ?? readRuntimeConfig(); const s = o.secrets?.defaults; const c = e.agentDir; const l = getSetupCredentialRuntimeProfile({ agentDir: c, profileId: i, profile: a }); const u = l === void 0 ? getRuntimeAuthProfileStoreSnapshotCore(c)?.profiles[i] : l; const d = authProfileSecretRefKey(a, s); const f = u ? authProfileSecretRefKey(u, s) : void 0; const p = Boolean(u && (isDeepStrictEqual(u, a) || d && f === d && u.type === a.type && u.provider === a.provider)); let m = a; if (p && u?.type === "api_key" && a.type === "api_key") { const e = u.key; m = { ...a, key: e }; } else if (p && u?.type === "token" && a.type === "token") { const e = u.token; m = { ...a, token: e }; } if (!isProfileConfigCompatible({ cfg: n, profileId: i, provider: m.provider, mode: m.type })) return null; assertNoOAuthSecretRefPolicyViolations({ store: r, cfg: o, profileIds: [i], context: `auth profile ${i}` }); if (m.type === "api_key" || m.type === "token") { if (m.type === "api_key") { if (!evaluateStoredCredentialEligibility({ credential: m }).eligible) return null; } else { const e = resolveTokenExpiryState(m.expires); if (e === "expired" || e === "invalid_expires") return null; } const n = resolveAuthProfileSecretOwnerId(e); const r = findActiveDegradedSecretOwner("account", n); if (r && p) throw new SecretSurfaceUnavailableError(r); const a = m.type === "api_key" ? m.key : m.token; const o = authProfileSecretRefKey(m, s); const c = normalizeOptionalSecretInput(a); if (o && (!p || !c)) throw new SecretSurfaceUnavailableError({ ownerKind: "account", ownerId: n, state: "unavailable", paths: [`auth-profiles.${i}.${m.type === "api_key" ? "key" : "token"}`], refKeys: [o], reason: "secret reference was not materialized by the active runtime" }); if (!c) return null; return buildApiKeyProfileResult({ apiKey: c, provider: m.provider, email: m.email, profileId: i, profileType: m.type, readCurrentCredential: t?.readCurrentCredential }); } try { const n = await resolveOAuthProfileAccess(e, m, t); e.signal?.throwIfAborted(); return n; } catch (r) { e.signal?.throwIfAborted(); if (hasSqliteWorkerOutcomeUnknown(r) || r instanceof OAuthRefreshOwnerError) throw r; let a = isSettledOAuthRefreshFailure(r); let o = r instanceof OAuthManagerRefreshError ? r.getRefreshedStore() : t ? await t.read() : await loadAuthProfileStoreForRuntimeAsync(e.agentDir, { profileId: i, readOnly: true, allowKeychainPrompt: false }); const s = r instanceof OAuthManagerRefreshError && r.cause ? r.cause : r; if (isRefreshTokenReusedError(s)) { const n = await resolvePersistedAuthProfileOwnerAgentDirAsync({ agentDir: e.agentDir, profileId: i }); let r = false; try { await clearLastGoodProfileWithLock({ provider: m.provider, profileId: i, agentDir: n }); r = true; } catch (e) { a = false; authProfilesLog.warn("failed to clear stale OAuth last-good state after refresh failure", { error: formatErrorMessage(e) }); } const s = e.agentDir !== n ? getRuntimeAuthProfileStoreSnapshotCore(e.agentDir) : void 0; if (s) { const t = resolveProviderIdForAuth(m.provider); if (s.lastGood?.[t] === i) { delete s.lastGood[t]; if (Object.keys(s.lastGood).length === 0) s.lastGood = void 0; updateRuntimeAuthProfileStoreSnapshot(s, e.agentDir); } } if (r) o = t ? await t.read() : await loadAuthProfileStoreForRuntimeAsync(e.agentDir, { profileId: i, readOnly: true, allowKeychainPrompt: false }); } const c = e.allowProfileFallback === false ? null : suggestOAuthProfileIdForLegacyDefault({ cfg: n, store: o, provider: m.provider, legacyProfileId: i }); if (c && c !== i) try { const t = await tryResolveOAuthProfile({ cfg: n, store: o, profileId: c, agentDir: e.agentDir, forceRefresh: e.forceRefresh, validateOAuthCredential: e.validateOAuthCredential, assertRefreshAdmission: e.assertRefreshAdmission, signal: e.signal }); e.signal?.throwIfAborted(); if (t) return t; } catch { e.signal?.throwIfAborted(); } const l = formatErrorMessage(s); const u = r instanceof OAuthRefreshFailureError && r.retryable === true; const d = u ? void 0 : await formatAuthDoctorHint({ cfg: n, store: o, provider: m.provider, profileId: i }); const f = new OAuthRefreshFailureError({ provider: m.provider, profileId: i, message: `OAuth token refresh failed for ${m.provider}: ${l}. ` + (u ? "Please try again shortly." : "Please try again or re-authenticate.") + (d ? `\n\n${d}` : ""), cause: r }); if (a) markOAuthRefreshFailureSettled(f); throw f; } } //#endregion export { resolveApiKeyForProfile as n, formatAuthDoctorHint as r, refreshOAuthCredentialForRuntime as t };