openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1,081 lines • 50.2 kB
JavaScript
import { c as normalizeOptionalLowercaseString, l as normalizeOptionalString, o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs";
import { E as parseStrictNonNegativeInteger } from "./number-coercion-D6u-4YD8.mjs";
import { r as asNullableRecord } from "./record-coerce-CVPuDqcc.mjs";
import { s as formatNodeSecurityWarning } from "./node-version-CYJ7qOPD.mjs";
import { f as normalizeStringEntries } from "./string-normalization-DLmfYZXI.mjs";
import { t as hasErrnoCode } from "./errno-DFcoqIT9.mjs";
import { r as resolveStateDir } from "./state-dir-DiG0gXzD.mjs";
import { m as resolveConfigPath } from "./paths-DAcAg5aV.mjs";
import { h as readLocalFileSafely, t as FsSafeError } from "./fs-safe-BbWvmdVn.mjs";
import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs";
import { i as listAgentIds, n as listAgentEntries, s as readAgentRosterProperty, t as hasAgentRosterProperty } from "./agent-roster-t1ooUdXp.mjs";
import { A as tryResolveLegacyCompatibilityAgentId, r as resolveAgentConfig } from "./agent-scope-config-DmXgFGKP.mjs";
import { l as emitTrustedSecurityEvent } from "./diagnostic-events-BjAH1Kbx.mjs";
import { d as hasUnresolvedConfigPath, i as copyConfigResolutionFacts, p as resolveConfigSecretRef } from "./resolution-facts-xaIKuREs.mjs";
import { n as resolvePluginControlPlaneWorkspace } from "./control-plane-workspace-OscAdfLv.mjs";
import { u as listRiskyConfiguredSafeBins } from "./exec-safe-bin-trust-DOHJJ8Cr.mjs";
import { r as isInvalidGatewaySecret } from "./known-weak-gateway-secrets-DrP6ACfl.mjs";
import { a as resolveControlUiAllowedOrigins } from "./gateway-control-ui-origins-jPuz3g3d.mjs";
import { t as createGatewayCredentialPlan } from "./credential-planner-DCQbkiQO.mjs";
import { i as resolveGatewayAuthForConfig } from "./auth-resolve-C6_i-P4T.mjs";
import { i as resolveSandboxConfigForAgent } from "./config-WbZbWrF1.mjs";
import { t as DEFAULT_GATEWAY_HTTP_TOOL_DENY } from "./dangerous-tools-DsHfDX-_.mjs";
import { r as loadExecApprovals } from "./exec-approvals-store-BUZ9uOWF.mjs";
import { l as isInterpreterLikeAllowlistPattern } from "./risks-CqlFotky.mjs";
import "./exec-approvals-rOfoWejC.mjs";
import { r as resolveExecDefaults } from "./exec-defaults-BaVI-sJD.mjs";
import { r as materializeGatewayAuthSecretRefs, t as canMaterializeGatewayAuthSecretRefsWithoutExec } from "./auth-config-utils-C9EXfOyf.mjs";
import { i as resolveMergedSafeBinProfileFixtures, n as listInterpreterLikeSafeBins } from "./exec-safe-bin-runtime-policy-DUQ-JlOU.mjs";
import { n as normalizeConfiguredTrustedSafeBinDirs, t as normalizeConfiguredSafeBins } from "./exec-safe-bin-config-EFTvuM64.mjs";
import { t as createPermissionAuditor } from "./audit-fs-DX0NF-Sb.mjs";
import { t as resolveGatewayAuthTokenSourceConflict } from "./auth-token-source-conflict-BouzQo5r.mjs";
import { n as collectCoreInsecureOrDangerousFlags } from "./dangerous-config-flags-core-CNiIxNmn.mjs";
import { t as listConfiguredOpenInboundPolicyPaths } from "./audit-open-inbound-Dy94Efvf.mjs";
import { t as collectEnabledInsecureOrDangerousFlags } from "./dangerous-config-flags-DPX8YEdt.mjs";
import { t as collectExecFilesystemPolicyDriftHits } from "./exec-filesystem-policy-iT8_0I4a.mjs";
import path from "node:path";
import fs from "node:fs/promises";
import { isIP } from "node:net";
//#region src/security/audit-agent-roster.ts
function collectAgentRosterFindings(e) {
const t = listAgentEntries(e);
if (t.length === 0 && !hasAgentRosterProperty(e)) return [];
const n = readAgentRosterProperty(e);
const r = (n?.kind === "entries" ? Object.values(asNullableRecord(n.value) ?? {}) : Array.isArray(n?.value) ? n.value : []).filter((e) => asNullableRecord(e)?.default === true).length;
const i = e.agents?.ownership === "explicit";
if (i ? r === 0 : tryResolveLegacyCompatibilityAgentId(e) !== void 0) return [];
return [{
checkId: "config.agent_roster.invalid_default_count",
severity: "warn",
title: "Agent roster has an invalid default selection",
detail: i ? `Expected no agents.entries default=true entries with agents.ownership=explicit, found ${r}.` : `Expected a resolvable default agent (sole entry, one default=true marker, or agents.ownership=explicit); found ${r} default markers across ${t.length} configured agents.`,
remediation: "Run `openclaw doctor --fix` to repair the authored agent roster."
}];
}
//#endregion
//#region src/security/audit-deep-code-safety.ts
async function collectDeepCodeSafetyFindings(e) {
if (!e.deep) return [];
const t = await import("./audit.deep.runtime.js");
return [...await t.collectPluginsCodeSafetyFindings({ stateDir: e.stateDir }), ...await t.collectInstalledSkillsCodeSafetyFindings({
cfg: e.cfg,
stateDir: e.stateDir,
workspaceDir: e.workspaceDir
})];
}
//#endregion
//#region src/security/audit-deep-probe-findings.ts
/**
* Convert optional deep gateway probe results into security audit findings.
* This keeps CLI/audit callers aligned on check ids, titles, and remediation text.
*/
function collectDeepProbeFindings(e) {
const t = [];
if (e.deep?.gateway?.attempted && !e.deep.gateway.ok) t.push({
checkId: "gateway.probe_failed",
severity: "warn",
title: "Gateway check failed (deep)",
detail: e.deep.gateway.error ?? "gateway unreachable",
remediation: `Run "${formatCliCommand("openclaw status --all")}" to debug connectivity/auth, then re-run "${formatCliCommand("openclaw security audit --deep")}".`
});
if (e.authWarning) t.push({
checkId: "gateway.probe_auth_secretref_unavailable",
severity: "warn",
title: "Gateway check auth SecretRef is unavailable",
detail: e.authWarning,
remediation: `Set OPENCLAW_GATEWAY_TOKEN/OPENCLAW_GATEWAY_PASSWORD in this shell or resolve the external secret provider, then re-run "${formatCliCommand("openclaw security audit --deep")}".`
});
return t;
}
//#endregion
//#region src/security/audit-gateway-config.ts
function collectGatewayConfigFindings(e, t, n, r = {}) {
const i = [];
const a = typeof e.gateway?.bind === "string" ? e.gateway.bind : "loopback";
const o = e.gateway?.tailscale?.mode ?? "off";
const s = resolveGatewayAuthForConfig({
config: e,
authOverride: r.gatewayAuthOverride,
tailscaleMode: o,
env: n
});
const c = e.gateway?.controlUi?.enabled !== false;
const l = normalizeStringEntries(resolveControlUiAllowedOrigins(e));
const u = e.gateway?.controlUi?.dangerouslyAllowHostHeaderOriginFallback === true;
const d = Array.isArray(e.gateway?.trustedProxies) ? e.gateway.trustedProxies : [];
const f = typeof s.token === "string" && s.token.trim().length > 0 && !hasUnresolvedConfigPath(t, "gateway.auth.token");
const p = typeof s.password === "string" && s.password.trim().length > 0 && !hasUnresolvedConfigPath(t, "gateway.auth.password");
const m = createGatewayCredentialPlan({
config: t,
env: n
});
const h = r.gatewayAuthOverride?.mode ?? t.gateway?.auth?.mode;
const g = Boolean(f || m.envToken || m.localToken.value || m.localToken.hasSecretRef || m.remoteToken.value || m.remoteToken.hasSecretRef);
const _ = Boolean(p || (h === "password" || h !== "token" && h !== "none" && h !== "trusted-proxy" && !g) && (m.envPassword || m.localPassword.value || m.localPassword.hasSecretRef));
const v = (h === "token" ? g : h === "password" ? _ : h === "none" || h === "trusted-proxy" ? false : g || _) || s.mode === "trusted-proxy";
const y = v || s.allowTailscale && o === "serve";
const b = e.gateway?.allowRealIpFallback === true;
const x = e.discovery?.mdns?.mode ?? "minimal";
const S = Array.isArray(e.gateway?.tools?.allow) ? e.gateway?.tools?.allow : [];
const C = new Set(S.map((e) => normalizeOptionalLowercaseString(e) ?? "").filter(Boolean));
const w = DEFAULT_GATEWAY_HTTP_TOOL_DENY.filter((e) => C.has(e));
if (w.length > 0) {
const e = a !== "loopback" || o === "funnel";
i.push({
checkId: "gateway.tools_invoke_http.dangerous_allow",
severity: e ? "critical" : "warn",
title: "Gateway HTTP /tools/invoke re-enables dangerous tools",
detail: `gateway.tools.allow includes ${w.join(", ")} which removes them from the default HTTP deny list. This can allow remote session spawning / control-plane actions via HTTP and increases the damage from remote code execution if the gateway is reachable.`,
remediation: "Remove these entries from gateway.tools.allow (recommended). If you keep them enabled, keep gateway.bind loopback-only (or tailnet-only), restrict network exposure, and treat the gateway token/password as full-admin."
});
}
if (a !== "loopback" && !v) i.push({
checkId: "gateway.bind_no_auth",
severity: "critical",
title: "Gateway binds beyond loopback without auth",
detail: `gateway.bind="${a}" but no gateway.auth token/password is configured.`,
remediation: `Set gateway.auth (token recommended) or bind to loopback.`
});
const T = resolveGatewayAuthTokenSourceConflict({
cfg: t,
env: n
});
if (T) i.push({
checkId: T.checkId,
severity: "warn",
title: T.title,
detail: T.detail,
remediation: T.remediation
});
if (a === "loopback" && c && d.length === 0) i.push({
checkId: "gateway.trusted_proxies_missing",
severity: "warn",
title: "Reverse proxy headers are not trusted",
detail: "gateway.bind is loopback and gateway.trustedProxies is empty. If you expose the Control UI through a reverse proxy, configure trusted proxies so local-client checks cannot be spoofed.",
remediation: "Set gateway.trustedProxies to your proxy IPs or keep the Control UI local-only."
});
if (a === "loopback" && c && !y) i.push({
checkId: "gateway.loopback_no_auth",
severity: "critical",
title: "Gateway auth missing on loopback",
detail: "gateway.bind is loopback but no gateway auth secret is configured. If the Control UI is exposed through a reverse proxy, unauthenticated access is possible.",
remediation: "Set gateway.auth (token recommended) or keep the Control UI local-only."
});
if (a !== "loopback" && c && l.length === 0 && !u) i.push({
checkId: "gateway.control_ui.allowed_origins_required",
severity: "critical",
title: "Non-loopback Control UI missing allowed origins",
detail: "Control UI is enabled on a non-loopback bind without an effective browser-origin allowlist. Set explicit allowed origins, or omit the list to use gateway.publicOrigin.",
remediation: "Set gateway.publicOrigin with gateway.controlUi.allowedOrigins omitted, or configure a list of full trusted origins (for example https://control.example.com). If your deployment intentionally relies on Host-header origin fallback, set gateway.controlUi.dangerouslyAllowHostHeaderOriginFallback=true."
});
if (l.includes("*")) {
const e = a !== "loopback";
i.push({
checkId: "gateway.control_ui.allowed_origins_wildcard",
severity: e ? "critical" : "warn",
title: "Control UI allowed origins contains wildcard",
detail: "gateway.controlUi.allowedOrigins includes \"*\" which means allow any browser origin for Control UI/WebChat requests. This disables origin allowlisting and should be treated as an intentional allow-all policy.",
remediation: "Replace wildcard origins with explicit trusted origins (for example https://control.example.com). Do not use \"*\" outside tightly controlled local testing."
});
}
if (u) {
const e = a !== "loopback";
i.push({
checkId: "gateway.control_ui.host_header_origin_fallback",
severity: e ? "critical" : "warn",
title: "DANGEROUS: Host-header origin fallback enabled",
detail: "gateway.controlUi.dangerouslyAllowHostHeaderOriginFallback=true enables Host-header origin fallback for Control UI/WebChat websocket checks and weakens DNS rebinding protections.",
remediation: "Disable gateway.controlUi.dangerouslyAllowHostHeaderOriginFallback and configure explicit gateway.controlUi.allowedOrigins."
});
}
if (b) {
const e = d.some((e) => !isStrictLoopbackTrustedProxyEntry(e));
const t = a !== "loopback" || s.mode === "trusted-proxy" && e;
i.push({
checkId: "gateway.real_ip_fallback_enabled",
severity: t ? "critical" : "warn",
title: "X-Real-IP fallback is enabled",
detail: "gateway.allowRealIpFallback=true trusts X-Real-IP when trusted proxies omit X-Forwarded-For. Misconfigured proxies that forward client-supplied X-Real-IP can spoof source IP and local-client checks.",
remediation: "Keep gateway.allowRealIpFallback=false (default). Only enable this when your trusted proxy always overwrites X-Real-IP and cannot provide X-Forwarded-For."
});
}
if (x === "full") {
const e = a !== "loopback";
i.push({
checkId: "discovery.mdns_full_mode",
severity: e ? "critical" : "warn",
title: "mDNS full mode can leak host metadata",
detail: "discovery.mdns.mode=\"full\" publishes cliPath/sshPort in local-network TXT records. This can reveal usernames, filesystem layout, and management ports.",
remediation: "Prefer discovery.mdns.mode=\"minimal\" (recommended) or \"off\", especially when gateway.bind is not loopback."
});
}
if (o === "funnel") i.push({
checkId: "gateway.tailscale_funnel",
severity: "critical",
title: "Tailscale Funnel exposure enabled",
detail: `gateway.tailscale.mode="funnel" exposes the Gateway publicly; keep auth strict and treat it as internet-facing.`,
remediation: `Prefer tailscale.mode="serve" (tailnet-only) or set tailscale.mode="off".`
});
else if (o === "serve") i.push({
checkId: "gateway.tailscale_serve",
severity: "info",
title: "Tailscale Serve exposure enabled",
detail: `gateway.tailscale.mode="serve" exposes the Gateway to your tailnet (loopback behind Tailscale).`
});
if (e.mcp?.apps?.enabled === true) i.push({
checkId: "mcp.apps.enabled",
severity: "warn",
title: "MCP Apps UI bridge enabled",
detail: "mcp.apps.enabled=true allows configured MCP servers to provide interactive HTML. Views are CSP-restricted and origin-isolated, but they can call app-visible tools on their owning MCP server while the session runtime remains active.",
remediation: "Keep this enabled only for MCP servers you trust. Disable with `openclaw config set mcp.apps.enabled false --strict-json` when it is not needed."
});
const E = (r.collectDangerousConfigFlags ?? collectCoreInsecureOrDangerousFlags)(e);
for (const e of E) i.push({
checkId: "config.insecure_or_dangerous_flags",
severity: "warn",
title: "Insecure or dangerous config flag enabled",
detail: `Detected enabled flag: ${e}.`,
remediation: "Disable this flag when not actively debugging, or keep deployment scoped to trusted/local-only networks."
});
for (const t of ["token", "password"]) {
if (s.mode !== t) continue;
const n = e.gateway?.auth?.[t];
const a = r.gatewayAuthOverride?.[t];
const o = t === "token" ? m.localToken : m.localPassword;
let c = s[t] ?? a ?? n;
if (a === void 0 && o.refPath) c = hasUnresolvedConfigPath(e, o.refPath) || resolveConfigSecretRef({
config: e,
path: o.refPath,
value: n,
defaults: e.secrets?.defaults
}) ? void 0 : n;
const l = typeof c === "string" ? c.trim() : null;
if (isInvalidGatewaySecret(c)) i.push({
checkId: `gateway.${t}_placeholder_value`,
severity: "critical",
title: `Gateway ${t} is a blank or undefined/null placeholder`,
detail: `The selected Gateway ${t} is a known non-secret value. Gateway startup rejects it.`,
remediation: t === "token" ? "Run `openclaw doctor --fix --generate-gateway-token` for an inline token; otherwise rotate its external secret source. Restart the Gateway afterward." : "Generate a real secret (for example, `openssl rand -hex 32`) and update OPENCLAW_GATEWAY_PASSWORD or gateway.auth.password (or its external source). Restart the Gateway afterward."
});
else if (l && l.length < 24) i.push({
checkId: `gateway.${t}_too_short`,
severity: "warn",
title: `Gateway ${t} looks short`,
detail: `gateway auth ${t} is ${l.length} chars; prefer a long random ${t}.`
});
}
if (s.mode === "trusted-proxy") {
const t = e.gateway?.auth?.trustedProxy;
i.push({
checkId: "gateway.trusted_proxy_auth",
severity: "critical",
title: "Trusted-proxy auth mode enabled",
detail: "gateway.auth.mode=\"trusted-proxy\" delegates authentication to a reverse proxy. Check that your proxy (Pomerium, Caddy, nginx) handles auth correctly and that gateway.trustedProxies only contains IPs of your actual proxy servers.",
remediation: "Verify: (1) Your proxy terminates TLS and authenticates users. (2) gateway.trustedProxies is restricted to proxy IPs only. (3) Direct access to the Gateway port is blocked by firewall. Same-host proxy requests are rejected unless gateway.auth.trustedProxy.allowLoopback=true and gateway.trustedProxies includes their loopback source; enable only for a deliberate same-host trust boundary. See /gateway/trusted-proxy-auth for setup guidance."
});
if (d.length === 0) i.push({
checkId: "gateway.trusted_proxy_no_proxies",
severity: "critical",
title: "Trusted-proxy auth enabled but no trusted proxies configured",
detail: "gateway.auth.mode=\"trusted-proxy\" but gateway.trustedProxies is empty. All requests will be rejected.",
remediation: "Set gateway.trustedProxies to the IP(s) of your reverse proxy."
});
if (!t?.userHeader) i.push({
checkId: "gateway.trusted_proxy_no_user_header",
severity: "critical",
title: "Trusted-proxy auth missing userHeader config",
detail: "gateway.auth.mode=\"trusted-proxy\" but gateway.auth.trustedProxy.userHeader is not configured.",
remediation: "Set gateway.auth.trustedProxy.userHeader to the header name your proxy uses (e.g., \"x-forwarded-user\", \"x-pomerium-claim-email\")."
});
if (t?.allowLoopback === true) i.push({
checkId: "gateway.trusted_proxy_allow_loopback",
severity: "warn",
title: "Trusted-proxy auth allows loopback proxy sources",
detail: "gateway.auth.trustedProxy.allowLoopback=true allows loopback-source requests from configured gateway.trustedProxies entries to satisfy trusted-proxy auth.",
remediation: "Enable this only when a same-host reverse proxy is the intended trust boundary. Keep direct Gateway access private to the host and require the proxy to strip or overwrite identity headers."
});
if (t?.deviceAutoApprove?.enabled === true) {
i.push({
checkId: "gateway.trusted_proxy_device_auto_approve",
severity: "warn",
title: "Trusted-proxy operator device auto-approval enabled",
detail: "gateway.auth.trustedProxy.deviceAutoApprove.enabled=true delegates new browser and native UI operator device pairing entirely to the reverse-proxy identity.",
remediation: "Enable this only when the proxy is the exclusive Gateway ingress, strongly authenticates users, overwrites identity headers, and restricts access with allowUsers."
});
if (t.deviceAutoApprove.scopes?.some((e) => e.trim() === "operator.admin")) i.push({
checkId: "gateway.trusted_proxy_device_auto_approve_admin",
severity: "critical",
title: "Trusted-proxy device auto-approval allows full admin",
detail: "gateway.auth.trustedProxy.deviceAutoApprove.scopes includes operator.admin, so every proxy-authenticated user can auto-approve a new operator device with full admin; requests without scopes receive full admin automatically.",
remediation: "Remove operator.admin and approve admin access manually, or grant admin per identity via gateway.auth.identityScopes."
});
}
if ((t?.allowUsers ?? []).length === 0) i.push({
checkId: "gateway.trusted_proxy_no_allowlist",
severity: "warn",
title: "Trusted-proxy auth allows all authenticated users",
detail: "gateway.auth.trustedProxy.allowUsers is empty, so any user authenticated by your proxy can access the Gateway.",
remediation: "Consider setting gateway.auth.trustedProxy.allowUsers to restrict access to specific users (e.g., [\"nick@example.com\"])."
});
}
if (a !== "loopback" && s.mode !== "trusted-proxy" && !e.gateway?.auth?.rateLimit) i.push({
checkId: "gateway.auth_no_rate_limit",
severity: "warn",
title: "No auth rate limiting configured",
detail: "gateway.bind is not loopback but no gateway.auth.rateLimit is configured. Without rate limiting, brute-force auth attacks are not mitigated.",
remediation: "Set gateway.auth.rateLimit (e.g. { maxAttempts: 10, windowMs: 60000, lockoutMs: 300000 })."
});
return i;
}
function isStrictLoopbackTrustedProxyEntry(e) {
const t = e.trim();
if (!t) return false;
if (!t.includes("/")) return t === "127.0.0.1" || t.toLowerCase() === "::1";
const [n, r] = t.split("/", 2);
if (!n || !r) return false;
const i = isIP(n.trim());
const a = parseStrictNonNegativeInteger(r);
if (a === void 0) return false;
if (i === 4) return n.trim() === "127.0.0.1" && a === 32;
if (i === 6) return a === 128 && normalizeLowercaseStringOrEmpty(n) === "::1";
return false;
}
//#endregion
//#region src/security/audit-mcporter-registry.ts
const MAX_MCPORTER_REGISTRY_BYTES = 16777216;
async function readBoundedMcporterRegistry(e) {
const t = path.join(e, "skills", "config", "mcporter.json");
try {
const { buffer: e } = await readLocalFileSafely({
filePath: await fs.realpath(t),
maxBytes: MAX_MCPORTER_REGISTRY_BYTES
});
try {
return {
status: "ok",
value: JSON.parse(e.toString("utf-8"))
};
} catch {
return {
status: "rejected",
reason: "malformed"
};
}
} catch (e) {
const t = e instanceof FsSafeError ? e.code : void 0;
if (hasErrnoCode(e, "ENOENT") || t === "not-found") return { status: "missing" };
return {
status: "rejected",
reason: t === "too-large" ? "oversized" : t === "not-file" ? "non-regular" : "unreadable"
};
}
}
//#endregion
//#region src/security/audit-runtime.ts
function collectNodeRuntimeSecurityFindings() {
const e = process.versions.bun ? null : formatNodeSecurityWarning(process.versions.node);
if (e) return [{
checkId: "runtime.node_security_patch",
severity: "warn",
title: "Audit process Node.js is below the recommended security patch level",
detail: `Audit process runtime: ${e}`,
remediation: "Upgrade the Node.js runtime used to run this audit to the recommended security patch level or a newer supported release. The Gateway may use a different runtime; upgrade that runtime separately and restart the Gateway if needed."
}];
return [];
}
function collectElevatedFindings(e) {
const t = [];
const n = e.tools?.elevated?.enabled;
const r = e.tools?.elevated?.allowFrom ?? {};
if (n === false) return t;
for (const [e, n] of Object.entries(r)) {
const r = normalizeStringEntries(Array.isArray(n) ? n : []);
if (r.includes("*")) t.push({
checkId: `tools.elevated.allowFrom.${e}.wildcard`,
severity: "critical",
title: "Elevated exec allowlist contains wildcard",
detail: `tools.elevated.allowFrom.${e} includes "*" which effectively approves everyone on that channel for elevated mode.`
});
else if (r.length > 25) t.push({
checkId: `tools.elevated.allowFrom.${e}.large`,
severity: "warn",
title: "Elevated exec allowlist is large",
detail: `tools.elevated.allowFrom.${e} has ${r.length} entries; consider tightening elevated access.`
});
}
return t;
}
//#endregion
//#region src/security/audit.ts
function countBySeverity(e) {
let t = 0;
let n = 0;
let r = 0;
for (const i of e) if (i.severity === "critical") t += 1;
else if (i.severity === "warn") n += 1;
else r += 1;
return {
critical: t,
warn: n,
info: r
};
}
function emitSecurityAuditReportEvent(e) {
const t = e.summary.critical > 0;
const n = e.summary.warn > 0;
emitTrustedSecurityEvent({
category: "audit",
action: "security.audit.completed",
outcome: t || n ? "failure" : "success",
severity: t ? "critical" : n ? "medium" : "info",
actor: { kind: "operator" },
target: {
kind: "config",
name: "security.audit"
},
policy: {
id: "security.audit",
decision: "not_applicable"
},
control: {
id: "security.audit",
family: "authorization"
},
attributes: {
critical_count: e.summary.critical,
warn_count: e.summary.warn,
info_count: e.summary.info,
suppressed_count: e.suppressedCount,
deep: e.deep,
include_filesystem: e.includeFilesystem,
include_channel_security: true
}
});
}
function normalizeSuppressionText(e) {
return (e ?? "").trim().toLowerCase();
}
async function materializeAuditGatewayAuthRefs(e) {
const t = {
cfg: e.cfg,
env: e.env,
mode: e.cfg.gateway?.auth?.mode,
hasTokenOverride: false,
hasPasswordOverride: false,
hasTokenFallback: Boolean(normalizeOptionalString(e.env.OPENCLAW_GATEWAY_TOKEN)),
hasPasswordFallback: Boolean(normalizeOptionalString(e.env.OPENCLAW_GATEWAY_PASSWORD))
};
if (!canMaterializeGatewayAuthSecretRefsWithoutExec(t)) return e.cfg;
try {
return await materializeGatewayAuthSecretRefs(t);
} catch {
return e.cfg;
}
}
function shouldMaterializeHooksGatewayAuthRefs(e) {
return e.hooks?.enabled === true && Boolean(normalizeOptionalString(e.hooks.token));
}
function findingMatchesSuppression(e, t) {
const n = t.checkId.trim();
if (!n || e.checkId !== n) return false;
const r = normalizeSuppressionText(t.titleIncludes);
if (r && !e.title.toLowerCase().includes(r)) return false;
const i = normalizeSuppressionText(t.detailIncludes);
if (i && !e.detail.toLowerCase().includes(i)) return false;
return true;
}
function buildSecurityAuditSuppressionsActiveFinding(e) {
return {
checkId: "security.audit.suppressions.active",
severity: "info",
title: "Security audit suppressions configured",
detail: `security.audit.suppressions has ${e.configuredCount} configured suppression(s); ${e.suppressedCount} finding(s) moved to suppressedFindings.`,
remediation: "Review suppressedFindings and remove suppressions when the accepted risk no longer applies."
};
}
function applySecurityAuditSuppressions(e, t) {
if (!Array.isArray(t) || t.length === 0) return {
findings: e,
suppressedFindings: []
};
const n = [];
const r = [];
for (const i of e) {
const e = t.find((e) => findingMatchesSuppression(i, e));
if (!e) {
n.push(i);
continue;
}
const a = e.reason?.trim();
r.push({
...i,
suppression: a ? { reason: a } : {}
});
}
return {
findings: n,
suppressedFindings: r
};
}
async function collectFilesystemFindings(e) {
const t = [];
const n = createPermissionAuditor(t, e);
await n(e.stateDir, true, (n) => {
if (n.isSymlink) t.push({
checkId: "fs.state_dir.symlink",
severity: "warn",
title: "State dir is a symlink",
detail: `${e.stateDir} is a symlink; treat this as an extra trust boundary.`
});
if (n.worldWritable) return {
checkId: "fs.state_dir.perms_world_writable",
severity: "critical",
title: "State dir is world-writable",
detail: "other users can write into your OpenClaw state."
};
else if (n.groupWritable) return {
checkId: "fs.state_dir.perms_group_writable",
severity: "warn",
title: "State dir is group-writable",
detail: "group users can write into your OpenClaw state."
};
else if (n.groupReadable || n.worldReadable) return {
checkId: "fs.state_dir.perms_readable",
severity: "warn",
title: "State dir is readable by others",
detail: "consider restricting to 700."
};
});
await n(e.configPath, false, (n) => {
const r = n.isSymlink;
if (n.isSymlink) t.push({
checkId: "fs.config.symlink",
severity: "warn",
title: "Config file is a symlink",
detail: `${e.configPath} is a symlink; make sure you trust its target.`
});
if (n.worldWritable || n.groupWritable) return {
checkId: "fs.config.perms_writable",
severity: "critical",
title: "Config file is writable by others",
detail: "another user could change gateway/auth/tool policies."
};
else if (!r && n.worldReadable) return {
checkId: "fs.config.perms_world_readable",
severity: "critical",
title: "Config file is world-readable",
detail: "config can contain tokens and private settings."
};
else if (!r && n.groupReadable) return {
checkId: "fs.config.perms_group_readable",
severity: "warn",
title: "Config file is group-readable",
detail: "config can contain tokens and private settings."
};
});
return t;
}
async function collectPluginSecurityAuditFindings(e) {
if (!e.loadPluginSecurityCollectors) return [];
const { getActivePluginRegistry: t } = await import("./runtime-BETi0o5k.mjs");
let n = t()?.securityAuditCollectors ?? [];
if (n.length === 0) {
const { applyPluginAutoEnable: t } = await import("./plugin-auto-enable-56ocMcft.mjs");
const r = t({
config: e.sourceConfig,
env: e.env
});
const i = new Set(normalizeStringEntries([
...Object.keys(r.autoEnabledReasons),
...(r.config.plugins?.allow ?? []).filter((e) => typeof e === "string"),
...Object.entries(r.config.plugins?.entries ?? {}).filter(([, e]) => e?.enabled !== false).map(([e]) => e)
]));
if (e.plugins !== void 0) {
const { resolveConfiguredChannelPluginIdsAsync: t } = await import("./channel-plugin-ids-Bt1RzFGs.mjs");
const n = new Set(e.plugins.map((e) => e.id));
for (const a of await t({
config: r.config,
activationSourceConfig: e.sourceConfig,
workspaceDir: e.workspaceDir,
env: e.env
})) if (n.has(a)) i.delete(a);
}
if (i.size === 0) return [];
n = (await import("./metadata-registry-loader-Bv8hn0st.mjs")).loadPluginMetadataRegistrySnapshot({
config: r.config,
activationSourceConfig: e.sourceConfig,
env: e.env,
workspaceDir: e.workspaceDir,
onlyPluginIds: [...i]
}).securityAuditCollectors ?? [];
}
return (await Promise.all(n.map(async (t) => {
try {
return await t.collector({
config: e.cfg,
sourceConfig: e.sourceConfig,
env: e.env,
stateDir: e.stateDir,
configPath: e.configPath
});
} catch (e) {
return [{
checkId: `plugins.${t.pluginId}.security_audit_failed`,
severity: "warn",
title: "Plugin security audit collector failed",
detail: `${t.pluginId}: ${String(e)}`
}];
}
}))).flat();
}
function collectExecRuntimeFindings(e, t) {
const n = [];
const r = e.tools?.exec?.host;
const i = e.tools?.exec?.strictInlineEval === true;
const a = resolveSandboxConfigForAgent(e).mode;
const o = r === "sandbox";
const s = loadExecApprovals();
if (o && a === "off") n.push({
checkId: "tools.exec.host_sandbox_no_sandbox_defaults",
severity: "warn",
title: "Exec host is sandbox but sandbox mode is off",
detail: "tools.exec.host is explicitly set to sandbox while agents.defaults.sandbox.mode=off. In this mode, exec fails closed because no sandbox runtime is available.",
remediation: "Enable sandbox mode (`agents.defaults.sandbox.mode=\"non-main\"` or `\"all\"`) or set tools.exec.host to \"gateway\" with approvals."
});
const c = listAgentEntries(e).filter((e) => typeof e.id === "string");
const l = c.filter((t) => t.tools?.exec?.host === "sandbox" && resolveSandboxConfigForAgent(e, t.id).mode === "off").map((e) => e.id).slice(0, 5);
if (l.length > 0) n.push({
checkId: "tools.exec.host_sandbox_no_sandbox_agents",
severity: "warn",
title: "Agent exec host uses sandbox while sandbox mode is off",
detail: `agents.entries.*.tools.exec.host is set to sandbox for: ${l.join(", ")}. With sandbox mode off, exec fails closed for those agents.`,
remediation: "Enable sandbox mode for these agents (`agents.entries.*.sandbox.mode`) or set their tools.exec.host to \"gateway\"."
});
const u = e.tools?.exec;
const d = listAgentIds(e).map((t) => {
const n = resolveAgentConfig(e, t)?.tools?.exec;
const r = resolveExecDefaults({
cfg: e,
agentId: t,
sandboxAvailable: resolveSandboxConfigForAgent(e, t).mode === "all",
execApprovals: s
});
const i = (n?.security ?? u?.security) === "full" || (n?.mode ?? u?.mode) === "full" || (n?.ask ?? u?.ask) === "off";
return {
id: t,
security: r.security,
host: r.host,
configured: i
};
});
const f = d.filter((e) => e.security === "full");
const p = d.filter((e) => e.security !== "deny");
const m = f.filter((e) => e.configured);
if (m.length > 0) n.push({
checkId: "tools.exec.security_full_configured",
severity: t.length > 0 ? "critical" : "warn",
title: "Exec security=full is configured",
detail: `Full exec trust is enabled for: ${m.map((e) => e.id).join(", ")}.` + (t.length > 0 ? ` Open channel access was also detected at:\n${t.map((e) => `- ${e}`).join("\n")}` : ""),
remediation: "Prefer tools.exec.mode=\"ask\" or \"allowlist\", and reserve \"full\" for tightly scoped break-glass agents only."
});
if (t.length > 0 && p.length > 0) n.push({
checkId: "security.exposure.open_channels_with_exec",
severity: f.length > 0 ? "critical" : "warn",
title: "Open channels can reach exec-enabled agents",
detail: `Open DM/group access detected at:\n${t.map((e) => `- ${e}`).join("\n")}\nExec-enabled scopes:\n${p.map((e) => `- ${e.id}: security=${e.security}, host=${e.host}`).join("\n")}`,
remediation: "Tighten dmPolicy/groupPolicy to pairing or allowlist, or disable exec for agents reachable from shared/public channels."
});
const h = collectExecFilesystemPolicyDriftHits(e);
if (h.length > 0) n.push({
checkId: "tools.exec.fs_tools_disabled_but_exec_enabled",
severity: "warn",
title: "Filesystem tool policy does not make exec read-only",
detail: `Found scopes where write/edit/apply_patch are unavailable but exec remains available:\n${h.map((e) => `- ${e.scopeLabel}: runtime=[${e.runtimeTools.join(", ")}], disabledFs=[${e.disabledFilesystemTools.join(", ")}], exec.host=${e.execHost}, sandbox=${e.sandboxMode}, workspaceAccess=${e.sandboxWorkspaceAccess}`).join("\n")}\nThe exec tool is a shell and can still write files wherever the selected host or sandbox filesystem permits it.`,
remediation: "For read-only agents, deny exec and process too. If shell access is intentional, constrain the filesystem boundary with sandbox mode \"all\" and workspaceAccess \"ro\" or \"none\"."
});
const g = collectAutoAllowSkillsHits(s);
if (g.length > 0) n.push({
checkId: "tools.exec.auto_allow_skills_enabled",
severity: "warn",
title: "autoAllowSkills is enabled for exec approvals",
detail: `Implicit skill-bin allowlisting is enabled at:\n${g.map((e) => `- ${e}`).join("\n")}\nThis widens host exec trust beyond explicit manual allowlist entries.`,
remediation: "Disable autoAllowSkills in exec approvals and keep manual allowlists tight when you need explicit host-exec trust."
});
const _ = collectInterpreterAllowlistHits({
approvals: s,
strictInlineEvalForAgentId: (e) => {
if (!e || e === "*") return i;
return c.find((t) => t?.id === e)?.tools?.exec?.strictInlineEval ?? i;
}
});
if (_.length > 0) n.push({
checkId: "tools.exec.allowlist_interpreter_without_strict_inline_eval",
severity: "warn",
title: "Interpreter allowlist entries are missing strictInlineEval hardening",
detail: `Interpreter/runtime allowlist entries were found without strictInlineEval enabled:\n${_.map((e) => `- ${e}`).join("\n")}`,
remediation: "Set tools.exec.strictInlineEval=true (or per-agent tools.exec.strictInlineEval=true) when allowlisting interpreters like python, node, ruby, perl, php, lua, or osascript."
});
const classifyRiskySafeBinTrustedDir = (e) => {
const t = e.trim();
if (!t) return null;
if (!path.isAbsolute(t)) return "relative path (trust boundary depends on process cwd)";
const n = path.resolve(t).replace(/\\/g, "/").toLowerCase();
if (n === "/tmp" || n.startsWith("/tmp/") || n === "/var/tmp" || n.startsWith("/var/tmp/") || n === "/private/tmp" || n.startsWith("/private/tmp/")) return "temporary directory is mutable and easy to poison";
if (n === "/usr/local/bin" || n === "/opt/homebrew/bin" || n === "/opt/local/bin" || n === "/home/linuxbrew/.linuxbrew/bin") return "package-manager bin directory (often user-writable)";
if (n.startsWith("/users/") || n.startsWith("/home/") || n.includes("/.local/bin")) return "home-scoped bin directory (typically user-writable)";
if (/^[a-z]:\/users\//.test(n)) return "home-scoped bin directory (typically user-writable)";
return null;
};
const v = e.tools?.exec;
const y = [];
const collectRiskyTrustedDirHits = (e, t) => {
for (const n of normalizeConfiguredTrustedSafeBinDirs(t)) {
const t = classifyRiskySafeBinTrustedDir(n);
if (!t) continue;
y.push(`- ${e}.safeBinTrustedDirs: ${n} (${t})`);
}
};
collectRiskyTrustedDirHits("tools.exec", v?.safeBinTrustedDirs);
for (const e of c) collectRiskyTrustedDirHits(`agents.entries.${e.id}.tools.exec`, e.tools?.exec?.safeBinTrustedDirs);
const b = [];
const x = [];
const collectSafeBinHits = (e, t, n) => {
const r = normalizeConfiguredSafeBins(t);
if (r.length === 0) return;
const i = resolveMergedSafeBinProfileFixtures(n) ?? {};
const a = listInterpreterLikeSafeBins(r).filter((e) => !i[e]);
if (a.length > 0) b.push(`- ${e}.safeBins: ${a.join(", ")}`);
for (const t of listRiskyConfiguredSafeBins(r)) x.push(`- ${e}.safeBins: ${t.bin} (${t.warning})`);
};
collectSafeBinHits("tools.exec", v?.safeBins, { global: v });
for (const e of c) {
const t = e.tools?.exec;
collectSafeBinHits(`agents.entries.${e.id}.tools.exec`, t?.safeBins, {
global: v,
local: t
});
}
if (b.length > 0) n.push({
checkId: "tools.exec.safe_bins_interpreter_unprofiled",
severity: "warn",
title: "safeBins includes interpreter/runtime binaries without explicit profiles",
detail: `Detected interpreter-like safeBins entries missing explicit profiles:\n${b.join("\n")}\nThese entries can turn safeBins into a broad execution surface when used with permissive argv profiles.`,
remediation: "Remove interpreter/runtime bins from safeBins (prefer allowlist entries) or define hardened tools.exec.safeBinProfiles.<bin> rules."
});
if (x.length > 0) n.push({
checkId: "tools.exec.safe_bins_broad_behavior",
severity: "warn",
title: "safeBins includes binaries with broader semantics than low-risk stream filters",
detail: `Detected risky safeBins entries:\n${x.join("\n")}\nThese tools expose semantics that do not fit the low-risk stdin-filter fast path.`,
remediation: "Remove these binaries from safeBins and prefer explicit allowlist entries or approval-gated execution."
});
if (y.length > 0) n.push({
checkId: "tools.exec.safe_bin_trusted_dirs_risky",
severity: "warn",
title: "safeBinTrustedDirs includes risky mutable directories",
detail: `Detected risky safeBinTrustedDirs entries:\n${y.slice(0, 10).join("\n")}` + (y.length > 10 ? `\n- +${y.length - 10} more entries.` : ""),
remediation: "Prefer root-owned immutable bins, keep default trust dirs (/bin, /usr/bin), and avoid trusting temporary/home/package-manager paths unless tightly controlled."
});
return n;
}
function formatNamesPreview(e) {
const t = e.slice(0, 6);
const n = e.length > t.length ? `, +${e.length - t.length} more` : "";
return `${t.join(", ")}${n}`;
}
function listConfiguredMcpServerNames(e) {
return Object.entries(e.mcp?.servers ?? {}).filter(([, e]) => e?.enabled !== false).map(([e]) => e).toSorted();
}
async function readGlobalMcporterRegistrySummary(e) {
const t = await readBoundedMcporterRegistry(e);
if (t.status === "missing") return { status: "absent" };
if (t.status === "rejected") return t;
const n = asNullableRecord(asNullableRecord(t.value)?.mcpServers);
if (!n) return { status: "absent" };
const r = Object.entries(n).filter(([, e]) => asNullableRecord(e)?.enabled !== false).map(([e]) => e).toSorted();
return r.length > 0 ? {
status: "source",
summary: {
label: "skills/config/mcporter.json",
names: r
}
} : { status: "absent" };
}
function describeMcporterRegistryRejection(e) {
switch (e) {
case "oversized": return "larger than the 16 MiB audit cap";
case "unreadable": return "unreadable";
case "non-regular": return "not a regular file";
case "malformed": return "not valid JSON";
default: return e;
}
}
function hasOwnSkillsAllowlist(e) {
return Boolean(e && Object.hasOwn(e, "skills"));
}
function collectAgentSkillMcpBoundaryScopes(e) {
const t = listAgentEntries(e);
const n = hasOwnSkillsAllowlist(e.agents?.defaults);
return [...n ? [{
kind: "defaults",
id: "agents.defaults",
skillSource: "agents.defaults.skills"
}] : [], ...t.filter((e) => typeof e.id === "string").flatMap((e) => {
const t = hasOwnSkillsAllowlist(e);
if (!t && !n) return [];
return [{
kind: "agent",
id: e.id,
skillSource: t ? "agents.entries.*.skills" : "agents.defaults.skills (inherited)",
agentId: e.id
}];
})].flatMap((t) => {
const n = t.kind === "agent" ? t.agentId : void 0;
const r = resolveSandboxConfigForAgent(e, n).mode;
const i = resolveExecDefaults({
cfg: e,
...t.kind === "defaults" ? { scope: { kind: "defaults" } } : { agentId: n },
sandboxAvailable: r !== "off"
});
if (i.security === "deny" || i.effectiveHost === "sandbox") return [];
return [{
id: t.id,
skillSource: t.skillSource,
execHost: i.effectiveHost,
execSecurity: i.security,
execAsk: i.ask
}];
});
}
async function collectAgentSkillMcpBoundaryFindings(e) {
const t = collectAgentSkillMcpBoundaryScopes(e.cfg);
if (t.length === 0) return [];
const n = [];
const r = [];
const i = listConfiguredMcpServerNames(e.cfg);
if (i.length > 0) r.push({
label: "mcp.servers",
names: i
});
const a = await readGlobalMcporterRegistrySummary(e.stateDir);
if (a.status === "rejected") n.push({
checkId: "tools.exec.mcporter_registry_inspection_incomplete",
severity: "warn",
title: "Global mcporter registry could not be inspected",
detail: `skills/config/mcporter.json exists but could not be safely inspected (${describeMcporterRegistryRejection(a.reason)}). The MCP boundary inspection is incomplete: the audit could not verify which MCP servers a host exec process can reach.`,
remediation: "Repair or remove skills/config/mcporter.json so the audit can inspect it: keep it a regular file readable by the gateway user, valid JSON, and below the 16 MiB audit cap."
});
else if (a.status === "source") r.push(a.summary);
if (r.length === 0) return n;
n.push({
checkId: "tools.exec.agent_skill_mcp_boundary_drift",
severity: "warn",
title: "Agent skill allowlists do not constrain host exec MCP clients",
detail: `Detected agent skill allowlists on host-exec-capable scopes:\n${t.slice(0, 8).map((e) => `- ${e.id}: ${e.skillSource}, exec.host=${e.execHost}, security=${e.execSecurity}, ask=${e.execAsk}`).join("\n")}` + (t.length > 8 ? `\n- +${t.length - 8} more scopes.` : "") + `\nMCP server registries visible to the gateway configuration/state:\n${r.map((e) => `- ${e.label}: ${formatNamesPreview(e.names)}`).join("\n")}\nagents.*.skills filters OpenClaw skill visibility and snapshots; it is not a shell-time authorization boundary. A host exec process can run external MCP clients or read a global mcporter registry unless sandbox, filesystem, network, or MCP credential boundaries block it.`,
remediation: "For agents that need per-agent MCP isolation, set their exec policy to security=\"deny\" or a tight allowlist, run them in sandbox/container/OS-user isolation where the global MCP registry is not readable, split sensitive MCP servers into a separate gateway/trust boundary, or require per-agent MCP credentials at the server layer."
});
return n;
}
function collectAutoAllowSkillsHits(e) {
const t = [];
if (e.defaults?.autoAllowSkills === true) t.push("defaults.autoAllowSkills");
for (const [n, r] of Object.entries(e.agents ?? {})) if (r?.autoAllowSkills === true) t.push(`agents.${n}.autoAllowSkills`);
return t;
}
function collectInterpreterAllowlistHits(e) {
const t = [];
for (const [n, r] of Object.entries(e.approvals.agents ?? {})) {
if (!r || e.strictInlineEvalForAgentId(n)) continue;
for (const e of r.allowlist ?? []) {
if (!isInterpreterLikeAllowlistPattern(e.pattern)) continue;
t.push(`agents.${n}.allowlist: ${e.pattern}`);
}
}
return t;
}
async function createAuditExecutionContext(e) {
const t = e.config;
const n = e.sourceConfig ?? e.config;
const r = e.env ?? process.env;
const i = e.platform ?? process.platform;
const a = e.includeFilesystem !== false;
const o = e.deep === true;
const s = Math.max(250, e.deepTimeoutMs ?? 5e3);
const c = e.stateDir ?? resolveStateDir(r);
const l = e.configPath ?? resolveConfigPath(r, c);
const u = resolvePluginControlPlaneWorkspace({
config: t,
workspaceDir: e.workspaceDir,
env: r
}).workspaceDir;
const { readConfigSnapshotForAudit: d } = await import("./audit.nondeep.runtime.js");
const f = a ? e.configSnapshot !== void 0 ? e.configSnapshot : await d({
env: r,
configPath: l
}).catch(() => null) : null;
return {
cfg: t,
sourceConfig: n,
env: r,
platform: i,
includeFilesystem: a,
deep: o,
deepTimeoutMs: s,
stateDir: c,
configPath: l,
execIcacls: e.execIcacls,
execDockerRawFn: e.execDockerRawFn,
probeGatewayFn: e.probeGatewayFn,
plugins: e.plugins,
loadPluginSecurityCollectors: e.loadPluginSecurityCollectors ?? o,
workspaceDir: u,
configSnapshot: f,
deepProbeAuth: e.deepProbeAuth,
auditGatewayAuthOverride: e.auditGatewayAuthOverride
};
}
async function runSecurityAuditCore(e) {
const t = [];
const n = await createAuditExecutionContext(e);
const { cfg: r, env: i, platform: a, stateDir: o, configPath: s } = n;
copyConfigResolutionFacts(n.sourceConfig, r);
const c = await import("./audit.nondeep.runtime.js");
const l = r.channels ? (await import("./plugin-registry-B4vbz_z1.mjs")).loadPluginRegistrySnapshot({
config: r,
env: i,
stateDir: o,
workspaceDir: n.workspaceDir
}).plugins.flatMap((e) => e.packageChannel ? [e.packageChannel] : []) : [];
const u = listConfiguredOpenInboundPolicyPaths(r, l);
t.push(...collectNodeRuntimeSecurityFindings());
t.push(...await c.collectAttackSurfaceSummaryFindings(r, u));
t.push(...collectAgentRosterFindings(n.sourceConfig));
t.push(...c.collectSyncedFolderFindings({
stateDir: o,
configPath: s
}));
t.push(...collectGatewayConfigFindings(r, n.sourceConfig, i, {
collectDangerousConfigFlags: collectEnabledInsecureOrDangerousFlags,
gatewayAuthOverride: n.auditGatewayAuthOverride
}));
t.push(...await collectPluginSecurityAuditFindings(n));
t.push(...collectElevatedFindings(r));
t.push(...collectExecRuntimeFindings(r, u));
t.push(...await collectAgentSkillMcpBoundaryFindings({
cfg: r,
stateDir: o
}));
const d = shouldMaterializeHooksGatewayAuthRefs(r) ? await materializeAuditGatewayAuthRefs({
cfg: r,
env: i
}) : r;
t.push(...c.collectHooksHardeningFindings(d, i, { gatewayAuthOverride: n.auditGatewayAuthOverride }));
t.push(...c.collectGatewayHttpNoAuthFindings(r, i, { gatewayAuthOverride: n.auditGatewayAuthOverride }));
t.push(...c.collectGatewayHttpSessionKeyOverrideFindings(r));
t.push(...c.collectSandboxDockerNoopFindings(r));
t.push(...c.collectSandboxDangerousConfigFindings(r));
t.push(...c.collectNodeDenyCommandPatternFindings(r));
t.push(...c.collectNodeDangerousAllowCommandFindings(r));
t.push(...c.collectMinimalProfileOverrideFindings(r));
t.push(...c.collectSecretsInConfigFindings(n.sourceConfig));
t.push(...c.collectSmallModelRiskFindings({
cfg: r,
env: i
}));
t.push(...c.collectExposureMatrixFindings(r, u));
t.push(...c.collectLikelyMultiUserSetupFindings(r, u));
t.push(...c.collectCrossAgentSessionAccessFindings(r, u));
if (n.includeFilesystem) {
t.push(...await collectFilesystemFindings(n));
if (n.configSnapshot) t.push(...await c.collectIncludeFilePermFindings({
configSnapshot: n.configSnapshot,
env: i,
platform: a,
execIcacls: n.execIcacls
}));
t.push(...await c.collectStateDeepFilesystemFindings(n));
t.push(...await c.collectWorkspaceSkillSymlinkEscapeFindings(n));
t.push(...await c.collectSandboxBrowserHashLabelFindings({
execDockerRawFn: n.execDockerRawFn,
timeoutMs: n.deepTimeoutMs
}));
t.push(...await c.collectPluginsTrustFindings({
cfg: r,
stateDir: o
}));
t.push(...await collectDeepCodeSafetyFindings({
cfg: r,
stateDir: o,
deep: n.deep,
workspaceDir: n.workspaceDir
}));
}
let f;
if (n.plugins !== void 0) f = true;
else {
const { hasConfiguredChannelsForReadOnlyScopeAsync: e, resolveConfiguredChannelPluginIdsAsync: t } = await import("./channel-plugin-ids-Bt1RzFGs.mjs");
f = await e({
config: r,
activationSourceConfig: n.sourceConfig,
workspaceDir: n.workspaceDir,
env: i
}) || (await t({
config: r,
activationSourceConfig: n.sourceConfig,
workspaceDir: n.workspaceDir,
env: i
})).length > 0;
}
if (f) {
const e = n.plugins ?? await (await import("./read-only-BeHuWFNs.mjs")).listReadOnlyChannelPluginsForConfigAsync(r, {
activationSourceConfig: n.sourceConfig,
workspaceDir: n.workspaceDir,
env: i,
stateDir: o,
includePersistedAuthState: true,
includeSetupFallbackPlugins: true
});
const { collectChannelSecurityFindings: a } = await import("./audit-channel.collect.runtime.js");
t.push(...await a({
cfg: r,
sourceConfig: n.sourceConfig,
plugins: e
}));
}
const p = n.deep ? await (await import("./audit-gateway-probe-BkT_Cy2B.mjs")).probeSecurityAuditGateway({
cfg: r,
env: i,
timeoutMs: n.deepTimeoutMs,
probe: n.probeGatewayFn,
explicitAuth: n.deepProbeAuth
}) : void 0;
const m = p?.deep;
t.push(...collectDeepProbeFindings({
deep: m,
authWarning: p?.authWarning
}));
const h = r.security?.audit?.suppressions;
const g = applySecurityAuditSuppressions(t, h);
const _ = h?.length ?? 0;
const v = _ > 0 ? [...g.findings, buildSecurityAuditSuppressionsActiveFinding({
configuredCount: _,
suppressedCount: g.suppressedFindings.length
})] : g.findings;
const y = countBySeverity(v);
emitSecurityAuditReportEvent({
summary: y,
deep: n.deep,
includeFilesystem: n.includeFilesystem,
suppressedCount: g.suppressedFindings.length
});
return {
ts: Date.now(),
summary: y,
findings: v,
...g.suppressedFindings.length > 0 ? { suppressedFindings: g.suppressedFindings } : {},
deep: m
};
}
//#endregion
export { runSecurityAuditCore as t };