openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
345 lines (344 loc) • 14.8 kB
JavaScript
import { m as readNonBlankString } from "./string-coerce-CCIiB4H7.mjs";
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { a as coerceSecretRef, s as hasLegacySecretRefExtraFields } from "./types.secrets-BmNLLnHp.mjs";
import { p as shortenHomePath } from "./utils-C8YECn2Q.mjs";
import { n as materializeErrorStack } from "./error-graph-internal-DdjdM90N.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { _ as AUTH_PROFILE_MIGRATION_COMMAND } from "./openclaw-state-worker-error-C8y1JGQN.mjs";
import { m as parseAuthProfileCredential, p as coercePersistedAuthProfileStore } from "./user-model-account-authority-CRj924IP.mjs";
import { i as resolveProviderIdForAuth, n as hasUnresolvedProviderAuthEndpoint, t as couldResolveProviderIdForAuth } from "./provider-auth-aliases-CgGlzANu.mjs";
import { c as prepareAuthProfileLegacySources, r as authProfileSourceExists } from "./file-state-DHEsgd_R.mjs";
import "./persisted-Dv3zNYHi.mjs";
import { R as listLegacyAuthProfileSources, a as inspectPersistedAuthProfileStoreRaw, b as resolveAuthProfileDatabasePath, s as inspectPersistedSharedAuthProfileStoreRaw, z as resolveLegacyAuthProfileSourceCandidates } from "./sqlite-B2CoJ4Om.mjs";
import { t as resolveSharedMainAuthAgentDir } from "./shared-main-dir-C2ynhf4g.mjs";
import { d as resolveSharedAuthStorePath } from "./path-resolve-CpNl_n1M.mjs";
import fs from "node:fs";
//#region src/agents/auth-profiles/legacy-flat-credential.ts
function inferLegacyCredentialType(e) {
const t = readNonBlankString(e.type) ?? readNonBlankString(e.mode);
if (t === "api_key" || t === "token" || t === "oauth") return t;
if ((readNonBlankString(e.key) ?? readNonBlankString(e.apiKey)) || coerceSecretRef(e.keyRef)) return "api_key";
if (readNonBlankString(e.token) || coerceSecretRef(e.tokenRef)) return "token";
if (readNonBlankString(e.access) && readNonBlankString(e.refresh) && typeof e.expires === "number") return "oauth";
}
function coerceLegacyFlatCredential(e, t) {
if (!isRecord(t)) return null;
const n = inferLegacyCredentialType(t);
if (!n) return null;
const r = readNonBlankString(t.provider) ?? e;
const i = parseLegacyCredentialEntry({
...t,
type: n,
provider: r
}, e);
if (!i || !hasUsableAuthProfileCredential(i)) return null;
return i;
}
function hasUsableAuthProfileCredential(e) {
if (e.type === "api_key") return Boolean(readNonBlankString(e.key) || e.keyRef);
if (e.type === "token") return Boolean(readNonBlankString(e.token) || e.tokenRef);
return Boolean(readNonBlankString(e.access)) && Boolean(readNonBlankString(e.refresh)) && typeof e.expires === "number";
}
/** Doctor normalization also supports provider-scoped refusal diagnostics, never runtime credentials. */
function normalizeLegacyCredentialFields(e) {
const t = { ...e };
const n = t.mode;
if (!("type" in t) && (n === "apiKey" || n === "api_key" || n === "token" || n === "oauth")) {
t.type = n;
delete t.mode;
}
if (t.type === "apiKey") t.type = "api_key";
if (t.type === "api_key" && !readNonBlankString(t.key) && !coerceSecretRef(t.key) && !coerceSecretRef(t.keyRef)) for (const e of ["apiKey", "api_key"]) {
const n = readNonBlankString(t[e]) ?? coerceSecretRef(t[e]);
if (n != null) {
t.key = n;
delete t[e];
break;
}
}
const r = t.type === "api_key" ? ["key", "keyRef"] : t.type === "token" ? ["token", "tokenRef"] : void 0;
if (r) {
const [e, n] = r;
const i = coerceSecretRef(t[n]);
if (i) t[n] = i;
const a = t[e];
const o = isRecord(a) ? coerceSecretRef(a) : null;
if (o && !coerceSecretRef(t[n])) {
t[n] = o;
delete t[e];
}
}
return t;
}
function parseLegacyCredentialEntry(e, t) {
return isRecord(e) ? parseAuthProfileCredential(normalizeLegacyCredentialFields(e), t) : null;
}
function normalizeLegacyAuthProfileFields(e) {
if (!isRecord(e) || !isRecord(e.profiles)) return 0;
let t = 0;
for (const [n, r] of Object.entries(e.profiles)) if (isRecord(r) && parseLegacyCredentialEntry(r)) {
const i = normalizeLegacyCredentialFields(r);
for (const e of [
"keyRef",
"tokenRef",
"key",
"token",
"apiKey",
"api_key"
]) if (hasLegacySecretRefExtraFields(r[e]) && i[e] !== r[e]) t += 1;
e.profiles[n] = i;
}
return t;
}
function coerceLegacyAuthProfileStore(e) {
const t = structuredClone(e);
normalizeLegacyAuthProfileFields(t);
return coercePersistedAuthProfileStore(t);
}
function coerceLegacyAuthStore(e) {
if (!isRecord(e) || "profiles" in e) return null;
const t = {};
for (const [n, r] of Object.entries(e)) {
const e = parseLegacyCredentialEntry(r, n);
if (e) t[n] = e;
}
return Object.keys(t).length > 0 ? t : null;
}
/** Applies legacy auth.json credentials into an auth profile store. */
function applyLegacyAuthStore(e, t) {
for (const [n, r] of Object.entries(t)) e.profiles[`${n}:default`] = {
...r,
provider: r.provider ?? n
};
}
//#endregion
//#region src/agents/auth-profiles/legacy-source-diagnostic.ts
const AUTH_PROFILE_MIGRATION_REQUIRED_CODE = "AUTH_PROFILE_MIGRATION_REQUIRED";
const log = createSubsystemLogger("auth-profiles/persistence");
function isCredentialSource(e) {
return e.kind !== "auth-state";
}
/** Read provider metadata only; unknown shapes retain the owner-wide refusal. */
function readLegacyAuthProfileProviders(e) {
return parseLegacyAuthProfileProviders(e.filter(isCredentialSource).map((e) => {
try {
return e.kind === "auth-profiles" ? fs.readFileSync(e.path, "utf8") : void 0;
} catch {
return;
}
}));
}
function parseLegacyAuthProfileProviders(e) {
const t = /* @__PURE__ */ new Set();
for (const n of e) {
if (n === void 0) return null;
try {
const e = JSON.parse(n);
if (!isRecord(e)) return null;
const r = Object.hasOwn(e, "profiles");
const i = r ? e.profiles : e;
if (!isRecord(i) || Object.keys(i).length === 0) return null;
for (const [e, n] of Object.entries(i)) {
const i = r ? parseLegacyCredentialEntry(n) : coerceLegacyFlatCredential(e, n);
if (!i) return null;
const a = i.provider;
if (typeof a !== "string" || !/^[a-z0-9][a-z0-9._-]{0,127}$/i.test(a)) return null;
t.add(a.toLowerCase());
if (a.toLowerCase() === "openai-codex") t.add("openai");
}
} catch {
return null;
}
}
return t.size > 0 ? [...t].toSorted() : null;
}
function resolveAuthProfileOwnerPath(e, t) {
return e ? resolveAuthProfileDatabasePath(e) : resolveSharedAuthStorePath(t);
}
function hasLegacyAuthProfileCredentialSource(e, t) {
return listLegacyAuthProfileSources({
agentDir: e,
env: t
}).some(isCredentialSource);
}
async function hasLegacyAuthProfileCredentialSourceAsync(e, t) {
const n = resolveLegacyAuthProfileSourceCandidates({
agentDir: e,
env: t
});
await prepareAuthProfileLegacySources(n.map((e) => e.path));
return n.some((e) => isCredentialSource(e) && authProfileSourceExists(e.path));
}
/**
* True when the canonical SQLite store already holds credentials for this owner.
* A retired JSON file sitting next to a populated store is leftover bytes Doctor
* has not archived yet, not unmigrated credentials: failing runtime closed there
* would strand a working store over a file nothing reads.
*/
function hasMigratedAuthProfileCredentials(e, t) {
let n;
try {
n = !e && t ? inspectPersistedSharedAuthProfileStoreRaw(t) : inspectPersistedAuthProfileStoreRaw(e);
} catch {
return false;
}
if (n.status !== "readable") return false;
const r = isRecord(n.raw) ? n.raw.profiles : void 0;
return isRecord(r) && Object.keys(r).length > 0;
}
function listStartupLegacyAuthProfileSources(e) {
const t = resolveSharedMainAuthAgentDir(e.env);
return [.../* @__PURE__ */ new Set([...e.agentDirs, t])].map((t) => {
const n = listLegacyAuthProfileSources({
agentDir: t,
env: e.env
});
const r = n.filter(isCredentialSource);
return {
agentDir: t,
sources: n,
unmigratedCredentialSources: r.length > 0 && hasMigratedAuthProfileCredentials(t) ? [] : r
};
});
}
function hasLegacyAuthProfileSourcesForStartup(e) {
let t = false;
for (const { agentDir: n, sources: r, unmigratedCredentialSources: i } of listStartupLegacyAuthProfileSources(e)) {
t ||= r.length > 0;
if (i.length > 0) markAuthProfileMigrationRequired(n, new AuthProfileMigrationRequiredError({
agentDir: n,
sources: i,
affectedProviders: readLegacyAuthProfileProviders(i)
}));
}
return t;
}
var AuthProfileMigrationRequiredError = class AuthProfileMigrationRequiredError extends Error {
constructor(e, t) {
const n = e instanceof AuthProfileMigrationRequiredError ? e : {
ownerId: shortenHomePath(e.databasePath ?? resolveAuthProfileOwnerPath(e.agentDir, e.env)),
sourceKinds: e.sources.map((e) => e.kind),
affectedProviders: e.affectedProviders ?? null
};
const { ownerId: r, affectedProviders: i } = n;
const a = [.../* @__PURE__ */ new Set([...t?.sourceKinds ?? [], ...n.sourceKinds])].toSorted();
const o = i && t?.affectedProviders !== null ? [.../* @__PURE__ */ new Set([...t?.affectedProviders ?? [], ...i])].toSorted() : null;
super(`Auth profile store ${r} requires legacy credential migration; affected providers: ${o?.join(", ") ?? "all (legacy provider scope unavailable)"}; run ${AUTH_PROFILE_MIGRATION_COMMAND}.`);
this.code = AUTH_PROFILE_MIGRATION_REQUIRED_CODE;
this.action = AUTH_PROFILE_MIGRATION_COMMAND;
this.name = "AuthProfileMigrationRequiredError";
this.ownerId = r;
this.sourceKinds = a;
this.affectedProviders = o;
}
blocksProvider(e, t) {
if (!e || !this.affectedProviders) return true;
if (hasUnresolvedProviderAuthEndpoint(e, { config: t })) return true;
const n = resolveProviderIdForAuth(e, {
config: t,
storedCredential: t === void 0
});
return this.affectedProviders.some((e) => resolveProviderIdForAuth(e, {
config: t,
storedCredential: true
}) === n);
}
};
const migrationRequiredByDatabase = /* @__PURE__ */ new Map();
const warnedLegacySourceDatabases = /* @__PURE__ */ new Set();
function warnLegacyAuthProfileSourcesIgnored(e) {
if (e.sources.length === 0) return;
const t = e.databasePath ?? resolveAuthProfileOwnerPath(e.agentDir, e.env);
if (warnedLegacySourceDatabases.has(t)) return;
warnedLegacySourceDatabases.add(t);
log.warn("retired auth profile files are ignored by runtime; run Doctor to archive them", {
code: AUTH_PROFILE_MIGRATION_REQUIRED_CODE,
ownerId: shortenHomePath(t),
sourceKinds: [...new Set(e.sources.map((e) => e.kind))].toSorted(),
action: AUTH_PROFILE_MIGRATION_COMMAND
});
}
function recordAuthProfileMigrationRequired(e, t) {
const n = migrationRequiredByDatabase.get(e);
const r = n ? new AuthProfileMigrationRequiredError(t, n) : t;
materializeErrorStack(r);
migrationRequiredByDatabase.set(e, r);
if (n?.message !== r.message) log.warn(r.message, {
code: r.code,
affectedProviders: r.affectedProviders,
action: r.action
});
return r;
}
function markAuthProfileMigrationRequired(e, t, n) {
recordAuthProfileMigrationRequired(resolveAuthProfileOwnerPath(e, n), t);
}
/** Publication must honor a recorded refusal without rediscovering an ambient owner. */
function assertAuthProfileMigrationStateAtDatabasePath(e, t, n, r = false) {
const i = migrationRequiredByDatabase.get(e);
if (i && !(r && i.affectedProviders !== null) && i.blocksProvider(t, n)) throw i;
}
/** A selected row cannot escape its own owner's fence by changing endpoint aliases. */
function assertAuthProfileCredentialMigrationStateAtDatabasePath(e, t, n) {
const r = migrationRequiredByDatabase.get(e);
if (!r) return;
const i = resolveProviderIdForAuth(t, { config: n });
if (!r.affectedProviders || hasUnresolvedProviderAuthEndpoint(t, { config: n }) || r.affectedProviders.some((e) => couldResolveProviderIdForAuth(e, i, { config: n }))) throw r;
}
function assertAuthProfileMigrationCandidates(e) {
assertAuthProfileMigrationStateAtDatabasePath(e.databasePath, e.provider, e.config, e.deferScopedRefusals);
const t = e.candidates.filter((e) => isCredentialSource(e) && authProfileSourceExists(e.path));
if (t.length === 0) return;
if (e.hasCredentials()) {
warnLegacyAuthProfileSourcesIgnored({
databasePath: e.databasePath,
sources: t
});
return;
}
const n = recordAuthProfileMigrationRequired(e.databasePath, new AuthProfileMigrationRequiredError({
databasePath: e.databasePath,
sources: t,
affectedProviders: readLegacyAuthProfileProviders(t)
}));
if (!(e.deferScopedRefusals && n.affectedProviders !== null) && n.blocksProvider(e.provider, e.config)) throw n;
}
/** Admit provider metadata off-thread; synchronous effects consume the retained refusal. */
async function prepareAuthProfileMigrationCandidates(e) {
await prepareAuthProfileLegacySources(e.candidates.map((e) => e.path));
const t = e.candidates.filter((t) => isCredentialSource(t) && (e.sourcePresence?.get(t.path) ?? authProfileSourceExists(t.path)));
const n = e.hasCredentials ? [] : await Promise.all(t.map(async (e) => e.kind === "auth-profiles" ? fs.promises.readFile(e.path, "utf8").catch(() => void 0) : void 0));
if (e.assertCurrent() === false) return;
if (!t.length) return;
if (e.hasCredentials) {
warnLegacyAuthProfileSourcesIgnored({
databasePath: e.databasePath,
sources: t
});
return;
}
recordAuthProfileMigrationRequired(e.databasePath, new AuthProfileMigrationRequiredError({
databasePath: e.databasePath,
sources: t,
affectedProviders: parseLegacyAuthProfileProviders(n)
}));
}
function assertAuthProfileMigrationReady(e, t, n, r, i = false) {
assertAuthProfileMigrationCandidates({
databasePath: resolveAuthProfileOwnerPath(e, t),
candidates: resolveLegacyAuthProfileSourceCandidates({
agentDir: e,
env: t
}),
hasCredentials: () => hasMigratedAuthProfileCredentials(e, t),
provider: n,
config: r,
deferScopedRefusals: i
});
}
function clearAuthProfileMigrationDiagnostics() {
migrationRequiredByDatabase.clear();
warnedLegacySourceDatabases.clear();
}
//#endregion
export { coerceLegacyFlatCredential as _, assertAuthProfileMigrationStateAtDatabasePath as a, normalizeLegacyCredentialFields as b, hasLegacyAuthProfileCredentialSourceAsync as c, prepareAuthProfileMigrationCandidates as d, readLegacyAuthProfileProviders as f, coerceLegacyAuthStore as g, coerceLegacyAuthProfileStore as h, assertAuthProfileMigrationReady as i, hasLegacyAuthProfileSourcesForStartup as l, applyLegacyAuthStore as m, assertAuthProfileCredentialMigrationStateAtDatabasePath as n, clearAuthProfileMigrationDiagnostics as o, warnLegacyAuthProfileSourcesIgnored as p, assertAuthProfileMigrationCandidates as r, hasLegacyAuthProfileCredentialSource as s, AuthProfileMigrationRequiredError as t, markAuthProfileMigrationRequired as u, hasUsableAuthProfileCredential as v, parseLegacyCredentialEntry as x, normalizeLegacyAuthProfileFields as y };