openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
402 lines (401 loc) • 13.7 kB
JavaScript
import { o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs";
import { t as expandHomePrefix } from "./home-dir-EKmgmdPG.mjs";
import { t as escapeRegExp } from "./regexp-dj3rRPbj.mjs";
import { o as resolveExecutablePath, s as resolveExecutablePathCandidate } from "./executable-path-D8oWZRS5.mjs";
import { a as extractBindableShellWrapperInlineCommand, b as unwrapKnownDispatchWrapperInvocation, f as isShellWrapperExecutable, h as unwrapKnownShellMultiplexerInvocation, s as extractShellWrapperInlineCommand, u as hasPosixShellStartupBeforeInlineCommand, v as resolveDispatchWrapperTrustPlan, w as resolveCarrierCommandArgv } from "./shell-wrapper-resolution-BEK558J4.mjs";
import path from "node:path";
import crypto from "node:crypto";
import { safeRealpathSync } from "@openclaw/fs-safe/path";
//#region src/infra/exec-allowlist-pattern.ts
const GLOB_REGEX_CACHE_LIMIT = 512;
const globRegexCache = /* @__PURE__ */ new Map();
const DOT_PATH_SEGMENT = /(?:^|[\\/])\.{1,2}(?![^\\/])/;
const WILDCARD = /[*?]/;
const WINDOWS_PREFIX = /^\\\\[?.]\\/;
const WINDOWS_SEPARATOR = /\\/g;
const ESCAPED_SEPARATOR = /\\\\/g;
function normalizeMatchTarget(e) {
if (process.platform === "win32") {
const t = e.replace(WINDOWS_PREFIX, "");
return normalizeLowercaseStringOrEmpty(t.replace(WINDOWS_SEPARATOR, "/"));
}
const t = e.includes("\\\\") ? e.replace(ESCAPED_SEPARATOR, "/") : e;
if (process.platform === "darwin") {
if (t === "/private/var") return "/var";
if (t.startsWith("/private/var/")) return t.slice(8);
}
return t;
}
function normalizeDotPathSegments(e) {
return normalizeMatchTarget(process.platform === "win32" ? path.win32.normalize(e) : path.posix.normalize(e));
}
function compileGlobRegex(e) {
const t = `${process.platform}:${e}`;
const n = globRegexCache.get(t);
if (n) return n;
const r = e.replace(/\*\*|[*?]|[^*?]+/g, (e) => {
switch (e) {
case "**": return ".*";
case "*": return "[^/]*";
case "?": return "[^/]";
default: return escapeRegExp(e);
}
});
const i = new RegExp(`^${r}$`, process.platform === "win32" ? "i" : "");
if (globRegexCache.size >= GLOB_REGEX_CACHE_LIMIT) globRegexCache.clear();
globRegexCache.set(t, i);
return i;
}
function compileExecAllowlistPattern(e) {
const t = e.trim();
if (!t) return () => false;
let n = WILDCARD.test(t);
const r = t.startsWith("~") || process.platform === "win32" && !n;
const resolvePattern = () => {
const e = t.startsWith("~") ? expandHomePrefix(t) : t;
n = WILDCARD.test(e);
return compileGlobRegex(normalizeMatchTarget(process.platform === "win32" && !n ? safeRealpathSync(e) ?? e : e));
};
const i = r ? void 0 : resolvePattern();
return (e) => {
const t = i ?? resolvePattern();
let r = process.platform === "win32" && !n ? safeRealpathSync(e) ?? e : e;
r = normalizeMatchTarget(r);
if (n && DOT_PATH_SEGMENT.test(r)) r = normalizeDotPathSegments(r);
return t.test(r);
};
}
//#endregion
//#region src/infra/exec-wrapper-trust-plan.ts
const TRANSPARENT_SHELL_ARGV_CARRIERS = /* @__PURE__ */ new Set([
"builtin",
"command",
"exec"
]);
function commandCarrierUsesDefaultPathSearch(e) {
if (e[0]?.trim() !== "command") return false;
for (let t = 1; t < e.length; t += 1) {
const n = e[t]?.trim() ?? "";
if (n === "--" || !n.startsWith("-")) return false;
if (/^-[^-]*p/u.test(n)) return true;
}
return false;
}
function unwrapTransparentShellArgvCarrierInvocation(e, t = process.platform) {
if (t === "win32") return { kind: "not-wrapper" };
const n = e[0]?.trim();
if (!n) return { kind: "not-wrapper" };
if (!TRANSPARENT_SHELL_ARGV_CARRIERS.has(n)) return { kind: "not-wrapper" };
if (commandCarrierUsesDefaultPathSearch(e)) return {
kind: "blocked",
wrapper: n
};
const r = resolveCarrierCommandArgv(e);
return r && r.length > 0 ? {
kind: "unwrapped",
wrapper: n,
argv: r
} : {
kind: "blocked",
wrapper: n
};
}
/**
* Resolves transparent dispatch wrappers into the executable that policy should inspect.
* Shell multiplexers keep their original argv as the trust target while exposing the
* nested shell command for shell-specific approval checks.
*/
function resolveExecWrapperTrustPlan(e, t = 4, n = process.platform) {
let r = e;
let i = e;
let a = false;
let o = true;
const s = [];
const c = [];
const blocked = (e, t = r, n = i) => ({
dispatchChain: null,
argv: t,
policyArgv: n,
wrapperChain: s,
wrapperInvocations: c,
policyBlocked: true,
blockedWrapper: e,
shellWrapperExecutable: false,
shellInlineCommand: null
});
for (let e = 0; e < t; e += 1) {
const e = resolveDispatchWrapperTrustPlan(r, t - s.length, n);
c.push(...e.wrapperInvocations);
o &&= e.dispatchChainComplete;
if (e.policyBlocked) return blocked(e.blockedWrapper ?? r[0] ?? "unknown", e.argv, e.argv);
if (e.wrappers.length > 0) {
s.push(...e.wrappers);
r = e.argv;
if (!a) i = r;
if (s.length >= t) break;
continue;
}
const l = unwrapTransparentShellArgvCarrierInvocation(r, n);
const u = l.kind === "not-wrapper";
const d = u ? unwrapKnownShellMultiplexerInvocation(r) : l;
if (d.kind === "blocked") return blocked(d.wrapper);
if (d.kind === "not-wrapper") break;
o = false;
s.push(d.wrapper);
c.push({
wrapper: d.wrapper,
sourceArgv: [...r]
});
if (!a) {
i = u ? r : d.argv;
a = u;
}
r = d.argv;
if (s.length >= t) break;
}
if (s.length >= t) for (const e of [
unwrapKnownDispatchWrapperInvocation,
unwrapTransparentShellArgvCarrierInvocation,
unwrapKnownShellMultiplexerInvocation
]) {
const t = e(r, n);
if (t.kind !== "not-wrapper") return blocked(t.wrapper);
}
const l = r[0]?.trim() ?? "";
const u = l.length > 0 && isShellWrapperExecutable(l);
return {
dispatchChain: o && l && (!u || extractShellWrapperInlineCommand(r) === null && !hasPosixShellStartupBeforeInlineCommand(r)) ? [...c.map(({ sourceArgv: e }) => e), r] : null,
argv: r,
policyArgv: i,
wrapperChain: s,
wrapperInvocations: c,
policyBlocked: false,
shellWrapperExecutable: u,
shellInlineCommand: u ? extractBindableShellWrapperInlineCommand(r) : null
};
}
//#endregion
//#region src/infra/exec-command-resolution.ts
function tryResolveRealpath(e) {
return e ? safeRealpathSync(e) ?? void 0 : void 0;
}
function buildExecutableResolution(e, t) {
const n = resolveExecutablePath(e, t);
return {
kind: "executable",
rawExecutable: e,
resolvedPath: n,
resolvedRealPath: tryResolveRealpath(n),
executableName: n ? path.basename(n) : e
};
}
function resolveCommandResolutionFromArgv(e, t, n, r = process.platform, i) {
const a = resolveExecWrapperTrustPlan(e, void 0, r);
const o = a.argv;
const s = o[0]?.trim();
if (!s) return null;
const c = {
cwd: t,
env: n,
useCache: i?.useCache
};
const l = buildExecutableResolution(s, c);
const u = a.policyArgv[0]?.trim();
return {
kind: "command",
execution: l,
policy: u ? buildExecutableResolution(u, c) : l,
effectiveArgv: o,
wrapperChain: a.wrapperChain,
policyBlocked: a.policyBlocked,
blockedWrapper: a.blockedWrapper
};
}
function resolveExecutableCandidatePathFromResolution(e, t) {
if (!e) return;
if (e.resolvedPath) return e.resolvedPath;
const n = e.rawExecutable?.trim();
if (!n) return;
return resolveExecutablePathCandidate(n, {
cwd: t,
requirePathSeparator: true
});
}
function resolveExecutableTrustPath(e, t) {
const n = e?.resolvedRealPath?.trim();
if (n) return n;
const r = resolveExecutableCandidatePathFromResolution(e, t);
return tryResolveRealpath(r) ?? r;
}
function resolveExecutionTargetResolution(e) {
return e?.kind === "command" ? e.execution : e ?? null;
}
function resolvePolicyTargetResolution(e) {
return e?.kind === "command" ? e.policy : e ?? null;
}
function resolveExecutionTargetCandidatePath(e, t) {
return resolveExecutableCandidatePathFromResolution(resolveExecutionTargetResolution(e), t);
}
function resolveExecutionTargetTrustPath(e, t) {
return resolveExecutableTrustPath(resolveExecutionTargetResolution(e), t);
}
function resolvePolicyTargetCandidatePath(e, t) {
return resolveExecutableCandidatePathFromResolution(resolvePolicyTargetResolution(e), t);
}
function resolvePolicyTargetTrustPath(e, t) {
return resolveExecutableTrustPath(resolvePolicyTargetResolution(e), t);
}
function resolveApprovalAuditTrustPath(e, t) {
return resolvePolicyTargetTrustPath(e, t);
}
const LEGACY_HASHED_ARG_PATTERN_PREFIX = "sha256:argv:";
const CWD_BOUND_HASHED_ARG_PATTERN_PREFIX = "sha256:cwd-argv:v1:";
function isGeneratedHashedArgPattern(e) {
return typeof e === "string" && (e.startsWith(CWD_BOUND_HASHED_ARG_PATTERN_PREFIX) || e.startsWith(LEGACY_HASHED_ARG_PATTERN_PREFIX));
}
function isCwdBoundHashedArgPattern(e) {
return typeof e === "string" && e.startsWith(CWD_BOUND_HASHED_ARG_PATTERN_PREFIX);
}
function classifyExecAllowlistScope(e) {
const t = e.pattern.trim();
const n = e.source === "allow-always";
if (n && (t.startsWith("=command:") || t.startsWith("=node-command:"))) return "command text";
if (e.argPattern?.startsWith(LEGACY_HASHED_ARG_PATTERN_PREFIX) === true || n && !isCwdBoundHashedArgPattern(e.argPattern)) return "inactive";
if (isCwdBoundHashedArgPattern(e.argPattern)) return "argv+cwd";
return e.argPattern ? "argv" : "any args";
}
function renderGeneratedArgPatternSubject(e) {
const t = e.slice(1);
return t.length === 0 ? "\0\0" : t.join("\0") + "\0";
}
function renderGeneratedHashedArgPatternSubject(e) {
const t = e.slice(1);
return `${t.length}\x00${t.map((e) => `${Buffer.byteLength(e, "utf8")}\x00${e}\x00`).join("")}`;
}
function normalizeGrantCwd(e, t) {
return (normalizeLowercaseStringOrEmpty(t ?? process.platform).startsWith("win") ? path.win32 : path.posix).normalize(e).replaceAll("\\", "/");
}
function buildCwdBoundHashedArgPattern(e, t, n) {
const r = normalizeGrantCwd(t, n);
const i = `${Buffer.byteLength(r, "utf8")}\x00${r}\x00${renderGeneratedHashedArgPatternSubject(e)}`;
const a = crypto.createHash("sha256").update(i, "utf8").digest("hex");
return `${CWD_BOUND_HASHED_ARG_PATTERN_PREFIX}${a}`;
}
function matchArgPattern(e, t, n, r) {
if (!t) return false;
const i = e.includes("\0") ? "\0" : " ";
const a = i === "\0" ? renderGeneratedArgPatternSubject(n) : n.slice(1).join(i);
try {
if (t.test(a)) return true;
if (normalizeLowercaseStringOrEmpty(r ?? process.platform).startsWith("win")) {
const e = a.replace(/\//g, "\\");
if (e !== a && t.test(e)) return true;
}
} catch {
return false;
}
return false;
}
function hasPathSelector(e) {
return e.includes("/") || e.includes("\\") || e.includes("~");
}
const compiledAllowlistEntries = /* @__PURE__ */ new WeakMap();
function prepareAllowlistEntry(e, t) {
let n = compiledAllowlistEntries.get(e);
if (n?.pattern !== t || n.argPattern !== e.argPattern || n.platform !== process.platform) {
let r = null;
if (e.argPattern && !isGeneratedHashedArgPattern(e.argPattern)) try {
r = new RegExp(e.argPattern);
} catch {}
n = {
pattern: t,
argPattern: e.argPattern,
platform: process.platform,
matches: compileExecAllowlistPattern(t),
argRegex: r
};
compiledAllowlistEntries.set(e, n);
}
return n;
}
function matchAllowlist(e, t, n, r, i) {
if (!e.length) return null;
for (const n of e) if (n.pattern?.trim() === "*" && !n.argPattern && n.source !== "allow-always") {
if (t) return n;
break;
}
if (!t?.resolvedPath) return null;
const a = t.resolvedRealPath?.trim() || t.resolvedPath;
const o = !hasPathSelector(t.rawExecutable);
let s;
let c = null;
let l;
for (const u of e) {
const e = u.pattern?.trim();
if (!e) continue;
const d = hasPathSelector(e);
if (!d && (e === "*" || !o)) continue;
const { matches: f, argRegex: p } = prepareAllowlistEntry(u, e);
if (!(d ? f(a) : t.executableName && f(t.executableName) || f(s ??= path.basename(t.resolvedPath)))) continue;
if (!u.argPattern) {
if (u.source === "allow-always") continue;
if (!c) c = u;
continue;
}
if (!n) continue;
if (isCwdBoundHashedArgPattern(u.argPattern)) {
if (i === void 0) continue;
l ??= buildCwdBoundHashedArgPattern(n, i, r);
if (u.argPattern === l) return u;
} else if (u.source !== "allow-always" && matchArgPattern(u.argPattern, p, n, r)) return u;
}
return c;
}
/**
* Tokenizes a single argv entry into a normalized option/positional model.
* Consumers can share this model to keep argv parsing behavior consistent.
*/
function parseExecArgvToken(e) {
if (!e) return {
kind: "empty",
raw: e
};
if (e === "--") return {
kind: "terminator",
raw: e
};
if (e === "-") return {
kind: "stdin",
raw: e
};
if (!e.startsWith("-")) return {
kind: "positional",
raw: e
};
if (e.startsWith("--")) {
const t = e.indexOf("=");
if (t > 0) return {
kind: "option",
raw: e,
style: "long",
flag: e.slice(0, t),
inlineValue: e.slice(t + 1)
};
return {
kind: "option",
raw: e,
style: "long",
flag: e
};
}
const t = e.slice(1);
return {
kind: "option",
raw: e,
style: "short-cluster",
cluster: t,
flags: t.split("").map((e) => `-${e}`)
};
}
//#endregion
export { matchAllowlist as a, resolveCommandResolutionFromArgv as c, resolveExecutionTargetResolution as d, resolveExecutionTargetTrustPath as f, resolveExecWrapperTrustPlan as g, resolvePolicyTargetTrustPath as h, isGeneratedHashedArgPattern as i, resolveExecutableTrustPath as l, resolvePolicyTargetResolution as m, classifyExecAllowlistScope as n, parseExecArgvToken as o, resolvePolicyTargetCandidatePath as p, isCwdBoundHashedArgPattern as r, resolveApprovalAuditTrustPath as s, buildCwdBoundHashedArgPattern as t, resolveExecutionTargetCandidatePath as u };