openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
213 lines (212 loc) • 9.18 kB
JavaScript
import { a as asOptionalRecord } from "./record-coerce-CVPuDqcc.mjs";
import { m as normalizeTrimmedStringList } from "./string-normalization-DLmfYZXI.mjs";
import { f as extensionUsesSkippedScannerPath, p as isPathInside } from "./includes-wjVi5Ymt.mjs";
import { E as statRegularFile, g as readRegularFile } from "./fs-safe-BbWvmdVn.mjs";
import { r as createLazyRuntimeModule } from "./lazy-runtime-zGjszCtt.mjs";
import { t as MANIFEST_KEY } from "./legacy-names-Cq8ruaO5.mjs";
import { n as resolveWorkshopSkillsDir } from "./skills-root-DFNOcDAR.mjs";
import { n as loadSkillRootRecords } from "./skill-root-loader-CRRdrbyf.mjs";
import { n as loadWorkspaceSkills } from "./workspace-skill-loader-BvWyDxJi.mjs";
import { t as listInstalledPluginDirs } from "./installed-plugin-dirs-Bh_CTCUN.mjs";
import path from "node:path";
//#region src/security/audit.deep.runtime.ts
/** Deep audit implementation for code-safety scans loaded only when requested. */
const loadSkillScannerModule = createLazyRuntimeModule(() => import("./scanner-BFXeOIbB.mjs"));
const MAX_PLUGIN_MANIFEST_BYTES = 1048576;
const MAX_SKILL_AUDIT_FILE_BYTES = 256e3;
async function readPluginManifestExtensions(e) {
const t = path.join(e, "package.json");
const n = await statRegularFile(t);
if (n.missing) return [];
if (n.stat.size > MAX_PLUGIN_MANIFEST_BYTES) throw new Error(`Plugin manifest at ${t} is too large (${n.stat.size} bytes, max ${MAX_PLUGIN_MANIFEST_BYTES})`);
const { buffer: r } = await readRegularFile({
filePath: t,
maxBytes: MAX_PLUGIN_MANIFEST_BYTES
});
const i = r.toString("utf-8");
if (!i.trim()) return [];
let a;
try {
a = JSON.parse(i);
} catch (e) {
throw new Error(`Failed to parse plugin manifest at ${t}: ${String(e)}`, { cause: e });
}
return normalizeTrimmedStringList(asOptionalRecord(asOptionalRecord(a)?.[MANIFEST_KEY])?.extensions);
}
function formatCodeSafetyDetails(e, t) {
return e.map((e) => {
const n = path.relative(t, e.file);
const r = (n && n !== "." && !n.startsWith("..") ? n : path.basename(e.file)).replaceAll("\\", "/");
return ` - [${e.ruleId}] ${e.message} (${r}:${e.line})`;
}).join("\n");
}
function appendCodeSafetySummaryFindings(e, t, n, r, i) {
const a = n === "skills";
const o = `${a ? "Skill" : "Plugin"} "${r}"`;
const s = `${n}.code_safety`;
if (t.truncated) e.push({
checkId: `${s}.scan_truncated`,
severity: "warn",
title: `${o} code scan is incomplete`,
detail: `Static code scan reached its file or directory-entry budget under ${i}. Some files were not checked.`,
remediation: "Review the remaining files manually; this bounded scan is not a full code audit."
});
const c = t.critical > 0 ? "critical" : t.warn > 0 ? "warn" : void 0;
if (!c) return;
const l = formatCodeSafetyDetails(t.findings.filter((e) => e.severity === c), i);
const u = c === "critical";
e.push({
checkId: s,
severity: c,
title: `${o} contains ${u ? "dangerous" : "suspicious"} code patterns`,
detail: `Found ${t[c]} ${u ? "critical issue(s)" : "warning(s)"} in ${t.scannedFiles} scanned file(s)${a ? ` under ${i}` : ""}:\n${l}`,
remediation: u ? a ? `Review the skill source code before use. If untrusted, remove "${i}".` : "Review the plugin source code carefully before use. If untrusted, remove the plugin from your OpenClaw extensions state directory." : a ? "Check that the behavior in flagged lines is intentional and safe." : "Check that the flagged code is intentional and safe."
});
}
async function getSkillCodeSafetySummary(e) {
const t = await loadSkillScannerModule();
const [n, r] = await Promise.all([t.scanDirectoryWithSummary(e.dirPath), readRegularFile({
filePath: e.skillFilePath,
maxBytes: MAX_SKILL_AUDIT_FILE_BYTES
}).then(({ buffer: e }) => e.toString("utf-8"))]);
const i = [...t.scanSkillContent(r, e.skillFilePath), ...t.scanSource(r, e.skillFilePath)];
return {
...n,
scannedFiles: n.scannedFiles + 1,
critical: n.critical + i.filter((e) => e.severity === "critical").length,
warn: n.warn + i.filter((e) => e.severity === "warn").length,
info: n.info + i.filter((e) => e.severity === "info").length,
findings: [...n.findings, ...i]
};
}
async function collectPluginsCodeSafetyFindings(e) {
const t = [];
const { extensionsDir: n, pluginDirs: r } = await listInstalledPluginDirs({
stateDir: e.stateDir,
onReadError: (e) => {
t.push({
checkId: "plugins.code_safety.scan_failed",
severity: "warn",
title: "Plugin extensions directory scan failed",
detail: `Static code scan could not list extensions directory: ${String(e)}`,
remediation: "Check file permissions and plugin layout, then rerun `openclaw security audit --deep`."
});
}
});
for (const e of r) {
const r = path.join(n, e);
let i = [];
try {
i = await readPluginManifestExtensions(r);
} catch (n) {
t.push({
checkId: "plugins.code_safety.manifest_parse_error",
severity: "warn",
title: `Plugin "${e}" has a malformed package.json`,
detail: `Could not parse plugin manifest: ${String(n)}.\nThe extension entrypoint list is unavailable. Deep scan will cover the plugin directory but may miss entries declared via \`openclaw.extensions\`.`,
remediation: "Inspect the plugin package.json for syntax errors. If the plugin is untrusted, remove it from your OpenClaw extensions state directory."
});
}
const a = [];
const o = [];
for (const n of i) {
const i = path.resolve(r, n);
if (!isPathInside(r, i)) {
o.push(n);
continue;
}
if (extensionUsesSkippedScannerPath(n)) t.push({
checkId: "plugins.code_safety.entry_path",
severity: "warn",
title: `Plugin "${e}" entry path is hidden or node_modules`,
detail: `Extension entry "${n}" points to a hidden or node_modules path. Deep code scan will cover this entry explicitly, but review this path choice carefully.`,
remediation: "Prefer extension entrypoints under normal source paths like dist/ or src/."
});
a.push(i);
}
if (o.length > 0) t.push({
checkId: "plugins.code_safety.entry_escape",
severity: "critical",
title: `Plugin "${e}" has extension entry path traversal`,
detail: `Found extension entries that escape the plugin directory:\n${o.map((e) => ` - ${e}`).join("\n")}`,
remediation: "Update the plugin manifest so all openclaw.extensions entries stay inside the plugin directory."
});
const s = await loadSkillScannerModule().then((e) => e.scanDirectoryWithSummary(r, { includeFiles: a })).catch((n) => {
t.push({
checkId: "plugins.code_safety.scan_failed",
severity: "warn",
title: `Plugin "${e}" code scan failed`,
detail: `Static code scan could not complete: ${String(n)}`,
remediation: "Check file permissions and plugin layout, then rerun `openclaw security audit --deep`."
});
return null;
});
if (!s) continue;
appendCodeSafetySummaryFindings(t, s, "plugins", e, r);
}
return t;
}
async function collectInstalledSkillsCodeSafetyFindings(e) {
const t = [];
const n = path.join(e.stateDir, "extensions");
const r = /* @__PURE__ */ new Set();
const [{ listAgentWorkspaceDirs: i, listExplicitAgentWorkspaceDirs: a }, { resolveSkillSource: o }] = await Promise.all([import("./workspace-dirs-boJTQe78.mjs"), import("./source-BvlwPKf5.mjs")]);
const s = new Set(e.workspaceDir ? [e.workspaceDir] : []);
try {
for (const t of i(e.cfg)) s.add(t);
} catch {
for (const t of a(e.cfg)) s.add(t);
}
const c = [...s].flatMap((t) => loadWorkspaceSkills(t, { config: e.cfg }));
const { listAgentIds: l } = await import("./agent-scope-7S_X4gNj.mjs");
const u = {
...process.env,
OPENCLAW_STATE_DIR: e.stateDir
};
const reportWorkshopScanFailure = (e, n) => {
t.push({
checkId: "skills.code_safety.scan_failed",
severity: "warn",
title: "Workshop skill inventory scan failed",
detail: `Static code scan could not inspect ${e}: ${String(n)}`,
remediation: "Check file permissions and skill layout, then rerun `openclaw security audit --deep`."
});
};
for (const t of l(e.cfg)) {
const n = resolveWorkshopSkillsDir(e.cfg, t, u);
c.push(...loadSkillRootRecords({
dir: n,
source: "openclaw-workshop",
config: e.cfg,
mode: "audit",
rejectHardlinks: true,
onDiagnostic: ({ path: e, message: t }) => reportWorkshopScanFailure(e, t)
}));
}
for (const e of c) {
if (o(e.skill) === "openclaw-bundled") continue;
const i = path.resolve(e.skill.baseDir);
if (isPathInside(n, i)) continue;
if (r.has(i)) continue;
r.add(i);
const a = e.skill.name;
const s = await getSkillCodeSafetySummary({
dirPath: i,
skillFilePath: e.skill.filePath
}).catch((e) => {
t.push({
checkId: "skills.code_safety.scan_failed",
severity: "warn",
title: `Skill "${a}" code scan failed`,
detail: `Static code scan could not complete for ${i}: ${String(e)}`,
remediation: "Check file permissions and skill layout, then rerun `openclaw security audit --deep`."
});
return null;
});
if (!s) continue;
appendCodeSafetySummaryFindings(t, s, "skills", a, i);
}
return t;
}
//#endregion
export { collectInstalledSkillsCodeSafetyFindings, collectPluginsCodeSafetyFindings };