openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
507 lines (506 loc) • 13.1 kB
JavaScript
import { o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs";
import { b as uniqueStrings, y as sortUniqueStrings } from "./string-normalization-DLmfYZXI.mjs";
import { n as sameFsObject, r as swapAsciiCase } from "./path-case-B6O0zibk.mjs";
import { o as parseExecArgvToken } from "./exec-command-resolution-DaBYjPqy.mjs";
import fs from "node:fs";
import path from "node:path";
//#region src/infra/exec-safe-bin-semantics.ts
const UNSAFE_SAFE_BIN_WARNINGS = {
awk: "awk-family interpreters can execute commands, access ENVIRON, and write files, so prefer explicit allowlist entries or approval-gated runs instead of safeBins.",
jq: "jq can read environment data and load jq code from modules or startup files, so prefer explicit allowlist entries or approval-gated runs instead of safeBins.",
sed: "sed scripts can execute commands and write files, so prefer explicit allowlist entries or approval-gated runs instead of safeBins."
};
const DENIED_SAFE_BIN_WARNINGS = /* @__PURE__ */ new Map([
["jq", UNSAFE_SAFE_BIN_WARNINGS.jq],
["awk", UNSAFE_SAFE_BIN_WARNINGS.awk],
["gawk", UNSAFE_SAFE_BIN_WARNINGS.awk],
["mawk", UNSAFE_SAFE_BIN_WARNINGS.awk],
["nawk", UNSAFE_SAFE_BIN_WARNINGS.awk],
["sed", UNSAFE_SAFE_BIN_WARNINGS.sed],
["gsed", UNSAFE_SAFE_BIN_WARNINGS.sed]
]);
/** Normalizes a configured safe-bin entry to its executable basename without Windows suffixes. */
function normalizeSafeBinName(e) {
const t = normalizeLowercaseStringOrEmpty(e);
if (!t) return "";
return (t.split(/[\\/]/).at(-1) ?? t).replace(/\.(?:exe|cmd|bat|com)$/i, "");
}
function getDeniedSafeBinWarning(e) {
const t = typeof e === "string" ? normalizeSafeBinName(e) : "";
return DENIED_SAFE_BIN_WARNINGS.get(t);
}
/** Applies command-specific semantic gates for executables that are risky as broad safeBins. */
function validateSafeBinSemantics(e) {
return getDeniedSafeBinWarning(e) === void 0;
}
/** Lists configured safeBins that need operator warnings because their semantics are broad. */
function listRiskyConfiguredSafeBins(e) {
const t = /* @__PURE__ */ new Map();
for (const n of e) {
const e = normalizeSafeBinName(n);
if (!e || t.has(e)) continue;
const r = getDeniedSafeBinWarning(e);
if (!r) continue;
t.set(e, r);
}
return Array.from(t.entries()).map(([e, t]) => ({
bin: e,
warning: t
})).toSorted((e, t) => e.bin.localeCompare(t.bin));
}
//#endregion
//#region src/infra/exec-safe-bin-policy.ts
const NO_FLAGS = /* @__PURE__ */ new Set();
const DEFAULT_SAFE_BINS = [
"cut",
"uniq",
"head",
"tail",
"tr",
"wc"
];
const toFlagSet = (e) => {
if (!e || e.length === 0) return NO_FLAGS;
return new Set(e);
};
function collectKnownLongFlags(e, t, n = NO_FLAGS) {
const r = /* @__PURE__ */ new Set();
for (const i of [
e,
n,
t
]) for (const e of i) if (e.startsWith("--")) r.add(e);
return Array.from(r);
}
function buildLongFlagPrefixMap(e) {
const t = /* @__PURE__ */ new Map();
for (const n of e) {
if (!n.startsWith("--") || n.length <= 2) continue;
for (let e = 3; e <= n.length; e += 1) {
const r = n.slice(0, e);
const i = t.get(r);
if (i === void 0) {
t.set(r, n);
continue;
}
if (i !== n) t.set(r, null);
}
}
return t;
}
function compileSafeBinProfile(e) {
const t = toFlagSet(e.allowedValueFlags);
const n = toFlagSet(e.allowedBooleanFlags);
const r = toFlagSet(e.deniedFlags);
const i = collectKnownLongFlags(t, r, n);
return {
minPositional: e.minPositional,
maxPositional: e.maxPositional,
allowedValueFlags: t,
allowedBooleanFlags: n,
deniedFlags: r,
knownLongFlags: i,
knownLongFlagsSet: new Set(i),
longFlagPrefixMap: buildLongFlagPrefixMap(i)
};
}
function compileSafeBinProfiles(e) {
return Object.fromEntries(Object.entries(e).map(([e, t]) => [e, compileSafeBinProfile(t)]));
}
const HEAD_TAIL_PROFILE = {
maxPositional: 0,
allowedBooleanFlags: [
"--quiet",
"--silent",
"--verbose",
"--zero-terminated",
"-q",
"-v",
"-z"
]
};
const SAFE_BIN_PROFILE_FIXTURES = {
jq: {
maxPositional: 1,
allowedValueFlags: [
"--arg",
"--argjson",
"--argstr"
],
deniedFlags: [
"--argfile",
"--rawfile",
"--slurpfile",
"--from-file",
"--library-path",
"-L",
"-f"
]
},
grep: {
maxPositional: 0,
allowedValueFlags: [
"--regexp",
"--max-count",
"--after-context",
"--before-context",
"--context",
"--devices",
"--binary-files",
"--exclude",
"--include",
"--label",
"-e",
"-m",
"-A",
"-B",
"-C",
"-D"
],
deniedFlags: [
"--file",
"--exclude-from",
"--dereference-recursive",
"--directories",
"--recursive",
"-f",
"-d",
"-r",
"-R"
]
},
cut: {
maxPositional: 0,
allowedValueFlags: [
"--bytes",
"--characters",
"--fields",
"--delimiter",
"--output-delimiter",
"-b",
"-c",
"-f",
"-d"
],
allowedBooleanFlags: [
"--complement",
"--only-delimited",
"--zero-terminated",
"-n",
"-s",
"-z"
]
},
sort: {
maxPositional: 0,
allowedValueFlags: [
"--key",
"--field-separator",
"--buffer-size",
"--parallel",
"--batch-size",
"-k",
"-t",
"-S"
],
deniedFlags: [
"--compress-program",
"--files0-from",
"--output",
"--random-source",
"--temporary-directory",
"-T",
"-o"
]
},
uniq: {
maxPositional: 0,
allowedValueFlags: [
"--skip-fields",
"--skip-chars",
"--check-chars",
"--group",
"-f",
"-s",
"-w"
],
allowedBooleanFlags: [
"--count",
"--repeated",
"--unique",
"--ignore-case",
"--zero-terminated",
"-c",
"-d",
"-u",
"-i",
"-z"
]
},
head: {
...HEAD_TAIL_PROFILE,
allowedValueFlags: [
"--lines",
"--bytes",
"-n",
"-c"
]
},
tail: {
...HEAD_TAIL_PROFILE,
allowedValueFlags: [
"--lines",
"--bytes",
"--sleep-interval",
"--max-unchanged-stats",
"--pid",
"-n",
"-c"
],
deniedFlags: [
"--follow",
"--retry",
"-F",
"-f"
]
},
tr: {
minPositional: 1,
maxPositional: 2,
allowedBooleanFlags: [
"--complement",
"--delete",
"--squeeze-repeats",
"--truncate-set1",
"-C",
"-c",
"-d",
"-s",
"-t"
]
},
wc: {
maxPositional: 0,
allowedBooleanFlags: [
"--bytes",
"--chars",
"--lines",
"--max-line-length",
"--words",
"-L",
"-c",
"-l",
"-m",
"-w"
],
deniedFlags: ["--files0-from"]
}
};
const SAFE_BIN_PROFILES = compileSafeBinProfiles(SAFE_BIN_PROFILE_FIXTURES);
function normalizeSafeBinProfileName(e) {
const t = normalizeLowercaseStringOrEmpty(e);
return t.length > 0 ? t : null;
}
function normalizeFixtureLimit(e) {
if (typeof e !== "number" || !Number.isFinite(e)) return;
const t = Math.trunc(e);
return t >= 0 ? t : void 0;
}
function normalizeFixtureFlags(e) {
if (!Array.isArray(e) || e.length === 0) return;
const t = Array.from(new Set(e.map((e) => e.trim()).filter((e) => e.length > 0))).toSorted((e, t) => e.localeCompare(t));
return t.length > 0 ? t : void 0;
}
function normalizeSafeBinProfileFixture(e) {
const t = normalizeFixtureLimit(e.minPositional);
const n = normalizeFixtureLimit(e.maxPositional);
return {
minPositional: t,
maxPositional: t !== void 0 && n !== void 0 && n < t ? t : n,
allowedValueFlags: normalizeFixtureFlags(e.allowedValueFlags),
deniedFlags: normalizeFixtureFlags(e.deniedFlags)
};
}
function normalizeSafeBinProfileFixtures(e) {
const t = {};
if (!e) return t;
for (const [n, r] of Object.entries(e)) {
const e = normalizeSafeBinProfileName(n);
if (!e) continue;
t[e] = normalizeSafeBinProfileFixture(r);
}
return t;
}
function resolveSafeBinProfiles(e) {
if (!e || Object.keys(e).length === 0) return SAFE_BIN_PROFILES;
return {
...SAFE_BIN_PROFILES,
...compileSafeBinProfiles(e)
};
}
function isPathLikeToken(e) {
const t = e.trim();
return t.startsWith("./") || t.startsWith("../") || t.startsWith("~") || t.startsWith("/") || /^[A-Za-z]:[\\/]/.test(t);
}
function isSafeLiteralToken(e) {
return !/[*?[\]]/.test(e) && !/\$(?:[A-Za-z0-9_@*?!$#-]|\{|\(|\[)/.test(e) && !isPathLikeToken(e);
}
const NO_VALIDATOR_FLAGS = /* @__PURE__ */ new Set();
function validateSafeBinArgv(e, t, n) {
const r = t.allowedValueFlags ?? NO_VALIDATOR_FLAGS;
const i = t.allowedBooleanFlags ?? NO_VALIDATOR_FLAGS;
const a = t.deniedFlags ?? NO_VALIDATOR_FLAGS;
const o = t.knownLongFlags ?? collectKnownLongFlags(r, a, i);
const s = t.knownLongFlagsSet ?? new Set(o);
const c = t.longFlagPrefixMap ?? buildLongFlagPrefixMap(o);
function consumeValue(t, n) {
if (n !== void 0) return isSafeLiteralToken(n) ? t + 1 : -1;
const r = e[t + 1];
return r && isSafeLiteralToken(r) ? t + 2 : -1;
}
let l = 0;
let u = false;
let d = 0;
while (d < e.length) {
const t = parseExecArgvToken(e[d] ?? "");
if (t.kind === "empty" || t.kind === "stdin") {
d += 1;
continue;
}
if (u || t.kind === "positional") {
if (!isSafeLiteralToken(t.raw)) return false;
l += 1;
d += 1;
continue;
}
if (t.kind === "terminator") {
u = true;
d += 1;
continue;
}
let n = d + 1;
if (t.style === "long") {
const e = t.flag.length > 2 ? s.has(t.flag) ? t.flag : c.get(t.flag) : void 0;
if (!e || a.has(e)) return false;
if (r.has(e)) n = consumeValue(d, t.inlineValue);
else if (t.inlineValue !== void 0) return false;
} else for (const [e, o] of t.flags.entries()) {
if (a.has(o)) return false;
if (r.has(o)) {
n = consumeValue(d, t.cluster.slice(e + 1) || void 0);
break;
}
if (!i.has(o)) return false;
}
if (n < 0) return false;
d = n;
}
if (l < (t.minPositional ?? 0) || typeof t.maxPositional === "number" && l > t.maxPositional) return false;
return validateSafeBinSemantics(n?.binName);
}
//#endregion
//#region src/infra/exec-safe-bin-trust.ts
const DEFAULT_SAFE_BIN_TRUSTED_DIRS = ["/bin", "/usr/bin"];
function pathCaseInsensitive(e) {
let t = e;
for (;;) {
const e = swapAsciiCase(t);
if (e !== t) try {
const n = fs.statSync(t);
try {
const t = fs.statSync(e);
return sameFsObject(n, t);
} catch {
return false;
}
} catch {}
const n = path.dirname(t);
if (n === t) return process.platform === "win32";
t = n;
}
}
function normalizeTrustComparisonPath(e) {
const t = path.resolve(e);
return pathCaseInsensitive(t) ? t.toLowerCase() : t;
}
function normalizeTrustedDir(e, t = true) {
const n = e.trim();
if (!n) return null;
return t ? normalizeTrustComparisonPath(n) : path.resolve(n);
}
function normalizeTrustedSafeBinDirs(e) {
if (!Array.isArray(e)) return [];
const t = e.map((e) => e.trim()).filter((e) => e.length > 0);
return uniqueStrings(t);
}
function resolveTrustedSafeBinDirs(e, t = true) {
const n = e.map((e) => normalizeTrustedDir(e, t)).filter((e) => Boolean(e));
return sortUniqueStrings(n);
}
function hasPathSelector(e) {
return e.includes("/") || e.includes("\\");
}
function isExecutableSafeBinFile(e) {
try {
if (!fs.statSync(e).isFile()) return false;
if (process.platform === "win32") return true;
fs.accessSync(e, fs.constants.X_OK);
return true;
} catch {
return false;
}
}
function resolveTrustedSafeBinTargetDirs(e, t) {
const n = [];
const r = Array.from(new Set(t.map((e) => e.trim()).filter((e) => e && !hasPathSelector(e)))).toSorted();
if (r.length === 0) return n;
for (const t of normalizeTrustedSafeBinDirs(e)) {
const e = path.resolve(t);
for (const t of r) {
const r = path.join(e, t);
if (!isExecutableSafeBinFile(r)) continue;
try {
const e = normalizeTrustedDir(path.dirname(fs.realpathSync(r)));
if (e) n.push(e);
} catch {}
}
}
return sortUniqueStrings(n);
}
function getTrustedSafeBinDirs(e = {}) {
const t = e.extraDirs ?? [];
const n = e.safeBins ?? [];
const r = [...normalizeTrustedSafeBinDirs(DEFAULT_SAFE_BIN_TRUSTED_DIRS), ...normalizeTrustedSafeBinDirs(t)];
const i = resolveTrustedSafeBinTargetDirs(r, n);
return /* @__PURE__ */ new Set([...resolveTrustedSafeBinDirs(r), ...i]);
}
function isTrustedSafeBinPath(e) {
const t = e.trustedDirs ?? getTrustedSafeBinDirs();
const n = normalizeTrustComparisonPath(path.dirname(path.resolve(e.resolvedPath)));
return t.has(n);
}
function listWritableExplicitTrustedSafeBinDirs(e) {
if (process.platform === "win32") return [];
const t = resolveTrustedSafeBinDirs(normalizeTrustedSafeBinDirs(e), false);
const n = [];
for (const e of t) {
let t;
try {
t = fs.statSync(e);
} catch {
continue;
}
if (!t.isDirectory()) continue;
const r = t.mode & 511;
const i = (r & 16) !== 0;
const a = (r & 2) !== 0;
if (!i && !a) continue;
n.push({
dir: e,
worldWritable: a
});
}
return n;
}
//#endregion
export { DEFAULT_SAFE_BINS as a, resolveSafeBinProfiles as c, normalizeSafeBinName as d, normalizeTrustedSafeBinDirs as i, validateSafeBinArgv as l, isTrustedSafeBinPath as n, SAFE_BIN_PROFILES as o, listWritableExplicitTrustedSafeBinDirs as r, normalizeSafeBinProfileFixtures as s, getTrustedSafeBinDirs as t, listRiskyConfiguredSafeBins as u };