openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
9 lines • 16.6 kB
JavaScript
import{c as normalizeOptionalLowercaseString,l as normalizeOptionalString,o as normalizeLowercaseStringOrEmpty}from"./string-coerce-CpTFcSwY.mjs";import{f as normalizeStringEntries,m as normalizeTrimmedStringList}from"./string-normalization-D_oBUpO3.mjs";import{i as normalizeChatChannelId}from"./ids-CXs0NhN-.mjs";import{n as normalizeAccountId}from"./account-id-3yqrEsRn.mjs";import{n as createRuntimeConfigReader}from"./runtime-snapshot-Bg5K4JNu.mjs";import{s as composeSessionSourceAssertion}from"./session-source-authority-Cun3s-rH.mjs";import{a as listLoadedChannelPlugins,i as getLoadedChannelPluginForRead,n as getLoadedChannelPluginById}from"./registry-loaded-BEn6LBRM.mjs";import{t as INTERNAL_MESSAGE_CHANNEL}from"./message-channel-constants-BbP_hczw.mjs";import{t as warnPluginSdkDeprecation}from"./sdk-deprecation-BDUCyBrU.mjs";import{t as normalizeAnyChannelId}from"./registry-normalize-BP0gv89S.mjs";import"./registry-yecJKTDP.mjs";import{n as normalizeMessageChannel}from"./message-channel-core-D_hPOadj.mjs";import{a as isInternalMessageChannel}from"./message-channel-514k57tV.mjs";import{i as resolveChannelAllowFrom}from"./account-resolution-BMEKSThh.mjs";import{i as prepareConfiguredCommandOwnerAuthority}from"./user-channel-identity-operations-BbYvG0PX.mjs";import{i as resolveUpdateChannelOperatorAdminIdentityAuthority,r as resolveChannelOperatorAdminAuthority,t as prepareChannelOperatorAdmin}from"./channel-operator-authority-D03OoTLP.mjs";import{r as resolveChannelAccountEntry}from"./account-lookup-DXbrh7Os.mjs";
//!src/auto-reply/command-owner-authority.ts
const COMMAND_OWNER_AUTHORITY=Symbol(`openclaw.commandOwnerAuthority`);var CommandOwnerRevokedError=class extends Error{};const capabilities=/* @__PURE__ */ new WeakMap;function bindCommandOwnerAuthority(e,t){const n=t.isCurrent.bind(t);const r=t.operatorAuthority;const i={recoveryReference:t.recoveryReference&&Object.freeze({...t.recoveryReference}),channelPrincipal:t.channelPrincipal&&Object.freeze({...t.channelPrincipal}),operatorAuthority:r,successor:t.successor,isCurrent:n,sourceAssertion:t.sourceAssertion};Object.setPrototypeOf(i,null);Object.freeze(i);capabilities.set(i,i);Object.assign(e,{[COMMAND_OWNER_AUTHORITY]:i})}function getCommandOwnerAuthority(e){const t=Reflect.get(e,COMMAND_OWNER_AUTHORITY);return typeof t===`object`&&t!==null?capabilities.get(t):void 0}function transferCommandOwnerAuthorityToSuccessor(e){const t=getCommandOwnerAuthority(e);if(!t)return`none`;Reflect.deleteProperty(e,COMMAND_OWNER_AUTHORITY);if(!t.successor)return`removed`;bindCommandOwnerAuthority(e,t.successor);return`transferred`}function captureCommandOwnerAssertion(e){const t=getCommandOwnerAuthority(e);if(!t)return;const assertCurrent=()=>{if(!t.isCurrent())throw new CommandOwnerRevokedError(`Channel operator authority changed; send a new request.`)};return Object.assign(assertCurrent,{recoveryReference:t.recoveryReference??null,prepareSessionSourceEffect:composeSessionSourceAssertion([t.sourceAssertion],e=>{e();assertCurrent()}).prepareSessionSourceEffect})}
//!src/auto-reply/command-sender-authority.ts
const COMMAND_SENDER_AUTHORITY=Symbol(`openclaw.commandSenderAuthority`);function withCommandSenderAuthority(e,t){return{...e,[COMMAND_SENDER_AUTHORITY]:t}}function getCommandSenderAuthority(e){return e?.[COMMAND_SENDER_AUTHORITY]}
//!src/auto-reply/sender-identity.ts
function isConversationLikeIdentity(e){const t=e.toLowerCase();if(t.startsWith(`chat_id:`))return true;return/(^|:)(channel|group|thread|topic|room|space|spaces):/.test(t)}function shouldUseFromAsSenderFallback(e){const t=normalizeOptionalString(e.from)??``;if(!t)return false;const n=normalizeLowercaseStringOrEmpty(e.chatType);if(n&&n!==`direct`)return false;return!isConversationLikeIdentity(t)}function formatAllowFromList(e){const{plugin:t,cfg:n,accountId:r,allowFrom:i}=e;if(!i||i.length===0)return[];if(t?.config?.formatAllowFrom)return t.config.formatAllowFrom({cfg:n,accountId:r,allowFrom:i});return normalizeStringEntries(i)}function normalizeAllowFromEntry(e){return formatAllowFromList({...e,allowFrom:[e.value]}).filter(e=>Boolean(e.trim()))}function resolveSenderCandidates(e){const{plugin:t,cfg:n,accountId:r}=e;const i=normalizeTrimmedStringList(t?.commands?.preferSenderE164ForCommands?[e.senderE164,e.senderId]:[e.senderId,e.senderE164]);if(i.length===0&&shouldUseFromAsSenderFallback({from:e.from,chatType:e.chatType}))i.push(...normalizeTrimmedStringList([e.from]));i.push(...normalizeTrimmedStringList([e.commandSenderId]));return[...new Set(i.flatMap(e=>normalizeAllowFromEntry({plugin:t,cfg:n,accountId:r,value:e})))]}
//!src/auto-reply/command-auth.ts
function resolveExplicitProviderFromContext(e){const t=[e.Surface,e.OriginatingChannel,e.Provider].map(e=>normalizeMessageChannel(e)).filter(e=>Boolean(e));const n=t.find(e=>e!==INTERNAL_MESSAGE_CHANNEL);if(!n&&t.includes(`webchat`))return{providerId:void 0,hadResolutionError:false};const r=normalizeAnyChannelId(n)??n??normalizeAnyChannelId(e.Provider)??normalizeAnyChannelId(e.Surface)??normalizeAnyChannelId(e.OriginatingChannel);if(r)return{providerId:r,hadResolutionError:false};const i=[e.From,e.To].filter(e=>Boolean(e?.trim())).flatMap(e=>e.split(`:`).map(e=>e.trim()));for(const e of i){const t=normalizeMessageChannel(e);if(t===`webchat`)return{providerId:void 0,hadResolutionError:false};const n=normalizeAnyChannelId(t)??t??normalizeAnyChannelId(e);if(n)return{providerId:n,hadResolutionError:false}}}function resolveInferredProvider(e){let t=false;const n=[];for(const{providerId:r,resolved:i}of e)if(i.allowFromList.length>0)n.push({providerId:r,hadResolutionError:i.hadResolutionError});else if(i.hadResolutionError)t=true;const r=n[0];if(n.length===1&&r)return r;return{providerId:void 0,hadResolutionError:t||n.some(e=>e.hadResolutionError)}}function isWildcardAllowFromEntry(e){return e.trim()===`*`}function stripWildcardAllowFrom(e){return e.filter(e=>!isWildcardAllowFromEntry(e))}function resolveProviderAllowFromResult(e,t){const{plugin:n,cfg:r,accountId:i}=e;const a=e.forceFallbackResolutionError?e.providerId??n?.id:n?.id;let o=Boolean(e.forceFallbackResolutionError);let s;if(`error`in t){console.warn(`[command-auth] resolveAllowFrom threw for provider "${a}", falling back to config allowFrom: ${describeAllowFromResolutionError(t.error)}`);o=true}else if(t.value!=null&&!Array.isArray(t.value)){console.warn(`[command-auth] resolveAllowFrom returned an invalid allowFrom for provider "${a}", falling back to config allowFrom: invalid_result`);o=true}if(o)s=resolveFallbackAllowFrom({cfg:r,providerId:a,accountId:i});else s=`value`in t&&Array.isArray(t.value)?t.value:[];return{allowFromList:formatAllowFromList({plugin:n,cfg:r,accountId:i,allowFrom:s}),hadResolutionError:o}}function resolveProviderAllowFrom(e){const{plugin:t,cfg:n,accountId:r}=e;let i;if(e.forceFallbackResolutionError||!t?.config?.resolveAllowFrom)i={value:resolveFallbackAllowFrom({cfg:n,providerId:e.forceFallbackResolutionError?e.providerId??t?.id:t?.id,accountId:r})};else try{i={value:t.config.resolveAllowFrom({cfg:n,accountId:r})}}catch(e){i={error:e}}return resolveProviderAllowFromResult(e,i)}async function resolveProviderAllowFromAsync(e){const{plugin:t,cfg:n,accountId:r}=e;if(e.forceFallbackResolutionError||!t)return resolveProviderAllowFrom(e);let i;try{i={value:t.config.resolveAllowFromAsync||t.config.resolveAllowFrom?await resolveChannelAllowFrom({plugin:t,cfg:n,accountId:r}):resolveFallbackAllowFrom({cfg:n,providerId:t.id,accountId:r})}}catch(e){i={error:e}}return resolveProviderAllowFromResult(e,i)}function describeAllowFromResolutionError(e){return e instanceof Error?normalizeOptionalString(e.name)??`Error`:`unknown_error`}function resolveOwnerAllowFromList(e){const t=e.allowFrom??e.cfg.commands?.ownerAllowFrom;if(!Array.isArray(t)||t.length===0)return[];const n=[];for(const r of normalizeStringEntries(t.map(e=>e??``))){const t=r.indexOf(`:`);const i=r.slice(0,t);const a=t>0?normalizeAnyChannelId(i)??normalizeChatChannelId(i):void 0;if(!a){n.push(r);continue}if(a!==e.providerId)continue;const o=r.slice(t+1).trim();if(normalizeChatChannelId(i)&&/^[^:]+:user:[^:\s*]+$/i.test(r)&&e.plugin?.messaging?.directTargetStyle!==`user-prefixed`){if(!e.plugin&&e.migrationDeferredChannels?.includes(a))n.push(o.slice(5));continue}if(o)n.push(o)}return formatAllowFromList({...e,allowFrom:n})}function resolveExplicitOwnerList(e){return Array.from(new Set(stripWildcardAllowFrom(resolveOwnerAllowFromList(e))))}function resolveFallbackAllowFrom(e){const t=normalizeOptionalString(e.providerId);if(!t)return[];const n=e.cfg.channels?.[t];let r=resolveFallbackAccountConfig(n?.accounts,t,e.accountId);if(r==null){const e=n?.accounts;if(e){r=resolveFallbackAccountConfig(e,t,n?.defaultAccount)??resolveFallbackAccountConfig(e,t,`default`);if(!r){const n=Object.keys(e).filter(t=>e[t]);const i=n.length===1?n[0]:void 0;r=i===void 0?void 0:resolveChannelAccountEntry(e,i,t)}}}const i=r?.allowFrom??r?.dm?.allowFrom??n?.allowFrom??n?.dm?.allowFrom;return Array.isArray(i)?i:[]}function resolveFallbackAccountConfig(e,t,n){const r=normalizeOptionalLowercaseString(n);if(!e||!r)return;return resolveChannelAccountEntry(e,r,t)}function resolveCommandAuthorizationState(e,t){const{ctx:n,cfg:r,commandAuthorized:i}=e;const{providerId:a,hadResolutionError:o}=t?.provider??resolveExplicitProviderFromContext(n)??resolveInferredProvider(listLoadedChannelPlugins().map(e=>({providerId:e.id,resolved:resolveProviderAllowFrom({plugin:e,cfg:r,accountId:n.AccountId})})));const s=a?getLoadedChannelPluginById(a):void 0;const c=normalizeOptionalString(n.From)??``;const l=normalizeOptionalString(n.To)??``;const u=Boolean(r.commands?.allowFrom&&typeof r.commands.allowFrom===`object`);const d={plugin:s,cfg:r,accountId:n.AccountId,providerId:a};const f=r.commands?.allowFrom;let p=null;if(f&&typeof f===`object`){const e=f[a??``];const t=f[`*`];const n=Array.isArray(e)?e:t;if(Array.isArray(n))p=formatAllowFromList({...d,allowFrom:n})}const m=t?.allowFrom??resolveProviderAllowFrom({...d,forceFallbackResolutionError:o});const{allowFromList:h,hadResolutionError:g}=m;const _=n.OwnerAllowFrom;const v=resolveOwnerAllowFromList({...d,allowFrom:_});const y=!g&&(h.length===0||h.some(isWildcardAllowFromEntry));const b=y?[]:stripWildcardAllowFrom(h);if(!y&&b.length===0&&l)b.push(...normalizeAllowFromEntry({...d,value:l}));const x=resolveExplicitOwnerList(d);const S=stripWildcardAllowFrom(v);const C=new Set(x.length>0?x:S.length>0?S:b);const w=resolveSenderCandidates({...d,senderId:n.SenderId,senderE164:n.SenderE164,commandSenderId:getCommandSenderAuthority(n)?.(),from:c,chatType:n.ChatType});const T=w.find(e=>x.includes(e));const E=w.find(e=>C.has(e));const D=T??E??w[0];const O=Boolean(s?.commands?.enforceOwnerForCommands);const k=Boolean(T);const A=isInternalMessageChannel(n.Provider)&&Array.isArray(n.GatewayClientScopes)&&n.GatewayClientScopes.includes(`operator.admin`);const j=x.length>0;const M=captureCommandOwnerAssertion(n);const N=k||A||getCommandOwnerAuthority(n)?.isCurrent()===true;const P=!(O||j)?true:j?N:N||Boolean(E);let F=`denied`;if(n.CommandInterpretationSuppressed!==true&&(!O||P)){if(p!==null||o&&u){if(!o)F=p?.some(e=>isWildcardAllowFromEntry(e)||w.includes(e))?`commands`:`denied`}else if(i)F=P?`commands`:`reset-only`}return{authorization:{providerId:a,ownerList:x,senderId:D||void 0,senderIsOwner:N,...M?{assertOwnerCurrent:M}:{},isAuthorizedSender:F===`commands`,from:c||void 0,to:l||void 0},access:F,prepared:{provider:{providerId:a,hadResolutionError:o},allowFrom:m}}}function retainCommandAuthorization(e,t,n){const r={...e,ctx:{...e.ctx},cfg:n()};const{authorization:i,prepared:a}=resolveCommandAuthorizationState(r,t);const o=i.providerId?getLoadedChannelPluginById(i.providerId):void 0;return{...i,assertAuthorizedCurrent:()=>{const e=resolveCommandAuthorizationState({...r,cfg:n()},a).authorization;if(!i.isAuthorizedSender||!e.isAuthorizedSender||e.providerId!==i.providerId||e.senderId!==i.senderId||i.providerId&&getLoadedChannelPluginById(i.providerId)!==o)throw new Error(`Your command authorization changed; send a new request.`)}}}function resolveCommandAuthorization(e){warnPluginSdkDeprecation({family:`command-authorization-sync`,method:`resolveCommandAuthorization`,replacement:`resolveCommandAuthorizationAsync`});return retainCommandAuthorization(e,void 0,createRuntimeConfigReader(e.cfg))}async function prepareCommandAuthorization(e){const{ctx:t,cfg:n}=e;const r=resolveExplicitProviderFromContext(t)??resolveInferredProvider(await Promise.all(listLoadedChannelPlugins().map(async e=>({providerId:e.id,resolved:await resolveProviderAllowFromAsync({plugin:e,cfg:n,accountId:t.AccountId})}))));return{provider:r,allowFrom:await resolveProviderAllowFromAsync({plugin:r.providerId?getLoadedChannelPluginById(r.providerId):void 0,cfg:n,accountId:t.AccountId,providerId:r.providerId,forceFallbackResolutionError:r.hadResolutionError})}}async function resolveCommandAuthorizationAsync(e){const t=createRuntimeConfigReader(e.cfg);return retainCommandAuthorization(e,await prepareCommandAuthorization(e),t)}function resolveConfiguredCommandOwners(e,t){const n=normalizeAnyChannelId(t.channel)??t.channel;return resolveExplicitOwnerList({cfg:e,plugin:n?getLoadedChannelPluginForRead(n):void 0,providerId:n,accountId:t.accountId})}function isConfiguredCommandOwner(e,t,n={}){const r=normalizeAnyChannelId(t.channel)??t.channel;const i={cfg:e,plugin:r?getLoadedChannelPluginForRead(r):void 0,providerId:r,accountId:t.accountId};const a=stripWildcardAllowFrom(resolveOwnerAllowFromList({...i,...n}));return resolveSenderCandidates({...i,senderId:t.senderId,senderE164:t.senderE164}).some(e=>a.includes(e))}function resolveCommandOwnerAuthority(e,t,n={}){return captureCommandOwnerIdentity(e,t,n,resolveChannelOperatorAdminAuthority)}function resolveUpdateRequesterIdentityAuthority(e,t,n={}){return captureCommandOwnerIdentity(e,t,n,resolveUpdateChannelOperatorAdminIdentityAuthority)}function resolveCommandOwnerIdentity(e){const t=normalizeAnyChannelId(e?.channel)??e?.channel;return t&&e?.senderId?{channelId:t,accountId:normalizeAccountId(e.accountId),senderId:e.senderId}:void 0}function captureCommandOwnerIdentity(e,t,n,r){const i={...t};if(isConfiguredCommandOwner(e,i))return Object.freeze({source:`configured-owner`,isCurrent:e=>isConfiguredCommandOwner(e,i)});const a=resolveCommandOwnerIdentity(i);const o=a?r(e,a,n):void 0;return Object.freeze({source:o?`profile:${o.profileId}`:void 0,...o?.signal?{signal:o.signal}:{},isCurrent:e=>o!==void 0&&!isConfiguredCommandOwner(e,i)&&o.isCurrent(e)})}async function prepareCommandOwnerAuthority(e,t,n={}){const r=`identity`in t?t:void 0;const i=`identity`in t?{channel:t.identity.channelId,accountId:t.identity.accountId,senderId:t.identity.senderId}:`version`in t?void 0:{...t};const a=`version`in t?t:void 0;if(a?.version===2||i&&isConfiguredCommandOwner(e,i)){const t=await prepareConfiguredCommandOwnerAuthority(e.commands?.ownerAllowFrom,n);const r=!a||t?.recoveryReference.id===a.id;return Object.freeze({source:r?`configured-owner`:void 0,recoveryReference:t?.recoveryReference,isCurrent:e=>r&&(t?t.isCurrent():!a)&&(!i||isConfiguredCommandOwner(e,i))})}const o=a??resolveCommandOwnerIdentity(i);const s=o&&await prepareChannelOperatorAdmin(e,r??o,n);return Object.freeze({source:s?`profile:${s.profileId}`:void 0,operatorProfile:s?.operatorProfile,recoveryReference:s?.recoveryReference,...s?.signal?{signal:s.signal}:{},isCurrent:e=>s!==void 0&&(!i||!isConfiguredCommandOwner(e,i))&&s.isCurrent(e)})}async function isResetAuthorizedForContext(e){return resolveCommandAuthorizationState(e,await prepareCommandAuthorization(e)).access!==`denied`&&isResetAllowedForGatewayScopes(e.ctx)}function isResetAllowedForGatewayScopes(e){const t=e.Provider;if(!(t?isInternalMessageChannel(t):isInternalMessageChannel(e.Surface)))return true;const n=e.GatewayClientScopes;if(!Array.isArray(n)||n.length===0)return true;return n.includes(`operator.admin`)}export{resolveCommandAuthorizationAsync as a,resolveUpdateRequesterIdentityAuthority as c,withCommandSenderAuthority as d,CommandOwnerRevokedError as f,transferCommandOwnerAuthorityToSuccessor as g,getCommandOwnerAuthority as h,resolveCommandAuthorization as i,shouldUseFromAsSenderFallback as l,captureCommandOwnerAssertion as m,isResetAuthorizedForContext as n,resolveCommandOwnerAuthority as o,bindCommandOwnerAuthority as p,prepareCommandOwnerAuthority as r,resolveConfiguredCommandOwners as s,isConfiguredCommandOwner as t,getCommandSenderAuthority as u};