UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

262 lines (261 loc) • 11.8 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { _ as resolveSecretInputRef, o as hasConfiguredSecretInput } from "./types.secrets-BmNLLnHp.mjs"; import { t as formatCliCommand } from "./command-format-CqdwUgPk.mjs"; import { r as listAgentEntriesWithSource } from "./agent-roster-t1ooUdXp.mjs"; import "./agent-scope-config-DmXgFGKP.mjs"; import { u as resolveExecApprovalsDisplayPath } from "./exec-approvals-config-BBzEUJlE.mjs"; import { n as discoverConfigSecretTargets } from "./target-registry-query-le6rMGHo.mjs"; import "./target-registry-C0PdHjLu.mjs"; import { g as resolveGatewayBindHost, s as isLoopbackHost } from "./net-BgRayX-P.mjs"; import { r as resolveGatewayAuth } from "./auth-resolve-C6_i-P4T.mjs"; import "./auth-dV1bLOjr.mjs"; import { t as ExecApprovalsMigrationRequiredError } from "./exec-approvals-migration-gate-B5wo0WQB.mjs"; import { i as loadExecApprovalsReadOnly } from "./exec-approvals-store-BUZ9uOWF.mjs"; import { n as countObsoleteGeneratedExecApprovals } from "./exec-approvals-generated-migration-BCmbxD17.mjs"; import "./exec-approvals-rOfoWejC.mjs"; import { t as note } from "./note-CnLgHvug.mjs"; import { t as listReadOnlyChannelPluginsForConfig } from "./read-only-idsFCBWl.mjs"; import { r as resolveExecPolicyScopeSnapshot } from "./exec-approvals-effective-e7qqZqNV.mjs"; import { t as resolveGatewayAuthTokenSourceConflict } from "./auth-token-source-conflict-BouzQo5r.mjs"; import { t as collectExecFilesystemPolicyDriftHits } from "./exec-filesystem-policy-iT8_0I4a.mjs"; import { t as classifyConfigSecretTarget } from "./config-secret-target-CHIIpojG.mjs"; import { n as findSecretStoreRedactedValueFindings } from "./audit-store-D5bFInjf.mjs"; import { t as collectChannelSecurityFindingsCore } from "./audit-channel-37DBKcO8.mjs"; //#region src/commands/doctor-security.ts function collectImplicitHeartbeatDirectPolicyWarnings(e) { return [{ label: "Heartbeat defaults", heartbeat: e.agents?.defaults?.heartbeat, pathHint: "agents.defaults.heartbeat.directPolicy" }, ...listAgentEntriesWithSource(e).map(({ entry: e, source: t }) => ({ label: `Heartbeat agent "${e.id}"`, heartbeat: e.heartbeat, pathHint: t.kind === "entries" ? `agents.entries.${t.key}.heartbeat.directPolicy` : `heartbeat.directPolicy for agent "${e.id}"` }))].flatMap(({ label: e, heartbeat: t, pathHint: n }) => { if (!t || t.target === void 0 || t.target === "none" || t.directPolicy !== void 0) return []; return [{ checkId: "doctor.heartbeat_direct_policy_unset", severity: "warn", title: e, detail: `heartbeat delivery is configured while ${n} is unset.`, remediation: "Heartbeat now allows direct/DM targets by default. Set it explicitly to \"allow\" or \"block\" to pin upgrade behavior." }]; }); } function collectExecPolicyConflictWarnings(e, t) { const n = []; const r = [{ scopeLabel: "tools.exec", scopeExecConfig: e.tools?.exec, globalExecConfig: void 0, agentId: void 0 }, ...Object.entries(e.agents?.entries ?? {}).map(([t, n]) => ({ scopeLabel: `agents.entries.${t}.tools.exec`, scopeExecConfig: n.tools?.exec, globalExecConfig: e.tools?.exec, agentId: t }))]; for (const { scopeLabel: e, scopeExecConfig: i, globalExecConfig: a, agentId: o } of r) { if (![i, a].some((e) => e?.mode || e?.security || e?.ask)) continue; const r = resolveExecPolicyScopeSnapshot({ approvals: t, scopeExecConfig: i, globalExecConfig: a, configPath: e, scopeLabel: e, agentId: o }); const s = []; const c = []; const l = r.security.requestedSource === r.ask.requestedSource && r.security.requestedSource.endsWith(".mode") ? r.security.requestedSource : void 0; if (l) s.push(`${l}="${r.mode.requested}"`); for (const [e, t] of [["security", "OpenClaw default (full)"], ["ask", "OpenClaw default (off)"]]) { const n = r[e]; if (n.requestedSource === t || n.requested === n.effective) continue; if (!l) s.push(`${n.requestedSource}="${n.requested}"`); c.push(`${n.hostSource}="${n.host}"`); } if (c.length === 0) continue; n.push({ checkId: "doctor.exec_policy_conflict", severity: "warn", title: `${e} is broader than the host exec policy.`, detail: "", remediation: [ `Config: ${s.join(", ")}`, `Host: ${c.join(", ")}`, `Effective host exec stays security="${r.security.effective}" ask="${r.ask.effective}" because the stricter side wins.`, "Headless runs like isolated cron cannot answer approval prompts; align both files, or keep the Control UI or a macOS/iOS/Android app connected so gateway automation runs can raise approval cards.", `Inspect with: ${formatCliCommand("openclaw approvals get --gateway")}` ].join("\n") }); } return n; } function collectDurableExecApprovalWarnings(e) { const t = countObsoleteGeneratedExecApprovals(e); if (t === 0) return []; return [{ checkId: "doctor.exec_approvals_require_cwd_renewal", severity: "warn", title: "Exec approvals need renewal", detail: `${t} older generated ${t === 1 ? "approval is" : "approvals are"} inactive because they are not tied to a working directory.`, remediation: [ `Run ${formatCliCommand("openclaw doctor --fix")} to remove the inactive entries.`, "Then rerun affected workflows and choose \"Always allow here\" when prompted.", "Manual allowlist rules are unchanged." ].join("\n") }]; } function collectExecFilesystemPolicyWarnings(e) { return collectExecFilesystemPolicyDriftHits(e).map((e) => ({ checkId: "doctor.exec_filesystem_policy", severity: "warn", title: e.scopeLabel, detail: "filesystem write tools are disabled, but exec is still available.", remediation: [ `Runtime tools: ${e.runtimeTools.join(", ")}; disabled filesystem tools: ${e.disabledFilesystemTools.join(", ")}.`, `Effective exec host is "${e.execHost}" with sandbox.mode="${e.sandboxMode}" and workspaceAccess="${e.sandboxWorkspaceAccess}".`, "The exec shell can still write wherever that host or sandbox filesystem permits.", "For read-only agents, also deny exec/process; otherwise use sandbox mode \"all\" with workspaceAccess \"ro\" or \"none\"." ].join("\n") })); } function collectPlaintextConfigSecretWarnings(e) { const t = discoverConfigSecretTargets(e).filter((t) => classifyConfigSecretTarget(e, t).plaintext).map((e) => e.path); if (t.length === 0) return []; const n = t.slice(0, 5); const r = t.length - n.length; const i = r > 0 ? `${n.join(", ")} (+${r} more)` : n.join(", "); return [{ checkId: "config.plaintext_secrets", severity: "warn", title: "WARNING", detail: "openclaw.json contains plaintext secret-bearing config fields.", remediation: [ `Migrate them to SecretRefs with ${formatCliCommand("openclaw secrets configure")} or ${formatCliCommand("openclaw secrets apply")}, then verify with ${formatCliCommand("openclaw secrets audit --check")}.`, `Paths: ${i}`, "Agents or workspace tools that can read config files may see these API keys/tokens." ].join("\n") }]; } async function collectSecurityWarnings(e, t = process.env) { const n = []; if (e.approvals?.exec?.enabled === false) n.push({ checkId: "doctor.approval_forwarding_disabled", severity: "warn", title: "Note", detail: "approvals.exec.enabled=false disables approval forwarding only.", remediation: [`Host exec gating still comes from ${resolveExecApprovalsDisplayPath()}.`, `Check local policy with: ${formatCliCommand("openclaw approvals get --gateway")}`].join("\n") }); n.push(...collectImplicitHeartbeatDirectPolicyWarnings(e)); let r; try { r = loadExecApprovalsReadOnly(); } catch (e) { if (!(e instanceof ExecApprovalsMigrationRequiredError)) throw e; } if (r) n.push(...collectExecPolicyConflictWarnings(e, r)); n.push(...collectExecFilesystemPolicyWarnings(e)); n.push(...collectPlaintextConfigSecretWarnings(e)); const i = resolveSecretInputRef({ value: e.gateway?.auth?.token, defaults: e.secrets?.defaults }).ref; n.push(...(await findSecretStoreRedactedValueFindings({ database: { env: t } })).map((e) => ({ checkId: "doctor.secret_store_redacted_value", severity: "warn", title: "Unavailable credential", detail: e.message, remediation: i?.source === "store" && i.id === e.name ? "Run `openclaw doctor --fix` to regenerate the Gateway token, then restart and reconnect or re-pair devices." : `This credential remains unavailable until replaced. Run \`openclaw secrets store set ${e.name}\` with the real credential, then \`openclaw secrets reload\`.` }))); if (r) n.push(...collectDurableExecApprovalWarnings(r)); const a = e.gateway?.tailscale?.mode ?? "off"; const o = e.gateway?.bind ?? "loopback"; const s = e.gateway?.customBindHost?.trim(); const c = [ "auto", "lan", "loopback", "custom", "tailnet" ].includes(o) ? o : void 0; const l = c ? await resolveGatewayBindHost(c, s) : "0.0.0.0"; const u = !isLoopbackHost(l); const d = resolveGatewayAuth({ authConfig: e.gateway?.auth, env: t, tailscaleMode: a }); const f = Boolean(normalizeOptionalString(d.token)) || hasConfiguredSecretInput(e.gateway?.auth?.token, e.secrets?.defaults); const p = Boolean(normalizeOptionalString(d.password)) || hasConfiguredSecretInput(e.gateway?.auth?.password, e.secrets?.defaults); const m = d.mode === "token" && f || d.mode === "password" && p; const h = `"${o}" (${l})`; const g = [ "Safer remote access: keep bind loopback and use Tailscale Serve/Funnel or an SSH tunnel.", "Example tunnel: ssh -N -L 18789:127.0.0.1:18789 user@gateway-host", "Docs: https://docs.openclaw.ai/gateway/remote" ]; if (u) { if (!m && d.mode !== "trusted-proxy") { const e = d.mode === "password" ? [`Fix: ${formatCliCommand("openclaw configure")} to set a password`, `Or switch to token: ${formatCliCommand("openclaw config set gateway.auth.mode token")}`] : [`Fix: ${formatCliCommand("openclaw doctor --fix")} to generate a token`, `Or set token directly: ${formatCliCommand("openclaw config set gateway.auth.mode token")}`]; n.push({ checkId: "gateway.bind_no_auth", severity: "critical", title: "CRITICAL", detail: [`Gateway bound to ${h} without authentication.`, "Anyone on your network (or internet if port-forwarded) can fully control your agent."].join("\n"), remediation: [ `Fix: ${formatCliCommand("openclaw config set gateway.bind loopback")}`, ...g, ...e ].join("\n") }); } else n.push({ checkId: "gateway.bind_network_accessible", severity: "warn", title: "WARNING", detail: [`Gateway bound to ${h} (network-accessible).`, "Use strong authentication credentials and keep them private."].join("\n"), remediation: g.join("\n") }); } const _ = resolveGatewayAuthTokenSourceConflict({ cfg: e, env: t }); if (_) n.push({ checkId: _.checkId, severity: _.severity, title: "WARNING", detail: `${_.title}.\n${_.detail}`, remediation: `Fix: ${_.remediation}` }); const v = await collectChannelSecurityFindingsCore({ cfg: e, mode: "doctor", plugins: listReadOnlyChannelPluginsForConfig(e, { includePersistedAuthState: true, includeSetupFallbackPlugins: true }) }); n.push(...v); return n; } function renderSecurityFindingLines(e) { const t = e.detail.split("\n"); const n = t.shift() ?? ""; const r = [`- ${e.title}${n ? `: ${n}` : ""}`]; r.push(...t.map((e) => ` ${e}`)); if (e.remediation) r.push(...e.remediation.split("\n").map((e) => ` ${e}`)); return r; } async function noteSecurityWarnings(e) { const t = await collectSecurityWarnings(e); if (t.length > 0) { const e = t.flatMap(renderSecurityFindingLines); e.push(`- Run: ${formatCliCommand("openclaw security audit --deep")}`); note(e.join("\n"), "Security"); } return t; } //#endregion export { collectSecurityWarnings, noteSecurityWarnings };