openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
749 lines (748 loc) • 20.3 kB
JavaScript
import { T as normalizeExecutableToken, f as isShellWrapperExecutable, m as resolveShellWrapperTransportArgv, o as extractShellWrapperCommand, s as extractShellWrapperInlineCommand, t as POSIX_PARSEABLE_SHELL_WRAPPERS, x as SOURCE_EXECUTABLES } from "./shell-wrapper-resolution-BEK558J4.mjs";
import "./exec-wrapper-resolution-BXAtcqj7.mjs";
import { a as detectInlineEvalArgv, i as detectCommandCarrierArgv, n as detectCarriedShellBuiltinArgv, r as detectCarrierInlineEvalArgv, s as detectShellWrapperThroughCarrierArgv } from "./risks-CqlFotky.mjs";
import { createRequire } from "node:module";
//#region src/infra/command-explainer/topology.ts
function commandTopologyBuckets(e) {
const t = /* @__PURE__ */ new Map();
for (const n of e) {
const e = `${n.context}\0${n.parentCommandId ?? ""}`;
const r = t.get(e);
if (r) r.push(n);
else t.set(e, [n]);
}
for (const e of t.values()) e.sort((e, t) => e.span.startIndex - t.span.startIndex);
return Array.from(t.values());
}
function commandSourceRanges(e, t) {
const n = /* @__PURE__ */ new Map();
let r = 0;
for (const i of t) {
const t = e.indexOf(i.text, r);
if (t < 0) return null;
const a = t + i.text.length;
n.set(i.id, {
startIndex: t,
endIndex: a
});
r = a;
}
return n;
}
function topologyOperatorFromSeparator(e) {
const t = [
{
kind: "and",
text: "&&"
},
{
kind: "or",
text: "||"
},
{
kind: "stderr-pipe",
text: "|&"
},
{
kind: "pipe",
text: "|"
},
{
kind: "sequence",
text: ";"
},
{
kind: "background",
text: "&"
},
{
kind: "newline-sequence",
text: "\r\n"
},
{
kind: "newline-sequence",
text: "\n"
},
{
kind: "newline-sequence",
text: "\r"
}
];
let n = null;
for (const r of t) {
const t = e.indexOf(r.text);
if (t < 0) continue;
if (!n || t < n.offset) n = {
kind: r.kind,
offset: t
};
}
return n?.kind ?? null;
}
function resolveCommandOperators(e, t, n) {
const r = [];
for (const i of commandTopologyBuckets(t)) {
const t = i[0].context;
const a = i[0].parentCommandId || void 0;
const o = n.find((e) => e.context === t && e.parentCommandId === a);
const s = o ? commandSourceRanges(o.source, i) : null;
for (const [t, n] of i.entries()) {
const c = i[t + 1];
if (!c) break;
let l = e;
let u = n.span.endIndex;
let d = c.span.startIndex;
const f = s?.get(n.id);
const p = s?.get(c.id);
if (o && f && p) {
l = o.source;
u = f.endIndex;
d = p.startIndex;
}
if (d < u) continue;
const m = topologyOperatorFromSeparator(l.slice(u, d));
if (!m) continue;
const h = {
kind: m,
fromCommandId: n.id
};
if (a) h.parentCommandId = a;
r.push(h);
}
}
return r;
}
//#endregion
//#region src/infra/command-explainer/tree-sitter-runtime.ts
createRequire(import.meta.url);
let parserPromise = null;
const MAX_COMMAND_EXPLANATION_SOURCE_CHARS = 131072;
const MAX_COMMAND_EXPLANATION_PARSE_MS = 500;
async function loadParser() {
const e = await import("web-tree-sitter");
await e.Parser.init();
const t = await e.Language.load(new URL(new URL("tree-sitter-bash.wasm", import.meta.url).href));
return parseBashForCommandExplanation.bind(null, new e.Parser().setLanguage(t));
}
/** Callers own each returned tree and must delete it before yielding. */
function getBashParserForCommandExplanation() {
parserPromise ??= loadParser().catch((e) => {
parserPromise = null;
throw e;
});
return parserPromise;
}
function parseBashForCommandExplanation(e, t) {
if (t.length > MAX_COMMAND_EXPLANATION_SOURCE_CHARS) throw new Error("Shell command is too large to explain");
const n = performance.now() + MAX_COMMAND_EXPLANATION_PARSE_MS;
let r = false;
const i = e.parse(t, null, { progressCallback: () => {
r = performance.now() > n;
return r;
} });
if (!i) {
e.reset();
if (r) throw new Error(`tree-sitter-bash timed out after ${MAX_COMMAND_EXPLANATION_PARSE_MS}ms while parsing shell command`);
throw new Error("tree-sitter-bash returned no parse tree");
}
return i;
}
//#endregion
//#region src/infra/command-explainer/extract.ts
const MAX_WRAPPER_PAYLOAD_DEPTH = 2;
const MAX_COMMAND_EXPLANATION_NODES = 5e4;
var CommandExplanationWorkLimitError = class extends Error {};
const ROOT_SPAN_BASE = {};
function hasDirectChildType(e, t) {
return e.children.some((e) => e.type === t);
}
function translateSpan(e, t) {
if (!t.mapOffset) return e;
const n = t.mapOffset(e.startIndex);
const r = t.mapOffset(e.endIndex);
return {
startIndex: n.index,
endIndex: r.index,
startPosition: n.position,
endPosition: r.position
};
}
function spanFromNode(e, t = ROOT_SPAN_BASE) {
const { startIndex: n, endIndex: r, startPosition: i, endPosition: a } = e;
return translateSpan({
startIndex: n,
endIndex: r,
startPosition: i,
endPosition: a
}, t);
}
function advancePosition(e, t) {
let n = e.row;
let r = e.column;
for (let e = 0; e < t.length; e += 1) {
const i = t[e];
if (i === "\r" || i === "\n") {
if (i === "\r" && t[e + 1] === "\n") e += 1;
n += 1;
r = 0;
continue;
}
r += 1;
}
return {
row: n,
column: r
};
}
function decodedSourceOffsetsForNode(e, t) {
const n = e.type === "string" || e.type === "raw_string" ? 1 : e.type === "ansi_c_string" ? 2 : 0;
if (e.type !== "raw_string") {
const n = [];
const r = e.type === "string" ? "double" : e.type === "ansi_c_string" ? "ansi-c" : "unquoted";
if (decodeShellText(e.text, r, n) === t && n.length === t.length + 1) return n;
}
return Array.from({ length: t.length + 1 }, (e, t) => n + t);
}
const DYNAMIC_WORD_NODE_TYPES = /* @__PURE__ */ new Set([
"arithmetic_expansion",
"command_substitution",
"expansion",
"process_substitution",
"simple_expansion"
]);
const COMMAND_ARGUMENT_NODE_TYPES = /* @__PURE__ */ new Set([
"ansi_c_string",
"arithmetic_expansion",
"command_substitution",
"concatenation",
"expansion",
"number",
"process_substitution",
"raw_string",
"simple_expansion",
"string",
"word"
]);
function hasEscapedLineContinuation(e) {
return /\\(?:\r\n|[\r\n])/.test(e);
}
function hasUnescapedDynamicPattern(e) {
for (let t = 0; t < e.length; t += 1) {
const n = e[t];
if (n === "\\") {
t += 1;
continue;
}
if (n === "*" || n === "?") return true;
if (n === "[" && e.indexOf("]", t + 1) > t + 1) return true;
if (n === "{" && e.indexOf("}", t + 1) > t + 1) return true;
}
return false;
}
const ANSI_C_SIMPLE_ESCAPES = {
"'": "'",
"\"": "\"",
"?": "?",
"\\": "\\",
a: "\x07",
b: "\b",
e: "\x1B",
E: "\x1B",
f: "\f",
n: "\n",
r: "\r",
t: " ",
v: "\v"
};
function decodeShellText(e, t = "unquoted", n) {
const r = t === "double" ? "\"" : t === "ansi-c" ? "$'" : "";
const i = r && e.startsWith(r) && e.endsWith(r.slice(-1));
const a = i ? r.length : 0;
const o = i ? e.slice(a, -1) : e;
let s = "";
if (n) n.push(a);
const append = (e, t) => {
s += e;
if (n) for (let r = e.length; r > 0; r -= 1) n.push(t);
};
for (let e = 0; e < o.length; e += 1) {
const r = o.charAt(e);
const i = o[e + 1];
const c = a + e;
if (r !== "\\" || i === void 0 || t === "double" && ![
"\\",
"\"",
"$",
"`",
"\n",
"\r"
].includes(i)) {
append(r, c + 1);
continue;
}
if (t !== "ansi-c" && (i === "\n" || i === "\r")) {
const t = i === "\r" && o[e + 2] === "\n" ? 3 : 2;
if (n) n[s.length] = c + t;
e += t - 1;
continue;
}
let l;
let u = 16;
let d = 2;
if (t === "ansi-c") {
if (i === "x" || i === "u" || i === "U") {
const t = i === "x" ? 2 : i === "u" ? 4 : 8;
l = o.slice(e + 2).match(new RegExp(`^[0-9A-Fa-f]{1,${t}}`))?.[0];
} else if (/^[0-7]$/.test(i)) {
l = o.slice(e + 1).match(/^[0-7]{1,3}/)?.[0];
u = 8;
d = 1;
}
}
if (l) {
const t = c + d + l.length;
try {
append(String.fromCodePoint(Number.parseInt(l, u)), t);
} catch {
append(`\\${i}${l}`, t);
}
e += d + l.length - 1;
continue;
}
append(t === "ansi-c" ? ANSI_C_SIMPLE_ESCAPES[i] ?? i : i, c + 2);
e += 1;
}
return s;
}
function hasDynamicWordPart(e) {
const t = [e];
for (let e = t.pop(); e; e = t.pop()) {
if (DYNAMIC_WORD_NODE_TYPES.has(e.type)) return true;
for (const n of e.namedChildren) t.push(n);
}
return false;
}
function shellWordValue(e) {
if (DYNAMIC_WORD_NODE_TYPES.has(e.type)) return {
kind: "dynamic",
value: e.text
};
if (e.type !== "command_name" && e.type !== "concatenation" && e.namedChildren.some((e) => hasDynamicWordPart(e))) return {
kind: "dynamic",
value: e.type === "string" ? decodeShellText(e.text, "double") : e.text
};
switch (e.type) {
case "command_name":
case "concatenation": {
const t = e.namedChildren;
if (e.type === "command_name" ? t.length === 0 : hasUnescapedDynamicPattern(e.text)) return {
kind: hasUnescapedDynamicPattern(e.text) ? "dynamic" : "literal",
value: decodeShellText(e.text)
};
let n = "";
let r = false;
for (const i of t) {
const t = shellWordValue(i);
n += t.value;
if (t.kind !== "literal") {
r = true;
if (e.type === "command_name") break;
}
}
return {
kind: r ? "dynamic" : "literal",
value: n
};
}
case "word": return {
kind: hasUnescapedDynamicPattern(e.text) ? "dynamic" : "literal",
value: decodeShellText(e.text)
};
case "raw_string": return {
kind: "literal",
value: e.text.slice(1, -1)
};
case "string": return {
kind: "literal",
value: decodeShellText(e.text, "double")
};
case "ansi_c_string": return {
kind: "literal",
value: decodeShellText(e.text, "ansi-c")
};
default: return {
kind: e.namedChildren.some((e) => shellWordValue(e).kind === "dynamic") ? "dynamic" : "literal",
value: decodeShellText(e.text)
};
}
}
function appendCommandArgument(e, t, n) {
const r = shellWordValue(e);
const i = {
text: e.text,
value: r.value,
span: spanFromNode(e, n.spanBase),
node: e
};
t.arguments.push(i);
if (r.kind === "dynamic") t.dynamicArguments.push(i);
t.argv.push(r.value);
}
function argvFromCommand(e, t, n) {
let r;
if (e.type === "command") {
if (!t || hasEscapedLineContinuation(t.text) || /^[^\s]*\\(?:\r\n|[\r\n])/.test(e.text)) return null;
const n = shellWordValue(t);
if (n.kind !== "literal") return null;
r = n.value;
} else if (e.type === "declaration_command") r = e.text.trimStart().match(/^\S+/)?.[0] ?? "";
else {
const t = e.text.trimStart();
r = t.startsWith("[[") ? "[[" : t.startsWith("[") ? "[" : "";
}
if (e.type !== "command" && !r) return null;
const i = {
argv: [r],
arguments: [],
dynamicArguments: []
};
const a = e.type === "command" ? e.childrenForFieldName("argument") : e.namedChildren;
for (const t of a) if (e.type === "test_command") appendTestCommandArguments(t, i, n);
else if (COMMAND_ARGUMENT_NODE_TYPES.has(t.type) || e.type === "declaration_command" && t.type === "variable_assignment") appendCommandArgument(t, i, n);
return i;
}
function appendTestCommandArguments(e, t, n) {
const r = [e];
for (let e = r.pop(); e; e = r.pop()) {
if (e.type === "test_operator" || COMMAND_ARGUMENT_NODE_TYPES.has(e.type)) {
appendCommandArgument(e, t, n);
continue;
}
for (let t = e.namedChildren.length - 1; t >= 0; t -= 1) {
const n = e.namedChildren[t];
if (n) r.push(n);
}
}
}
function isCommandLikeNode(e) {
return e.type === "command" || e.type === "declaration_command" || e.type === "test_command";
}
function isDynamicStandaloneAssignment(e) {
if (e.type !== "variable_assignment") return false;
const t = e.parent?.type;
if (t === "command" || t === "declaration_command") return false;
const n = e.childForFieldName("value");
return e.childForFieldName("name")?.type === "subscript" || n?.type === "array" && n.namedChildren.some((e) => /^\s*\[[\s\S]*\]\+?=/u.test(e.text)) || e.descendantsOfType(["arithmetic_expansion", "expansion"]).length > 0;
}
function recordShape(e, t) {
if ((e.type === "program" || e.type === "list") && (hasDirectChildType(e, ";") || e.namedChildren.filter(isCommandLikeNode).length > 1)) t.shapes.add("sequence");
if (hasDirectChildType(e, "&")) t.shapes.add("background");
if (e.type === "list") {
if (hasDirectChildType(e, "&&")) t.shapes.add("and");
if (hasDirectChildType(e, "||")) t.shapes.add("or");
}
const n = STATEMENT_SHAPES.get(e.type);
if (n) t.shapes.add(n);
}
const STATEMENT_SHAPES = /* @__PURE__ */ new Map([
["pipeline", "pipeline"],
["if_statement", "if"],
["for_statement", "for"],
["while_statement", "while"],
["case_statement", "case"],
["subshell", "subshell"],
["compound_statement", "group"]
]);
function shellCommandFlag(e, t) {
const n = normalizeExecutableToken(e[t - 1] ?? e[0] ?? "");
const r = n !== "cmd" && n !== "powershell" && n !== "pwsh";
const i = n === "cmd" ? ["/c", "/k"] : r ? ["-c", "--command"] : [
"-c",
"-command",
"--command",
"-encodedcommand",
"-enc",
"-e",
"-f",
"-file"
];
for (let n = t; n < e.length; n += 1) {
const t = e[n]?.trim();
if (!t) continue;
if (t === "--") break;
const a = t.toLowerCase();
if (i.includes(a) || r && t.startsWith("-") && !t.startsWith("--") && a.slice(1).includes("c")) return {
flag: t,
index: n
};
}
return null;
}
function canParseShellWrapperPayload(e, t) {
const n = normalizeExecutableToken(e[0] ?? "");
if (!POSIX_PARSEABLE_SHELL_WRAPPERS.has(n)) return false;
const r = t?.toLowerCase() ?? "";
return r === "-c" || r === "--command" || /^-[^-]*c[^-]*$/i.test(r);
}
function payloadBaseFromArgument(e, t) {
const n = e.value.indexOf(t);
if (n < 0) return null;
const r = decodedSourceOffsetsForNode(e.node, e.value);
const i = r[n];
if (i === void 0) return null;
return { mapOffset(t) {
const a = r[n + t] ?? i + t;
return {
index: e.span.startIndex + a,
position: advancePosition(e.span.startPosition, e.text.slice(0, a))
};
} };
}
function payloadBaseFromArguments(e, t) {
const n = t.find((t) => t.value === e);
if (n) return payloadBaseFromArgument(n, e);
for (const n of t) {
const t = payloadBaseFromArgument(n, e);
if (t) return t;
}
return null;
}
function recordCommandRisks(e, t, n) {
const { argv: r, dynamicArguments: i } = e;
const a = r[0];
if (!a) return null;
const o = normalizeExecutableToken(a);
for (const e of i) n.risks.push({
kind: "dynamic-argument",
command: o,
text: e.text,
span: e.span
});
const s = detectInlineEvalArgv(r) ?? detectCarrierInlineEvalArgv(r);
if (s) n.risks.push({
kind: "inline-eval",
command: s.normalizedExecutable,
flag: s.flag,
span: t
});
const c = extractShellWrapperCommand(r);
const l = c.command ?? extractShellWrapperInlineCommand(r);
let u = null;
if (c.isWrapper && l) {
const o = resolveShellWrapperTransportArgv(r) ?? r;
const s = o[0] ?? a;
const c = shellCommandFlag(o, 1) ?? shellCommandFlag(r, 1);
if (!i.some((e) => e.value === l) && canParseShellWrapperPayload(o, c?.flag ?? null)) {
const t = payloadBaseFromArguments(l, e.arguments);
if (t) u = {
command: l,
spanBase: t
};
}
if (isShellWrapperExecutable(a)) n.risks.push({
kind: "shell-wrapper",
executable: s,
flag: c?.flag ?? "-c",
payload: l,
span: t
});
else n.risks.push({
kind: "shell-wrapper-through-carrier",
span: t
});
}
for (const e of detectCommandCarrierArgv(r)) n.risks.push({
kind: "command-carrier",
command: e.command,
flag: e.flag,
span: t
});
if (o === "eval") n.risks.push({
kind: "eval",
span: t
});
if (SOURCE_EXECUTABLES.has(o)) n.risks.push({
kind: "source",
command: o,
span: t
});
if (o === "alias") n.risks.push({
kind: "alias",
span: t
});
if (!c.isWrapper ? detectShellWrapperThroughCarrierArgv(r, shellCommandFlag) : null) n.risks.push({
kind: "shell-wrapper-through-carrier",
span: t
});
const d = detectCarriedShellBuiltinArgv(r);
if (d?.kind === "eval") n.risks.push({
kind: "eval",
span: t
});
else if (d?.kind === "source") n.risks.push({
kind: "source",
command: d.command,
span: t
});
return u;
}
function visitNode(e, t, n, r) {
recordShape(e, t);
const i = spanFromNode(e, r.spanBase);
let a = n;
if (e.type === "program" && hasEscapedLineContinuation(e.text)) t.risks.push({
kind: "line-continuation",
span: i
});
else if (e.type === "word" && /(?:\r\n|[\r\n])\\/.test(e.text)) t.risks.push({
kind: "line-continuation",
span: i
});
if (e.type === "function_definition") {
const n = e.childForFieldName("name");
t.risks.push({
kind: "function-definition",
name: n?.text ?? "",
span: i
});
a = "function-definition";
} else if (e.type === "command_substitution") {
t.risks.push({
kind: "command-substitution",
span: i
});
a = "command-substitution";
} else if (e.type === "process_substitution") {
t.risks.push({
kind: "process-substitution",
span: i
});
a = "process-substitution";
} else if (e.type === "heredoc_redirect") t.risks.push({
kind: "heredoc",
span: i
});
else if (e.type === "herestring_redirect") t.risks.push({
kind: "here-string",
span: i
});
else if (e.type === "file_redirect") t.risks.push({
kind: "redirect",
span: i
});
else if (e.type === "ERROR") t.risks.push({
kind: "syntax-error",
span: i
});
else if (isDynamicStandaloneAssignment(e)) t.risks.push({
kind: "dynamic-assignment",
span: i
});
if (isCommandLikeNode(e)) {
const a = e.type === "command" ? e.childForFieldName("name") : null;
const o = argvFromCommand(e, a, r);
if (e.type === "command" && a && !o) t.risks.push({
kind: "dynamic-executable",
span: spanFromNode(a, r.spanBase)
});
else if (o) {
const s = `command-${t.commands.length}`;
const c = {
id: s,
context: n,
executable: o.argv[0] ?? "",
argv: o.argv,
text: e.text,
span: i,
executableSpan: a !== null ? spanFromNode(a, r.spanBase) : o.arguments[0]?.span ?? i
};
if (a) c.argvSpans = [c.executableSpan, ...o.arguments.map((e) => e.span)];
if (r.parentCommandId) c.parentCommandId = r.parentCommandId;
if (c.executable) {
t.commands.push(c);
const e = recordCommandRisks(o, i, t);
if (e && r.wrapperPayloadDepth < MAX_WRAPPER_PAYLOAD_DEPTH) {
const n = r.parse(e.command);
const i = e.spanBase;
try {
t.operatorSources.push({
context: "wrapper-payload",
parentCommandId: s,
source: e.command
});
if (n.rootNode.hasError) {
t.hasParseError = true;
t.risks.push({
kind: "syntax-error",
span: spanFromNode(n.rootNode, i)
});
}
walk(n.rootNode, t, "wrapper-payload", {
parse: r.parse,
wrapperPayloadDepth: r.wrapperPayloadDepth + 1,
spanBase: i,
parentCommandId: s
});
} finally {
n.delete();
}
}
}
}
}
return a;
}
function walk(e, t, n, r) {
if (e.descendantCount > t.remainingNodes) throw new CommandExplanationWorkLimitError("Shell command syntax is too complex to explain safely");
t.remainingNodes -= e.descendantCount;
const i = [{
node: e,
context: n,
state: r
}];
for (let e = i.pop(); e; e = i.pop()) {
const { node: n, context: r, state: a } = e;
const o = visitNode(n, t, r, a);
for (let e = n.namedChildren.length - 1; e >= 0; e -= 1) {
const t = n.namedChildren[e];
if (t) i.push({
node: t,
context: o,
state: a
});
}
}
}
async function explainShellCommand(e) {
const t = await getBashParserForCommandExplanation();
const n = t(e);
try {
const r = {
shapes: /* @__PURE__ */ new Set(),
commands: [],
operatorSources: [],
risks: [],
hasParseError: n.rootNode.hasError,
remainingNodes: MAX_COMMAND_EXPLANATION_NODES
};
walk(n.rootNode, r, "top-level", {
parse: t,
wrapperPayloadDepth: 0,
spanBase: ROOT_SPAN_BASE
});
const i = r.commands.filter((e) => e.context === "top-level");
const a = resolveCommandOperators(e, r.commands, r.operatorSources);
return {
ok: !r.hasParseError,
shapes: [...r.shapes],
topLevelCommands: i,
nestedCommands: r.commands.filter((e) => e.context !== "top-level"),
operators: a,
risks: r.risks
};
} finally {
n.delete();
}
}
//#endregion
export { explainShellCommand as n, CommandExplanationWorkLimitError as t };