openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
193 lines (192 loc) • 7.86 kB
JavaScript
import { o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs";
import "./src-H3RMXyFL.mjs";
import { t as expectDefined } from "./expect-DDakjvvQ.mjs";
import { b as uniqueStrings, f as normalizeStringEntries } from "./string-normalization-DLmfYZXI.mjs";
import { r as resolvePathViaExistingAncestorSync } from "./boundary-path-C2gXEiXe.mjs";
import { r as isPathInside } from "./path-guards-TIjxtj6H.mjs";
import { r as splitShellArgs } from "./shell-argv-CjhAXJXb.mjs";
import { t as buildCommandPayloadArgvCandidates } from "./risks-CqlFotky.mjs";
import { n as explainShellCommand, t as CommandExplanationWorkLimitError } from "./extract-CX0M_WKo.mjs";
import { fileURLToPath } from "node:url";
import path from "node:path";
import os from "node:os";
//#region src/infra/exec-control-command-guard.ts
const SQLITE_OPTIONS_WITH_VALUES = /* @__PURE__ */ new Map([
["cmd", 1],
["escape", 1],
["heap", 1],
["init", 1],
["lookaside", 2],
["maxsize", 1],
["mmap", 1],
["newline", 1],
["nonce", 1],
["nullvalue", 1],
["pagecache", 2],
["separator", 1],
["vfs", 1]
]);
const SQLITE_OPEN_OPTIONS_WITH_VALUES = /* @__PURE__ */ new Map([
["hexkey", 1],
["key", 1],
["maxsize", 1],
["textkey", 1]
]);
function isExecApprovalShellCommand(e) {
return /^\/approve(?:@[^\s]+)?\s+([A-Za-z0-9][A-Za-z0-9._:-]*)\s+(allow-once|allow-always|always|deny)\b/i.test(e.trimStart());
}
function normalizeCommandBaseName(e) {
if (!e) return "";
return normalizeLowercaseStringOrEmpty(e.split(/[\\/]/u).at(-1)).replace(/\.(?:cmd|exe)$/u, "");
}
function stripOpenClawPackageRunner(e) {
const t = normalizeCommandBaseName(e[0]);
if (t === "openclaw") return e;
if ((t === "pnpm" || t === "npm" || t === "yarn") && normalizeCommandBaseName(e[1]) === "openclaw") return e.slice(1);
if ((t === "pnpm" || t === "npm" || t === "yarn") && (e[1] === "exec" || e[1] === "dlx" || e[1] === "run") && normalizeCommandBaseName(e[2]) === "openclaw") return e.slice(2);
if (t === "npx" || t === "bunx") {
let t = 1;
while (t < e.length) {
const n = expectDefined(e[t], "argv entry at idx");
if (n === "--") {
t += 1;
break;
}
if (!n.startsWith("-") || n === "-") break;
t += 1;
if ((n === "-p" || n === "--package") && t < e.length) t += 1;
}
if (normalizeCommandBaseName(e[t]) === "openclaw") return e.slice(t);
}
return e;
}
function parseOpenClawChannelsLoginShellCommand(e) {
const t = splitShellArgs(e);
if (!t) return false;
const n = stripOpenClawPackageRunner(t);
return normalizeCommandBaseName(n[0]) === "openclaw" && (n[1] === "channels" || n[1] === "channel") && n[2] === "login";
}
function parseSqliteOpenCommandDatabaseToken(e) {
const t = splitShellArgs(e);
if (!t || !/^\.op(?:e(?:n)?)?$/u.test(t[0] ?? "")) return null;
for (let e = 1; e < t.length; e += 1) {
const n = expectDefined(t[e], "sqlite3 .open argv entry");
if (n === "--") return t[e + 1] ?? null;
if (n === "-" || !n.startsWith("-")) return n;
const r = n.replace(/^-+/u, "").split("=", 1)[0]?.toLowerCase() ?? "";
if (!n.includes("=")) e += SQLITE_OPEN_OPTIONS_WITH_VALUES.get(r) ?? 0;
}
return null;
}
function parseSqliteDatabaseTokens(e) {
if (normalizeCommandBaseName(e[0]) !== "sqlite3") return [];
const t = [];
const n = [];
for (let r = 1; r < e.length; r += 1) {
const i = expectDefined(e[r], "sqlite3 argv entry");
if (i === "--") {
const i = e[r + 1];
if (i) t.push(i);
n.push(...e.slice(r + 2));
break;
}
if (i === "-" || !i.startsWith("-")) {
t.push(i);
n.push(...e.slice(r + 1));
break;
}
const a = i.replace(/^-+/u, "").split("=", 1)[0]?.toLowerCase() ?? "";
if (a === "cmd") {
const t = i.includes("=") ? i.slice(i.indexOf("=") + 1) : e[r + 1];
if (t) n.push(t);
}
if (!i.includes("=")) r += SQLITE_OPTIONS_WITH_VALUES.get(a) ?? 0;
}
for (const e of n) {
const n = parseSqliteOpenCommandDatabaseToken(e);
if (n) t.push(n);
}
return t;
}
const SQLITE_URI_RECOGNIZED_VARIABLE_BODY = /^(?:\/\/(?:localhost)?)?\$(?:\{?OPENCLAW_STATE_DIR\}?|\{?HOME\}?)(?=$|[\\/])/iu;
const SQLITE_URI_EMPTY_AUTHORITY = /^\/\/(?:localhost)?(?=\$)/iu;
function expandSqliteDatabaseToken(e, t) {
let n = e.trim();
if (!n || n === ":memory:") return null;
const r = n.toLowerCase().startsWith("file:") ? n.slice(5) : null;
if (r !== null) {
let e;
if (SQLITE_URI_RECOGNIZED_VARIABLE_BODY.test(r)) e = r.replace(SQLITE_URI_EMPTY_AUTHORITY, "").split(/[?#]/u, 1)[0] ?? "";
else try {
n = fileURLToPath(n);
} catch {
e = r.split(/[?#]/u, 1)[0] ?? "";
}
if (e !== void 0) {
if (!e) return null;
try {
n = decodeURIComponent(e);
} catch {
n = e;
}
}
}
const i = n.match(/^\$(?:OPENCLAW_STATE_DIR|\{OPENCLAW_STATE_DIR\})(?=$|[\\/])/u);
if (i) n = `${t}${n.slice(i[0].length)}`;
const a = n.match(/^\$(?:HOME|\{HOME\})(?=$|[\\/])/u);
if (a) n = `${os.homedir()}${n.slice(a[0].length)}`;
if (n === "~" || n.startsWith("~/") || n.startsWith("~\\")) n = path.join(os.homedir(), n.slice(2));
return n;
}
function targetsLiveStateSqliteDatabase(e, t) {
const n = t.stateDir?.trim();
if (!n) return false;
const r = resolvePathViaExistingAncestorSync(n);
return parseSqliteDatabaseTokens(e).some((e) => {
const i = expandSqliteDatabaseToken(e, n);
if (!i) return false;
const a = path.isAbsolute(i) ? i : path.resolve(t.workdir ?? process.cwd(), i);
const o = resolvePathViaExistingAncestorSync(a);
return o === r || isPathInside(r, o);
});
}
async function detectUnsafeExecControlShellCommand(e, t = {}) {
const n = e.trim();
let r = null;
try {
r = await explainShellCommand(n);
} catch (e) {
if (e instanceof CommandExplanationWorkLimitError) return "incomplete-analysis";
}
const i = (() => {
if (r?.ok) return [...r.topLevelCommands, ...r.nestedCommands].flatMap((e) => buildCommandPayloadArgvCandidates(e.argv));
return normalizeStringEntries(n.split(/\r?\n/)).flatMap((e) => {
const t = splitShellArgs(e);
return t ? buildCommandPayloadArgvCandidates(t) : [[e]];
});
})();
const a = uniqueStrings(i.map((e) => e.join(" ")));
for (const e of a) {
if (isExecApprovalShellCommand(e)) return "approve";
if (parseOpenClawChannelsLoginShellCommand(e)) return "channel-login";
}
for (const e of i) if (targetsLiveStateSqliteDatabase(e, t)) return "live-state-sqlite";
return null;
}
function rejectIncompleteCommandAnalysis(e) {
if (e === "incomplete-analysis") throw new Error("exec cannot run a shell command that exceeds the command explanation work limit. Simplify the command so its complete syntax can be inspected before execution.");
}
async function rejectUnsafeExecControlShellCommand(e) {
const t = await detectUnsafeExecControlShellCommand(e);
rejectIncompleteCommandAnalysis(t);
if (t === "approve") throw new Error(["exec cannot run /approve commands.", "Show the /approve command to the user as chat text, or route it through the approval command handler instead of shell execution."].join(" "));
if (t === "channel-login") throw new Error(["exec cannot run interactive OpenClaw channel login commands.", "Run `openclaw channels login` in a terminal on the gateway host, or use the channel-specific login agent tool when available (for WhatsApp: `whatsapp_login`)."].join(" "));
}
async function rejectUnsafeExecLiveStateSqliteShellCommand(e, t) {
const n = await detectUnsafeExecControlShellCommand(e, t);
rejectIncompleteCommandAnalysis(n);
if (n !== "live-state-sqlite") return;
throw new Error(["external sqlite3 cannot open databases under the active OpenClaw state directory.", "Use OpenClaw commands for live state, or inspect a private backup copy outside `OPENCLAW_STATE_DIR`."].join(" "));
}
//#endregion
export { rejectUnsafeExecControlShellCommand as n, rejectUnsafeExecLiveStateSqliteShellCommand as r, detectUnsafeExecControlShellCommand as t };