openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
624 lines (623 loc) • 20.9 kB
JavaScript
import { D as parseStrictPositiveInteger } from "./number-coercion-D6u-4YD8.mjs";
import { p as isPathInside } from "./includes-wjVi5Ymt.mjs";
import { r as terminalText } from "./safe-text-C80HAQ2e.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { r as resolveOpenClawPackageRootSync } from "./openclaw-root-C-ayo09z.mjs";
import { n as getGlobalHookRunner } from "./hook-runner-global-DmYyIVDp.mjs";
import { t as collectInstalledRuntimePackageGraph } from "./installed-package-runtime-graph-edwp64R2.mjs";
import { n as runInstallPolicy } from "./install-policy-3Frq4hdS.mjs";
import path from "node:path";
import fs from "node:fs/promises";
import { walkDirectory } from "@openclaw/fs-safe/walk";
//#region src/plugins/install-policy-context.ts
function createBeforeInstallHookPayload(e) {
return {
event: {
targetType: e.targetType,
targetName: e.targetName,
sourcePath: e.sourcePath,
sourcePathKind: e.sourcePathKind,
...e.origin ? { origin: e.origin } : {},
request: e.request,
builtinScan: {
status: "ok",
scannedFiles: 0,
critical: 0,
warn: 0,
info: 0,
findings: []
},
...e.skill ? { skill: e.skill } : {},
...e.plugin ? { plugin: e.plugin } : {}
},
ctx: {
targetType: e.targetType,
requestKind: e.request.kind,
...e.origin ? { origin: e.origin } : {}
}
};
}
//#endregion
//#region src/plugins/install-security-scan.runtime.ts
const FULL_GIT_COMMIT_PATTERN = /^[0-9a-f]{40}$/i;
const INSTALL_POLICY_BLOCK_REASON_PREFIX = "blocked by install policy: ";
const INSTALL_POLICY_ACKNOWLEDGEMENT_FLAG = "--acknowledge-install-policy-warning";
const MAX_INSTALL_POLICY_NOTICE_CHARS = 4e3;
const INSTALL_POLICY_REVIEW_GUIDANCE = [
"This invocation cannot approve install policy warnings.",
"To continue:",
" • Run the matching direct `openclaw plugins ...` or `openclaw skills ...` command interactively.",
` • For reviewed direct CLI automation, add ${INSTALL_POLICY_ACKNOWLEDGEMENT_FLAG}.`,
" • If no equivalent direct command exists, change security.installPolicy to allow this reviewed request, then retry.",
" • --force does not approve install policy warnings."
];
function formatInstallPolicyFinding(e) {
const t = e.file ? ` (${e.file}${e.line ? `:${e.line}` : ""})` : "";
const n = e.evidence ? ` Evidence: ${e.evidence}` : "";
return terminalText`[${e.severity.toUpperCase()}] ${e.ruleId}: ${e.message}${t}${n}`;
}
function formatInstallPolicyNotice(e) {
const t = e.targetType === "skill" ? "Skill" : "Plugin";
const n = [
e.decision === "warn" ? "Install requires approval" : "Install blocked by policy",
"",
terminalText` ${t}: ${e.targetName}`,
terminalText` Reason: ${e.reason}`
];
if (e.findings?.length) {
n.push(" Findings:");
for (const t of e.findings) n.push(` • ${formatInstallPolicyFinding(t)}`);
}
if (e.guidance?.length) n.push("", ...e.guidance);
return n.join("\n");
}
function formatInstallPolicyFailure(e) {
if (e.result?.warning) {
if (formatInstallPolicyNotice({
decision: "warn",
findings: e.result.findings,
guidance: INSTALL_POLICY_REVIEW_GUIDANCE,
reason: e.result.warning.reason,
targetName: e.targetName,
targetType: e.targetType
}).length > MAX_INSTALL_POLICY_NOTICE_CHARS) return { blocked: {
code: "security_scan_failed",
reason: "install policy failed closed: policy review exceeds the 4,000-character display limit; reduce or coalesce the reason and findings"
} };
}
const t = e.result?.blocked;
if (!t) return;
if (t.code !== "security_scan_blocked" || !t.reason.startsWith(INSTALL_POLICY_BLOCK_REASON_PREFIX)) return { blocked: t };
const n = {
decision: "block",
reason: t.reason.slice(27),
targetName: e.targetName,
targetType: e.targetType
};
let r = formatInstallPolicyNotice({
...n,
findings: e.result?.findings
});
if (r.length > MAX_INSTALL_POLICY_NOTICE_CHARS) {
const e = `${formatInstallPolicyNotice(n)}\n Findings omitted: policy review exceeds the 4,000-character display limit.`;
r = e.length <= MAX_INSTALL_POLICY_NOTICE_CHARS ? e : "Install blocked by policy: review exceeds the 4,000-character display limit.";
}
return { blocked: {
...t,
reason: r
} };
}
const DEFAULT_PACKAGE_TRAVERSAL_LIMITS = {
maxDepth: 64,
maxDirectories: 1e4
};
function pathContainsNodeModulesSegment(e) {
return e.split(/[\\/]+/).map((e) => e.trim().toLowerCase()).includes("node_modules");
}
function isPackageRootOpenClawPeerSymlink(e) {
return e.length === 2 && e[0] === "node_modules" && e[1] === "openclaw" || e.length === 3 && e[0] === "node_modules" && e[1] === ".bin" && e[2] === "openclaw";
}
function isManagedNpmRootPackagePeerSymlink(e) {
if (e[0] !== "node_modules") return false;
const t = e[1]?.startsWith("@") ? 3 : 2;
const n = e.slice(1, t);
if (n.length === 0 || n.some((e) => !e || e === "." || e === "..")) return false;
return isPackageRootOpenClawPeerSymlink(e.slice(t));
}
function isTrustedOpenClawPeerSymlink(e) {
const t = e.relativePath.split(/[\\/]+/);
return isPackageRootOpenClawPeerSymlink(t) || e.allowManagedNpmRootPackagePeerSymlinks === true && isManagedNpmRootPackagePeerSymlink(t);
}
async function resolveTrustedHostOpenClawRootRealPath() {
const e = resolveOpenClawPackageRootSync({
argv1: process.argv[1],
cwd: process.cwd(),
moduleUrl: import.meta.url
});
if (!e) return null;
return await fs.realpath(e).catch(() => path.resolve(e));
}
function isTrustedHostOpenClawPath(e) {
return e.trustedHostOpenClawRootRealPath !== null && isPathInside(e.trustedHostOpenClawRootRealPath, e.resolvedTargetPath);
}
async function inspectNodeModulesSymlinkTarget(e) {
let t;
try {
t = await fs.realpath(e.symlinkPath);
} catch (t) {
throw new Error(`dependency boundary scan could not resolve symlink target ${e.symlinkRelativePath}: ${String(t)}`, { cause: t });
}
if (!isPathInside(e.rootRealPath, t)) {
if (isTrustedOpenClawPeerSymlink({
allowManagedNpmRootPackagePeerSymlinks: e.allowManagedNpmRootPackagePeerSymlinks,
relativePath: e.symlinkRelativePath
}) && isTrustedHostOpenClawPath({
resolvedTargetPath: t,
trustedHostOpenClawRootRealPath: e.trustedHostOpenClawRootRealPath
})) return;
throw new Error(`dependency boundary scan found node_modules symlink target outside install root at ${e.symlinkRelativePath}`);
}
}
function readPositiveIntegerEnv(e, t) {
return parseStrictPositiveInteger(process.env[e]) ?? t;
}
function resolvePackageTraversalLimits() {
return {
maxDepth: readPositiveIntegerEnv("OPENCLAW_INSTALL_SCAN_MAX_DEPTH", DEFAULT_PACKAGE_TRAVERSAL_LIMITS.maxDepth),
maxDirectories: readPositiveIntegerEnv("OPENCLAW_INSTALL_SCAN_MAX_DIRECTORIES", DEFAULT_PACKAGE_TRAVERSAL_LIMITS.maxDirectories)
};
}
function isSamePathOrInside(e, t) {
return e === t || isPathInside(e, t);
}
async function collectNonOverlappingPackageScanRoots(e) {
const t = [];
for (const n of e) {
const e = await fs.realpath(n).catch(() => path.resolve(n));
if (t.some((t) => isSamePathOrInside(t.realPath, e))) continue;
t.push({
packageDir: n,
realPath: e
});
}
return t.map((e) => e.packageDir);
}
async function validatePackageDependencyBoundaries(e) {
const t = resolvePackageTraversalLimits();
const n = e.rootDir;
const r = await fs.realpath(n).catch(() => n);
const i = await resolveTrustedHostOpenClawRootRealPath();
let a = 1;
const { failedDirs: o } = await walkDirectory(n, {
symlinks: "include",
include: (t) => t.kind === "symlink" && pathContainsNodeModulesSegment(t.relativePath) ? inspectNodeModulesSymlinkTarget({
allowManagedNpmRootPackagePeerSymlinks: e.allowManagedNpmRootPackagePeerSymlinks,
rootRealPath: r,
symlinkPath: t.path,
symlinkRelativePath: t.relativePath,
trustedHostOpenClawRootRealPath: i
}).then(() => false) : false,
descend: (e) => {
if (e.depth > t.maxDepth) throw new Error(`dependency boundary scan exceeded max depth (${t.maxDepth}) at ${e.path}`);
if (++a > t.maxDirectories) throw new Error(`dependency boundary scan exceeded max directories (${t.maxDirectories}) under ${n}`);
return true;
}
});
if (o.length > 0) {
const e = o[0];
throw new Error(`dependency boundary scan could not read ${e.path}: ${String(e.error)}`, { cause: e.error });
}
}
async function runBeforeInstallHook(e) {
const t = getGlobalHookRunner();
if (!t?.hasHooks("before_install")) return;
try {
const { event: n, ctx: r } = createBeforeInstallHookPayload({
targetName: e.targetName,
targetType: e.targetType,
origin: e.origin,
sourcePath: e.sourcePath,
sourcePathKind: e.sourcePathKind,
request: {
kind: e.requestKind,
mode: e.requestMode,
...e.requestedSpecifier ? { requestedSpecifier: e.requestedSpecifier } : {}
},
...e.skill ? { skill: e.skill } : {},
...e.plugin ? { plugin: e.plugin } : {}
});
const i = await t.runBeforeInstall(n, r);
if (i?.block) {
const t = i.blockReason || "Installation blocked by plugin hook";
e.logger.warn?.(`WARNING: ${e.installLabel} blocked by plugin hook: ${t}`);
return { blocked: {
code: "security_scan_blocked",
reason: t
} };
}
if (i?.findings) {
for (const t of i.findings) if (t.severity === "critical" || t.severity === "warn") e.logger.warn?.(`Plugin scanner: ${t.message} (${t.file}:${t.line})`);
}
} catch (t) {
const n = `Installation blocked because before_install hook failed: ${formatErrorMessage(t)}`;
e.logger.warn?.(`WARNING: ${e.installLabel} blocked by plugin hook failure: ${n}`);
return { blocked: {
code: "security_scan_failed",
reason: n
} };
}
}
function formatInstallPolicyOriginForHook(e) {
const t = typeof e.type === "string" ? e.type : "unknown";
if (t === "upload") return "skill-upload";
const n = typeof e.spec === "string" ? e.spec : void 0;
const r = typeof e.slug === "string" ? e.slug : void 0;
return n ?? r ?? t;
}
function isMutableGitOrigin(e) {
const t = typeof e?.ref === "string" ? e.ref : void 0;
return !FULL_GIT_COMMIT_PATTERN.test(t ?? "");
}
function resolvePolicySource(e) {
if (e.requestKind === "skill-install") switch (e.origin?.type) {
case "clawhub": return {
kind: "clawhub",
authority: "openclaw",
mutable: false,
network: true
};
case "git": return {
kind: "git",
authority: "third-party",
mutable: isMutableGitOrigin(e.origin),
network: true
};
case "path": return {
kind: "local-path",
authority: "user",
mutable: true,
network: false
};
case "upload": return {
kind: "upload",
authority: "user",
mutable: false,
network: false
};
case "openclaw-bundled": return {
kind: "bundled",
authority: "openclaw",
mutable: false,
network: false
};
case "openclaw-managed":
case "openclaw-extra": return {
kind: "managed",
authority: "openclaw",
mutable: false,
network: false
};
default: return {
kind: "workspace",
authority: "user",
mutable: true,
network: false
};
}
switch (e.requestKind) {
case "plugin-archive": return {
kind: "archive",
authority: "third-party",
mutable: true,
network: false
};
case "plugin-file": return {
kind: "file",
authority: "user",
mutable: true,
network: false
};
case "plugin-git": return {
kind: "git",
authority: "third-party",
mutable: true,
network: true
};
case "plugin-npm": return {
kind: "npm",
authority: "third-party",
mutable: false,
network: true
};
case "plugin-dir": return {
kind: "local-path",
authority: "user",
mutable: true,
network: false
};
}
return {
kind: "local-path",
authority: "unknown",
mutable: true,
network: false
};
}
function shouldBypassOpenClawInstallFriction(e) {
if (e.trustedSourceLinkedOfficialInstall === true) return true;
const t = e.source;
if (!t || t.mutable) return false;
if (t.authority === "official") return t.kind === "clawhub" || t.kind === "git" || t.kind === "npm";
return t.authority === "openclaw" && (t.kind === "bundled" || t.kind === "managed");
}
async function runOperatorInstallPolicy(e) {
const t = {
targetName: e.targetName,
targetType: e.targetType,
sourcePath: e.sourcePath,
sourcePathKind: e.sourcePathKind,
...e.source ? { source: e.source } : {},
origin: e.origin,
request: {
kind: e.requestKind,
mode: e.requestMode,
...e.requestedSpecifier ? { requestedSpecifier: e.requestedSpecifier } : {}
},
...e.skill ? { skill: e.skill } : {},
...e.plugin ? { plugin: e.plugin } : {}
};
const evaluatePolicy = () => runInstallPolicy({
config: e.config,
logger: e.logger,
request: t
});
const logPolicyResult = (t) => {
if (t?.warning) {
e.logger.warn?.(`${formatInstallPolicyNotice({
decision: "warn",
findings: t.findings,
reason: t.warning.reason,
targetName: e.targetName,
targetType: e.targetType
})}\n`);
return;
}
const n = (t?.findings ?? []).filter((e) => e.severity === "critical" || e.severity === "warn").map((e) => `Install policy: ${formatInstallPolicyFinding(e)}`);
if (n.reduce((e, t) => e + t.length + 1, 0) <= MAX_INSTALL_POLICY_NOTICE_CHARS) {
for (const t of n) e.logger.warn?.(t);
return;
}
const r = "Install policy: additional findings omitted because the 4,000-character log limit was reached.";
let i = 3905;
for (const t of n) {
if (t.length + 1 > i) continue;
e.logger.warn?.(t);
i -= t.length + 1;
}
e.logger.warn?.(r);
};
let n;
while (true) {
const t = await evaluatePolicy();
const r = formatInstallPolicyFailure({
result: t,
targetName: e.targetName,
targetType: e.targetType
});
if (r) return r;
if (!t?.warning) {
logPolicyResult(t);
return;
}
const i = {
targetName: e.targetName,
targetType: e.targetType,
requestMode: e.requestMode,
reason: t.warning.reason,
...t.findings?.length ? { findings: t.findings } : {}
};
if (n && n.fingerprint === t.warning.fingerprint) return;
if (n || !e.onInstallPolicyWarning) return { blocked: {
code: "security_scan_blocked",
installPolicyWarning: i,
reason: formatInstallPolicyNotice({
decision: "warn",
findings: t.findings,
guidance: n ? ["The policy warning changed after approval.", "Review the current warning and try again."] : INSTALL_POLICY_REVIEW_GUIDANCE,
reason: t.warning.reason,
targetName: e.targetName,
targetType: e.targetType
})
} };
logPolicyResult(t);
if ((await e.onInstallPolicyWarning({ ...i })).status !== "approved") return { blocked: {
code: "security_scan_blocked",
installPolicyWarning: i,
reason: "Install cancelled: the install policy warning was not approved."
} };
n = t.warning;
}
}
async function runInstallPolicyAndHook(e) {
const t = await runOperatorInstallPolicy({
...e,
origin: e.policyOrigin
});
if (e.skipHook || t?.blocked) return t;
return await runBeforeInstallHook({
...e,
origin: e.hookOrigin
});
}
function pluginInstallPolicyRequest(e, t) {
return {
config: e.config,
logger: e.logger,
onInstallPolicyWarning: e.onInstallPolicyWarning,
targetName: t,
targetType: "plugin",
requestMode: e.mode ?? "install",
requestedSpecifier: e.requestedSpecifier
};
}
async function scanPluginArtifact(e, t, n) {
const r = e.requestKind ?? "plugin-dir";
const i = e.source ?? resolvePolicySource({ requestKind: r });
const a = n.contentType === "bundle";
const o = a ? "plugin-bundle" : "plugin-package";
await validatePackageDependencyBoundaries({ rootDir: t });
return await runInstallPolicyAndHook({
...pluginInstallPolicyRequest(e, e.pluginId),
policyOrigin: {
type: o,
...!a && e.packageName ? { packageName: e.packageName } : {},
...e.version ? { version: e.version } : {}
},
hookOrigin: o,
installLabel: `${a ? "Bundle" : "Plugin"} "${e.pluginId}" installation`,
source: i,
sourcePath: t,
sourcePathKind: "directory",
requestKind: r,
plugin: n,
skipHook: shouldBypassOpenClawInstallFriction({
source: e.source,
trustedSourceLinkedOfficialInstall: a ? void 0 : e.trustedSourceLinkedOfficialInstall
})
});
}
async function scanBundleInstallSourceRuntime(e) {
return await scanPluginArtifact(e, e.sourceDir, {
contentType: "bundle",
pluginId: e.pluginId,
manifestId: e.pluginId,
...e.version ? { version: e.version } : {}
});
}
async function scanPackageInstallSourceRuntime(e) {
return await scanPluginArtifact(e, e.packageDir, {
contentType: "package",
pluginId: e.pluginId,
...e.packageName ? { packageName: e.packageName } : {},
...e.manifestId ? { manifestId: e.manifestId } : {},
...e.version ? { version: e.version } : {},
extensions: e.extensions.slice()
});
}
async function warnPluginRuntimeCompatibility(e, t) {
try {
const { scanPluginRuntimeCompatibility: n, formatPluginRuntimeCompatibilityWarning: r } = await import("./plugin-runtime-compatibility-x14jsjNm.mjs");
const i = await n(e);
for (const e of i.warnings) t.warn?.(`Plugin runtime compatibility: ${r(e)}`);
} catch (e) {
t.warn?.(terminalText`Plugin runtime compatibility inspection incomplete: ${formatErrorMessage(e)}. Run openclaw plugins lint --root <plugin-directory> for details.`);
}
}
async function scanInstalledPackageDependencyTreeRuntime(e) {
const t = e.requestKind ?? "plugin-npm";
const n = e.additionalPackageDirs;
const r = e.dependencyScanRootDir;
const i = e.allowManagedNpmRootPackagePeerSymlinks;
const a = e.packageDir;
const o = resolvePackageTraversalLimits();
const s = r ?? a;
const c = await fs.realpath(s).catch(() => path.resolve(s));
const l = await resolveTrustedHostOpenClawRootRealPath();
const u = await collectInstalledRuntimePackageGraph({
packageDir: a,
additionalPackageDirs: n,
lookupRootDir: s,
maxPackages: o.maxDirectories,
admitPackage: ({ packageDir: e, realPath: t, dependencyName: n }) => {
if (isSamePathOrInside(c, t)) return true;
if (i === true && n === "openclaw" && isTrustedHostOpenClawPath({
resolvedTargetPath: t,
trustedHostOpenClawRootRealPath: l
})) return false;
throw new Error(`installed dependency scan found package outside install root at ${e}`);
}
});
const d = u.packageDirs;
const f = await collectNonOverlappingPackageScanRoots(d);
for (const t of f) await validatePackageDependencyBoundaries({
rootDir: t,
allowManagedNpmRootPackagePeerSymlinks: e.allowManagedNpmRootPackagePeerSymlinks
});
const p = await runOperatorInstallPolicy({
...pluginInstallPolicyRequest(e, e.pluginId),
origin: { type: "plugin-dependency-tree" },
source: e.source ?? resolvePolicySource({ requestKind: t }),
sourcePath: e.dependencyScanRootDir ?? e.packageDir,
sourcePathKind: "directory",
requestKind: t,
plugin: {
contentType: "dependency-tree",
pluginId: e.pluginId
}
});
if (!p?.blocked) await warnPluginRuntimeCompatibility(u, e.logger);
return p;
}
async function preflightPluginNpmInstallPolicyRuntime(e) {
const t = e.pluginId ?? e.packageName;
return await runOperatorInstallPolicy({
...pluginInstallPolicyRequest(e, t),
origin: {
type: "plugin-npm",
packageName: e.packageName
},
source: e.source ?? resolvePolicySource({ requestKind: "plugin-npm" }),
sourcePath: e.sourcePath,
sourcePathKind: "file",
requestKind: "plugin-npm",
plugin: {
contentType: "package",
pluginId: t,
packageName: e.packageName
}
});
}
async function preflightPluginGitInstallPolicyRuntime(e) {
return await runOperatorInstallPolicy({
...pluginInstallPolicyRequest(e, e.pluginId),
origin: { type: "plugin-git" },
source: e.source ?? resolvePolicySource({ requestKind: "plugin-git" }),
sourcePath: e.sourcePath,
sourcePathKind: "directory",
requestKind: "plugin-git",
plugin: {
contentType: "package",
pluginId: e.pluginId
}
});
}
async function evaluateSkillInstallPolicyRuntime(e) {
const t = e.source ?? resolvePolicySource({
requestKind: "skill-install",
origin: e.origin
});
const n = {
installId: e.installId,
...e.installSpec ? { installSpec: e.installSpec } : {}
};
return await runInstallPolicyAndHook({
config: e.config,
logger: e.logger,
onInstallPolicyWarning: e.onInstallPolicyWarning,
policyOrigin: e.origin,
hookOrigin: formatInstallPolicyOriginForHook(e.origin),
installLabel: `Skill "${e.skillName}" installation`,
source: t,
sourcePath: e.sourceDir,
sourcePathKind: "directory",
targetName: e.skillName,
targetType: "skill",
requestKind: "skill-install",
requestMode: e.mode ?? "install",
requestedSpecifier: e.requestedSpecifier,
skill: n,
skipHook: shouldBypassOpenClawInstallFriction({ source: e.source })
});
}
//#endregion
export { evaluateSkillInstallPolicyRuntime, preflightPluginGitInstallPolicyRuntime, preflightPluginNpmInstallPolicyRuntime, scanBundleInstallSourceRuntime, scanInstalledPackageDependencyTreeRuntime, scanPackageInstallSourceRuntime };