UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

670 lines (669 loc) • 25 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { A as resolveExpiresAtMsFromDurationMs, o as asDateTimestampMs } from "./number-coercion-D6u-4YD8.mjs"; import { i as resolveOsHomeRelativePath } from "./home-dir-EKmgmdPG.mjs"; import { a as asOptionalRecord, l as isRecord, t as asNonArrayRecord } from "./record-coerce-CVPuDqcc.mjs"; import { a as extractErrorCode } from "./error-coercion-hDrHOSGy.mjs"; import { t as loadJsonFileThroughSymlink } from "./json-file-Dp3xU7Al.mjs"; import fs from "node:fs"; import path from "node:path"; import { createHash, createHmac, randomBytes } from "node:crypto"; import { userInfo } from "node:os"; import { execSync } from "node:child_process"; //#region src/plugin-sdk/provider-auth-claude-compat.ts const CLAUDE_CLI_CREDENTIALS_FILE = ".credentials.json"; const CLAUDE_CLI_USER_SETTINGS_FILE = "settings.json"; const CLAUDE_MANAGED_SETTINGS_FILE = "managed-settings.json"; const CLAUDE_MANAGED_SETTINGS_DROP_IN_DIR = "managed-settings.d"; const CLAUDE_CLI_KEYCHAIN_SERVICE = "Claude Code-credentials"; const CLAUDE_CLI_KEYCHAIN_TIMEOUT_MS = 2e3; const CLAUDE_CLI_KEYCHAIN_ACCOUNT_FALLBACK = "claude-code-user"; const MACOS_SECURITY_PATH = "/usr/bin/security"; const CLAUDE_NON_NATIVE_AUTH_ENV_KEYS = [ "ANTHROPIC_API_KEY", "ANTHROPIC_API_TOKEN", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_OAUTH_TOKEN", "CLAUDE_CODE_OAUTH_REFRESH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN", "CLAUDE_CODE_OAUTH_TOKEN_FILE_DESCRIPTOR", "CLAUDE_CODE_API_KEY_FILE_DESCRIPTOR", "CLAUDE_CODE_USE_BEDROCK", "CLAUDE_CODE_USE_VERTEX", "CLAUDE_CODE_USE_FOUNDRY", "ANTHROPIC_UNIX_SOCKET" ]; const SAFE_KEYCHAIN_ACCOUNT_PATTERN = /^[a-zA-Z0-9._-]+$/u; let claudeCliCache = null; function resolveClaudeCliConfigDir(e, t = process.env) { if (e !== void 0) return path.join(resolveOsHomeRelativePath(e, { env: t }), ".claude"); const n = t.CLAUDE_CONFIG_DIR; return n ? path.resolve(n) : path.join(resolveOsHomeRelativePath("~", { env: t }), ".claude"); } function resolveClaudeCliPath(e, t, n = process.env) { return path.join(resolveClaudeCliConfigDir(e, n), t); } function resolveClaudeCliCredentialsPath(e, t = process.env) { if (e !== void 0) return path.join(resolveClaudeCliConfigDir(e, t), CLAUDE_CLI_CREDENTIALS_FILE); const n = t.CLAUDE_SECURESTORAGE_CONFIG_DIR; if (n === void 0) return resolveClaudeCliPath(void 0, CLAUDE_CLI_CREDENTIALS_FILE, t); const r = n ? path.resolve(n) : path.join(resolveOsHomeRelativePath("~", { env: t }), ".claude"); return path.join(r, CLAUDE_CLI_CREDENTIALS_FILE); } function resolveClaudeCliAccountPath(e) { if (e !== void 0) return path.join(resolveOsHomeRelativePath(e), ".claude.json"); const t = process.env.CLAUDE_CONFIG_DIR; return t ? path.join(path.resolve(t), ".claude.json") : path.join(resolveOsHomeRelativePath("~"), ".claude.json"); } function resolveClaudeCliKeychainService(e, t = process.env) { if (e !== void 0) return CLAUDE_CLI_KEYCHAIN_SERVICE; const n = t.CLAUDE_SECURESTORAGE_CONFIG_DIR; const r = t.CLAUDE_CONFIG_DIR; const i = n !== void 0 ? n : r; if (!i) return CLAUDE_CLI_KEYCHAIN_SERVICE; const a = createHash("sha256").update(i.normalize("NFC")).digest("hex").slice(0, 8); return `${CLAUDE_CLI_KEYCHAIN_SERVICE}-${a}`; } function readFileMtimeMs$1(e) { try { return fs.statSync(e).mtimeMs; } catch { return null; } } function parseClaudeCliOauthCredential(e) { if (!e || typeof e !== "object") return null; const t = asNonArrayRecord(e); const n = t.accessToken; const r = t.refreshToken; const i = t.expiresAt; if (typeof n !== "string" || !n || typeof i !== "number" || !Number.isFinite(i) || i <= 0) return null; const a = normalizeOptionalString(t.subscriptionType); const o = normalizeOptionalString(t.rateLimitTier); const s = { ...a ? { subscriptionType: a } : {}, ...o ? { rateLimitTier: o } : {} }; return typeof r === "string" && r ? { type: "oauth", provider: "anthropic", access: n, refresh: r, expires: i, ...s } : { type: "token", provider: "anthropic", token: n, expires: i, ...s }; } function readClaudeAccountEmail(e) { const t = loadJsonFileThroughSymlink(resolveClaudeCliAccountPath(e)); const n = asNonArrayRecord(t).oauthAccount; const r = asNonArrayRecord(n).emailAddress; return normalizeOptionalString(r); } /** Anthropic's account lookup for a Claude OAuth access token, the one Claude CLI itself uses. */ const CLAUDE_OAUTH_PROFILE_URL = "https://api.anthropic.com/api/oauth/profile"; const CLAUDE_OAUTH_PROFILE_TIMEOUT_MS = 3e3; const CLAUDE_NATIVE_LOGIN_REFRESH_MARGIN_MS = 6e5; const CLAUDE_NATIVE_LOGIN_ATTESTATION_LIMIT = 64; const claudeNativeLoginAttestationKey = randomBytes(32); const claudeNativeLoginAttestations = /* @__PURE__ */ new Map(); function fingerprintClaudeNativeLoginToken(e) { return createHmac("sha256", claudeNativeLoginAttestationKey).update(e).digest("hex"); } /** * Owner of the login a local `claude` process would use, as Anthropic attested it for the * exact access token it reads (Keychain, then the credentials file), or undefined when no * attestation in this process covers that token. Synchronous and local: never makes a * network call, so a rotated or replaced token has no owner until * {@link attestClaudeNativeLoginOwner} runs again. Never returns token material and never * uses the interactive Keychain path. */ function readClaudeNativeLoginOwner(e = {}) { const t = readClaudeNativeLoginCredential(e); return t ? claudeNativeLoginAttestations.get(fingerprintClaudeNativeLoginToken(t.value)) : void 0; } /** * Attest the owner of the login a local `claude` process would use: the account uuid * Anthropic's OAuth profile endpoint returns for the access token itself. The token goes * only to that endpoint, with a short timeout, and is never logged, stored or refreshed * here. Any failure, an expired token, or a response without an account uuid yields no * owner. `refreshDueAt` is when Claude CLI starts rotating the token, which it does before * it accepts a prompt, so a check at send time can see a token attested only after the run. */ async function attestClaudeNativeLoginOwner(e = {}) { const t = readClaudeNativeLoginCredential(e); if (!t) return {}; const n = t.expires - CLAUDE_NATIVE_LOGIN_REFRESH_MARGIN_MS; const r = fingerprintClaudeNativeLoginToken(t.value); const i = claudeNativeLoginAttestations.get(r); if (i || t.expires <= Date.now()) return { ...i ? { owner: i } : {}, refreshDueAt: n }; let a; try { const n = await (e.fetchFn ?? globalThis.fetch)(CLAUDE_OAUTH_PROFILE_URL, { headers: { Authorization: `Bearer ${t.value}`, Accept: "application/json", "User-Agent": "openclaw" }, redirect: "error", signal: AbortSignal.timeout(CLAUDE_OAUTH_PROFILE_TIMEOUT_MS) }); if (n.ok) { const e = asNonArrayRecord(asNonArrayRecord(await n.json()).account); const t = normalizeOptionalString(e.uuid); a = t ? `uuid:${t}` : void 0; } } catch { a = void 0; } if (a) { claudeNativeLoginAttestations.set(r, a); if (claudeNativeLoginAttestations.size > CLAUDE_NATIVE_LOGIN_ATTESTATION_LIMIT) { const e = claudeNativeLoginAttestations.keys().next().value; if (e !== void 0) claudeNativeLoginAttestations.delete(e); } } return { ...a ? { owner: a } : {}, refreshDueAt: n }; } /** The access token a local `claude` process would authenticate with, or undefined. */ function readClaudeNativeLoginCredential(e) { const { homeDir: t } = e; const n = e.env ?? process.env; if (CLAUDE_NON_NATIVE_AUTH_ENV_KEYS.some((e) => Boolean(n[e]?.trim())) || [n.CLAUDE_CONFIG_DIR, n.CLAUDE_SECURESTORAGE_CONFIG_DIR].some((e) => e && !path.isAbsolute(e)) || path.dirname(resolveClaudeCliCredentialsPath(t, n)) !== resolveClaudeCliConfigDir(t, n) || readClaudeApiKeyHelper(t, n) || userSettingsSelectNonNativeAuth(t, n) || managedSettingsSelectNonNativeAuth(e.platform ?? process.platform)) return; const r = e.execSync ?? execSync; const i = resolveClaudeCliKeychainService(t, n); let a = null; if ((e.platform ?? process.platform) === "darwin") { const e = readClaudeKeychain(r, CLAUDE_CLI_KEYCHAIN_TIMEOUT_MS, i, n); if (e.state === "ok") { a = parseClaudeCliOauthCredential(e.value.claudeAiOauth); if (!a) return; } else if ((e.state === "absent" ? "absent" : probeClaudeKeychainItem(r, i, n)) !== "absent") return; } a ??= parseClaudeCliOauthCredential(asNonArrayRecord(loadJsonFileThroughSymlink(resolveClaudeCliCredentialsPath(t, n))).claudeAiOauth); if (!a || a.type === "api_key_helper") return; return { value: a.type === "oauth" ? a.access : a.token, expires: a.expires }; } function withClaudeAccountEmail(e, t) { if (!e || e.type === "api_key_helper") return e; if (path.dirname(resolveClaudeCliCredentialsPath(t)) !== resolveClaudeCliConfigDir(t)) return e; const n = readClaudeAccountEmail(t); return n ? { ...e, email: n } : e; } /** * Claude's user settings `env` block outranks the spawned environment, so it can select an * API key, token or cloud provider too. The bundled backend loads no other settings source * except admin-managed settings, which Claude always loads. */ function userSettingsSelectNonNativeAuth(e, t = process.env) { return settingsEnvSelectsNonNativeAuth(loadJsonFileThroughSymlink(resolveClaudeCliPath(e, CLAUDE_CLI_USER_SETTINGS_FILE, t))); } function settingsEnvSelectsNonNativeAuth(e) { const t = asNonArrayRecord(asNonArrayRecord(e).env); return CLAUDE_NON_NATIVE_AUTH_ENV_KEYS.some((e) => { const n = t[e]; return typeof n === "string" && n.trim() !== ""; }); } function resolveClaudeManagedSettingsDir(e) { return e === "darwin" ? "/Library/Application Support/ClaudeCode" : e === "win32" ? "C:\\Program Files\\ClaudeCode" : "/etc/claude-code"; } /** * Claude loads admin-managed settings whatever `--setting-sources` says: the managed file, * then each non-hidden `*.json` drop-in. Any of them can set an API key helper or an `env` * auth key. A later file can only blank such a key, so checking each file alone may refuse * too often but never misses one. MDM and server-managed policy are not readable here. */ function managedSettingsSelectNonNativeAuth(e) { const t = resolveClaudeManagedSettingsDir(e); const n = path.join(t, CLAUDE_MANAGED_SETTINGS_DROP_IN_DIR); let r = []; try { r = fs.readdirSync(n).filter((e) => e.endsWith(".json") && !e.startsWith(".")); } catch {} return [path.join(t, CLAUDE_MANAGED_SETTINGS_FILE), ...r.map((e) => path.join(n, e))].some((e) => { let t; try { t = asNonArrayRecord(loadJsonFileThroughSymlink(e)); } catch { return false; } const n = t.apiKeyHelper; return typeof n === "string" && n.trim() !== "" || settingsEnvSelectsNonNativeAuth(t); }); } function readClaudeApiKeyHelper(e, t = process.env) { const n = loadJsonFileThroughSymlink(resolveClaudeCliPath(e, CLAUDE_CLI_USER_SETTINGS_FILE, t)); const r = asNonArrayRecord(n).apiKeyHelper; return typeof r === "string" && r.trim() ? { type: "api_key_helper", provider: "anthropic", helperHash: createHash("sha256").update(r.trim()).digest("hex") } : null; } const SECURITY_ITEM_NOT_FOUND_STATUS = 44; function isKeychainItemNotFound(e) { return typeof e === "object" && e !== null && "status" in e && e.status === SECURITY_ITEM_NOT_FOUND_STATUS; } /** Tri-state read of the Keychain login: readable, confirmed absent, or unknown. */ function readClaudeKeychain(e, t, n, r = process.env) { let i; try { const a = resolveClaudeCliKeychainAccount(r); i = e(`${MACOS_SECURITY_PATH} find-generic-password -a "${a}" -w -s "${n}"`, { encoding: "utf8", stdio: [ "pipe", "pipe", "pipe" ], ...t === void 0 ? {} : { timeout: t } }); } catch (e) { return isKeychainItemNotFound(e) ? { state: "absent" } : { state: "unknown" }; } try { const e = JSON.parse(i.trim()); return isRecord(e) ? { state: "ok", value: e } : { state: "unknown" }; } catch { return { state: "unknown" }; } } /** Tri-state metadata lookup: the item exists, is confirmed absent, or the lookup failed. */ function probeClaudeKeychainItem(e, t, n = process.env) { try { e(`${MACOS_SECURITY_PATH} find-generic-password -a "${resolveClaudeCliKeychainAccount(n)}" -s "${t}"`, { encoding: "utf8", timeout: CLAUDE_CLI_KEYCHAIN_TIMEOUT_MS, stdio: [ "pipe", "pipe", "pipe" ] }); return "present"; } catch (e) { return isKeychainItemNotFound(e) ? "absent" : "unknown"; } } function resolveClaudeCliKeychainAccount(e = process.env) { let t; try { t = e.USER || userInfo().username; } catch { t = void 0; } return t && SAFE_KEYCHAIN_ACCOUNT_PATTERN.test(t) ? t : CLAUDE_CLI_KEYCHAIN_ACCOUNT_FALLBACK; } function readClaudeCliCredentials(e) { const t = readClaudeApiKeyHelper(e.homeDir); if (t) return t; const n = e.platform ?? process.platform; const r = e.execSync ?? execSync; const i = resolveClaudeCliKeychainService(e.homeDir); if (n === "darwin" && e.allowKeychainPrompt !== false) { const t = readClaudeKeychain(r, e.tryKeychainWithoutPrompt ? CLAUDE_CLI_KEYCHAIN_TIMEOUT_MS : void 0, i); const n = parseClaudeCliOauthCredential(t.state === "ok" ? t.value.claudeAiOauth : void 0); if (n) return withClaudeAccountEmail(n, e.homeDir); } const a = resolveClaudeCliCredentialsPath(e.homeDir); const o = loadJsonFileThroughSymlink(a); const s = withClaudeAccountEmail(parseClaudeCliOauthCredential(asNonArrayRecord(o).claudeAiOauth), e.homeDir); if (s) return s; if (e.onStoredCredentialUnreadable && e.tryKeychainWithoutPrompt && (fs.existsSync(a) || n === "darwin" && probeClaudeKeychainItem(r, i) === "present")) e.onStoredCredentialUnreadable(); return null; } /** * @deprecated Claude CLI owns native login. Kept functional for shipped Plugin SDK callers only. * Scheduled for removal after v2026.10. */ function readClaudeCliCredentialsCached(e = {}) { const t = e.platform ?? process.platform; const n = e.ttlMs ?? 0; const r = resolveClaudeCliCredentialsPath(e.homeDir); const i = resolveClaudeCliPath(e.homeDir, CLAUDE_CLI_USER_SETTINGS_FILE); const a = resolveClaudeCliAccountPath(e.homeDir); const o = resolveClaudeCliKeychainService(e.homeDir); const s = `${r}:${i}:${a}:${t !== "darwin" ? "file" : e.allowKeychainPrompt === false ? e.tryKeychainWithoutPrompt ? "keychain-presence" : "file" : e.tryKeychainWithoutPrompt ? "keychain-bounded" : "keychain"}:${o}:${e.onStoredCredentialUnreadable && e.tryKeychainWithoutPrompt ? "notify" : "silent"}`; const c = `${readFileMtimeMs$1(r) ?? "missing"}:${readFileMtimeMs$1(i) ?? "missing"}:${readFileMtimeMs$1(a) ?? "missing"}`; const l = Date.now(); if (n > 0 && claudeCliCache?.cacheKey === s && claudeCliCache.sourceFingerprint === c && l - claudeCliCache.readAt < n) return claudeCliCache.value; const u = readClaudeCliCredentials({ ...e, platform: t }); claudeCliCache = n > 0 ? { value: u, readAt: l, cacheKey: s, sourceFingerprint: c } : null; return u; } //#endregion //#region src/agents/cli-credentials.ts const CODEX_CLI_AUTH_FILENAME = "auth.json"; const MINIMAX_CLI_CREDENTIALS_RELATIVE_PATH = ".minimax/oauth_creds.json"; const GEMINI_CLI_CREDENTIALS_RELATIVE_PATH = ".gemini/oauth_creds.json"; const CODEX_CLI_FALLBACK_EXPIRY_MS = 36e5; const readCachedCodexCredential = createCachedCliCredentialReader(); function resolveCodexCliHomePath(e, t = process.env) { const n = e ?? t.CODEX_HOME; const r = resolveOsHomeRelativePath(n || "~/.codex", { env: t }); try { return fs.realpathSync.native(r); } catch { return r; } } function readCodexAuthMode(e) { return (typeof e.auth_mode === "string" ? e.auth_mode.toLowerCase() : void 0) || (typeof e.OPENAI_API_KEY === "string" ? "api_key" : "chatgpt"); } /** Presence is only a discovery hint; Codex verifies the login without exporting its tokens. */ function hasCodexCliAuthFile(e) { try { const t = fs.statSync(path.join(resolveCodexCliHomePath(e), CODEX_CLI_AUTH_FILENAME)); return t.isFile() && t.size > 0; } catch (e) { const t = extractErrorCode(e); if (t === "ENOENT" || t === "ENOTDIR") return false; throw e; } } function readFileMtimeMs(e) { try { return fs.statSync(e).mtimeMs; } catch { return null; } } function createCachedCliCredentialReader() { let e = null; return (t) => { const { ttlMs: n, cacheKey: r, read: i, sourcePath: a } = t; if (n <= 0) return i(); const o = Date.now(); const s = readFileMtimeMs(a); if (e && e.cacheKey === r && e.sourceFingerprint === s && o - e.readAt < n) return e.value; const c = i(); const l = readFileMtimeMs(a); if (l === s) e = { value: c, readAt: o, cacheKey: r, sourceFingerprint: l }; else e = null; return c; }; } function computeCodexKeychainAccount(e) { return `cli|${createHash("sha256").update(e).digest("hex").slice(0, 16)}`; } function resolveCodexKeychainParams(e) { return { platform: e?.platform ?? process.platform, execSyncImpl: e?.execSync ?? execSync, codexHome: resolveCodexCliHomePath(e?.codexHome) }; } function decodeJwtPayload(e) { const t = e.split(".").at(1); if (!t) return; try { const e = JSON.parse(Buffer.from(t, "base64url").toString("utf8")); return asOptionalRecord(e); } catch { return; } } function decodeJwtExpiryMs(e) { const t = decodeJwtPayload(e)?.exp; return typeof t === "number" && Number.isFinite(t) && t > 0 ? asDateTimestampMs(t * 1e3) ?? null : null; } function readCodexKeychainAuthRecord(e) { const { platform: t, execSyncImpl: n, codexHome: r } = resolveCodexKeychainParams(e); if (t !== "darwin" || e?.allowKeychainPrompt === false) return null; const i = computeCodexKeychainAccount(r); try { const e = n(`security find-generic-password -s "Codex Auth" -a "${i}" -w`, { encoding: "utf8", timeout: 5e3, stdio: [ "pipe", "pipe", "pipe" ] }).trim(); return JSON.parse(e); } catch { return null; } } function resolveCodexFallbackExpiryMs(e) { return resolveExpiresAtMsFromDurationMs(CODEX_CLI_FALLBACK_EXPIRY_MS, { nowMs: e === void 0 ? void 0 : Math.floor(e) }); } function parseCodexOauthCredential(e, t) { if (!["chatgpt", "chatgptauthtokens"].includes(readCodexAuthMode(e))) return null; const n = e.tokens; const r = n?.access_token; const i = n?.refresh_token; if (typeof r !== "string" || !r) return null; if (typeof i !== "string" || !i) return null; const a = decodeJwtExpiryMs(r) ?? t; if (a === void 0) return null; return { type: "oauth", provider: "openai", access: r, refresh: i, expires: a, accountId: typeof n?.account_id === "string" ? n.account_id : void 0, idToken: typeof n?.id_token === "string" ? n.id_token : void 0 }; } function parseCodexApiKeyCredential(e) { if (!["apikey", "api_key"].includes(readCodexAuthMode(e))) return null; const t = typeof e.OPENAI_API_KEY === "string" ? e.OPENAI_API_KEY.trim() : ""; return t ? { type: "api_key", provider: "openai", key: t } : null; } function readCliOauthTokenFields(e) { const t = e.access_token; const n = e.refresh_token; const r = e.expiry_date; if (typeof t !== "string" || !t) return null; if (typeof n !== "string" || !n) return null; if (typeof r !== "number" || !Number.isFinite(r)) return null; return { access: t, refresh: n, expires: r }; } function readMiniMaxCliCredentials(e) { const t = loadJsonFileThroughSymlink(e); if (!t || typeof t !== "object") return null; const n = readCliOauthTokenFields(t); return n ? { type: "oauth", provider: "minimax-portal", ...n } : null; } function readGeminiCliCredentials(e) { const t = loadJsonFileThroughSymlink(e); if (!t || typeof t !== "object") return null; const n = t; const r = readCliOauthTokenFields(n); if (!r) return null; const i = n.id_token; const a = typeof i === "string" && i ? decodeJwtPayload(i) : void 0; return { type: "oauth", provider: "google-gemini-cli", ...r, ...typeof a?.email === "string" && a.email ? { email: a.email } : {}, ...typeof a?.sub === "string" && a.sub ? { accountId: a.sub } : {} }; } function formatCodexApiKeyForLoginStatus(e) { return e.length <= 13 ? "***" : `${e.slice(0, 8)}***${e.slice(-5)}`; } /** Reads an API key only when Codex confirms that exact credential is active. */ function readCodexCliActiveApiKey(e) { const { execSyncImpl: t, codexHome: n } = resolveCodexKeychainParams(e); let r; try { r = t("codex login status 2>&1", { encoding: "utf8", timeout: 5e3, stdio: [ "pipe", "pipe", "pipe" ], env: { ...process.env, CODEX_HOME: n } }).trim(); } catch { return null; } const i = /^Logged in using an API key - (.+)$/mu.exec(r)?.[1]?.trim(); const a = r.trim() === "Logged in using an API key"; if (!i && !a) return null; const o = []; const s = path.join(n, CODEX_CLI_AUTH_FILENAME); const c = loadJsonFileThroughSymlink(s); if (c && typeof c === "object") { const e = parseCodexApiKeyCredential(c); if (e) o.push(e); } const l = readCodexKeychainAuthRecord({ codexHome: n, allowKeychainPrompt: e?.allowKeychainPrompt, platform: e?.platform, execSync: e?.execSync }); if (l) { const e = parseCodexApiKeyCredential(l); if (e) o.push(e); } const u = new Set(o.filter((e) => a || formatCodexApiKeyForLoginStatus(e.key) === i).map((e) => e.key)); if (u.size !== 1) return null; const d = [...u][0]; return d ? { type: "api_key", provider: "openai", key: d } : null; } function readCodexCliCredentials(e) { const t = readCodexKeychainAuthRecord(e); if (t) { const e = t.last_refresh; const n = parseCodexOauthCredential(t, resolveCodexFallbackExpiryMs(typeof e === "string" || typeof e === "number" ? new Date(e).getTime() : Date.now()) ?? resolveCodexFallbackExpiryMs()); if (n) return n; } const n = path.join(resolveCodexCliHomePath(e?.codexHome), CODEX_CLI_AUTH_FILENAME); const r = loadJsonFileThroughSymlink(n); if (!r || typeof r !== "object") return null; let i; try { i = resolveCodexFallbackExpiryMs(fs.statSync(n).mtimeMs); } catch { i = resolveCodexFallbackExpiryMs(); } return parseCodexOauthCredential(r, i); } function readCodexCliCredentialsCached(e) { const t = e?.platform ?? process.platform; const n = e?.ttlMs ?? 0; const r = path.join(resolveCodexCliHomePath(e?.codexHome), CODEX_CLI_AUTH_FILENAME); const i = t === "darwin" && e?.allowKeychainPrompt !== false ? "keychain" : "file"; return readCachedCodexCredential({ ttlMs: n, cacheKey: `${t}|${r}:${i}`, read: () => readCodexCliCredentials({ codexHome: e?.codexHome, allowKeychainPrompt: e?.allowKeychainPrompt, platform: e?.platform, execSync: e?.execSync }), sourcePath: r }); } function createCachedCliFileReader(e, t) { const n = createCachedCliCredentialReader(); return (r) => { const i = path.join(resolveOsHomeRelativePath(r?.homeDir ?? "~"), e); return n({ ttlMs: r?.ttlMs ?? 0, cacheKey: i, read: () => t(i), sourcePath: i }); }; } const readCachedMiniMax = createCachedCliFileReader(MINIMAX_CLI_CREDENTIALS_RELATIVE_PATH, readMiniMaxCliCredentials); const readCachedGemini = createCachedCliFileReader(GEMINI_CLI_CREDENTIALS_RELATIVE_PATH, readGeminiCliCredentials); function readMiniMaxCliCredentialsCached(e) { return readCachedMiniMax(e); } function readGeminiCliCredentialsCached(e) { return readCachedGemini(e); } /** * Attestation sends the CLI's own access token to its provider, so it runs only when the * owning plugin opts in. For Claude that is * `plugins.entries.anthropic.config.historyRecovery.attestNativeLogin: true`. Off by default: * the native login then has no owner and history stays refused, as before. */ function isNativeCliLoginAttestationEnabled(e, t) { const n = asOptionalRecord(t?.plugins?.entries?.anthropic?.config); return e === "claude-cli" && asOptionalRecord(n?.historyRecovery)?.attestNativeLogin === true; } /** * Owner of the native login a local run of this CLI backend would use under * `env`, attested by the provider for the credential itself rather than read * from local account metadata. No owner when the backend has no native login or * the attestation fails; callers must then treat history as unknown. */ async function resolveNativeCliLoginOwner(e, t) { return e === "claude-cli" ? await attestClaudeNativeLoginOwner({ env: t }) : {}; } /** * Synchronous recheck for spawn, send and commit boundaries: the owner this * process already attested for the credential `env` selects now, or undefined * when that credential changed since and has not been attested. Never waits on * the network. */ function readAttestedNativeCliLoginOwner(e, t) { return e === "claude-cli" ? readClaudeNativeLoginOwner({ env: t }) : void 0; } //#endregion export { readCodexCliCredentialsCached as a, resolveCodexCliHomePath as c, readCodexCliActiveApiKey as i, resolveNativeCliLoginOwner as l, isNativeCliLoginAttestationEnabled as n, readGeminiCliCredentialsCached as o, readAttestedNativeCliLoginOwner as r, readMiniMaxCliCredentialsCached as s, hasCodexCliAuthFile as t, readClaudeCliCredentialsCached as u };