openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
425 lines (424 loc) • 16 kB
JavaScript
import { t as hasNonEmptyString } from "./string-coerce-CCIiB4H7.mjs";
import { c as resolveUserPath } from "./home-dir-EKmgmdPG.mjs";
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { a as coerceSecretRef } from "./types.secrets-BmNLLnHp.mjs";
import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs";
import "./utils-C8YECn2Q.mjs";
import { r as normalizeProviderId } from "./provider-id-b5XGSf9C.mjs";
import { a as resolveAgentDir } from "./agent-scope-config-DmXgFGKP.mjs";
import { r as decodeUtf8Input } from "./utf8-input-BHczGT8v.mjs";
import { p as coercePersistedAuthProfileStore } from "./user-model-account-authority-CRj924IP.mjs";
import { a as findPluginConfigEntry, c as normalizePluginConfigId, o as hasPluginConfigId } from "./provider-auth-aliases-CgGlzANu.mjs";
import { i as listKnownSecretEnvVarNames } from "./provider-env-vars-DPvuIf4v.mjs";
import "./agent-scope-BwB8YH6y.mjs";
import { r as parseEnvValue } from "./shared-DyBTHA2R.mjs";
import { p as assertExpectedResolvedSecretValue } from "./runtime-shared-BVJ4BbUu.mjs";
import { n as getPath, r as setPathCreateStrict, t as deletePathStrict } from "./path-utils-A4pcYa4R.mjs";
import { n as resolveSecretRefValue } from "./resolve-BYfGhigB.mjs";
import { i as loadPersistedSharedAuthProfileStore, n as loadPersistedAuthProfileStore } from "./persisted-Dv3zNYHi.mjs";
import { b as resolveAuthProfileDatabasePath } from "./sqlite-B2CoJ4Om.mjs";
import { d as resolveSharedAuthStorePath } from "./path-resolve-CpNl_n1M.mjs";
import { r as replaceConfigFile } from "./mutate-DhAOi0-2.mjs";
import "./config-CMA-J084.mjs";
import "./model-selection-C2A4Wyix.mjs";
import { l as restoreAuthProfileStorePersistenceSnapshot, n as captureAuthProfileStorePersistenceSnapshot } from "./store-Bh2lUvOT.mjs";
import { p as loadAuthProfileStoreForSecretsRuntime, x as saveAuthProfileStoreIfPersistenceSnapshotMatches } from "./store-runtime-dW0pXLJI.mjs";
import "./auth-profiles-VRLhewIH.mjs";
import { t as getSkippedExecRefStaticError } from "./exec-resolution-policy-DTeP4tsd.mjs";
import { n as listSecretsDotEnvPaths } from "./storage-scan-BUHFlvPI.mjs";
import { a as prepareSecretsRuntimeSnapshot } from "./runtime-Dc04zUgW.mjs";
import { i as iterateAuthProfileCredentials, n as writeTextFileAtomic, r as listAuthProfileStoreTargets, t as createSecretsConfigIO } from "./config-io-C2NM6IWl.mjs";
import { n as normalizeSecretsPlanOptions, r as resolveValidatedPlanTarget } from "./plan-sn-AQU2k.mjs";
import fs from "node:fs";
import os from "node:os";
import { isDeepStrictEqual } from "node:util";
//#region src/secrets/apply.ts
/** Applies secrets migration plans across config files, auth stores, and env files. */
function planContainsExecReferences(e) {
if (e.targets.some((e) => e.ref.source === "exec")) return true;
return Object.values(e.providerUpserts ?? {}).some((e) => e.source === "exec");
}
function resolveTarget(e) {
const t = resolveValidatedPlanTarget(e);
if (!t) throw new Error(`Invalid plan target path for ${e.type}: ${e.path}`);
return t;
}
function scrubEnvRaw(e, t, n) {
if (t.size === 0 || n.size === 0) return e;
const r = e.split(/\r?\n/);
const i = r.filter((e) => {
const r = e.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);
return !r || !n.has(r[1] ?? "") || !t.has(parseEnvValue(r[2] ?? ""));
});
if (i.length === r.length) return e;
const a = e.endsWith("\n");
const o = i.join("\n");
return a || o.length === 0 ? `${o}${o.endsWith("\n") ? "" : "\n"}` : o;
}
function applyProviderPlanMutations(e) {
const t = e.config.secrets?.providers ?? {};
let n = false;
for (const r of e.deletes ?? []) {
if (!Object.hasOwn(t, r)) continue;
delete t[r];
n = true;
}
for (const [r, i] of Object.entries(e.upserts ?? {})) {
const e = t[r];
if (isDeepStrictEqual(e, i)) continue;
t[r] = i;
n = true;
}
for (const t of Object.values(e.upserts ?? {})) {
if (t.source !== "exec" || !("pluginIntegration" in t)) continue;
const r = normalizePluginConfigId(t.pluginIntegration.pluginId);
e.config.plugins ??= {};
if (e.config.plugins.enabled === false) throw new Error(`Cannot apply plugin-managed SecretRef provider "${r}" because plugins.enabled is false. Enable plugins before applying this plan.`);
if (hasPluginConfigId(e.config.plugins.deny, r)) throw new Error(`Cannot apply plugin-managed SecretRef provider "${r}" because plugins.deny includes "${r}". Remove the deny rule before applying this plan.`);
const i = findPluginConfigEntry(e.config.plugins.entries, r);
if (i?.enabled === false) throw new Error(`Cannot apply plugin-managed SecretRef provider "${r}" because plugins.entries.${r}.enabled is false. Enable the plugin explicitly before applying this plan.`);
if (Array.isArray(e.config.plugins.allow) && e.config.plugins.allow.length > 0 && !hasPluginConfigId(e.config.plugins.allow, r)) throw new Error(`Cannot apply plugin-managed SecretRef provider "${r}" because plugins.allow does not include "${r}". Add the plugin to plugins.allow before applying this plan.`);
e.config.plugins.entries ??= {};
if (i?.enabled === true) continue;
e.config.plugins.entries[r] = {
...i,
enabled: true
};
n = true;
}
if (!n) return false;
e.config.secrets ??= {};
if (Object.keys(t).length === 0) {
if ("providers" in e.config.secrets) delete e.config.secrets.providers;
return true;
}
e.config.secrets.providers = t;
return true;
}
async function projectPlanState(e) {
const { snapshot: t, writeOptions: n } = await createSecretsConfigIO({ env: e.env }).readConfigFileSnapshotForWrite();
if (!t.valid) throw new Error("Cannot apply secrets plan: config is invalid.");
const r = normalizeSecretsPlanOptions(e.plan.options);
const i = structuredClone(t.config);
const a = resolveStateDir(e.env, os.homedir);
const o = {
...e.env,
OPENCLAW_STATE_DIR: a
};
const s = /* @__PURE__ */ new Set();
const c = [];
const l = resolveUserPath(t.path);
if (applyProviderPlanMutations({
config: i,
upserts: e.plan.providerUpserts,
deletes: e.plan.providerDeletes
})) s.add(l);
const u = /* @__PURE__ */ new Map();
const d = e.plan.targets.map((e) => ({
target: e,
resolved: resolveTarget(e)
}));
const f = /* @__PURE__ */ new Set();
const p = /* @__PURE__ */ new Set();
let m = false;
for (const { target: t, resolved: n } of d) {
if (n.entry.configFile === "auth-profile-store") {
const { path: r, store: o } = resolveAuthStoreForTarget({
target: t,
nextConfig: i,
stateDir: a,
env: e.env,
authStores: u
});
const c = ensureAuthProfileContainer({
target: t,
resolved: n,
store: o
});
const l = applySecretRefTargetMutation(o, t, n, f);
if (c || l) s.add(r);
continue;
}
if (applySecretRefTargetMutation(i, t, n, f)) m = true;
if (n.entry.secretShape !== "sibling_ref" && n.entry.trackProviderShadowing && n.providerId) p.add(normalizeProviderId(n.providerId));
}
if (m) s.add(l);
if (r.scrubAuthProfilesForProviderTargets && p.size > 0) for (const t of listAuthProfileStoreTargets(i, a, e.env)) {
const e = t.path;
const n = u.get(e)?.store;
if (!n && !fs.existsSync(e)) continue;
const r = n ?? (t.kind === "shared" ? loadPersistedSharedAuthProfileStore(t.env) : loadPersistedAuthProfileStore(t.agentDir));
if (!r || !isRecord(r.profiles)) continue;
let a = false;
for (const t of iterateAuthProfileCredentials(r.profiles)) {
const n = normalizeProviderId(t.provider);
if (!p.has(n)) continue;
if (t.kind === "api_key" || t.kind === "token") {
if (hasNonEmptyString(t.value)) f.add(t.value.trim());
if (t.valueField in t.profile) {
delete t.profile[t.valueField];
a = true;
}
if (t.refField in t.profile && coerceSecretRef(t.refValue, i.secrets?.defaults) === null) {
delete t.profile[t.refField];
a = true;
}
continue;
}
if (t.kind === "oauth" && (t.hasAccess || t.hasRefresh)) c.push(`Provider "${n}" has OAuth credentials in ${e}; those still take precedence and are out of scope for static SecretRef migration.`);
}
if (a) {
u.set(e, {
store: r,
target: t
});
s.add(e);
}
}
const h = /* @__PURE__ */ new Map();
if (r.scrubEnv && f.size > 0) {
const e = new Set(listKnownSecretEnvVarNames());
for (const t of listSecretsDotEnvPaths({
configPath: l,
stateDir: a
})) {
if (!fs.existsSync(t)) continue;
const n = fs.readFileSync(t);
const r = n.toString("utf8");
const i = scrubEnvRaw(r, f, e);
if (i !== r) {
decodeUtf8Input(n, `File ${t}`);
h.set(t, i);
s.add(t);
}
}
}
const g = e.write ? s.size > 0 : e.allowExecInDryRun;
const { env: _, write: v, allowExecInDryRun: y } = e;
const b = {};
let x = 0;
let S = 0;
for (const { target: e, resolved: t } of d) {
if (!v && e.ref.source === "exec" && !y) {
S += 1;
const t = getSkippedExecRefStaticError({
ref: e.ref,
config: i
});
if (t) throw new Error(t);
continue;
}
const n = await resolveSecretRefValue(e.ref, {
config: i,
env: _,
cache: b
});
x += 1;
assertExpectedResolvedSecretValue({
value: n,
expected: t.entry.expectedResolvedValue,
errorMessage: t.entry.expectedResolvedValue === "string" ? `Ref ${e.ref.source}:${e.ref.provider}:${e.ref.id} is not a non-empty string.` : `Ref ${e.ref.source}:${e.ref.provider}:${e.ref.id} is not string/object.`
});
}
const C = /* @__PURE__ */ new Map();
for (const [e, { store: t }] of u) C.set(resolveUserPath(e, _), t);
if (g) await prepareSecretsRuntimeSnapshot({
config: i,
env: _,
includeAuthStoreRefs: v || u.size > 0,
loadAuthStore: (e) => {
const t = resolveUserPath(e ? resolveAuthProfileDatabasePath(e) : resolveSharedAuthStorePath(_), _);
const n = C.get(t);
if (n) return coercePersistedAuthProfileStore(n) ?? {
version: 1,
profiles: {}
};
return loadAuthProfileStoreForSecretsRuntime(e);
}
});
return {
nextConfig: i,
authStoreEnv: o,
configSnapshot: t,
configPath: l,
configWriteOptions: n,
authStores: u,
envRawByPath: h,
changedFiles: s,
warnings: c,
refsChecked: x,
skippedExecRefs: S,
resolvabilityComplete: v || y || S === 0
};
}
function resolveAuthStoreForTarget(e) {
const t = (e.target.agentId ?? "").trim();
if (!t) throw new Error(`Missing required agentId for auth-profiles target ${e.target.path}.`);
const n = {
...e.env,
OPENCLAW_STATE_DIR: e.stateDir,
OPENCLAW_AGENT_DIR: void 0
};
const r = resolveAgentDir(e.nextConfig, t, n);
const i = {
kind: "agent",
agentDir: r,
path: resolveAuthProfileDatabasePath(r)
};
const a = i.path;
const o = e.authStores.get(a)?.store ?? loadPersistedAuthProfileStore(i.agentDir);
const s = isRecord(o) ? o : {};
const c = isRecord(s.profiles) ? s.profiles : {};
if (typeof s.version !== "number" || !Number.isFinite(s.version)) s.version = 1;
const l = {
...s,
profiles: c
};
e.authStores.set(a, {
store: l,
target: i
});
return {
path: a,
store: l
};
}
function ensureAuthProfileContainer(e) {
const t = e.resolved.pathSegments.slice(0, 2);
const n = t[1];
if (!n) throw new Error(`Invalid auth profile target path: ${e.target.path}`);
const r = getPath(e.store, t);
const i = e.resolved.entry.authProfileType;
if (isRecord(r)) {
if (i && typeof r.type === "string" && r.type !== i) throw new Error(`Auth profile "${n}" type mismatch for ${e.target.path}: expected "${i}", got "${r.type}".`);
if (!hasNonEmptyString(r.provider) && hasNonEmptyString(e.target.authProfileProvider)) return setPathCreateStrict(e.store, [...t, "provider"], e.target.authProfileProvider);
return false;
}
if (!i) throw new Error(`Auth profile target ${e.target.path} is missing auth profile type metadata.`);
const a = (e.target.authProfileProvider ?? "").trim();
if (!a) throw new Error(`Cannot create auth profile "${n}" for ${e.target.path} without authProfileProvider.`);
return setPathCreateStrict(e.store, t, {
type: i,
provider: a
});
}
function applySecretRefTargetMutation(e, t, n, r) {
const i = getPath(e, n.pathSegments);
if (hasNonEmptyString(i)) r.add(i.trim());
if (n.entry.secretShape === "sibling_ref") {
const r = n.refPathTokens;
if (!r) throw new Error(n.entry.configFile === "auth-profile-store" ? `Missing sibling ref path for auth-profiles target ${t.path}.` : `Missing sibling ref path for target ${t.type}.`);
const i = setPathCreateStrict(e, r, t.ref);
const a = deletePathStrict(e, n.pathSegments);
return i || a;
}
return setPathCreateStrict(e, n.pathTokens, t.ref);
}
function captureFileSnapshot(e) {
if (!fs.existsSync(e)) return {
existed: false,
content: "",
mode: 384
};
const t = fs.statSync(e);
return {
existed: true,
content: decodeUtf8Input(fs.readFileSync(e), `File ${e}`),
mode: t.mode & 511
};
}
function restoreFileSnapshot(e, t, n) {
if (!t.existed) {
if (fs.existsSync(e)) fs.rmSync(e, { force: true });
return;
}
writeTextFileAtomic(e, t.content, t.mode || 384, n);
}
/** Applies a normalized secrets plan, or reports file/auth-store changes in dry-run mode. */
async function runSecretsApply(e) {
const t = e.env ?? process.env;
const n = e.write === true;
const r = Boolean(e.allowExec);
if (n && planContainsExecReferences(e.plan) && !r) throw new Error("Plan contains exec SecretRefs/providers. Re-run with --allow-exec.");
const i = n ? true : r;
const a = await projectPlanState({
plan: e.plan,
env: t,
write: n,
allowExecInDryRun: i
});
const o = [...a.changedFiles].toSorted();
const s = {
mode: n ? "write" : "dry-run",
changed: o.length > 0,
changedFiles: o,
checks: {
resolvability: true,
resolvabilityComplete: a.resolvabilityComplete
},
refsChecked: a.refsChecked,
skippedExecRefs: a.skippedExecRefs,
warningCount: a.warnings.length,
warnings: a.warnings
};
if (!n || o.length === 0) return s;
const c = createSecretsConfigIO({ env: t });
const l = /* @__PURE__ */ new Map();
const u = /* @__PURE__ */ new Map();
const capture = (e) => {
if (!l.has(e)) l.set(e, captureFileSnapshot(e));
};
capture(a.configPath);
for (const e of a.envRawByPath.keys()) capture(e);
for (const [e, { target: t }] of a.authStores) u.set(e, {
target: t,
persistence: captureAuthProfileStorePersistenceSnapshot(t.kind === "agent" ? t.agentDir : void 0, { env: t.kind === "shared" ? t.env : a.authStoreEnv })
});
try {
await replaceConfigFile({
nextConfig: a.nextConfig,
snapshot: a.configSnapshot,
writeOptions: a.configWriteOptions,
io: c,
afterWrite: { mode: "auto" }
});
for (const [e, n] of a.envRawByPath.entries()) writeTextFileAtomic(e, n, 384, t);
for (const [e, { store: t, target: n }] of a.authStores) {
const r = coercePersistedAuthProfileStore(t);
if (r) {
const t = u.get(e);
if (!t) throw new Error(`missing captured auth profile store for ${e}`);
const i = saveAuthProfileStoreIfPersistenceSnapshotMatches({
store: r,
snapshot: t.persistence,
agentDir: n.kind === "agent" ? n.agentDir : void 0,
...n.kind === "shared" ? { stateDir: n.stateDir } : {}
});
t.owned = i.owned;
if (!i.publishRuntimeSnapshots()) throw new Error(`auth profile runtime publication failed for ${e}`);
}
}
} catch (e) {
for (const [e, n] of l.entries()) try {
restoreFileSnapshot(e, n, t);
} catch {}
for (const e of u.values()) {
if (!e.owned) continue;
try {
restoreAuthProfileStorePersistenceSnapshot(e.persistence, e.owned, e.target.kind === "agent" ? e.target.agentDir : void 0, e.target.kind === "shared" ? { stateDir: e.target.stateDir } : {});
} catch {}
}
throw new Error(`Secrets apply failed: ${String(e)}`, { cause: e });
}
return s;
}
const testing = { async projectConfigForTest(e) {
return (await projectPlanState({
plan: e.plan,
env: e.env ?? process.env,
write: false,
allowExecInDryRun: false
})).nextConfig;
} };
//#endregion
export { testing as n, runSecretsApply as t };