openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
3 lines • 13.8 kB
JavaScript
import{o as normalizeLowercaseStringOrEmpty}from"./string-coerce-CpTFcSwY.mjs";import{g as normalizeUniqueStringEntries}from"./string-normalization-D_oBUpO3.mjs";import{n as formatConcreteConfigPath}from"./dot-path-B1bYAWM5.mjs";import{_ as resolveSecretInputRef}from"./types.secrets-UWdyCdE6.mjs";import{a as copyConfigResolutionFactsExcept,n as cloneConfigWithResolutionFacts,p as resolveConfigSecretRef}from"./resolution-facts-DYKtoyes.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{i as resolveManifestContractOwnerPluginId}from"./plugin-registry-contributions-C4xBwxaW.mjs";import{a as createResolverContext,p as assertExpectedResolvedSecretValue}from"./runtime-shared-ByPlHLvN.mjs";import{i as setPathExistingStrict,n as getPath}from"./path-utils-Da5tqfDE.mjs";import{r as discoverConfigSecretTargetsByIds}from"./target-registry-query-UuUEzVi7.mjs";import"./target-registry-D_8Q9dwn.mjs";import{o as readGatewaySecretInputValue,t as ALL_GATEWAY_SECRET_INPUT_PATHS}from"./secret-input-paths-DKW4Nh7w.mjs";import{t as gatewaySecretInputPathCanWin}from"./credentials-secret-inputs-CK6zIfEz.mjs";import{n as resolveSecretRefValue}from"./resolve-B002P2vn.mjs";import{t as analyzeCommandSecretAssignmentsFromSnapshot}from"./command-config-B-4MrWQD.mjs";import{t as collectConfigAssignments}from"./runtime-config-collectors-BXXV_ga9.mjs";import{t as resolveRuntimeWebTools}from"./runtime-web-tools-BkG34m7Z.mjs";
//!src/cli/command-secret-gateway.ts
function classifyRuntimeWebTarget(e){const t=/^plugins\.entries\.([^.]+)\.config\.(webSearch|webFetch)\.apiKey$/.exec(e.path);if(!t)return{state:`unknown`};const n=t[2]===`webFetch`?`fetch`:`search`;const r=e.config.tools?.web?.[n];if(r?.enabled===false)return{state:`inactive`,detail:`tools.web.${n} is disabled.`};const i=normalizeLowercaseStringOrEmpty(r?.provider);if(!i)return{state:`active`};const a=resolveManifestContractOwnerPluginId({contract:n===`fetch`?`webFetchProviders`:`webSearchProviders`,value:i,origin:`bundled`,config:e.config});if(!a)return{state:`unknown`};return a===t[1]?{state:`active`}:{state:`inactive`,detail:`tools.web.${n}.provider is "${i}".`}}function targetsRuntimeWebPath(e){return e.startsWith(`plugins.entries.`)}function inactiveSurfaceDiagnosticPath(e){const t=e.indexOf(`: secret ref is configured on an inactive surface;`);return t>0?e.slice(0,t).trim():void 0}function collectActiveGatewayExecSecretRefCredentialPaths(e){const t=e.secrets?.defaults;return ALL_GATEWAY_SECRET_INPUT_PATHS.filter(n=>{const{ref:r}=resolveSecretInputRef({value:readGatewaySecretInputValue(e,n),defaults:t});return r?.source===`exec`&&gatewaySecretInputPathCanWin({config:e,path:n,env:process.env})})}async function resolveCommandSecretRefsLocally(e){const t=e.config;const n=cloneConfigWithResolutionFacts(e.config);const r=createResolverContext({sourceConfig:t,env:process.env});const i=[];const a=discoverConfigSecretTargetsByIds(t,e.targetIds).filter(t=>!e.allowedPaths||e.allowedPaths.has(t.path));const o=a.filter(e=>targetsRuntimeWebPath(e.path));await collectConfigAssignments({config:cloneConfigWithResolutionFacts(e.config),context:r,agentId:e.agentId});if([...e.allowedPaths??e.targetIds].some(targetsRuntimeWebPath)&&!o.every(e=>/^plugins\.entries\.[^.]+\.config\.(webSearch|webFetch)\.apiKey$/.test(e.path)))try{await resolveRuntimeWebTools({sourceConfig:t,resolvedConfig:n,context:r})}catch(t){if(e.enforceResolved)throw t;i.push(`${e.commandName}: failed to resolve web tool secrets locally (${formatErrorMessage(t)}).`)}const s=r.warnings.filter(t=>t.code===`SECRETS_REF_IGNORED_INACTIVE_SURFACE`&&(!e.allowedPaths||e.allowedPaths.has(t.path))&&!e.forcedActivePaths?.has(t.path)&&!e.optionalActivePaths?.has(t.path));const c=new Set(s.map(e=>e.path));const l=/* @__PURE__ */ new Set;const u=[];for(const n of o){if(e.forcedActivePaths?.has(n.path)||e.optionalActivePaths?.has(n.path)){l.add(n.path);continue}const r=classifyRuntimeWebTarget({config:t,path:n.path});if(r.state===`inactive`){c.add(n.path);if(r.detail)u.push(`${n.path}: ${r.detail}`);continue}if(r.state===`active`)l.add(n.path)}const d=new Set(r.assignments.map(e=>e.path));for(const o of a){const a=t.secrets?.defaults;const{ref:s}=resolveSecretInputRef({value:resolveConfigSecretRef({config:t,path:o.path,value:o.value,defaults:a}),refValue:o.refValue,defaults:a});if(!s||c.has(o.path)||!d.has(o.path)&&!l.has(o.path)&&!e.forcedActivePaths?.has(o.path)&&!e.optionalActivePaths?.has(o.path))continue;if(s.source===`exec`&&!e.resolutionPolicy.allowExecSecretRefs){if(!e.enforceResolved)i.push(`${e.commandName}: skipped local exec SecretRef resolution for ${o.path}; rerun with --allow-exec to execute configured exec providers.`);continue}try{const e=await resolveSecretRefValue(s,{config:t,env:r.env,cache:r.cache});assertExpectedResolvedSecretValue({value:e,expected:o.entry.expectedResolvedValue,errorMessage:o.entry.expectedResolvedValue===`string`?`${o.path} resolved to a non-string or empty value.`:`${o.path} resolved to an unsupported value type.`});setPathExistingStrict(n,o.pathSegments,e);copyConfigResolutionFactsExcept(n,n,[o.path])}catch(t){if(!e.enforceResolved)i.push(`${e.commandName}: failed to resolve ${o.path} locally (${formatErrorMessage(t)}).`)}}const f=analyzeCommandSecretTargets({sourceConfig:t,resolvedConfig:n,targetIds:e.targetIds,inactiveRefPaths:c,allowedPaths:e.allowedPaths,optionalActivePaths:e.optionalActivePaths});const p=buildTargetStatesByPath({analyzed:f,resolvedState:`resolved_local`});const m=handleUnresolvedAssignments(e,n,f.unresolved);return{resolvedConfig:n,diagnostics:normalizeUniqueStringEntries([...e.preflightDiagnostics,...u,...s.map(e=>e.message),...filterInactiveSurfaceDiagnostics({diagnostics:f.diagnostics,inactiveRefPaths:c}),...i,...m]),targetStatesByPath:p,hadUnresolvedTargets:f.unresolved.length>0}}function analyzeCommandSecretTargets(e){const{optionalActivePaths:t,...n}=e;const r=analyzeCommandSecretAssignmentsFromSnapshot(n);const i=r.unresolved.filter(e=>t?.has(e.path));if(i.length===0)return r;for(const{path:e}of i)n.inactiveRefPaths.add(e);return analyzeCommandSecretAssignmentsFromSnapshot(n)}function buildTargetStatesByPath(e){const t={};for(const n of e.analyzed.assignments)t[n.path]=e.resolvedState;for(const n of e.analyzed.inactive)t[n.path]=`inactive_surface`;for(const n of e.analyzed.unresolved)t[n.path]=`unresolved`;return t}function handleUnresolvedAssignments(e,t,n){if(n.length>0&&e.enforceResolved)throw new Error(`${e.commandName}: ${n[0]?.path??`target`} is unresolved in the active runtime snapshot.`);if(e.resolutionPolicy.scrubUnresolvedSecretRefs)for(const e of n)setPathExistingStrict(t,e.pathSegments,void 0);return n.map(t=>`${e.commandName}: ${t.path} is unavailable in this command path; continuing with degraded read-only config.`)}function filterInactiveSurfaceDiagnostics(e){return e.diagnostics.filter(t=>{const n=inactiveSurfaceDiagnosticPath(t);return n===void 0||!e.inactiveRefPaths.has(n)})}async function resolveCommandSecretRefsViaGateway(e){const t=!e.mode||e.mode===`enforce_resolved`||e.mode===`strict`;const n={allowExecSecretRefs:e.allowLocalExecSecretRefs!==false,scrubUnresolvedSecretRefs:e.scrubUnresolvedSecretRefs!==false};const r={...e,enforceResolved:t,resolutionPolicy:n};const i=e.config.secrets?.defaults;const a=/* @__PURE__ */ new Set;for(const t of discoverConfigSecretTargetsByIds(e.config,e.targetIds)){if(e.allowedPaths&&!e.allowedPaths.has(t.path))continue;const{ref:n}=resolveSecretInputRef({value:resolveConfigSecretRef({config:e.config,path:t.path,value:t.value,defaults:i}),refValue:t.refValue,defaults:i});if(n)a.add(t.path)}let o={needsResolution:false,diagnostics:[]};if(a.size>0){const t={...e,configuredTargetRefPaths:a};const n=createResolverContext({sourceConfig:t.config,env:process.env});await collectConfigAssignments({config:cloneConfigWithResolutionFacts(t.config),context:n,agentId:t.agentId});const r=new Set(n.assignments.map(e=>e.path));const i=/* @__PURE__ */ new Map;for(const e of n.warnings){if(e.code!==`SECRETS_REF_IGNORED_INACTIVE_SURFACE`)continue;i.set(e.path,e.message)}const s=/* @__PURE__ */ new Set;let c=false;for(const e of t.configuredTargetRefPaths){const n=!r.has(e)&&!t.forcedActivePaths?.has(e)&&!t.optionalActivePaths?.has(e)?i.get(e):void 0;if(n)s.add(n);else c=true}o={needsResolution:c,diagnostics:[...s]}}if(!o.needsResolution)return{resolvedConfig:e.config,diagnostics:o.diagnostics,targetStatesByPath:{},hadUnresolvedTargets:false};const resolveLocally=(t=e.allowedPaths,n=o.diagnostics)=>resolveCommandSecretRefsLocally({...r,preflightDiagnostics:n,allowedPaths:t});if(e.localGatewayAbsent&&e.config.gateway?.mode!==`remote`&&!process.env.OPENCLAW_GATEWAY_URL?.trim()&&!process.env.OPENCLAW_GATEWAY_PORT?.trim())try{return await resolveLocally()}catch{throw new Error(`${e.commandName}: failed to resolve command secrets locally. Check the configured secret sources, then retry.`)}const s=n.allowExecSecretRefs?[]:collectActiveGatewayExecSecretRefCredentialPaths(e.config);if(s.length>0){const t=await resolveLocally();return{...t,diagnostics:normalizeUniqueStringEntries([...t.diagnostics,`${e.commandName}: skipped gateway secrets.resolve because gateway credentials use exec SecretRefs at ${s.join(`, `)}; rerun with --allow-exec to execute configured exec providers.`])}}const{callGatewaySecretsResolve:c,isAllowedPathsSecretsResolveCompatError:l}=await import(`./command-secret-gateway-request-CVgEdTHM.mjs`);let u;try{u=await c(e)}catch(t){const n=Boolean(e.forcedActivePaths?.size)&&l(t);let r=`Local resolution also failed.`;try{const r=await resolveLocally();const i=Object.values(r.targetStatesByPath).some(e=>e===`resolved_local`);if(!n||i&&!r.hadUnresolvedTargets){const n=i&&!r.hadUnresolvedTargets?`resolved command secrets locally.`:`attempted local command-secret resolution.`;return{...r,diagnostics:normalizeUniqueStringEntries([...r.diagnostics,`${e.commandName}: gateway secrets.resolve unavailable (${formatErrorMessage(t)}); ${n}`])}}}catch(e){r=`Local resolution also failed (${formatErrorMessage(e)}).`}if(n)throw new Error(`${e.commandName}: active gateway does not support command-scoped secret resolution (${formatErrorMessage(t)}). Update the gateway or run this command where the configured SecretRefs can be resolved locally.`,{cause:t});const i=normalizeLowercaseStringOrEmpty(formatErrorMessage(t));if(i.includes(`secrets.resolve`)&&(i.includes(`does not support required method`)||i.includes(`unknown method`)||i.includes(`method not found`)||i.includes(`invalid request`)))throw new Error(`${e.commandName}: active gateway does not support secrets.resolve (${formatErrorMessage(t)}). Update the gateway or run without SecretRefs.`,{cause:t});throw new Error(`${e.commandName}: failed to resolve secrets from the active gateway snapshot (${formatErrorMessage(t)}). ${r} Check the configured secret sources and gateway access, then retry.`,{cause:t})}const{validateSecretsResolveResult:d}=await import(`./gateway/protocol/index.js`);if(!d(u))throw new Error(`gateway returned invalid secrets.resolve payload.`);const f={assignments:u.assignments??[],diagnostics:(u.diagnostics??[]).filter(e=>e.trim().length>0),inactiveRefPaths:(u.inactiveRefPaths??[]).filter(e=>e.trim().length>0)};const p={...e,diagnostics:f.diagnostics};const m=p.diagnostics.filter(e=>{const t=e.indexOf(`:`);if(t<=0)return true;const n=e.slice(0,t).trim();if(!n.includes(`.`))return true;if(p.forcedActivePaths?.has(n)||p.optionalActivePaths?.has(n))return false;return!p.allowedPaths||p.allowedPaths.has(n)});const h=e.allowedPaths?f.inactiveRefPaths.filter(t=>e.allowedPaths?.has(t)):f.inactiveRefPaths;const g=cloneConfigWithResolutionFacts(e.config);const _=[];for(const{pathSegments:t,value:n}of f.assignments){if(t.length===0)continue;const r=formatConcreteConfigPath(t,g);if(e.allowedPaths&&!e.allowedPaths.has(r))continue;try{setPathExistingStrict(g,t,n);_.push(r)}catch(t){throw new Error(`${e.commandName}: failed to apply resolved secret assignment at ${r} (${formatErrorMessage(t)}).`,{cause:t})}}copyConfigResolutionFactsExcept(g,g,_);const v=new Set(h.length>0?h:m.flatMap(e=>{const t=inactiveSurfaceDiagnosticPath(e);return t?[t]:[]}));for(const t of e.forcedActivePaths??[])v.delete(t);for(const t of e.optionalActivePaths??[])v.delete(t);const y=analyzeCommandSecretTargets({sourceConfig:e.config,resolvedConfig:g,targetIds:e.targetIds,inactiveRefPaths:v,allowedPaths:e.allowedPaths,optionalActivePaths:e.optionalActivePaths});let b=normalizeUniqueStringEntries(m);const x=buildTargetStatesByPath({analyzed:y,resolvedState:`resolved_gateway`});if(y.unresolved.length>0)try{const t=await resolveLocally(new Set(y.unresolved.map(e=>e.path)),[]);const n=/* @__PURE__ */ new Set;for(const e of y.unresolved){const r=t.targetStatesByPath[e.path];if(r!==`resolved_local`&&r!==`inactive_surface`)continue;if(r===`resolved_local`){setPathExistingStrict(g,e.pathSegments,getPath(t.resolvedConfig,e.pathSegments));n.add(e.path)}x[e.path]=r}copyConfigResolutionFactsExcept(g,g,[...n]);b=normalizeUniqueStringEntries([...b,...t.diagnostics]);const i=y.unresolved.filter(e=>x[e.path]===`unresolved`);if(i.length>0)b=normalizeUniqueStringEntries([...b,...handleUnresolvedAssignments(r,g,i)]);else if(n.size>0)b=normalizeUniqueStringEntries([...b,`${e.commandName}: resolved ${n.size} secret ${n.size===1?`path`:`paths`} locally after the gateway snapshot was incomplete.`])}catch(n){if(t)throw n;b=normalizeUniqueStringEntries([...b,`${e.commandName}: local fallback after incomplete gateway snapshot failed (${formatErrorMessage(n)}).`,...handleUnresolvedAssignments(r,g,y.unresolved)])}return{resolvedConfig:g,diagnostics:b,targetStatesByPath:x,hadUnresolvedTargets:Object.values(x).includes(`unresolved`)}}export{resolveCommandSecretRefsViaGateway as t};