openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
7 lines • 13.7 kB
JavaScript
import{t as hasNonEmptyString}from"./string-coerce-CpTFcSwY.mjs";import{c as resolveUserPath}from"./home-dir-DEN5DisQ.mjs";import{l as isRecord}from"./record-coerce-BTbqdJ3-.mjs";import{a as coerceSecretRef}from"./types.secrets-UWdyCdE6.mjs";import{r as resolveStateDir}from"./state-dir-BwIClCab.mjs";import"./utils-Dlk0IYAa.mjs";import{r as normalizeProviderId}from"./provider-id-A-8WTtLA.mjs";import{a as resolveAgentDir}from"./agent-scope-config-CG9CFpGX.mjs";import{r as decodeUtf8Input}from"./utf8-input-CiFSnxL0.mjs";import{d as coercePersistedAuthProfileStore}from"./user-model-account-authority-B8H7rvCb.mjs";import{a as findPluginConfigEntry,c as normalizePluginConfigId,o as hasPluginConfigId}from"./provider-auth-aliases-BRA1A5Vm.mjs";import{i as listKnownSecretEnvVarNames}from"./provider-env-vars-CSXML2JF.mjs";import"./agent-scope-Dw5XRSEh.mjs";import{r as parseEnvValue}from"./shared-D0HXA3v0.mjs";import{p as assertExpectedResolvedSecretValue}from"./runtime-shared-ByPlHLvN.mjs";import{n as getPath,r as setPathCreateStrict,t as deletePathStrict}from"./path-utils-Da5tqfDE.mjs";import{i as loadPersistedSharedAuthProfileStore,n as loadPersistedAuthProfileStore}from"./persisted-CpbPYi0y.mjs";import{b as resolveAuthProfileDatabasePath}from"./sqlite-y_WDH-Xr.mjs";import{d as resolveSharedAuthStorePath}from"./path-resolve-TSS6dv07.mjs";import{r as replaceConfigFile}from"./mutate-DcH8aT_4.mjs";import"./config-DkZ8y8Gv.mjs";import"./model-selection-CNHinoVN.mjs";import{l as restoreAuthProfileStorePersistenceSnapshot,n as captureAuthProfileStorePersistenceSnapshot}from"./store-CX8ovUiF.mjs";import{p as loadAuthProfileStoreForSecretsRuntime,x as saveAuthProfileStoreIfPersistenceSnapshotMatches}from"./store-runtime-GNz-2GjY.mjs";import{n as resolveSecretRefValue}from"./resolve-B002P2vn.mjs";import"./auth-profiles-nMUErGRQ.mjs";import{t as getSkippedExecRefStaticError}from"./exec-resolution-policy-CUMwyHPr.mjs";import{n as listSecretsDotEnvPaths}from"./storage-scan-D4Z_UnUK.mjs";import{a as prepareSecretsRuntimeSnapshot}from"./runtime-_5KWLVzx.mjs";import{i as iterateAuthProfileCredentials,n as writeTextFileAtomic,r as listAuthProfileStoreTargets,t as createSecretsConfigIO}from"./config-io-DR0419tG.mjs";import{n as normalizeSecretsPlanOptions,r as resolveValidatedPlanTarget}from"./plan-BKl7BXRl.mjs";import fs from"node:fs";import os from"node:os";import{isDeepStrictEqual}from"node:util";
//!src/secrets/apply.ts
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(`
`);const o=i.join(`
`);return a||o.length===0?`${o}${o.endsWith(`
`)?``:`
`}`: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(coerceSecretRef(t.refValue,i.secrets?.defaults)===null){if(hasNonEmptyString(t.value))c.push(`Auth profile "${t.profileId}" for provider "${n}" in ${e} retains its plaintext credential because it has no valid ${t.refField}. Add an explicit auth-profile target to migrate this account.`);continue}if(hasNonEmptyString(t.value))f.add(t.value.trim());if(t.valueField in t.profile){delete t.profile[t.valueField];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)}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}};export{testing as n,runSecretsApply as t};