openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
6 lines • 13.4 kB
JavaScript
import{o as normalizeLowercaseStringOrEmpty}from"./string-coerce-CpTFcSwY.mjs";import{r as asNullableRecord}from"./record-coerce-BTbqdJ3-.mjs";import{b as uniqueStrings,f as normalizeStringEntries}from"./string-normalization-D_oBUpO3.mjs";import{t as formatErrorMessage}from"./errors-D37BJTfI.mjs";import{D as parseSessionDeliveryRoute,d as resolveLinkedDirectPeerId}from"./session-key-BPgKfU2m.mjs";import{t as AgentSelectionRequiredError}from"./agent-scope-config-CG9CFpGX.mjs";import{t as dedupeByKey}from"./dedupe-by-key-Bdyq9B5M.mjs";import{n as parseToolsBySenderTypedKey}from"./types.tools-BsJ4sBxh.mjs";import{a as resolvePluginDmPolicy,r as resolveChannelAccount}from"./account-resolution-BMEKSThh.mjs";import{n as canonicalizeMainSessionAlias}from"./main-session-C6FGqx0x.mjs";import{i as listExactDirectMessageBindingPeerIds,o as resolveAgentRoute}from"./resolve-route-DpjPYoyg.mjs";import{a as parseAccessGroupAllowFromEntry}from"./allow-from-DWjUTXyB.mjs";import{n as readChannelIngressStoreAllowFromForDmPolicy}from"./store-allow-from-CZObZKr8.mjs";import{n as isDangerousNameMatchingEnabled}from"./dangerous-name-matching-eM3V_QcL.mjs";import{i as resolveChannelDefaultAccountId}from"./helpers-1A2j6LGz.mjs";import{i as hasResolvedCredentialValue,r as hasConfiguredUnavailableCredentialStatus}from"./account-snapshot-fields-Dt8EOHJC.mjs";import{t as inspectReadOnlyChannelAccount}from"./read-only-account-inspect-DIBat5m6.mjs";
//!src/channels/message-access/dm-allow-state.ts
async function resolveDmAllowAuditState(e){const t=normalizeStringEntries(Array.isArray(e.allowFrom)?e.allowFrom:void 0);const n=t.includes(`*`);const r=await readChannelIngressStoreAllowFromForDmPolicy({provider:e.provider,accountId:e.accountId,dmPolicy:e.dmPolicy});const i=e.normalizeEntry??(e=>e);const a=normalizeStringEntries(t.filter(e=>e!==`*`).map(e=>i(e)));const o=normalizeStringEntries(r.map(e=>i(e)));return{hasWildcard:n,admittedPrincipals:Array.from(/* @__PURE__ */ new Set([...a,...o]))}}
//!src/security/audit-channel.ts
function*mutableToolsBySenderKeys(e,t,n=true){const r=asNullableRecord(e);if(!r)return;for(const[e,i]of Object.entries(r)){if(e===`toolsBySender`){const e=asNullableRecord(i);for(const n of Object.keys(e??{})){const e=parseToolsBySenderTypedKey(n);if(e?.type===`name`||e?.type===`username`)yield{path:`${t}.toolsBySender`,key:e.type}}continue}if(n&&e===`accounts`)continue;yield*mutableToolsBySenderKeys(i,`${t}.${e}`,false)}}function hasExplicitProviderAccountConfig(e,t,n){const r=e.channels?.[t];if(!r||typeof r!==`object`)return false;const i=r.accounts;if(!i||typeof i!==`object`)return false;return Object.hasOwn(i,n)}async function collectChannelSecurityFindingsCore(e){const t=[];const n=[];const r=e.sourceConfig??e.cfg;const i=e.mode!==`doctor`;const recordPrincipal=(t,r,i,a,o=false)=>{const s=canonicalizeMainSessionAlias({cfg:e.cfg,agentId:r.agentId,sessionKey:i});const c={accountKey:`${t.id}-${r.accountId}`,logicalPrincipalKey:a,bucketKey:`${r.agentId}\0${s}`};n.push(c);if(!o)return;const l=parseSessionDeliveryRoute(s);const u=l?.peerKind===`direct`||l?.peerKind===`dm`?l.channel:void 0;if(u||i===r.sessionKey&&r.dmScope===`per-peer`)n.push({...c,bucketKey:`${r.agentId}\0symbolic:dm:peer`});if(u)n.push({...c,bucketKey:`${r.agentId}\0symbolic:dm:channel:${u}`})};const inspectChannelAccount=async(e,t,n)=>{if(e.config.inspectAccount)return await e.config.inspectAccount(t,n);return await inspectReadOnlyChannelAccount({channelId:e.id,cfg:t,accountId:n})};const resolveChannelAuditAccount=async(t,n)=>{const i=[];const a=await inspectChannelAccount(t,r,n);const o=await inspectChannelAccount(t,e.cfg,n);const s=a;const c=o;let l=o;if(!l)try{l=await resolveChannelAccount({plugin:t,cfg:e.cfg,accountId:n})}catch(e){i.push(`${t.id}:${n}: failed to resolve account (${formatErrorMessage(e)}).`)}if(!l&&a)l=a;if(!l)return{account:{},enabled:false,configured:false,diagnostics:i};const u=Boolean(a&&hasConfiguredUnavailableCredentialStatus(a)&&(!hasResolvedCredentialValue(l)||s?.configured===true&&c?.configured===false));const d=u?a:l;const f=u?s:c;const p=asNullableRecord(d);const m={enabled:true,configured:true};for(const r of[`enabled`,`configured`]){const a=f?.[r];if(typeof a===`boolean`){m[r]=a;continue}const o=p?.[r];if(typeof o===`boolean`){m[r]=o;continue}try{if(r===`enabled`&&t.config.isEnabled)m.enabled=t.config.isEnabled(d,e.cfg);else if(r===`configured`&&t.config.isConfigured)m.configured=await t.config.isConfigured(d,e.cfg)}catch(e){m[r]=false;i.push(`${t.id}:${n}: failed to evaluate ${r} state (${formatErrorMessage(e)}).`)}}return{account:d,...m,diagnostics:i}};const warnDmPolicy=async e=>{const n=e.policyPath??`${e.allowFromPath}policy`;const r=await resolveDmAllowAuditState({provider:e.provider,accountId:e.accountId,allowFrom:e.allowFrom,dmPolicy:e.dmPolicy,normalizeEntry:e.normalizeEntry});const{hasWildcard:i}=r;if(e.dmPolicy===`open`){const r=`${e.allowFromPath}allowFrom`;t.push({checkId:`channels.${e.provider}.dm.open`,severity:`critical`,title:`${e.label} DMs are open`,detail:`${n}="open" allows anyone to DM the bot.`,remediation:`Use pairing/allowlist; if you really need open DMs, check that ${r} includes "*".`});if(!i)t.push({checkId:`channels.${e.provider}.dm.open_invalid`,severity:`warn`,title:`${e.label} DM config looks inconsistent`,detail:`"open" requires ${r} to include "*".`})}if(e.dmPolicy===`disabled`){t.push({checkId:`channels.${e.provider}.dm.disabled`,severity:`info`,title:`${e.label} DMs are disabled`,detail:`${n}="disabled" ignores inbound DMs.`});return r}if(e.dmPolicy!==`open`&&r.admittedPrincipals.length===0)t.push({checkId:`channels.${e.provider}.dm.locked`,severity:`info`,title:`${e.label} DMs are locked`,detail:`${n}="${e.dmPolicy}" has no admitted senders; unknown senders are blocked or receive a pairing code.`,remediation:e.approveHint});return r};for(const a of e.plugins){if(!a.security)continue;const o=a.config.listAccountIds(r);const s=resolveChannelDefaultAccountId({plugin:a,cfg:r,accountIds:o});const c=uniqueStrings([s,...o]);for(const o of c){const s=hasExplicitProviderAccountConfig(r,a.id,o);const{account:l,enabled:u,configured:d,diagnostics:f}=await resolveChannelAuditAccount(a,o);for(const e of f)t.push({checkId:`channels.${a.id}.account.read_only_resolution`,severity:`warn`,title:`[secrets] ${a.meta.label??a.id} account could not be fully resolved`,detail:e,remediation:`Make the referenced secrets available in this shell or run with a running gateway snapshot so security audit can inspect the full channel configuration.`});if(!u||!d)continue;const p=c.length>1||s?` (account: ${o})`:``;const m=l?.config??asNullableRecord(l);const h=await resolvePluginDmPolicy({plugin:a,cfg:e.cfg,accountId:o,account:l});const g=isDangerousNameMatchingEnabled(m);const _=[...mutableToolsBySenderKeys(m,s?`channels.${a.id}.accounts.${o}`:`channels.${a.id}`)];if(_.length>0){const e=[...new Set(_.map(e=>e.path))];t.push({checkId:`channels.${a.id}.toolsBySender.mutable_entries`,severity:`warn`,title:`${a.meta.label??a.id} toolsBySender uses mutable sender keys${p}`,detail:`${_.length} toolsBySender ${_.length===1?`entry`:`entries`} in ${e.slice(0,3).join(`, `)}${e.length>3?`, …`:``} match mutable username:/name: sender attributes. Because group members can change their display names or handles, another sender could select that tool policy override.`,remediation:`Prefer stable id: keys in toolsBySender, especially for entries that grant extra tools or override group deny rules.`})}const v=(h?.allowFrom??[]).map(String).filter(e=>e.trim()!==`*`);const y=v.filter(e=>parseAccessGroupAllowFromEntry(e)===null&&h?.classifyEntryAuthentication?.(e)===`mutable`).length;if(i&&g)t.push({checkId:`channels.${a.id}.allowFrom.dangerous_name_matching_enabled`,severity:`info`,title:`${a.meta.label??a.id} dangerous name matching is enabled${p}`,detail:`dangerouslyAllowNameMatching=true enables mutable aliases (changeable/shared labels, weak even when honestly set) for sender authorization. Exact, stable identifiers with unproven ownership are a separate weak class; ingress diagnostics distinguish mutable_identifier_disabled from identifier_authentication_too_weak.`+(h?.classifyEntryAuthentication?` ${y} of ${v.length} allowFrom entries depend on mutable matching and would stop authorizing if dangerouslyAllowNameMatching is disabled.`:``),remediation:`Prefer stable sender IDs in allowlists, then disable dangerouslyAllowNameMatching.`});if(!g&&y>0&&h)t.push({checkId:`channels.${a.id}.allowFrom.mutable_entries_inert`,severity:`warn`,title:`${a.meta.label??a.id} mutable allowFrom entries are inert${p}`,detail:`${y} of ${v.length} entries in ${h.allowFromPath}allowFrom only match mutable identifiers (display names/tags/aliases) and can never authorize a sender under the current policy, so they are silently inert.`,remediation:`Replace them with stable sender IDs; enabling dangerouslyAllowNameMatching is a discouraged break-glass alternative.`});if(h){const r=await warnDmPolicy({label:`${a.meta.label??a.id}${p}`,provider:a.id,accountId:o,dmPolicy:h.policy,allowFrom:h.allowFrom,policyPath:h.policyPath,allowFromPath:h.allowFromPath,approveHint:h.approveHint,normalizeEntry:h.normalizeEntry});if(h.policy!==`disabled`){const i=a.security.dmRouting;const s=uniqueStrings([...r.admittedPrincipals,...r.hasWildcard?listExactDirectMessageBindingPeerIds({cfg:e.cfg,channel:a.id,accountId:o}):[]]);for(const c of[...s,...r.hasWildcard?[void 0]:[]]){const r={cfg:e.cfg,accountId:o,account:l,...c===void 0?{}:{principalId:c}};const s=i?.resolveDmScope?.(r);let u;try{u=resolveAgentRoute({cfg:e.cfg,channel:a.id,accountId:o,peer:{kind:`direct`,id:c??``},dmScope:s})}catch(e){if(!(e instanceof AgentSelectionRequiredError))throw e;t.push({checkId:`channels.${a.id}.routing.owner_missing.${o}`,severity:`warn`,title:`${a.meta.label??a.id}${p} routing has no explicit owner`,detail:e.message,remediation:e.hint});continue}const d=i?.resolveDmRoute?.({...r,route:u});if(c!==void 0){const t=d&&`sessionKey`in d?d.sessionKey:u.sessionKey;const n=resolveLinkedDirectPeerId({identityLinks:e.cfg.session?.identityLinks,channel:a.id,peerId:c});recordPrincipal(a,u,t,n?`linked:${normalizeLowercaseStringOrEmpty(n)}`:`direct:${a.id}:${u.accountId}:${normalizeLowercaseStringOrEmpty(c)}`,true);continue}const f=i?.resolveDmRoute;if(f&&!d)t.push({checkId:`channels.${a.id}.dm.wildcard_routing_unverified.${u.accountId}`,severity:`warn`,title:`${a.meta.label??a.id}${p} wildcard DM isolation is unverified`,detail:`dmRouting.resolveDmRoute returned no unknown-principal policy; isolation for arbitrary senders cannot be established.`});const m=!f||Boolean(d&&`kind`in d&&d.kind===`core`);const h=d&&`sessionKey`in d?d.sessionKey:m&&u.dmScope===`main`?u.sessionKey:void 0;if(h)for(const e of[`1`,`2`])recordPrincipal(a,u,h,`wildcard:shared:${a.id}-${u.accountId}:${e}`);else if(m&&(u.dmScope===`per-channel-peer`||u.dmScope===`per-peer`)){const e=u.dmScope===`per-peer`?[`peer`]:[`channel:${a.id}`,`peer`];for(const t of e)n.push({accountKey:`${a.id}-${u.accountId}`,logicalPrincipalKey:`wildcard:${u.dmScope}:${a.id}-${u.accountId}`,bucketKey:`${u.agentId}\0symbolic:dm:${t}`})}}}}if(a.security.collectWarnings){const n=await a.security.collectWarnings({cfg:e.cfg,accountId:o,account:l});for(const e of n??[]){if(typeof e!==`string`){t.push(e);continue}const n=e.trim();if(!n)continue;t.push({checkId:`channels.${a.id}.warning.${t.length+1}`,severity:`warn`,title:`${a.meta.label??a.id} security warning`,detail:n.replace(/^-\s*/,``)})}}if(i&&a.security.collectAuditFindings){const n=await a.security.collectAuditFindings({cfg:e.cfg,sourceConfig:r,accountId:o,account:l,orderedAccountIds:c,hasExplicitAccountPath:s});for(const e of n??[])t.push(e)}}}const a=/* @__PURE__ */ new Map;for(const e of n){const t=a.get(e.bucketKey)??[];t.push(e);a.set(e.bucketKey,t)}const o=[...a.entries()].filter(([,e])=>new Set(e.map(e=>e.logicalPrincipalKey)).size>1);const s=new Set(o.filter(([e,t])=>e.endsWith(`\0symbolic:dm:peer`)&&t.some(e=>e.logicalPrincipalKey.startsWith(`wildcard:per-peer:`))).map(([e])=>e.split(`\0`,1)[0]));const c=o.filter(([e,t])=>{if(!e.includes(`\0symbolic:`))return true;const n=e.split(`\0`,1)[0];if(e.endsWith(`\0symbolic:dm:peer`))return t.some(e=>e.logicalPrincipalKey.startsWith(`wildcard:per-peer:`));return!s.has(n)&&t.some(e=>e.logicalPrincipalKey.startsWith(`wildcard:per-channel-peer:`))}).toSorted(([e],[t])=>e.localeCompare(t));for(const[n,[r,i]]of c.entries()){const a=uniqueStrings(i.map(e=>e.accountKey)).toSorted();const o=r.includes(`\0symbolic:`);t.push({checkId:`channels.dm.session_collision.${a.join(`_`)}.${n+1}`,severity:`warn`,title:o?`DM principals may share a session`:`DM principals share a session`,detail:`Collision topology ${n+1}: ${new Set(i.map(e=>e.logicalPrincipalKey)).size} distinct admitted DM principals from ${a.join(`, `)} ${o?`can resolve`:`resolve`} to the same session bucket owned by agent "${r.split(`\0`,1)[0]}"`+(e.cfg.session?.scope===`global`?` under session.scope="global".`:`.`)+` This can leak context across users.`,remediation:`Set the effective DM route to an account-safe isolated scope; update the matching binding or session.dmScope as applicable.`})}return dedupeByKey(t,e=>[e.checkId,e.severity,e.title,e.detail??``,e.remediation??``].join(`
`))}export{collectChannelSecurityFindingsCore as t};