UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

46 lines • 57.8 kB
import{c as normalizeOptionalLowercaseString,l as normalizeOptionalString,p as normalizeStringifiedOptionalString}from"./string-coerce-CpTFcSwY.mjs";import{i as asOptionalObjectRecord}from"./record-coerce-BTbqdJ3-.mjs";import{b as uniqueStrings,f as normalizeStringEntries}from"./string-normalization-D_oBUpO3.mjs";import{d as hasUnresolvedConfigPath,u as getResolvedConfigEnvSecretRef}from"./resolution-facts-DYKtoyes.mjs";import{C as normalizePluginsConfigWithResolverCore,u as normalizePluginsConfig}from"./config-state-C1eV6UWf.mjs";import{i as passesManifestOwnerBasePolicy}from"./manifest-owner-policy-DVnu9FAE.mjs";import{p as isPathInside$1}from"./includes-gwK90iIZ.mjs";import{T as resolveOAuthDir}from"./paths-D_FOvGon.mjs";import{i as createLazyRuntimeNamedExport,r as createLazyRuntimeModule}from"./lazy-runtime-Ds6M7vp4.mjs";import{n as normalizeAgentId}from"./agent-id-cOfqmfln.mjs";import{n as LEGACY_IMPLICIT_AGENT_ID}from"./session-key-BPgKfU2m.mjs";import"./model-ref-shared-T-aCqInj.mjs";import{t as formatCliCommand}from"./command-format-D7KhNLP0.mjs";import{i as listAgentIds,n as listAgentEntries}from"./agent-roster-4XrgUgPK.mjs";import{r as resolveAgentConfig}from"./agent-scope-config-CG9CFpGX.mjs";import{n as listExplicitAgentWorkspaceDirs,t as listAgentWorkspaceDirs}from"./workspace-dirs-7cywZOgC.mjs";import{r as loadInstalledPluginIndexInstallRecords}from"./installed-plugin-index-record-reader-rJXlMUQ8.mjs";import{o as resolveAgentModelFallbackValues,s as resolveAgentModelPrimaryValue}from"./model-input-CJnF-FEy.mjs";import{i as DEFAULT_PROVIDER}from"./defaults-k51tX6yK.mjs";import{x as createPluginRegistryIdNormalizer}from"./plugin-metadata-snapshot-CDKhemiT.mjs";import{i as loadPluginRegistrySnapshot}from"./plugin-registry-snapshot-Dz_L4M3w.mjs";import{n as isDangerousNetworkMode,r as normalizeNetworkMode}from"./network-mode-B_FlcMRy.mjs";import"./plugin-registry-BAbRxjjy.mjs";import{s as loadManifestMetadataSnapshot}from"./manifest-contract-eligibility-BFn2JM5T.mjs";import{i as buildModelAliasIndex,y as resolveModelRefFromString}from"./model-selection-shared-CIOFxJ36.mjs";import{r as modelKey}from"./provider-registry-index-fv5AHL27.mjs";import{n as parseModelRef}from"./model-selection-normalize-DU37Sfvg.mjs";import{_ as resolveAuthProfileDatabaseFilePaths}from"./sqlite-y_WDH-Xr.mjs";import{o as isToolAllowedByPolicies}from"./tool-policy-match-D9XrfLbh.mjs";import{i as resolveSandboxConfigForAgent}from"./config-CNA3Oz0X.mjs";import{r as resolveChannelAccount}from"./account-resolution-BMEKSThh.mjs";import{r as listEffectiveGroupRouteBindings}from"./resolve-route-DpjPYoyg.mjs";import{t as mergeAccountConfig}from"./channel-account-config-DFPObbzi.mjs";import{n as resolveProviderToolPolicy}from"./provider-tool-policy-Bnqgc4hq.mjs";import{t as resolveConfiguredToolPolicies}from"./agent-tools.policy-KzzDFr2X.mjs";import{n as GATEWAY_CONTROL_PLANE_TOOLS}from"./dangerous-tools-Bm_fma95.mjs";import{i as resolveGatewayAuthForConfig}from"./auth-resolve-UwT9_UjV.mjs";import{t as resolveAllowedAgentIds}from"./hooks-policy-Bv4DqBTT.mjs";import{o as resolveSandboxSessionToolsVisibility,s as resolveSessionToolsVisibility,t as createAgentToAgentPolicy}from"./session-visibility-BMQ-jzdi.mjs";import{i as isPinnedRegistrySpec,o as readInstalledPackageVersion}from"./package-update-utils-Cy597x_4.mjs";import{n as listReadOnlyChannelPluginsForConfigAsync}from"./read-only-B-Uv2t8Q.mjs";import{t as levenshteinDistance}from"./levenshtein-distance-D9oM68DG.mjs";import{t as getBlockedBindReason}from"./validate-sandbox-security-DVI5QmIV.mjs";import{t as inspectReadOnlyChannelAccount}from"./read-only-account-inspect-DIBat5m6.mjs";import{c as listDangerousPluginNodeCommands,d as resolveNodePairingCommandAllowlist,t as DEFAULT_DANGEROUS_NODE_COMMANDS}from"./node-command-policy-Qm4E-4M-.mjs";import{r as resolveNativeSkillsEnabled}from"./commands-BM10w20C.mjs";import{t as inferParamBFromIdOrName}from"./model-param-b-DTIDYIPF.mjs";import{t as readHookInstalls}from"./installs-DthN4quj.mjs";import{t as listConfiguredOpenInboundPolicyPaths}from"./audit-open-inbound-UZ8EGJ_l.mjs";import{t as collectIncludePathsRecursive}from"./includes-scan-ClVTKrDx.mjs";import{t as describeBinding}from"./agents.binding-format-CQkTjZnX.mjs";import{r as resolveInternalHookSelection}from"./configured-BCq_2Ag4.mjs";import{t as listInstalledPluginDirs}from"./installed-plugin-dirs-C4iEqaj-.mjs";import path from"node:path";import fs from"node:fs/promises";import{withTimeout}from"@openclaw/fs-safe/advanced";import{isNotFoundPathError}from"@openclaw/fs-safe/path";import{walkDirectory}from"@openclaw/fs-safe/walk";import{clearTimeout,setTimeout}from"node:timers";
//!src/plugins/web-search-credential-presence.ts
function hasConfiguredCredentialValue(e){if(typeof e===`string`)return e.trim().length>0;return e!==void 0&&e!==null}function hasConfiguredSearchCredentialCandidate(e){const t=asOptionalObjectRecord(e);if(!t)return false;return Object.entries(t).some(([e,t])=>e!==`enabled`&&hasConfiguredCredentialValue(t))}function hasConfiguredPluginWebSearchCandidate(e){const t=asOptionalObjectRecord(e.plugins?.entries);if(!t)return false;return Object.values(t).some(e=>{const t=asOptionalObjectRecord(e)?.config;return hasConfiguredSearchCredentialCandidate(asOptionalObjectRecord(t)?.webSearch)})}function hasManifestWebSearchEnvCredentialCandidate(e){const t=e.env;if(!t)return false;return loadManifestMetadataSnapshot({config:e.config,env:t}).plugins.some(e=>{if(e.origin!==`bundled`)return false;if((e.contracts?.webSearchProviders?.length??0)===0)return false;return(e.setup?.providers??[]).flatMap(e=>e.envVars??[]).some(e=>hasConfiguredCredentialValue(t[e]))})}function hasConfiguredWebSearchCredential(e){return hasConfiguredSearchCredentialCandidate(e.config.tools?.web?.search)||hasConfiguredPluginWebSearchCandidate(e.config)||hasManifestWebSearchEnvCredentialCandidate(e)}
//!src/security/audit-extra.sync.ts
function isProbablySyncedPath(e){const t=e.toLowerCase();return t.includes(`icloud`)||t.includes(`dropbox`)||t.includes(`google drive`)||t.includes(`googledrive`)||t.includes(`onedrive`)}function isGatewayRemotelyExposed(e){if((typeof e.gateway?.bind===`string`?e.gateway.bind:`loopback`)!==`loopback`)return true;const t=e.gateway?.tailscale?.mode??`off`;return t===`serve`||t===`funnel`}function findHooksTokenGatewayAuthReuse(e){for(const[t,n]of[[`config`,e.configGatewayAuth],[`override`,e.overrideGatewayAuth]]){if(!n)continue;if(n.mode===`token`&&normalizeOptionalString(n.token)===e.hooksToken)return{label:`gateway auth token`,source:t};if((n.mode===`password`||n.mode===`trusted-proxy`)&&normalizeOptionalString(n.password)===e.hooksToken)return{label:`gateway auth password`,source:t}}}function hasResolvedGatewayHttpAuth(e){if(e.mode===`token`)return Boolean(normalizeOptionalString(e.token));if(e.mode===`password`)return Boolean(normalizeOptionalString(e.password));if(e.mode===`trusted-proxy`)return true;return false}function hasConfiguredDockerConfig(e){if(!e||typeof e!==`object`)return false;return Object.values(e).some(e=>e!==void 0)}function normalizeNodeCommand(e){return normalizeOptionalString(e)??``}function isWildcardEntry(e){return normalizeStringifiedOptionalString(e)===`*`}function listKnownNodeCommands(e){const t={...e,gateway:{...e.gateway,nodes:{...e.gateway?.nodes,commands:{...e.gateway?.nodes?.commands,deny:[]}}}};const n=/* @__PURE__ */ new Set;for(const e of[...[{platform:`ios`,deviceFamily:`iPhone`},{platform:`android`,deviceFamily:`Android`},{platform:`macos`,deviceFamily:`Mac`},{platform:`linux`,deviceFamily:`Linux`},{platform:`windows`,deviceFamily:`Windows`},{platform:`unknown`}].map(e=>resolveNodePairingCommandAllowlist(t,e)),resolveNodePairingCommandAllowlist(t,{caps:[`talk`]}),DEFAULT_DANGEROUS_NODE_COMMANDS])for(const t of e){const e=normalizeNodeCommand(t);if(e)n.add(e)}return n}function looksLikeNodeCommandPattern(e){if(/[?*[\]{}(),|]/.test(e))return true;if(e.startsWith(`/`)||e.endsWith(`/`)||e.startsWith(`^`)||e.endsWith(`$`))return true;return/\s/.test(e)||e.includes(`group:`)}function suggestKnownNodeCommands(e,t){const n=e.includes(`.`)?e.split(`.`).slice(0,2).join(`.`):e;const r=Array.from(t).filter(e=>e.startsWith(n)).slice(0,3);if(r.length>0)return r;const i=Array.from(t).map(t=>({cmd:t,d:levenshteinDistance(e,t)})).toSorted((e,t)=>e.d-t.d||e.cmd.localeCompare(t.cmd));const a=i[0]?.d??Infinity;const o=Math.max(2,Math.min(4,a));return i.filter(e=>e.d<=o).slice(0,3).map(e=>e.cmd)}function hasConfiguredGroupTargets(e){return[`groups`,`guilds`,`channels`,`rooms`].some(t=>{const n=e[t];return Boolean(n&&typeof n===`object`&&Object.keys(n).length>0)})}function listPotentialMultiUserSignals(e,t=listConfiguredOpenInboundPolicyPaths(e)){const n=new Set(t.map(e=>`${e}="open"`));const r=e.channels;if(!r||typeof r!==`object`)return[];const inspectSection=(e,t)=>{if((typeof e.groupPolicy===`string`?e.groupPolicy:null)===`allowlist`&&hasConfiguredGroupTargets(e))n.add(`${t}.groupPolicy="allowlist" with configured group targets`);if((Array.isArray(e.allowFrom)?e.allowFrom:[]).some(e=>isWildcardEntry(e)))n.add(`${t}.allowFrom includes "*"`);if((Array.isArray(e.groupAllowFrom)?e.groupAllowFrom:[]).some(e=>isWildcardEntry(e)))n.add(`${t}.groupAllowFrom includes "*"`);const r=e.dm;if(r&&typeof r===`object`){const e=r;if((Array.isArray(e.allowFrom)?e.allowFrom:[]).some(e=>isWildcardEntry(e)))n.add(`${t}.dm.allowFrom includes "*"`)}};for(const[e,t]of Object.entries(r)){if(!t||typeof t!==`object`)continue;const n=t;inspectSection(n,`channels.${e}`);const r=n.accounts;if(!r||typeof r!==`object`)continue;for(const[t,i]of Object.entries(r)){if(!i||typeof i!==`object`)continue;inspectSection(mergeAccountConfig({channelConfig:n,accountConfig:i}),`channels.${e}.accounts.${t}`)}}return Array.from(n)}function listAuditAgentToolContexts(e){const t=[{label:`agents.defaults`}];for(const n of listAgentEntries(e)){if(!n||typeof n!==`object`||typeof n.id!==`string`)continue;t.push({label:`agents.entries.${n.id}`,agentId:n.id,tools:n.tools})}return t}function collectToolExposureContexts(e){const t=[];const n=[];let r=false;for(const i of listAuditAgentToolContexts(e)){const a=resolveSandboxConfigForAgent(e,i.agentId).mode;const o=resolveConfiguredToolPolicies({cfg:e,agentTools:i.tools,sandboxMode:a,agentId:i.agentId??null});const s=GATEWAY_CONTROL_PLANE_TOOLS.filter(e=>isToolAllowedByPolicies(e,o));if(s.length>0){const t=i.tools?.profile??e.tools?.profile??`none`;n.push(`${i.label} (profile=${t}; controlPlane=[${s.join(`, `)}])`)}const c=[`exec`,`process`].filter(e=>isToolAllowedByPolicies(e,o));const l=[`read`,`write`,`edit`,`apply_patch`].filter(e=>isToolAllowedByPolicies(e,o));const u=i.tools?.fs?.workspaceOnly??e.tools?.fs?.workspaceOnly;const d=c.length>0&&a!==`all`;const f=l.length>0&&a!==`all`&&u!==true;if(!d&&!f)continue;if(d)r=true;t.push(`${i.label} (sandbox=${a}; runtime=[${c.join(`, `)||`off`}]; fs=[${l.join(`, `)||`off`}]; fs.workspaceOnly=${u===true?`true`:`false`})`)}return{riskyContexts:t,hasRuntimeRisk:r,controlPlaneContexts:n}}function collectSyncedFolderFindings(e){const t=[];if(isProbablySyncedPath(e.stateDir)||isProbablySyncedPath(e.configPath))t.push({checkId:`fs.synced_dir`,severity:`warn`,title:`State/config path looks like a synced folder`,detail:`stateDir=${e.stateDir}, configPath=${e.configPath}. Synced folders (iCloud/Dropbox/OneDrive/Google Drive) can leak tokens and chat history onto other devices.`,remediation:`Keep OPENCLAW_STATE_DIR on a local-only volume and re-run "${formatCliCommand(`openclaw security audit --fix`)}".`});return t}function collectHooksHardeningFindings(e,t=process.env,n={}){const r=[];if(e.hooks?.enabled!==true)return r;const i=normalizeOptionalString(e.hooks?.token)??``;if(i&&i.length<24)r.push({checkId:`hooks.token_too_short`,severity:`warn`,title:`Hooks token looks short`,detail:`hooks.token is ${i.length} chars; prefer a long random token.`});const a=findHooksTokenGatewayAuthReuse({hooksToken:i,configGatewayAuth:resolveGatewayAuthForConfig({config:e,tailscaleMode:e.gateway?.tailscale?.mode??`off`,env:t}),overrideGatewayAuth:n.gatewayAuthOverride?resolveGatewayAuthForConfig({config:e,authOverride:n.gatewayAuthOverride,tailscaleMode:e.gateway?.tailscale?.mode??`off`,env:t}):void 0});if(a){const e=a.label===`gateway auth password`;r.push({checkId:`hooks.token_reuse_gateway_token`,severity:`critical`,title:`Hooks token reuses the Gateway ${e?`password`:`token`}`,detail:e?`hooks.token matches gateway.auth password; a stolen hooks token also grants Gateway password access.`:`hooks.token matches gateway.auth token; a stolen hooks token also grants Gateway API access.`,remediation:a.source===`override`?`Rotate hooks.token or the runtime Gateway shared-secret auth value used for this audit; doctor can only repair reuse that is present in persisted config or process env.`:`Run ${formatCliCommand(`openclaw doctor --fix`)} to rotate a persisted hooks.token, then update external hook senders to use the new hook token.`})}if((normalizeOptionalString(e.hooks?.path)??``)===`/`)r.push({checkId:`hooks.path_root`,severity:`critical`,title:`Hooks base path is '/'`,detail:`hooks.path='/' would shadow other HTTP endpoints and is unsafe.`,remediation:`Use a dedicated path like '/hooks'.`});const o=e.hooks?.allowRequestSessionKey===true;const s=normalizeOptionalString(e.hooks?.defaultSessionKey)??``;const c=resolveAllowedAgentIds(e.hooks?.allowedAgentIds);const l=Array.isArray(e.hooks?.allowedSessionKeyPrefixes)?e.hooks.allowedSessionKeyPrefixes.map(e=>e.trim()).filter(e=>e.length>0):[];const u=isGatewayRemotelyExposed(e);if(!s)r.push({checkId:`hooks.default_session_key_unset`,severity:`warn`,title:`hooks.defaultSessionKey is not configured`,detail:`Hook agent runs without explicit sessionKey use generated per-request keys. Set hooks.defaultSessionKey to keep hook ingress scoped to a known session.`,remediation:`Set hooks.defaultSessionKey (for example, "hook:ingress").`});if(c===void 0)r.push({checkId:`hooks.allowed_agent_ids_unrestricted`,severity:u?`critical`:`warn`,title:`Hook agent routing allows any configured agent`,detail:`hooks.allowedAgentIds is unset or includes '*', so authenticated hook callers may route to any configured agent id, including the default agent when agentId is omitted.`,remediation:`Set hooks.allowedAgentIds to an explicit allowlist (for example, ["hooks", "main"]) or [] to deny hook agent routing.`});if(o)r.push({checkId:`hooks.request_session_key_enabled`,severity:u?`critical`:`warn`,title:`External hook payloads may override sessionKey`,detail:"hooks.allowRequestSessionKey=true allows `/hooks/agent` callers to choose the session key. Treat hook token holders as full-trust unless you also restrict prefixes.",remediation:`Set hooks.allowRequestSessionKey=false (recommended) or constrain hooks.allowedSessionKeyPrefixes.`});if(o&&l.length===0)r.push({checkId:`hooks.request_session_key_prefixes_missing`,severity:u?`critical`:`warn`,title:`Request sessionKey override is enabled without prefix restrictions`,detail:`hooks.allowRequestSessionKey=true and hooks.allowedSessionKeyPrefixes is unset/empty, so request payloads can target arbitrary session key shapes.`,remediation:`Set hooks.allowedSessionKeyPrefixes (for example, ["hook:"]) or disable request overrides.`});return r}function collectGatewayHttpSessionKeyOverrideFindings(e){const t=[];const n=e.gateway?.http?.endpoints?.chatCompletions?.enabled===true;const r=e.gateway?.http?.endpoints?.responses?.enabled===true;if(!n&&!r)return t;const i=[n?`/v1/chat/completions`:null,r?`/v1/responses`:null].filter(e=>Boolean(e));t.push({checkId:`gateway.http.session_key_override_enabled`,severity:`info`,title:`HTTP API session-key override is enabled`,detail:`${i.join(`, `)} accept x-openclaw-session-key for per-request session routing. Treat API credential holders as trusted principals.`});return t}function collectGatewayHttpNoAuthFindings(e,t,n={}){const r=[];const i=e.gateway?.tailscale?.mode??`off`;if(hasResolvedGatewayHttpAuth(resolveGatewayAuthForConfig({config:e,authOverride:n.gatewayAuthOverride,tailscaleMode:i,env:t})))return r;const a=e.gateway?.http?.endpoints?.chatCompletions?.enabled===true;const o=e.gateway?.http?.endpoints?.responses?.enabled===true;const s=e.plugins?.entries?.[`admin-http-rpc`]?.enabled===true;const c=[`/tools/invoke`,a?`/v1/chat/completions`:null,o?`/v1/responses`:null,s?`/api/v1/admin/rpc`:null].filter(e=>Boolean(e));const l=isGatewayRemotelyExposed(e);r.push({checkId:`gateway.http.no_auth`,severity:l?`critical`:`warn`,title:`Gateway HTTP APIs are reachable without auth`,detail:`gateway.auth.mode="none" leaves ${c.join(`, `)} callable without a shared secret. Treat this as trusted-local only and avoid exposing the gateway beyond loopback.`,remediation:`Set gateway.auth.mode to token/password (recommended). If you intentionally keep mode=none, keep gateway.bind=loopback and disable optional HTTP endpoints/plugins.`});return r}function collectSandboxDockerNoopFindings(e){const t=[];const n=[];const r=listAgentEntries(e);const i=e.agents?.defaults?.sandbox;const a=hasConfiguredDockerConfig(i?.docker);const o=i?.mode??`off`;const s=r.some(t=>{if(!t||typeof t!==`object`||typeof t.id!==`string`)return false;return resolveSandboxConfigForAgent(e,t.id).mode!==`off`});if(a&&o===`off`&&!s)n.push(`agents.defaults.sandbox.docker`);for(const t of r){if(!t||typeof t!==`object`||typeof t.id!==`string`)continue;if(!hasConfiguredDockerConfig(t.sandbox?.docker))continue;if(resolveSandboxConfigForAgent(e,t.id).mode===`off`)n.push(`agents.entries.${t.id}.sandbox.docker`)}if(n.length===0)return t;t.push({checkId:`sandbox.docker_config_mode_off`,severity:`warn`,title:`Sandbox docker settings configured while sandbox mode is off`,detail:`These docker settings will not take effect until sandbox mode is enabled:
`+n.map(e=>`- ${e}`).join(`
`),remediation:'Enable sandbox mode (`agents.defaults.sandbox.mode="non-main"` or `"all"`) where needed, or remove unused docker settings.'});return t}function collectSandboxDangerousConfigFindings(e){const t=[];const n=listAgentEntries(e);const r=[];const i=e.agents?.defaults?.sandbox?.docker;if(i&&typeof i===`object`)r.push({source:`agents.defaults.sandbox.docker`,docker:i});for(const e of n){if(!e||typeof e!==`object`||typeof e.id!==`string`)continue;const t=e.sandbox?.docker;if(t&&typeof t===`object`)r.push({source:`agents.entries.${e.id}.sandbox.docker`,docker:t})}for(const{source:e,docker:n}of r){const r=Array.isArray(n.binds)?n.binds:[];for(const n of r){if(typeof n!==`string`)continue;const r=getBlockedBindReason(n);if(!r)continue;if(r.kind===`non_absolute`){t.push({checkId:`sandbox.bind_mount_non_absolute`,severity:`warn`,title:`Sandbox bind mount uses a non-absolute source path`,detail:`${e}.binds contains "${n}" which uses source path "${r.sourcePath}". Non-absolute bind sources are hard to validate safely and may resolve unexpectedly.`,remediation:`Rewrite "${n}" to use an absolute host path (for example: /home/user/project:/project:ro).`});continue}if(r.kind!==`covers`&&r.kind!==`targets`)continue;const i=r.kind===`covers`?`covers`:`targets`;t.push({checkId:`sandbox.dangerous_bind_mount`,severity:`critical`,title:`Dangerous bind mount in sandbox config`,detail:`${e}.binds contains "${n}" which ${i} blocked path "${r.blockedPath}". This can expose host system directories or the Docker socket to sandbox containers.`,remediation:`Remove "${n}" from ${e}.binds. Use project-specific paths instead.`})}const i=typeof n.network===`string`?n.network:void 0;const a=normalizeNetworkMode(i);if(isDangerousNetworkMode(i)){const n=a===`host`?`"host"`:`"${i}"`;const r=a===`host`?`${e}.network is "host" which bypasses container network isolation entirely.`:`${e}.network is ${n} which joins another container namespace and can bypass sandbox network isolation.`;t.push({checkId:`sandbox.dangerous_network_mode`,severity:`critical`,title:`Dangerous network mode in sandbox config`,detail:r,remediation:`Set ${e}.network to "bridge", "none", or a custom bridge network name. Use ${e}.dangerouslyAllowContainerNamespaceJoin=true only as a break-glass override when you fully trust this runtime.`})}const o=typeof n.seccompProfile===`string`?n.seccompProfile:void 0;if(normalizeOptionalLowercaseString(o)===`unconfined`)t.push({checkId:`sandbox.dangerous_seccomp_profile`,severity:`critical`,title:`Seccomp unconfined in sandbox config`,detail:`${e}.seccompProfile is "unconfined" which disables syscall filtering.`,remediation:`Remove ${e}.seccompProfile or use a custom seccomp profile file.`});const s=typeof n.apparmorProfile===`string`?n.apparmorProfile:void 0;if(normalizeOptionalLowercaseString(s)===`unconfined`)t.push({checkId:`sandbox.dangerous_apparmor_profile`,severity:`critical`,title:`AppArmor unconfined in sandbox config`,detail:`${e}.apparmorProfile is "unconfined" which disables AppArmor enforcement.`,remediation:`Remove ${e}.apparmorProfile or use a named AppArmor profile.`})}return t}function collectNodeDenyCommandPatternFindings(e){const t=[];const n=e.gateway?.nodes?.commands?.deny;if(!Array.isArray(n)||n.length===0)return t;const r=n.map(normalizeNodeCommand).filter(Boolean);if(r.length===0)return t;const i=listKnownNodeCommands(e);const a=r.filter(e=>looksLikeNodeCommandPattern(e));const o=r.filter(e=>!looksLikeNodeCommandPattern(e)&&!i.has(e));if(a.length===0&&o.length===0)return t;const s=[];if(a.length>0)s.push(`Pattern-like entries (not supported by exact matching): ${a.join(`, `)}`);if(o.length>0){const e=o.map(e=>{const t=suggestKnownNodeCommands(e,i);if(t.length===0)return e;return`${e} (did you mean: ${t.join(`, `)})`}).join(`, `);s.push(`Unknown command names (not in defaults/gateway.nodes.commands.allow): ${e}`)}const c=Array.from(i).slice(0,8);t.push({checkId:`gateway.nodes.deny_commands_ineffective`,severity:`warn`,title:`Some gateway.nodes.commands.deny entries are ineffective`,detail:"gateway.nodes.commands.deny uses exact node command-name matching only (for example `system.run`), not shell-text filtering inside a command payload.\n"+s.map(e=>`- ${e}`).join(`
`),remediation:`Use exact command names (for example: ${c.join(`, `)}). If you need broader restrictions, remove risky command IDs from gateway.nodes.commands.allow/default workflows and tighten tools.exec policy.`});return t}function collectNodeDangerousAllowCommandFindings(e){const t=[];const n=e.gateway?.nodes?.commands?.allow;if(!Array.isArray(n)||n.length===0)return t;const r=new Set(n.map(normalizeNodeCommand).filter(Boolean));if(r.size===0)return t;const i=new Set((e.gateway?.nodes?.commands?.deny??[]).map(normalizeNodeCommand));const a=[...DEFAULT_DANGEROUS_NODE_COMMANDS,...listDangerousPluginNodeCommands()].filter(e=>r.has(e)&&!i.has(e));if(a.length===0)return t;t.push({checkId:`gateway.nodes.allow_commands_dangerous`,severity:isGatewayRemotelyExposed(e)?`critical`:`warn`,title:`Dangerous node commands explicitly enabled`,detail:`gateway.nodes.commands.allow includes: ${a.join(`, `)}. These commands can trigger high-impact device actions or read sensitive data (desktop input/camera/screen/contacts/calendar/reminders/health/SMS/file).`,remediation:`Remove these entries from gateway.nodes.commands.allow (recommended). If you keep them, treat gateway auth as full operator access and keep gateway exposure local/tailnet-only.`});return t}function collectMinimalProfileOverrideFindings(e){const t=[];if(e.tools?.profile!==`minimal`)return t;const n=listAgentEntries(e).filter(e=>{return Boolean(e&&typeof e===`object`&&typeof e.id===`string`&&e.tools?.profile&&e.tools.profile!==`minimal`)}).map(e=>`${e.id}=${e.tools?.profile}`);if(n.length===0)return t;t.push({checkId:`tools.profile_minimal_overridden`,severity:`warn`,title:`Global tools.profile=minimal is overridden by agent profiles`,detail:`Global minimal profile is set, but these agent profiles take precedence:
`+n.map(e=>`- agents.entries.${e}`).join(`
`),remediation:'Set those agents to `tools.profile="minimal"` (or remove the agent override) if you want minimal tools enforced globally.'});return t}function collectExposureMatrixFindings(e,t=listConfiguredOpenInboundPolicyPaths(e)){const n=[];if(t.length===0)return n;if(e.tools?.elevated?.enabled!==false)n.push({checkId:`security.exposure.open_groups_with_elevated`,severity:`critical`,title:`Open group/DM policy with elevated tools enabled`,detail:`Found inbound policy="open" at:\n${t.map(e=>`- ${e}`).join(`
`)}\nWith tools.elevated enabled, a prompt injection in those conversations can become a high-impact incident.`,remediation:`Set each listed group/DM policy to "allowlist" and keep elevated allowlists extremely tight.`});const{riskyContexts:r,hasRuntimeRisk:i,controlPlaneContexts:a}=collectToolExposureContexts(e);if(r.length>0)n.push({checkId:`security.exposure.open_groups_with_runtime_or_fs`,severity:i?`critical`:`warn`,title:`Open group/DM policy with runtime/filesystem tools exposed`,detail:`Found inbound policy="open" at:\n${t.map(e=>`- ${e}`).join(`
`)}\nRisky tool exposure contexts:\n${r.map(e=>`- ${e}`).join(`
`)}\nPrompt injection in open conversations can trigger command/file actions in these contexts.`,remediation:`For open groups or DMs, prefer tools.profile="messaging" (or deny group:runtime/group:fs), set tools.fs.workspaceOnly=true, and use agents.defaults.sandbox.mode="all" for exposed agents.`});if(a.length>0)n.push({checkId:`security.exposure.open_groups_with_control_plane_tools`,severity:`critical`,title:`Open group/DM policy with control-plane tools exposed`,detail:`Found inbound policy="open" at:\n${t.map(e=>`- ${e}`).join(`
`)}\nControl-plane tool exposure contexts:\n${a.map(e=>`- ${e}`).join(`
`)}\nPrompt injection in open conversations can trigger OpenClaw updates, plugin changes, or scheduled automation.`,remediation:`For open groups or DMs, deny control-plane tools (${GATEWAY_CONTROL_PLANE_TOOLS.map(e=>`\`${e}\``).join(`, `)}) and prefer tools.profile="messaging". Tighten dmPolicy/groupPolicy to pairing or allowlist when possible.`});return n}function collectLikelyMultiUserSetupFindings(e,t=listConfiguredOpenInboundPolicyPaths(e)){const n=[];const r=listEffectiveGroupRouteBindings(e).filter(e=>e.session?.groupScope===`main`).map(e=>`- bindings[].session.groupScope="main": ${describeBinding(e)} (agent=${e.agentId})`);if(e.session?.groupScope===`main`)r.unshift(`- session.groupScope="main" (global: all group/channel rooms unless a binding overrides it)`);if(r.length>0)n.push({checkId:`security.trust_model.group_scope_main`,severity:`warn`,title:`Group rooms share the main session`,detail:`The following group routing scopes merge room conversations into the agent main session:
`+r.join(`
`)+`
Every member of each affected room shares the main-session context. Use this only for mutually trusted rooms.`,remediation:`Use session.groupScope="per-group" globally and remove binding overrides, or reserve "main" for rooms whose members you trust: https://docs.openclaw.ai/channels/groups#session-keys`});const i=listPotentialMultiUserSignals(e,t);if(i.length===0)return n;const{riskyContexts:a,hasRuntimeRisk:o}=collectToolExposureContexts(e);const s=o?`Runtime/process tools are exposed without full sandboxing in at least one context.`:`No unguarded runtime/process tools were detected by this heuristic.`;const c=a.length>0?`Potential high-impact tool exposure contexts:\n${a.map(e=>`- ${e}`).join(`
`)}`:`No unguarded runtime/filesystem contexts detected.`;n.push({checkId:`security.trust_model.multi_user_heuristic`,severity:`warn`,title:`Potential multi-user setup detected (personal-assistant model warning)`,detail:`Heuristic signals indicate this gateway may be reachable by multiple users:
`+i.map(e=>`- ${e}`).join(`
`)+`\n${s}\n${c}\nOpenClaw's default security model is personal-assistant (one trusted operator boundary), not hostile multi-tenant isolation on one shared gateway. For mutually untrusted users or organizations, run separate Gateways with separate credentials, ideally under separate OS users or hosts: https://docs.openclaw.ai/gateway/security/trust-model`,remediation:`If users may be mutually untrusted, split trust boundaries (separate gateways + credentials, ideally separate OS users/hosts). If you intentionally run shared-user access, set agents.defaults.sandbox.mode="all", keep tools.fs.workspaceOnly=true, deny runtime/fs/web tools unless required, and keep personal/private identities + credentials off that runtime.`});return n}
//!src/security/audit-model-refs.ts
function collectAuditModelRefs(e){const t=buildModelAliasIndex({cfg:e,defaultProvider:DEFAULT_PROVIDER,allowPluginNormalization:false});const n=[];const add=(r,i)=>{if(typeof r!==`string`)return;const a=r.trim();if(!a)return;const o=resolveModelRefFromString({cfg:e,raw:a,defaultProvider:DEFAULT_PROVIDER,aliasIndex:t,allowPluginNormalization:false})?.ref;n.push({id:o?modelKey(o.provider,o.model):a,source:i})};add(resolveAgentModelPrimaryValue(e.agents?.defaults?.model),`agents.defaults.model.primary`);for(const t of resolveAgentModelFallbackValues(e.agents?.defaults?.model))add(t,`agents.defaults.model.fallbacks`);for(const t of listAgentEntries(e)){if(!t||typeof t!==`object`)continue;const e=typeof t.id===`string`?t.id:``;const n=t.model;if(typeof n===`string`)add(n,`agents.entries.${e}.model`);else if(n&&typeof n===`object`){add(n.primary,`agents.entries.${e}.model.primary`);const t=n.fallbacks;if(Array.isArray(t))for(const n of t)add(n,`agents.entries.${e}.model.fallbacks`)}}return n}
//!src/security/audit-extra.summary.ts
const SMALL_MODEL_PARAM_B_MAX=300;function summarizeGroupPolicy(e,t){const n=e.channels;if(!n||typeof n!==`object`)return{open:0,allowlist:0,openDm:0};let r=0;for(const e of Object.values(n)){if(!e||typeof e!==`object`)continue;if(e.groupPolicy===`allowlist`)r+=1}return{open:t.filter(e=>e.endsWith(`.groupPolicy`)).length,allowlist:r,openDm:t.filter(e=>!e.endsWith(`.groupPolicy`)).length}}function extractAgentIdFromSource(e){return e.match(/^agents\.entries\.([^.]*)\./)?.[1]??null}function resolveToolPolicies(e){const t=resolveProviderToolPolicy({byProvider:e.cfg.tools?.byProvider,modelProvider:e.modelProvider,modelId:e.modelId});const n=resolveProviderToolPolicy({byProvider:e.agentTools?.byProvider,modelProvider:e.modelProvider,modelId:e.modelId});return resolveConfiguredToolPolicies({cfg:e.cfg,agentTools:e.agentTools,sandboxMode:e.sandboxMode,agentId:e.agentId,extraPolicies:[t,n]})}function isWebSearchEnabled(e,t){const n=e.tools?.web?.search?.enabled;if(n===false)return false;if(n===true)return true;return hasConfiguredWebSearchCredential({config:e,env:t})}function isBrowserEnabled(e){if(e.browser?.enabled===false)return false;return passesManifestOwnerBasePolicy({plugin:{id:`browser`},normalizedConfig:normalizePluginsConfigWithResolverCore(e.plugins,e=>normalizeOptionalLowercaseString(e)??``)})}async function collectAttackSurfaceSummaryFindings(e,t=listConfiguredOpenInboundPolicyPaths(e)){const n=summarizeGroupPolicy(e,t);const r=e.tools?.elevated?.enabled!==false;const i=e.hooks?.enabled===true;const a=(await resolveInternalHookSelection(e)).configured;const o=isBrowserEnabled(e);const s=[{checkId:`summary.attack_surface`,severity:`info`,title:`Exposure summary`,detail:`groups: open=${n.open}, allowlist=${n.allowlist}\ndirect messages: open=${n.openDm}\ntools.elevated: ${r?`enabled`:`disabled`}\nhooks.webhooks: ${i?`enabled`:`disabled`}\nhooks.internal: ${a?`enabled`:`disabled`}\nbrowser control: ${o?`enabled`:`disabled`}\ntrust model: personal assistant (one trusted operator boundary), not hostile multi-tenant on one shared gateway. For mutually untrusted users or organizations, run separate Gateways with separate credentials, ideally under separate OS users or hosts: https://docs.openclaw.ai/gateway/security/trust-model`}];for(const t of listAgentEntries(e)){if(typeof t.id!==`string`||t.tools?.github?.allowInSandbox!==true)continue;const e=`agents.entries.${t.id}.tools.github.allowInSandbox`;s.push({checkId:`sandbox.github_identity_exposed`,severity:`warn`,title:`Managed GitHub identity reaches sandboxed execution`,detail:`${e}=true allows agent "${t.id}" to use its managed GitHub credentials and Git author in its own sandboxed execution. Commands in that sandbox can read and use the credentials.`,remediation:`Set ${e}=false unless this agent's sandboxed code is trusted with its GitHub access.`})}return s}function collectCrossAgentSessionAccessFindings(e,t=listConfiguredOpenInboundPolicyPaths(e)){const n=listAgentIds(e);if(n.length<2||resolveSessionToolsVisibility(e)!==`all`)return[];if(!createAgentToAgentPolicy(e).enabled||e.tools?.agentToAgent?.allow?.length)return[];const r=resolveSandboxSessionToolsVisibility(e);const i=[];const a=[];const o=[];for(const t of n){const n=resolveSandboxConfigForAgent(e,t).mode;if(n!==`off`)o.push(`${t}: sandbox.mode="${n}"`);const s=resolveAgentConfig(e,t)?.tools;const c=resolveToolPolicies({cfg:e,agentTools:s,sandboxMode:n,agentId:t});const l=[`sessions_list`,`sessions_history`,`sessions_search`,`sessions_send`,`session_status`].filter(e=>isToolAllowedByPolicies(e,c));const u=n!==`all`||r===`all`;if(u&&l.length>0){const e=n===`off`?`unsandboxed sessions`:n===`non-main`?`unsandboxed main session`:`sandboxed sessions (clamp disabled)`;i.push(`- ${t}: ${e}; allowed session tools: ${l.join(`, `)}.`)}else{const e=u?`session tools removed by agent tool policy`:`sandboxed sessions clamped to their spawn tree`;a.push(`- ${t}: ${e}; its chat history remains readable by the agents above.`)}const d=[`profile`,`allow`,`deny`].filter(e=>s?.[e]!==void 0);if(d.length>0)o.push(`${t}: agent-level tool restrictions (${d.map(e=>`tools.${e}`).join(`, `)})`)}if(i.length===0)return[];o.push(...listPotentialMultiUserSignals(e,t));const s=o.length>0?`
Trust-boundary signals:
`+o.map(e=>`- ${e}`).join(`
`)+`
Sandboxing, agent-level tool restrictions, or shared-user ingress suggest different trust levels, but session access remains Gateway-wide.`:``;return[{checkId:`security.trust_model.cross_agent_session_access_default`,severity:o.length>0?`warn`:`info`,title:`Agents share Gateway-wide session access (default)`,detail:`Agents: ${n.join(`, `)}\ntools.sessions.visibility resolves to "all" and tools.agentToAgent is enabled with no allow list.
Agents that can reach other agents' sessions, including other users' transcripts:
`+[...i,...a,`Incognito sessions remain hidden.`].join(`
`)+s,remediation:`Set tools.sessions.visibility to "agent", "tree", or "self"; use agents.entries.<id>.tools.agentToAgent.send for explicit send-only destinations when needed. Restrict tools.agentToAgent.allow to the intended requester and target ids, or set tools.agentToAgent.enabled: false. See https://docs.openclaw.ai/gateway/config-tools#tools-agenttoagent and https://docs.openclaw.ai/gateway/security#scope-one-trust-boundary-per-gateway.`}]}function collectSmallModelRiskFindings(e){const t=[];const n=collectAuditModelRefs(e.cfg);if(n.length===0)return t;const r=[];for(const e of n){const t=inferParamBFromIdOrName(e.id);if(t&&t<=SMALL_MODEL_PARAM_B_MAX)r.push({id:e.id,source:e.source,paramB:t})}if(r.length===0)return t;let i=false;const a=[];const o=/* @__PURE__ */ new Set;for(const t of r){const n=extractAgentIdFromSource(t.source);const r=parseModelRef(t.id,`openai`,{allowPluginNormalization:false});const s=resolveSandboxConfigForAgent(e.cfg,n??void 0).mode;const c=n?resolveAgentConfig(e.cfg,n)?.tools:void 0;const l=resolveToolPolicies({cfg:e.cfg,agentTools:c,sandboxMode:s,agentId:n,modelProvider:r?.provider,modelId:r?.model});const u=[];if(isWebSearchEnabled(e.cfg,e.env)&&isToolAllowedByPolicies(`web_search`,l))u.push(`web_search`);if(e.cfg.tools?.web?.fetch?.enabled!==false&&isToolAllowedByPolicies(`web_fetch`,l))u.push(`web_fetch`);if(isBrowserEnabled(e.cfg)&&isToolAllowedByPolicies(`browser`,l))u.push(`browser`);for(const e of u)o.add(e);const d=s===`all`?`sandbox=all`:`sandbox=${s}`;const f=u.length>0?` web=[${u.join(`, `)}]`:` web=[off]`;const p=u.length===0;if(!p)i=true;const m=p?`ok`:`unsafe`;a.push(`- ${t.id} (${t.paramB}B) @ ${t.source} (${m}; ${d};${f})`)}const s=Array.from(o);const c=s.length>0?`Uncontrolled input tools allowed: ${s.join(`, `)}.`:`No web/browser tools detected for these models.`;t.push({checkId:`models.small_params`,severity:i?`critical`:`info`,title:`Small models require sandboxing and web tools disabled`,detail:`Small models (<=${SMALL_MODEL_PARAM_B_MAX}B params) detected:\n`+a.join(`
`)+`\n`+c+`
Small models are not recommended for untrusted inputs.`,remediation:`If you must use small models, disable web_search/web_fetch/browser globally or for each small model with tools.byProvider["provider/model"].deny=["group:web","browser"]; use agents.defaults.sandbox.mode="all" for defense in depth.`});return t}
//!src/security/audit-extra.async.ts
const DEFAULT_SANDBOX_BROWSER_DOCKER_PROBE_TIMEOUT_MS=5e3;const loadConfigModule=createLazyRuntimeModule(()=>import(`./config/config.js`));const loadAuditFsModule=createLazyRuntimeModule(()=>import(`./audit-fs-x8XgzOAR.mjs`));const loadAgentScopeModule=createLazyRuntimeModule(()=>import(`./agent-scope-FEZ3WYd3.mjs`));const loadExecDockerRaw=createLazyRuntimeNamedExport(()=>import(`./docker-dWVv5beD.mjs`),`execDockerRaw`);const loadSandboxBrowserSecurityHashEpoch=createLazyRuntimeNamedExport(()=>import(`./constants-68VV452k.mjs`),`SANDBOX_BROWSER_SECURITY_HASH_EPOCH`);function expandTilde(e,t){if(!e.startsWith(`~`))return e;const n=normalizeOptionalString(t.HOME)??null;if(!n)return null;if(e===`~`)return n;if(e.startsWith(`~/`)||e.startsWith(`~\\`))return path.join(n,e.slice(2));return null}function normalizeDockerLabelValue(e){const t=normalizeOptionalString(e)??``;if(!t||t===`<no value>`)return null;return t}var DockerProbeTimeoutError=class extends Error{constructor(e){super(`Docker check timed out after ${e}ms`);this.name=`DockerProbeTimeoutError`}};function normalizeDockerProbeTimeoutMs(e){if(Number.isFinite(e)&&e!==void 0)return Math.max(250,Math.floor(e));return DEFAULT_SANDBOX_BROWSER_DOCKER_PROBE_TIMEOUT_MS}async function withDockerProbeTimeout(e,t){const n=new AbortController;let r;const i=new Promise((t,i)=>{r=setTimeout(()=>{i(new DockerProbeTimeoutError(e));n.abort()},e)});try{return await Promise.race([t(n.signal),i])}finally{clearTimeout(r)}}async function readSandboxBrowserDocker(e,t,n){try{const r=await withDockerProbeTimeout(e.timeoutMs,n=>e.execDockerRawFn(t,{allowFailure:true,signal:n}));if(r.code!==0)return null;return n(r.stdout.toString(`utf8`))}catch(t){if(t instanceof DockerProbeTimeoutError)e.onTimeout?.();return null}}function readDockerOutputLines(e){return normalizeStringEntries(e.split(/\r?\n/))}function parsePublishedHostFromDockerPortLine(e){const t=normalizeOptionalString(e)??``;const n=t.includes(`->`)?normalizeOptionalString(t.split(`->`).at(-1))??``:t;if(!n)return null;const r=n.match(/^\[([^\]]+)\]:\d+$/);if(r?.[1])return r[1];const i=n.match(/^([^:]+):\d+$/);if(i?.[1])return i[1];return null}function isLoopbackPublishHost(e){const t=normalizeOptionalLowercaseString(e);return t===`127.0.0.1`||t===`::1`||t===`localhost`}async function collectSandboxBrowserHashLabelFindings(e){const t=[];const n=normalizeDockerProbeTimeoutMs(e?.timeoutMs);let r=false;const markTimedOut=()=>{r=true};const[i,a]=await Promise.all([e?.execDockerRawFn?Promise.resolve(e.execDockerRawFn):loadExecDockerRaw(),loadSandboxBrowserSecurityHashEpoch()]);const o={execDockerRawFn:i,timeoutMs:n,onTimeout:markTimedOut};const s=await readSandboxBrowserDocker(o,[`ps`,`-a`,`--filter`,`label=openclaw.sandboxBrowser=1`,`--format`,`{{.Names}}`],readDockerOutputLines);if(!s||s.length===0){if(r)t.push(buildSandboxBrowserDockerProbeTimeoutFinding(n));return t}const c=[];const l=[];const u=[];for(const e of s){const t=await readSandboxBrowserDocker(o,[`inspect`,`-f`,`{{ index .Config.Labels "openclaw.configHash" }}	{{ index .Config.Labels "openclaw.browserConfigEpoch" }}`,e],e=>{const[t,n]=e.split(`	`);return{configHash:normalizeDockerLabelValue(t),epoch:normalizeDockerLabelValue(n)}});if(r)break;if(!t)continue;if(!t.configHash)c.push(e);if(t.epoch!==a)l.push(e);const n=await readSandboxBrowserDocker(o,[`port`,e],readDockerOutputLines);if(r)break;if(!n?.length)continue;const i=n.filter(e=>{const t=parsePublishedHostFromDockerPortLine(e);return Boolean(t&&!isLoopbackPublishHost(t))});if(i.length>0)u.push(`${e} (${i.join(`; `)})`)}if(c.length>0)t.push({checkId:`sandbox.browser_container.hash_label_missing`,severity:`warn`,title:`Sandbox browser container missing config hash label`,detail:`Containers: ${c.join(`, `)}. These browser containers predate hash-based drift checks and may miss security remediations until recreated.`,remediation:`${formatCliCommand(`openclaw sandbox recreate --browser --all`)} (add --force to skip prompt).`});if(l.length>0)t.push({checkId:`sandbox.browser_container.hash_epoch_stale`,severity:`warn`,title:`Sandbox browser container hash epoch is stale`,detail:`Containers: ${l.join(`, `)}. Expected openclaw.browserConfigEpoch=${a}.`,remediation:`${formatCliCommand(`openclaw sandbox recreate --browser --all`)} (add --force to skip prompt).`});if(u.length>0)t.push({checkId:`sandbox.browser_container.non_loopback_publish`,severity:`critical`,title:`Sandbox browser container publishes ports on non-loopback interfaces`,detail:`Containers: ${u.join(`, `)}. Sandbox browser observer/control ports should stay loopback-only to avoid unintended remote access.`,remediation:`${formatCliCommand(`openclaw sandbox recreate --browser --all`)} (add --force to skip prompt), then verify published ports are bound to 127.0.0.1.`});if(r)t.push(buildSandboxBrowserDockerProbeTimeoutFinding(n));return t}function buildSandboxBrowserDockerProbeTimeoutFinding(e){return{checkId:`sandbox.browser_container.docker_probe_timeout`,severity:`warn`,title:`Sandbox browser Docker audit check timed out`,detail:`Docker did not answer within ${e}ms while checking sandbox browser containers. OpenClaw skipped any remaining sandbox browser container drift checks for this status run.`,remediation:`Retry after Docker is responsive, or recreate sandbox browser containers if drift is suspected.`}}async function collectIncludeFilePermFindings(e){const t=[];if(!e.configSnapshot.exists)return t;const n=e.configSnapshot.path;const r=await collectIncludePathsRecursive({configPath:n,parsed:e.configSnapshot.parsed,env:e.env});if(r.length===0)return t;const{createPermissionAuditor:i}=await loadAuditFsModule();const a=i(t,e);for(const e of r)await a(e,false,e=>{if(e.worldWritable||e.groupWritable)return{checkId:`fs.config_include.perms_writable`,severity:`critical`,title:`Config include file is writable by others`,detail:`another user could influence your effective config.`};else if(e.worldReadable)return{checkId:`fs.config_include.perms_world_readable`,severity:`critical`,title:`Config include file is world-readable`,detail:`include files can contain tokens and private settings.`};else if(e.groupReadable)return{checkId:`fs.config_include.perms_group_readable`,severity:`warn`,title:`Config include file is group-readable`,detail:`include files can contain tokens and private settings.`}});return t}async function collectStateDeepFilesystemFindings(e){const t=[];const n=resolveOAuthDir(e.env,e.stateDir);const{createPermissionAuditor:r}=await loadAuditFsModule();const i=r(t,e);await i(n,true,e=>{if(!e.isDir)return;if(e.worldWritable||e.groupWritable)return{checkId:`fs.credentials_dir.perms_writable`,severity:`critical`,title:`Credentials dir is writable by others`,detail:`another user could drop/modify credential files.`};else if(e.groupReadable||e.worldReadable)return{checkId:`fs.credentials_dir.perms_readable`,severity:`warn`,title:`Credentials dir is readable by others`,detail:`credentials and allowlists can be sensitive.`}});const a=await loadAgentScopeModule();const o=a.listAgentEntries(e.cfg).map(e=>e.id);let s;if(o.length>0)try{s=a.resolveDefaultAgentId(e.cfg)}catch{}const c=uniqueStrings([LEGACY_IMPLICIT_AGENT_ID,...s?[s]:[],...o]).map(e=>normalizeAgentId(e));for(const t of c){const n=path.join(e.stateDir,`agents`,t,`agent`);const r=[{path:path.join(n,`auth-profiles.json`),label:`legacy auth-profiles.json`},...resolveAuthProfileDatabaseFilePaths(n).map(e=>({path:e,label:`auth profile SQLite store`}))];for(const e of r)await i(e.path,false,t=>{if(t.worldWritable||t.groupWritable)return{checkId:`fs.auth_profiles.perms_writable`,severity:`critical`,title:`${e.label} is writable by others`,detail:`another user could inject credentials.`};else if(t.worldReadable||t.groupReadable)return{checkId:`fs.auth_profiles.perms_readable`,severity:`warn`,title:`${e.label} is readable by others`,detail:`auth profile storage contains API keys and OAuth tokens.`}});await i(path.join(e.stateDir,`agents`,t,`sessions`,`sessions.json`),false,e=>{if(e.worldReadable||e.groupReadable)return{checkId:`fs.sessions_store.perms_readable`,severity:`warn`,title:`sessions.json is readable by others`,detail:`routing and transcript metadata can be sensitive.`}})}const l=normalizeOptionalString(e.cfg.logging?.file)??``;if(l){const t=l.startsWith(`~`)?expandTilde(l,e.env):l;if(t)await i(path.resolve(t),false,e=>{if(e.worldReadable||e.groupReadable)return{checkId:`fs.log_file.perms_readable`,severity:`warn`,title:`Log file is readable by others`,detail:`logs can contain private messages and tool output.`}})}return t}async function readConfigSnapshotForAudit(e){const{createConfigIO:t}=await loadConfigModule();return await t({env:e.env,configPath:e.configPath}).readConfigFileSnapshot()}
//!src/skills/security/workspace-audit.ts
const MAX_WORKSPACE_SKILL_SCAN_FILES_PER_WORKSPACE=2e3;const MAX_WORKSPACE_SKILL_SCAN_ENTRIES_PER_WORKSPACE=1e5;const MAX_WORKSPACE_SKILL_ESCAPE_DETAIL_ROWS=12;function realpathWithTimeout(e,t=2e3){return withTimeout(fs.realpath(e),t).catch(()=>null)}async function listWorkspaceSkillMarkdownFiles(e){const t=path.join(e,`skills`);let n;try{n=await fs.stat(t)}catch(e){return{skillFilePaths:[],truncated:!isNotFoundPathError(e)}}if(!n.isDirectory())return{skillFilePaths:[],truncated:false};const r=MAX_WORKSPACE_SKILL_SCAN_FILES_PER_WORKSPACE;const i=r*20;let a=0;let o=1;let s=false;const visible=e=>!e.startsWith(`.`)&&e!==`node_modules`;const c=await walkDirectory(t,{maxEntries:MAX_WORKSPACE_SKILL_SCAN_ENTRIES_PER_WORKSPACE,symlinks:`follow`,include:e=>{if(e.kind!==`file`||e.name!==`SKILL.md`)return false;if(a>=r){s=true;return false}a+=1;return true},descend:e=>{if(!visible(e.name))return false;if(a>=r||o>=i){s=true;return false}o+=1;return true}});return{skillFilePaths:c.entries.map(e=>e.path).toSorted(),truncated:s||c.truncated||c.failedDirs.length>0}}async function collectWorkspaceSkillSymlinkEscapeFindings(e){const t=[];const n=new Set(e.workspaceDir?[e.workspaceDir]:[]);try{for(const t of listAgentWorkspaceDirs(e.cfg))n.add(t)}catch{for(const t of listExplicitAgentWorkspaceDirs(e.cfg))n.add(t)}if(n.size===0)return t;const r=[];const i=/* @__PURE__ */ new Set;for(const e of n){const n=path.resolve(e);const a=await realpathWithTimeout(n)??n;const{skillFilePaths:o,truncated:s}=await listWorkspaceSkillMarkdownFiles(n);if(s)t.push({checkId:`skills.workspace.scan_truncated`,severity:`warn`,title:`Workspace skill scan was incomplete`,detail:`The skills/ directory scan in ${n} reached a file, directory, or entry limit, or could not read part of the tree. Skill files in the unscanned portion were not checked for symlink escapes.`,remediation:`Check directory access, flatten or simplify the skills/ tree, or move large skill collections to a managed skill location.`});for(const e of o){const t=path.resolve(e);if(i.has(t))continue;i.add(t);const o=await realpathWithTimeout(t);if(o&&isPathInside$1(a,o))continue;r.push({workspaceDir:n,skillFilePath:t,skillRealPath:o||`(realpath timed out - symlink target unverifiable)`})}}if(r.length===0)return t;t.push({checkId:`skills.workspace.symlink_escape`,severity:`warn`,title:`Workspace skill files resolve outside the workspace root`,detail:"Detected workspace `skills/**/SKILL.md` paths whose realpath escapes their workspace root:\n"+r.slice(0,MAX_WORKSPACE_SKILL_ESCAPE_DETAIL_ROWS).map(e=>`- workspace=${e.workspaceDir}\n  skill=${e.skillFilePath}\n  realpath=${e.skillRealPath}`).join(`
`)+(r.length>MAX_WORKSPACE_SKILL_ESCAPE_DETAIL_ROWS?`\n- +${r.length-MAX_WORKSPACE_SKILL_ESCAPE_DETAIL_ROWS} more`:``),remediation:`Keep workspace skills inside the workspace root (replace symlinked escapes with real in-workspace files), or move trusted shared skills to managed/bundled skill locations.`});return t}
//!src/security/audit-plugins-trust.ts
function readChannelCommandSetting(e,t){const n=e.channels?.[t];if(!n||typeof n!==`object`||Array.isArray(n))return;const r=n.commands;if(!r||typeof r!==`object`||Array.isArray(r))return;return r.nativeSkills}async function isChannelPluginConfigured(e,t){const n=t.config.listAccountIds(e);const r=n.length>0?n:[void 0];for(const n of r){const r=t.config.inspectAccount?.(e,n)??await inspectReadOnlyChannelAccount({channelId:t.id,cfg:e,accountId:n});const i=r&&typeof r===`object`&&!Array.isArray(r)?r:null;let a=r;if(!a)try{a=await resolveChannelAccount({plugin:t,cfg:e,accountId:n})}catch{a=null}let o=typeof i?.enabled===`boolean`?i.enabled:a!=null;if(typeof i?.enabled!==`boolean`&&a!=null&&t.config.isEnabled)try{o=t.config.isEnabled(a,e)}catch{o=false}let s=typeof i?.configured===`boolean`?i.configured:a!=null;if(typeof i?.configured!==`boolean`&&a!=null&&t.config.isConfigured)try{s=await t.config.isConfigured(a,e)}catch{s=false}if(o&&s)return true}return false}function resolveEnabledExtensionPluginIds(e){const t=normalizePluginsConfig(e.cfg.plugins);if(!t.enabled)return[];const n=new Set(t.allow);const r=new Set(t.deny);const i=new Map(Object.entries(t.entries));const a=[];for(const t of e.pluginDirs){const e=normalizeOptionalLowercaseString(t);if(!e)continue;if(r.has(e))continue;if(n.size>0&&!n.has(e))continue;if(i.get(e)?.enabled===false)continue;a.push(e)}return a}async function collectNpmInstallFindings(e,t,n){const r=e.filter(([,e])=>typeof e.spec===`string`&&!isPinnedRegistrySpec(e.spec)).map(([e,t])=>`${e} (${t.spec})`);const i=e.filter(([,e])=>typeof e.integrity!==`string`||e.integrity.trim()===``).map(([e])=>e);const a=[];for(const[r,i]of e){const e=i.resolvedVersion??i.version;if(!e)continue;const o=i.installPath??path.join(t,n,r);const s=await readInstalledPackageVersion(o);if(!s||s===e)continue;a.push(`${r} (recorded ${e}, installed ${s})`)}const o=n===`extensions`;const s=o?`plugins`:`hooks`;const c=[];const report=(e,t)=>{if(e.length>0)c.push({...t,severity:`warn`,detail:`${t.detail}:\n${e.map(e=>`- ${e}`).join(`
`)}`})};report(r,{checkId:`${s}.installs_unpinned_npm_specs`,title:o?`Plugin index includes unpinned npm specs`:`Hook installs include unpinned npm specs`,detail:`Unpinned ${o?`plugin index`:`hook`} install records`,remediation:o?"Pin install specs to exact versions (for example, `@scope/pkg@1.2.3`) for higher supply-chain stability.":"Pin hook install specs to exact versions (for example, `@scope/pkg@1.2.3`) for higher supply-chain stability."});report(i,{checkId:`${s}.installs_missing_integrity`,title:o?`Plugin index is missing integrity metadata`:`Hook installs are missing integrity metadata`,detail:`${o?`Plugin index`:`Hook install`} records missing integrity`,remediation:`Reinstall or update ${s} to refresh install metadata with resolved integrity hashes.`});report(a,{checkId:`${s}.installs_version_drift`,title:o?`Plugin index records drift from installed package versions`:`Hook install records drift from installed package versions`,detail:`Detected ${o?`plugin`:`hook`} install metadata drift`,remediation:`Run \`openclaw ${s} update --all\` (or reinstall affected ${s}) to refresh install metadata.`});return c}async function collectPluginsTrustFindings(e){const t=[];const{extensionsDir:n,pluginDirs:r}=await listInstalledPluginDirs({stateDir:e.stateDir});if(r.length>0){const i=e.cfg.plugins?.allow;const a=Array.isArray(i)&&i.length>0;const o=loadPluginRegistrySnapshot({config:e.cfg,stateDir:e.stateDir});const s=createPluginRegistryIdNormalizer(o);if(a){const e=new Set(r.map(e=>path.basename(e).toLowerCase()));const n=new Set(o.plugins.map(e=>e.pluginId.toLowerCase()));const a=i.filter(t=>{if(typeof t!==`string`||t===`group:plugins`)return false;const r=t.toLowerCase();if(e.has(r)||n.has(r))return false;const i=normalizeOptionalLowercaseString(s(t))??``;return!i||!n.has(i)});if(a.length>0)t.push({checkId:`plugins.allow_phantom_entries`,severity:`warn`,title:`plugins.allow contains entries with no matching installed plugin`,detail:`The following plugins.allow entries do not correspond to any installed plugin: ${a.join(`, `)}.\nPhantom entries could be exploited by registering a new plugin with an allowlisted ID.`,remediation:`Remove unused entries from plugins.allow, or verify the expected plugins are installed.`})}if(!a){const i=await listReadOnlyChannelPluginsForConfigAsync(e.cfg,{stateDir:e.stateDir});const a=(await Promise.all(i.map(async t=>{if(t.capabilities.nativeCommands!==true&&t.commands?.nativeSkillsAutoEnabled!==true)return false;if(!await isChannelPluginConfigured(e.cfg,t))return false;return resolveNativeSkillsEnabled({providerId:t.id,providerSetting:readChannelCommandSetting(e.cfg,t.id),globalSetting:e.cfg.commands?.nativeSkills,stateDir:e.stateDir,autoDefault:t.commands?.nativeSkillsAutoEnabled===true})}))).some(Boolean);t.push({checkId:`plugins.extensions_no_allowlist`,severity:a?`critical`:`warn`,title:`Extensions exist but plugins.allow is not set`,detail:`Found ${r.length} extension(s) under ${n}. Without plugins.allow, any discovered plugin id may load (depending on config and plugin behavior).`+(a?`
Native skill commands are enabled on at least one configured chat surface; treat unpinned/unallowlisted extensions as high risk.`:``),remediation:`Set plugins.allow to an explicit list of plugin ids you trust.`})}const c=resolveEnabledExtensionPluginIds({cfg:e.cfg,pluginDirs:r});if(c.length>0){const[{resolveConfiguredToolPolicies:n},{resolveSandboxConfigForAgent:r},{isToolAllowedByPolicies:i},{buildPluginToolGroups:a,expandPolicyWithPluginGroups:l}]=await Promise.all([import(`./agent-tools.policy-DNBACOsq.mjs`),import(`./config-Da5s4J3u.mjs`),import(`./tool-policy-match-RXClTh2S.mjs`),import(`./tool-policy-C_cWnP3J.mjs`)]);const u=new Map(o.plugins.map(e=>[s(e.pluginId).toLowerCase(),e.contributions?.contracts.tools]));const d=a({tools:c.flatMap(e=>{const t=s(e).toLowerCase();return(u.get(t)??[`__openclaw_plugin_probe_${t}__`]).map(e=>({name:e,pluginId:t}))}),toolMeta:e=>({pluginId:e.pluginId})});const f=[{label:`default`}];for(const t of listAgentEntries(e.cfg)){if(!t||typeof t!==`object`||typeof t.id!==`string`)continue;f.push({label:`agents.entries.${t.id}`,agentId:t.id,tools:t.tools})}const p=[];for(const t of f){const a=r(e.cfg,t.agentId).mode;const o=n({cfg:e.cfg,agentTools:t.tools,sandboxMode:a,agentId:t.agentId}).map(e=>l(e,d));if(d.all.some(e=>i(e,o)))p.push(t.label)}if(p.length>0)t.push({checkId:`plugins.tools_reachable_permissive_policy`,severity:`warn`,title:`Extension plugin tools may be reachable under permissive tool policy`,detail:`Enabled extension plugins: ${c.join(`, `)}.\nPermissive tool policy contexts:\n${p.map(e=>`- ${e}`).join(`
`)}`,remediation:"Use restrictive profiles (`minimal`/`coding`) or explicit tool allowlists that exclude plugin tools for agents handling untrusted input."})}}const i=await loadInstalledPluginIndexInstallRecords({stateDir:e.stateDir});const a=Object.entries(i).filter(([,e])=>e?.source===`npm`);t.push(...await collectNpmInstallFindings(a,e.stateDir,`extensions`));const o=readHookInstalls({env:{...process.env,OPENCLAW_STATE_DIR:e.stateDir}});const s=Object.entries(o).filter(([,e])=>e?.source===`npm`);t.push(...await collectNpmInstallFindings(s,e.stateDir,`hooks`));return t}
//!src/security/audit-secrets.ts
function collectSecretsInConfigFindings(e){const t=[];if((normalizeOptionalString(e.gateway?.auth?.password)??``)&&!hasUnresolvedConfigPath(e,`gateway.auth.password`)&&!getResolvedConfigEnvSecretRef(e,`gateway.auth.password`))t.push({checkId:`config.secrets.gateway_password_in_config`,severity:`warn`,title:`Gateway password is stored in config`,detail:`gateway.auth.password is set in the config file; prefer environment variables for secrets when possible.`,remediation:`Prefer OPENCLAW_GATEWAY_PASSWORD (env) and remove gateway.auth.password from disk.`});const n=normalizeOptionalString(e.hooks?.token)??``;if(e.hooks?.enabled===true&&n&&!hasUnresolvedConfigPath(e,`hooks.token`)&&!getResolvedConfigEnvSecretRef(e,`hooks.token`))t.push({checkId:`config.secrets.hooks_token_in_config`,severity:`info`,title:`Hooks token is stored in config`,detail:`hooks.token is set in the config file; keep config perms tight and treat it like an API secret.`});return t}export{collectAttackSurfaceSummaryFindings,collectCrossAgentSessionAccessFindings,collectExposureMatrixFindings,collectGatewayHttpNoAuthFindings,collectGatewayHttpSessionKeyOverrideFindings,collectHooksHardeningFindings,collectIncludeFilePermFindings,collectLikelyMultiUserSetupFindings,collectMinimalProfileOverrideFindings,collectNodeDangerousAllowCommandFindings,collectNodeDenyCommandPatternFindings,collectPluginsTrustFindings,collectSandboxBrowserHashLabelFindings,collectSandboxDangerousConfigFindings,collectSandboxDockerNoopFindings,collectSecretsInConfigFindings,collectSmallModelRiskFindings,collectStateDeepFilesystemFindings,collectSyncedFolderFindings,collectWorkspaceSkillSymlinkEscapeFindings,readConfigSnapshotForAudit};