openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1,638 lines • 51.3 kB
JavaScript
import { c as normalizeOptionalLowercaseString, l as normalizeOptionalString, o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs";
import { t as expandHomePrefix } from "./home-dir-EKmgmdPG.mjs";
import { t as parseInlineOptionToken } from "./inline-option-token-C-F7QPPY.mjs";
import { b as uniqueStrings } from "./string-normalization-DLmfYZXI.mjs";
import { d as isPowerShellInlineFileCommandFlag, l as isDirectShellPositionalCarrierCommand, m as resolvePowerShellInlineCommandMatch, n as POSIX_INLINE_COMMAND_FLAGS, o as hasPosixInteractiveStartupBeforeInlineCommand, p as resolveInlineCommandMatch, r as advancePosixInlineOptionScan, s as hasPosixLoginStartupBeforeInlineCommand } from "./shell-inline-command-BOQk0l-l.mjs";
import { a as matchAllowlist, c as resolveCommandResolutionFromArgv, d as resolveExecutionTargetResolution, f as resolveExecutionTargetTrustPath, g as resolveExecWrapperTrustPlan, h as resolvePolicyTargetTrustPath, l as resolveExecutableTrustPath, m as resolvePolicyTargetResolution, p as resolvePolicyTargetCandidatePath, t as buildCwdBoundHashedArgPattern, u as resolveExecutionTargetCandidatePath } from "./exec-command-resolution-DaBYjPqy.mjs";
import { T as normalizeExecutableToken, _ as isDispatchWrapperExecutable, a as extractBindableShellWrapperInlineCommand, f as isShellWrapperExecutable, i as POWERSHELL_WRAPPERS, n as POSIX_SHELLS_WITH_PLUS_OPTIONS, r as POSIX_SHELL_WRAPPERS, t as POSIX_PARSEABLE_SHELL_WRAPPERS, v as resolveDispatchWrapperTrustPlan, y as unwrapDispatchWrappersForResolution } from "./shell-wrapper-resolution-BEK558J4.mjs";
import { a as DEFAULT_SAFE_BINS, l as validateSafeBinArgv, n as isTrustedSafeBinPath, o as SAFE_BIN_PROFILES } from "./exec-safe-bin-trust-DOHJJ8Cr.mjs";
import "./exec-wrapper-resolution-BXAtcqj7.mjs";
import { a as detectInlineEvalArgv, l as isInterpreterLikeAllowlistPattern } from "./risks-CqlFotky.mjs";
import { n as explainShellCommand } from "./extract-CX0M_WKo.mjs";
import path from "node:path";
//#region src/infra/windows-shell-command.ts
const WINDOWS_UNSUPPORTED_TOKENS = /* @__PURE__ */ new Set([
"&",
"|",
"<",
">",
";",
"^",
"(",
")",
"%",
"!",
"`",
"\n",
"\r"
]);
const WINDOWS_ALWAYS_UNSAFE_TOKENS = /* @__PURE__ */ new Set([
"\n",
"\r",
"%",
"`"
]);
function findWindowsUnsupportedToken(e) {
let t = false;
for (let n = 0; n < e.length; n++) {
const r = e.charAt(n);
if (r === "\"") {
t = !t;
continue;
}
if (r === "$") {
const t = e[n + 1];
if (t !== void 0 && /[A-Za-z_{(?$]/.test(t)) return "$";
continue;
}
if (WINDOWS_UNSUPPORTED_TOKENS.has(r)) {
if (t && !WINDOWS_ALWAYS_UNSAFE_TOKENS.has(r)) continue;
if (r === "\n" || r === "\r") return "newline";
return r;
}
}
return null;
}
function tokenizeWindowsSegment(e) {
const t = [];
let n = "";
let r;
let i = false;
const pushToken = () => {
if (n.length > 0 || i) {
t.push(n);
n = "";
}
i = false;
};
for (let t = 0; t < e.length; t += 1) {
const a = e.charAt(t);
if ((a === "\"" || a === "'") && (!r || r === a)) {
if (r === "'" && e[t + 1] === "'") {
n += "'";
t += 1;
continue;
}
if (!r) i = true;
r = r ? void 0 : a;
continue;
}
if (!r && /\s/.test(a)) {
pushToken();
continue;
}
n += a;
}
if (r) return null;
pushToken();
return t.length > 0 ? t : null;
}
function stripWindowsShellWrapper(e) {
const t = 5;
let n = e;
for (let e = 0; e < t; e++) {
const e = n;
n = stripWindowsShellWrapperOnce(n.trim());
if (n === e) break;
}
return n;
}
const POWERSHELL_INVOKE_PREFIX = `^(?:powershell|pwsh)(?:\\.exe)?\\s+${/(?:-(?!c(?:ommand)?\b|-command\b)\w+(?:\s+(?!-)(?:"[^"]*(?:""[^"]*)*"|'[^']*(?:''[^']*)*'|\S+))?\s+)*/i.source}(?:-command|-c|--command)\\s+`;
const POWERSHELL_INVOKE_PATTERNS = [
"\"",
"'",
""
].map((e) => ({
quote: e,
pattern: new RegExp(`${POWERSHELL_INVOKE_PREFIX}${e}(.+)${e}$`, "is")
}));
function stripWindowsShellWrapperOnce(e) {
const t = e.match(/^&\s+(.+)$/s);
if (t?.[1]) return t[1];
for (const { quote: t, pattern: n } of POWERSHELL_INVOKE_PATTERNS) {
const r = e.match(n);
if (r?.[1]) return t ? r[1].replaceAll(t + t, t) : r[1];
}
return e;
}
function analyzeWindowsShellCommand(e) {
const t = stripWindowsShellWrapper(e.command.trim());
const n = findWindowsUnsupportedToken(t);
if (n) return {
ok: false,
reason: `unsupported windows shell token: ${n}`,
segments: []
};
const r = tokenizeWindowsSegment(t);
if (!r) return {
ok: false,
reason: "unable to parse windows command",
segments: []
};
return {
ok: true,
segments: [{
raw: e.command,
argv: r,
resolution: resolveCommandResolutionFromArgv(r, e.cwd, e.env, e.platform ?? void 0)
}]
};
}
function isWindowsPlatform(e) {
return normalizeLowercaseStringOrEmpty(e ?? process.platform).startsWith("win");
}
function windowsEscapeArg(e) {
if (e === "") return {
ok: true,
escaped: "\"\""
};
const t = e.replace(/"/g, "\"\"");
if (findWindowsUnsupportedToken(`"${t}"`)) return { ok: false };
if (/^[a-zA-Z0-9_./:~\\=-]+$/.test(e)) return {
ok: true,
escaped: e
};
return {
ok: true,
escaped: `"${t}"`
};
}
function rebuildWindowsShellCommandFromSource(e) {
const t = stripWindowsShellWrapper(e.command.trim());
if (!t) return {
ok: false,
reason: "empty command"
};
const n = findWindowsUnsupportedToken(t);
if (n) return {
ok: false,
reason: `unsupported windows shell token: ${n}`
};
const r = e.renderSegment(t, 0);
if (!r.ok) return {
ok: false,
reason: r.reason
};
return {
ok: true,
command: `& ${r.rendered}`,
segmentCount: 1
};
}
//#endregion
//#region src/infra/exec-argv-analysis.ts
function analyzeArgvCommand(e) {
const t = e.argv.filter((e) => e.trim().length > 0);
if (t.length === 0) return {
ok: false,
reason: "empty argv",
segments: []
};
return {
ok: true,
segments: [{
raw: t.join(" "),
argv: t,
sourceArgv: [...e.argv],
resolution: resolveCommandResolutionFromArgv(t, e.cwd, e.env)
}]
};
}
//#endregion
//#region src/infra/exec-approvals-analysis.ts
function renderWindowsQuotedArgv(e) {
const t = [];
for (const n of e) {
const e = windowsEscapeArg(n);
if (!e.ok) return {
ok: false,
reason: `unsafe windows token: ${n}`
};
t.push(e.escaped);
}
return {
ok: true,
rendered: t.join(" ")
};
}
function resolvePlannedSegmentArgv(e) {
if (e.resolution?.policyBlocked === true) return null;
const t = e.resolution?.effectiveArgv && e.resolution.effectiveArgv.length > 0 ? e.resolution.effectiveArgv : e.argv;
if (t.length === 0) return null;
const n = [...t];
const r = e.resolution?.execution;
const i = r?.resolvedRealPath?.trim() ?? r?.resolvedPath?.trim() ?? "";
if (i) n[0] = i;
return n;
}
function buildEnforcedShellCommand(e) {
if (e.platform !== "win32") return {
ok: false,
reason: "unsupported platform"
};
const t = rebuildWindowsShellCommandFromSource({
command: e.command,
renderSegment: (t, n) => {
const r = e.segments[n];
if (!r) return {
ok: false,
reason: "segment mapping failed"
};
const i = resolvePlannedSegmentArgv(r);
if (!i) return {
ok: false,
reason: "segment execution plan unavailable"
};
return renderWindowsQuotedArgv(i);
}
});
if (!t.ok) return {
ok: false,
reason: t.reason
};
if (t.segmentCount !== e.segments.length) return {
ok: false,
reason: "segment count mismatch"
};
return {
ok: true,
command: t.command
};
}
//#endregion
//#region src/infra/exec-authorization-plan.ts
const PROMPT_ONLY_RISKS = /* @__PURE__ */ new Set([
"eval",
"source",
"alias",
"shell-wrapper-through-carrier",
"command-carrier"
]);
const NON_REUSABLE_RISKS = /* @__PURE__ */ new Set(["inline-eval"]);
const UNANALYZABLE_RISKS = /* @__PURE__ */ new Set([
"command-substitution",
"dynamic-executable",
"dynamic-assignment",
"line-continuation",
"heredoc",
"here-string",
"process-substitution",
"redirect",
"syntax-error",
"function-definition"
]);
const POWERSHELL_NAMES = /* @__PURE__ */ new Set(["powershell", "pwsh"]);
const WINDOWS_CMD_NAMES = /* @__PURE__ */ new Set(["cmd", "cmd.exe"]);
const POSITIONAL_CARRIER_BLOCKED_EXECUTABLES = /* @__PURE__ */ new Set(["find", "xargs"]);
const SHELL_WRAPPER_PRELUDE_REASON = "shell-env-assignment";
const UNSUPPORTED_DIRECT_SHELL_TOPOLOGY_SHAPES = /* @__PURE__ */ new Set([
"background",
"if",
"for",
"while",
"case",
"subshell",
"group"
]);
function normalizePlanningPlatform(e) {
switch (e) {
case "aix":
case "android":
case "cygwin":
case "darwin":
case "freebsd":
case "haiku":
case "linux":
case "netbsd":
case "openbsd":
case "sunos":
case "win32": return e;
default: return;
}
}
function commandSegmentFromStep(e, t) {
return {
raw: e.text,
argv: e.argv,
resolution: resolveCommandResolutionFromArgv(e.argv, t.cwd, t.env, t.platform)
};
}
function commandSegmentFromArgv(e, t, n) {
return {
raw: e.join(" "),
argv: e,
sourceArgv: n,
resolution: resolveCommandResolutionFromArgv(e, t.cwd, t.env, t.platform)
};
}
const AUTHORIZATION_OPERATOR_BY_KIND = {
and: "&&",
or: "||",
pipe: "pipe",
"stderr-pipe": "pipe",
sequence: ";",
"newline-sequence": ";",
background: "&"
};
function riskInsideStep(e, t) {
return e.span.startIndex >= t.span.startIndex && e.span.endIndex <= t.span.endIndex;
}
function riskBeforeStepExecutable(e, t) {
return riskInsideStep(e, t) && e.span.endIndex <= t.executableSpan.startIndex;
}
function stepReasons(e, t, n = PROMPT_ONLY_RISKS) {
const r = [];
for (const i of t) if (n.has(i.kind) && riskInsideStep(i, e)) r.push(i.kind);
return uniqueStrings(r);
}
function isShellExpansionDynamicArgument(e) {
return e.kind === "dynamic-argument" && /(?:\$[A-Za-z0-9_@*?#$!-]|\$\{|`|\$\(|\$\[|[<>]\()/u.test(e.text);
}
function riskInsidePromptOnlyStep(e, t) {
return [...t.topLevelCommands, ...t.nestedCommands].some((n) => riskInsideStep(e, n) && stepReasons(n, t.risks).length > 0);
}
function findUnanalyzableRisk(e) {
return e.risks.find((e) => UNANALYZABLE_RISKS.has(e.kind)) ?? null;
}
function hasBlockingRisk(e) {
const t = findUnanalyzableRisk(e);
if (t) return t.kind;
const n = e.shapes.find((e) => UNSUPPORTED_DIRECT_SHELL_TOPOLOGY_SHAPES.has(e));
if (n) return n;
const r = e.risks.find((t) => isShellExpansionDynamicArgument(t) && !riskInsidePromptOnlyStep(t, e));
if (r) return r.kind;
return null;
}
function shellWrapperPreludeReasons(e) {
const t = e.risks.filter((t) => UNANALYZABLE_RISKS.has(t.kind) && riskBeforeStepExecutable(t, e.step)).map((e) => e.kind);
return uniqueStrings(t);
}
function isPathScopedExecutableToken(e) {
return e.includes("/") || e.includes("\\");
}
function isUnresolvedPathScopedExecutable(e) {
const t = e.resolution?.execution;
return isPathScopedExecutableToken(e.argv[0]?.trim() ?? "") && !(t?.resolvedPath?.trim() || t?.resolvedRealPath?.trim());
}
function canUseReusableWrapperPayloadCandidates(e) {
if (!(e[0]?.argv[0]?.trim() ?? "")) return false;
if (e.some((e) => isPathScopedExecutableToken(e.argv[0]?.trim() ?? ""))) return false;
return !e.some((e) => normalizeExecutableToken(e.argv[0] ?? "").endsWith("-wrapper"));
}
function isShellExecutable(e) {
const t = normalizeExecutableToken(e[0] ?? "");
return POSIX_PARSEABLE_SHELL_WRAPPERS.has(t);
}
function canUseWrapperShellInvocation(e) {
const t = e.argv;
if (isPathScopedExecutableToken(t[0]?.trim() ?? "")) return false;
return isShellExecutable(t) && !hasPosixInteractiveStartupBeforeInlineCommand(t, POSIX_INLINE_COMMAND_FLAGS) && !hasPosixLoginStartupBeforeInlineCommand(t, POSIX_INLINE_COMMAND_FLAGS);
}
function wrapperPrefixForStep(e) {
const t = Math.max(0, e.executableSpan.startIndex - e.span.startIndex);
return e.text.slice(0, t);
}
function hasCommandPrelude(e) {
return /^[A-Za-z_][A-Za-z0-9_]*\+?=/u.test(wrapperPrefixForStep(e).trimStart());
}
function positionalCarrierSteps(e) {
const t = resolveInlineCommandMatch(e.wrapper.segment.argv, POSIX_INLINE_COMMAND_FLAGS, { allowCombinedC: true });
if (t.valueTokenIndex === null || !t.command) return null;
if (!canUseWrapperShellInvocation(e.wrapper.segment)) return null;
if (!isDirectShellPositionalCarrierCommand(t.command)) return null;
const n = e.wrapper.segment.argv.slice(t.valueTokenIndex + 1).filter((e) => e.trim().length > 0);
if (n.length === 0) return null;
const r = normalizeExecutableToken(n[0] ?? "");
if (isDispatchWrapperExecutable(r) || POSITIONAL_CARRIER_BLOCKED_EXECUTABLES.has(r) || POSIX_PARSEABLE_SHELL_WRAPPERS.has(r) || r.endsWith("-wrapper")) return null;
const i = n.join(" ");
const a = {
startIndex: e.wrapper.step.span.endIndex,
endIndex: e.wrapper.step.span.endIndex,
startPosition: e.wrapper.step.span.endPosition,
endPosition: e.wrapper.step.span.endPosition
};
return [{
step: {
context: "wrapper-payload",
executable: n[0] ?? "",
argv: n,
text: i,
span: a,
executableSpan: a
},
segment: commandSegmentFromArgv(n, e.context, e.wrapper.segment.sourceArgv)
}];
}
function createCandidate(e) {
const t = e.transport.kind === "direct" && extractBindableShellWrapperInlineCommand(e.segment.argv);
const n = stepReasons(e.step, e.risks);
const r = stepReasons(e.step, e.risks, NON_REUSABLE_RISKS);
const i = hasCommandPrelude(e.step) ? shellWrapperPreludeReasons({
step: e.step,
risks: e.risks
}) : [];
if (hasCommandPrelude(e.step) && i.length === 0) i.push(SHELL_WRAPPER_PRELUDE_REASON);
const a = uniqueStrings([
...n,
...r,
...i
]);
const o = e.segment.resolution?.policyBlocked === true ? "prompt-only" : i.length > 0 ? "prompt-only" : t ? "exact-command" : n.length > 0 ? "prompt-only" : "executable";
return {
sourceSegment: e.segment,
sourceStep: e.step,
transport: e.transport,
trustMode: o,
allowAlways: r.length === 0 && o === "executable" && !(e.relationship === "pipeline" && isShellExecutable(e.segment.argv)),
reasons: a
};
}
function groupsFromSteps(e) {
const finalizeGroup = (t) => {
const n = e.transport;
const r = e.risks;
const i = t.length > 1 ? "pipeline" : "simple";
return { candidates: t.map((e) => createCandidate({
step: e.step,
segment: e.segment,
relationship: i,
transport: n,
risks: r
})) };
};
const t = e.steps.toSorted((e, t) => e.step.span.startIndex - t.step.span.startIndex);
const n = [];
let r = [];
const i = /* @__PURE__ */ new Map();
for (const t of e.operators ?? []) i.set(t.fromCommandId, AUTHORIZATION_OPERATOR_BY_KIND[t.kind]);
for (const e of t) {
const t = r[r.length - 1];
if (!t) {
r = [e];
continue;
}
const a = t.step.id;
if ((a ? i.get(a) : void 0) === "pipe" || i.size === 0) {
r.push(e);
continue;
}
n.push(finalizeGroup(r));
r = [e];
}
if (r.length > 0) n.push(finalizeGroup(r));
return n;
}
function shellWrapperRiskForStep(e, t) {
return t.find((t) => t.kind === "shell-wrapper" && riskInsideStep(t, e)) ?? null;
}
function wrapperPayloadPlan(e) {
const t = e.topLevelSteps[0];
if (!t) return null;
const n = shellWrapperRiskForStep(t.step, e.risks);
if (!n) return null;
if (hasCommandPrelude(t.step)) return null;
if (!canUseWrapperShellInvocation(t.segment)) return null;
if (!e.allowNestedPayload) return null;
const r = positionalCarrierSteps({
wrapper: t,
context: e.context
});
const i = t.step.id ? e.nestedSteps.filter((e) => e.step.parentCommandId === t.step.id) : e.nestedSteps;
if (!r && (e.topLevelSteps.length !== 1 || !canUseReusableWrapperPayloadCandidates(i.map((e) => e.segment)))) return null;
const a = {
kind: "shell-wrapper",
wrapperSegment: t.segment,
wrapperArgv: t.segment.argv,
inlineCommand: n.payload
};
const o = t.step.id ? e.operators.filter((e) => e.parentCommandId === t.step.id) : e.operators;
const s = groupsFromSteps({
steps: r ?? i,
operators: r ? void 0 : o,
transport: a,
risks: e.risks
});
return s.length > 0 ? s : null;
}
function dialectForArgv(e) {
const t = normalizeExecutableToken(e[0] ?? "");
if (POWERSHELL_NAMES.has(t)) return "powershell";
if (WINDOWS_CMD_NAMES.has(t)) return "windows-cmd";
return "argv";
}
function unanalyzablePlan(e) {
return {
ok: false,
dialect: e.dialect,
originalCommand: e.command,
reason: e.reason,
groups: [],
operators: []
};
}
function planFromExplanation(e) {
const t = e.explanation.topLevelCommands.map((t) => ({
step: t,
segment: commandSegmentFromStep(t, e.context)
}));
const n = e.explanation.nestedCommands.filter((e) => e.context === "wrapper-payload").map((t) => ({
step: t,
segment: commandSegmentFromStep(t, e.context)
}));
const r = hasBlockingRisk(e.explanation);
const i = findUnanalyzableRisk(e.explanation);
const a = t[0]?.step;
const o = t.length === 1 && Boolean(a && shellWrapperRiskForStep(a, e.explanation.risks) && (!i || riskInsideStep(i, a)));
if (!e.explanation.ok || r && !o) return unanalyzablePlan({
dialect: "posix-shell",
command: e.command,
reason: r ?? "unable to parse command"
});
const s = wrapperPayloadPlan({
context: e.context,
allowNestedPayload: !r,
topLevelSteps: t,
nestedSteps: n,
operators: e.explanation.operators ?? [],
risks: e.explanation.risks
}) ?? groupsFromSteps({
steps: t,
operators: (e.explanation.operators ?? []).filter((e) => e.parentCommandId === void 0),
transport: { kind: "direct" },
risks: e.explanation.risks
});
if (s.length === 0) return unanalyzablePlan({
dialect: "posix-shell",
command: e.command,
reason: "no commands to authorize"
});
return {
ok: true,
dialect: "posix-shell",
originalCommand: e.command,
groups: s,
operators: e.explanation.operators ?? []
};
}
async function planShellAuthorization(e) {
if (e.platform === "win32") return unanalyzablePlan({
dialect: "windows-cmd",
command: e.command,
reason: "non-POSIX shell command"
});
try {
const t = await explainShellCommand(e.command);
return planFromExplanation({
command: e.command,
explanation: t,
context: {
cwd: e.cwd,
env: e.env,
platform: normalizePlanningPlatform(e.platform)
}
});
} catch (t) {
return unanalyzablePlan({
dialect: "posix-shell",
command: e.command,
reason: t instanceof Error ? t.message : "unable to parse command"
});
}
}
async function planExecAuthorization(e) {
const t = e.command ?? e.analysis.segments.map((e) => e.raw).join(e.analysis.chains ? " && " : " | ");
if (!e.analysis.ok) return unanalyzablePlan({
dialect: "argv",
command: t,
reason: e.analysis.reason ?? "unable to parse command"
});
const n = e.analysis.segments[0]?.argv ?? [];
const r = dialectForArgv(n);
if (r !== "argv") return unanalyzablePlan({
dialect: r,
command: t,
reason: "non-POSIX command wrapper"
});
if (e.analysis.segments.length === 1) {
const r = e.analysis.segments[0];
const i = extractBindableShellWrapperInlineCommand(n);
if (i && r && canUseWrapperShellInvocation(r)) {
const n = await planShellAuthorization({
command: i,
cwd: e.cwd,
env: e.env
});
if (n.ok) {
if (canUseReusableWrapperPayloadCandidates(n.groups.flatMap((e) => e.candidates.map((e) => e.sourceSegment)))) {
const e = !isUnresolvedPathScopedExecutable(r);
return {
ok: true,
dialect: "argv",
originalCommand: t,
groups: n.groups.map((t) => ({
...t,
candidates: t.candidates.map((t) => {
const n = {
kind: "shell-wrapper",
wrapperSegment: r,
wrapperArgv: r.argv,
inlineCommand: i
};
return {
...t,
transport: n,
allowAlways: e ? t.allowAlways : false
};
})
})),
operators: n.operators
};
}
}
}
}
return {
ok: true,
dialect: "argv",
originalCommand: t,
groups: groupsFromSteps({
steps: e.analysis.segments.map((t, n) => ({
step: {
context: "top-level",
executable: t.argv[0] ?? "",
argv: t.argv,
text: t.raw,
span: {
startIndex: n,
endIndex: n + t.raw.length,
startPosition: {
row: 0,
column: n
},
endPosition: {
row: 0,
column: n + t.raw.length
}
},
executableSpan: {
startIndex: n,
endIndex: n + (t.argv[0]?.length ?? 0),
startPosition: {
row: 0,
column: n
},
endPosition: {
row: 0,
column: n + (t.argv[0]?.length ?? 0)
}
}
},
segment: t.resolution === null ? commandSegmentFromArgv(t.argv, {
cwd: e.cwd,
env: e.env
}, t.sourceArgv) : t
})),
transport: { kind: "direct" },
risks: []
}),
operators: []
};
}
//#endregion
//#region src/infra/exec-safe-builtins.ts
const DEFAULT_SAFE_BUILTINS = /* @__PURE__ */ new Set([
":",
"cd",
"false",
"pwd",
"test",
"true"
]);
const UNSAFE_PREDICATE_BUILTIN_OPERANDS = /* @__PURE__ */ new Set(["-v"]);
/** Returns true when a parsed POSIX shell segment is one of the closed safe builtin forms. */
function isSafeBuiltinSegment(e) {
if (isWindowsPlatform(e.platform ?? process.platform)) return false;
const t = e.segment.argv[0]?.trim();
if (!t) return false;
if (t === "[") return isSafePredicateBuiltinArgv(e.segment.argv, {
requiresClosingBracket: true,
fallbackRawCheck: e.segment.raw,
head: t
});
if (!DEFAULT_SAFE_BUILTINS.has(t)) return false;
if (t === "test") return isSafePredicateBuiltinArgv(e.segment.argv, {
fallbackRawCheck: e.segment.raw,
head: t
});
return true;
}
function isSafePredicateBuiltinArgv(e, t) {
if (t.requiresClosingBracket) {
if (e.at(-1) !== "]" && !t.fallbackRawCheck.trim().endsWith("]")) return false;
}
if (e.some((e) => UNSAFE_PREDICATE_BUILTIN_OPERANDS.has(e?.trim() ?? ""))) return false;
const n = t.fallbackRawCheck.trim();
const r = n.slice(t.head.length);
if (!n.startsWith(t.head) || r.length > 0 && !/^\s/u.test(r)) return false;
const i = n.slice(t.head.length, t.requiresClosingBracket ? -1 : void 0);
for (const e of i) if ("\\$`*?{}[]".includes(e)) return false;
return true;
}
//#endregion
//#region src/infra/package-manager-exec-wrapper.ts
const NPM_EXEC_CONTEXT_OPTIONS_WITH_VALUE = /* @__PURE__ */ new Set([
"--cache",
"--package",
"--prefix",
"--script-shell",
"--userconfig",
"--workspace",
"-p",
"-w"
]);
const NPM_EXEC_OPTIONS_WITH_VALUE = /* @__PURE__ */ new Set([...NPM_EXEC_CONTEXT_OPTIONS_WITH_VALUE, "--loglevel"]);
const NPM_EXEC_FLAG_OPTIONS = /* @__PURE__ */ new Set([
"--no",
"--quiet",
"--ws",
"--workspaces",
"--yes",
"-q",
"-y"
]);
const NPM_EXEC_SUBCOMMANDS = /* @__PURE__ */ new Set(["exec", "x"]);
const PNPM_OPTIONS_WITH_VALUE = /* @__PURE__ */ new Set([
"--config",
"--dir",
"--filter",
"--reporter",
"--stream",
"--test-pattern",
"--workspace-concurrency"
]);
const PNPM_CASE_SENSITIVE_OPTIONS_WITH_VALUE = /* @__PURE__ */ new Set(["-C"]);
const PNPM_FLAG_OPTIONS = /* @__PURE__ */ new Set([
"--aggregate-output",
"--color",
"--parallel",
"--recursive",
"--silent",
"--workspace-root",
"-r",
"-s",
"-w"
]);
const PNPM_DLX_OPTIONS_WITH_VALUE = /* @__PURE__ */ new Set([
"--allow-build",
"--package",
"-p"
]);
const PNPM_EXEC_CONTEXT_OPTIONS_WITH_VALUE = /* @__PURE__ */ new Set([
"--allow-build",
"--config",
"--dir",
"--filter",
"--package",
"-p"
]);
const PNPM_EXEC_SUBCOMMANDS = /* @__PURE__ */ new Set([
"exec",
"dlx",
"node"
]);
const PNPM_SCRIPT_RUN_SUBCOMMANDS = /* @__PURE__ */ new Set([
"restart",
"run",
"start",
"stop",
"test"
]);
const PNPM_BUILTIN_NON_EXEC_SUBCOMMANDS = /* @__PURE__ */ new Set([
"add",
"audit",
"bin",
"config",
"dedupe",
"deploy",
"help",
"import",
"init",
"install",
"licenses",
"link",
"list",
"outdated",
"patch",
"prune",
"publish",
"rebuild",
"remove",
"root",
"server",
"store",
"unlink",
"update",
"view",
"why"
]);
const YARN_OPTIONS_WITH_VALUE = /* @__PURE__ */ new Set(["--cwd"]);
const YARN_FLAG_OPTIONS = /* @__PURE__ */ new Set([
"--immutable",
"--silent",
"-s"
]);
const YARN_DLX_OPTIONS_WITH_VALUE = /* @__PURE__ */ new Set(["--package", "-p"]);
const YARN_DLX_FLAG_OPTIONS = /* @__PURE__ */ new Set(["--quiet", "-q"]);
const YARN_EXEC_SUBCOMMANDS = /* @__PURE__ */ new Set(["exec", "dlx"]);
const YARN_BUILTIN_NON_EXEC_SUBCOMMANDS = /* @__PURE__ */ new Set([
"add",
"audit",
"autoclean",
"bin",
"cache",
"check",
"config",
"create",
"dedupe",
"generate-lock-entry",
"global",
"help",
"import",
"info",
"init",
"install",
"licenses",
"link",
"list",
"login",
"logout",
"outdated",
"owner",
"pack",
"policies",
"prune",
"publish",
"remove",
"self-update",
"tag",
"team",
"unlink",
"upgrade",
"upgrade-interactive",
"version",
"versions",
"why",
"workspace"
]);
const NPM_DIRECT_EXEC_OPTIONS = {
optionsWithValue: NPM_EXEC_OPTIONS_WITH_VALUE,
flagOptions: NPM_EXEC_FLAG_OPTIONS
};
const NPM_EXEC_OPTIONS = {
...NPM_DIRECT_EXEC_OPTIONS,
caseSensitiveOptionsWithValue: /* @__PURE__ */ new Set(["-C"]),
contextOptionsWithValue: NPM_EXEC_CONTEXT_OPTIONS_WITH_VALUE,
contextFlagOptions: /* @__PURE__ */ new Set(["--ws", "--workspaces"])
};
const PNPM_EXEC_OPTIONS = {
optionsWithValue: /* @__PURE__ */ new Set([...PNPM_OPTIONS_WITH_VALUE, ...PNPM_DLX_OPTIONS_WITH_VALUE]),
caseSensitiveOptionsWithValue: PNPM_CASE_SENSITIVE_OPTIONS_WITH_VALUE,
flagOptions: PNPM_FLAG_OPTIONS,
contextOptionsWithValue: PNPM_EXEC_CONTEXT_OPTIONS_WITH_VALUE,
contextFlagOptions: /* @__PURE__ */ new Set([
"--recursive",
"--workspace-root",
"-r",
"-w"
])
};
const PNPM_DLX_OPTIONS = {
optionsWithValue: PNPM_EXEC_OPTIONS.optionsWithValue,
flagOptions: PNPM_FLAG_OPTIONS
};
const YARN_EXEC_OPTIONS = {
optionsWithValue: /* @__PURE__ */ new Set([...YARN_OPTIONS_WITH_VALUE, ...YARN_DLX_OPTIONS_WITH_VALUE]),
flagOptions: /* @__PURE__ */ new Set([...YARN_FLAG_OPTIONS, ...YARN_DLX_FLAG_OPTIONS]),
contextOptionsWithValue: YARN_OPTIONS_WITH_VALUE
};
const YARN_DLX_OPTIONS = {
optionsWithValue: YARN_DLX_OPTIONS_WITH_VALUE,
flagOptions: YARN_DLX_FLAG_OPTIONS,
contextOptionsWithValue: YARN_DLX_OPTIONS_WITH_VALUE
};
function scanPackageManagerOptions(e, t, n, r, i) {
let a = t;
while (a < e.length) {
const t = e[a]?.trim() ?? "";
if (!t) {
a += 1;
continue;
}
if (t === "--") {
if (r === "reject" || i?.scope === "before-terminator") return null;
if (r === "stop") return a + 1 < e.length ? a + 1 : null;
a += 1;
continue;
}
if (!t.startsWith("-")) {
if (i?.scope === "before-terminator") {
a += 1;
continue;
}
return i ? null : a;
}
const o = parseInlineOptionToken(t);
const s = normalizeLowercaseStringOrEmpty(o.name);
if (i && (n.caseSensitiveOptionsWithValue?.has(o.name) || i.options.contextOptionsWithValue.has(s) || i.options.contextFlagOptions?.has(s))) return a;
if (n.caseSensitiveOptionsWithValue?.has(o.name) || n.optionsWithValue.has(s)) {
a += o.hasInlineValue ? 1 : 2;
continue;
}
if (n.flagOptions.has(s) || i?.scope === "before-terminator") {
a += 1;
continue;
}
return null;
}
return null;
}
function hasContextOption(e, t, n, r = "leading") {
return scanPackageManagerOptions(e, t, n, "skip", {
options: n,
scope: r
}) !== null;
}
function hasKnownPackageManagerExecContextOptions(e) {
const t = normalizePackageManagerExecToken(e[0] ?? "");
if (t === "npx" || t === "bunx") return hasContextOption(e, 1, NPM_EXEC_OPTIONS);
if (t !== "npm" && t !== "pnpm" && t !== "yarn") return false;
const [n] = PACKAGE_EXEC_MANAGERS[t];
if (hasContextOption(e, 1, n)) return true;
const r = scanPackageManagerOptions(e, 1, n, "skip");
if (r === null) return false;
if (t === "npm") return NPM_EXEC_SUBCOMMANDS.has(e[r] ?? "") && hasContextOption(e, r + 1, n, "before-terminator");
return e[r] === "dlx" && hasContextOption(e, r + 1, t === "pnpm" ? n : YARN_DLX_OPTIONS);
}
function normalizePackageManagerExecToken(e) {
return normalizeExecutableToken(e).replace(/\.(?:c|m)?js$/i, "");
}
function unwrapPackageExecArguments(e, t, n, r) {
const i = scanPackageManagerOptions(e, t, n, r);
return i === null ? null : e.slice(i);
}
function unwrapNpmExecInvocation(e) {
const t = scanPackageManagerOptions(e, 1, NPM_EXEC_OPTIONS, "reject");
if (t === null || !NPM_EXEC_SUBCOMMANDS.has(e[t]?.trim() ?? "")) return null;
const n = e.slice(t + 1);
if (n[0] === "--") return n.length > 1 ? n.slice(1) : null;
return unwrapPackageExecArguments(e, t + 1, NPM_DIRECT_EXEC_OPTIONS, "reject");
}
function unwrapPnpmOrYarnExecInvocation(e, t) {
const n = scanPackageManagerOptions(e, 1, t === "pnpm" ? PNPM_EXEC_OPTIONS : {
optionsWithValue: YARN_OPTIONS_WITH_VALUE,
flagOptions: YARN_FLAG_OPTIONS
}, "skip");
if (n === null) return null;
const r = e[n]?.trim();
if (r === "dlx") return unwrapPackageExecArguments(e, n + 1, t === "pnpm" ? PNPM_DLX_OPTIONS : YARN_DLX_OPTIONS, "stop");
const i = e.slice(n + 1);
const a = i[0] === "--" ? i.slice(1) : i;
if (t === "pnpm" && r === "node") return ["node", ...a];
if (r !== "exec") return null;
if (t === "pnpm") {
const e = normalizeLowercaseStringOrEmpty(parseInlineOptionToken(a[0] ?? "").name);
if (e === "-c" || e === "--shell-mode") return null;
}
return a.length > 0 ? a : null;
}
function unwrapKnownPackageManagerExecInvocation(e) {
const t = resolveKnownPackageManagerExecInvocation(e);
return t.kind === "unwrapped" ? t.argv : null;
}
const PACKAGE_EXEC_MANAGERS = {
npm: [NPM_EXEC_OPTIONS, NPM_EXEC_SUBCOMMANDS],
pnpm: [PNPM_EXEC_OPTIONS, PNPM_EXEC_SUBCOMMANDS],
yarn: [YARN_EXEC_OPTIONS, YARN_EXEC_SUBCOMMANDS]
};
function resolveKnownPackageManagerExecInvocation(e) {
const t = normalizePackageManagerExecToken(e[0] ?? "");
if (t === "npx" || t === "bunx") {
const t = unwrapPackageExecArguments(e, 1, NPM_DIRECT_EXEC_OPTIONS, "reject");
return t ? {
kind: "unwrapped",
argv: t
} : { kind: "unsafe-exec" };
}
if (t !== "npm" && t !== "pnpm" && t !== "yarn") return { kind: "not-package-manager" };
const [n, r] = PACKAGE_EXEC_MANAGERS[t];
const i = t === "npm" ? unwrapNpmExecInvocation(e) : unwrapPnpmOrYarnExecInvocation(e, t);
if (i) return {
kind: "unwrapped",
argv: i
};
const a = scanPackageManagerOptions(e, 1, n, "skip");
const o = a === null ? null : normalizeLowercaseStringOrEmpty(e[a] ?? "");
const s = o === null ? e.slice(1).some((e) => r.has(normalizeLowercaseStringOrEmpty(e))) : r.has(o);
const c = o !== null && (t === "pnpm" ? !PNPM_SCRIPT_RUN_SUBCOMMANDS.has(o) && !PNPM_BUILTIN_NON_EXEC_SUBCOMMANDS.has(o) : t === "yarn" && (o === "run" || !YARN_BUILTIN_NON_EXEC_SUBCOMMANDS.has(o)));
return s || c ? { kind: "unsafe-exec" } : { kind: "not-exec" };
}
//#endregion
//#region src/infra/exec-approvals-allowlist.ts
function hasShellLineContinuation(e) {
return /\\(?:\r\n|\n|\r)/.test(e);
}
function commandStepToPolicySegment(e, t) {
return {
raw: e.text,
argv: e.argv,
resolution: resolveCommandResolutionFromArgv(e.argv, t.cwd, t.env, t.platform ?? void 0)
};
}
async function explainShellPolicySegments(e) {
try {
const t = await explainShellCommand(e.command);
return [...t.topLevelCommands, ...t.nestedCommands].map((t) => commandStepToPolicySegment(t, e));
} catch {
return [];
}
}
function resolveSafeBins(e) {
const t = e === void 0 ? DEFAULT_SAFE_BINS : e;
return new Set(Array.isArray(t) ? t.map((e) => normalizeLowercaseStringOrEmpty(e)).filter(Boolean) : []);
}
function isSafeBinUsage(e) {
if (isWindowsPlatform(e.platform ?? process.platform)) return false;
if (e.safeBins.size === 0) return false;
const t = e.resolution;
const n = normalizeOptionalLowercaseString(t?.executableName);
if (!n) return false;
if (!e.safeBins.has(n)) return false;
const r = resolveExecutableTrustPath(t);
if (!r) return false;
if (!isTrustedSafeBinPath({
resolvedPath: r,
trustedDirs: e.trustedSafeBinDirs
})) return false;
const i = e.argv.slice(1);
const a = (e.safeBinProfiles ?? SAFE_BIN_PROFILES)[n];
if (!a) return false;
return validateSafeBinArgv(i, a, { binName: n });
}
function normalizeSkillBinResolvedPath(e) {
const t = normalizeOptionalString(e);
if (!t) return null;
const n = path.resolve(t);
if (process.platform === "win32") return normalizeLowercaseStringOrEmpty(n.replace(/\\/g, "/"));
return n;
}
function buildSkillBinTrustIndex(e) {
const t = /* @__PURE__ */ new Map();
if (!e || e.length === 0) return t;
for (const n of e) {
const e = normalizeOptionalLowercaseString(n.name);
const r = normalizeSkillBinResolvedPath(n.resolvedPath);
if (!e || !r) continue;
const i = t.get(e) ?? /* @__PURE__ */ new Set();
i.add(r);
t.set(e, i);
}
return t;
}
function isSkillAutoAllowedSegment(e) {
if (!e.allowSkills) return false;
const t = e.segment.resolution;
const n = resolveExecutionTargetResolution(t);
const r = resolveExecutionTargetTrustPath(t);
if (!n?.resolvedPath || !r) return false;
const i = n.rawExecutable?.trim() ?? "";
if (!i || isPathScopedExecutableToken(i)) return false;
const a = normalizeOptionalLowercaseString(n.executableName);
const o = normalizeSkillBinResolvedPath(r);
if (!a || !o) return false;
return Boolean(e.skillBinTrust.get(a)?.has(o));
}
const MAX_SHELL_WRAPPER_INLINE_EVAL_DEPTH = 3;
const MAX_PACKAGE_MANAGER_EXEC_UNWRAP_DEPTH = 6;
function resolvePackageManagerTrustTargetArgv(e, t = process.platform) {
let n = e;
let r = false;
for (let e = 0; e < MAX_PACKAGE_MANAGER_EXEC_UNWRAP_DEPTH; e += 1) {
const e = resolveDispatchWrapperTrustPlan(n, void 0, t);
if (e.policyBlocked) return { kind: "blocked" };
n = e.argv;
const i = resolveKnownPackageManagerExecInvocation(n);
if (i.kind === "unwrapped" && hasKnownPackageManagerExecContextOptions(n)) return { kind: "blocked" };
if (i.kind === "unsafe-exec") return { kind: "blocked" };
if (i.kind !== "unwrapped") return r ? {
kind: "package-manager",
argv: n
} : {
kind: "not-package-manager",
argv: n
};
r = true;
n = i.argv;
}
return { kind: "blocked" };
}
function resolvePackageManagerAllowlistTargetArgv(e, t = process.platform) {
const n = resolvePackageManagerTrustTargetArgv(e, t);
if (n.kind === "blocked") return null;
if (n.kind !== "package-manager") return;
const r = resolveExecWrapperTrustPlan(n.argv, void 0, t);
if (r.policyBlocked || r.shellWrapperExecutable && r.shellInlineCommand) return null;
return r.argv;
}
function executableResolutionsReferToSameTarget(e, t) {
if (!e || !t) return false;
return e.rawExecutable === t.rawExecutable && e.resolvedPath === t.resolvedPath && e.resolvedRealPath === t.resolvedRealPath && e.executableName === t.executableName;
}
function resolveShellWrapperScriptArgv(e) {
const t = normalizeLowercaseStringOrEmpty(path.basename(e.shellScriptCandidatePath));
const n = e.cwd && e.cwd.trim() ? e.cwd : process.cwd();
const resolveArgPath = (e) => path.isAbsolute(e) ? e : path.resolve(n, e);
let r = e.effectiveArgv.findIndex((t) => resolveArgPath(t) === e.shellScriptCandidatePath);
if (r === -1) r = e.effectiveArgv.findIndex((e) => normalizeLowercaseStringOrEmpty(path.basename(e)) === t);
const i = r !== -1 ? e.effectiveArgv.slice(r + 1) : [];
return [e.shellScriptCandidatePath, ...i];
}
function resolvePowerShellFileScriptArgv(e) {
const t = resolveSegmentSourceArgv(e.segment);
if (!Array.isArray(t) || t.length < 3) return null;
const n = normalizeExecutableToken(t[0] ?? "");
if (!POWERSHELL_WRAPPERS.has(n)) return null;
const r = resolvePowerShellInlineCommandMatch(t);
if (r.valueTokenIndex === null || !r.command) return null;
if (!isPowerShellInlineFileCommandFlag(t[r.valueTokenIndex - 1] ?? "")) return null;
const i = t[r.valueTokenIndex]?.trim();
if (!i) return null;
const a = i.startsWith("~") ? expandHomePrefix(i) : i;
const o = e.cwd && e.cwd.trim().length > 0 ? e.cwd : process.cwd();
return [path.isAbsolute(a) ? a : path.resolve(o, a), ...t.slice(r.valueTokenIndex + 1)];
}
function resolveSegmentSourceArgv(e) {
const t = e.sourceArgv;
if (!Array.isArray(t) || t.length === 0) return e.argv;
const n = normalizeExecutableToken(e.argv[0] ?? "");
if (!n) return e.argv;
if (normalizeExecutableToken(t[0] ?? "") === n) return t;
const r = unwrapDispatchWrappersForResolution(t);
return normalizeExecutableToken(r[0] ?? "") === n ? r : e.argv;
}
function resolveSegmentAllowlistMatch(e) {
const t = e.segment.resolution?.effectiveArgv && e.segment.resolution.effectiveArgv.length > 0 ? e.segment.resolution.effectiveArgv : e.segment.argv;
const n = resolvePackageManagerAllowlistTargetArgv(t, e.context.platform ?? void 0);
if (n === null) return {
effectiveArgv: t,
inlineCommand: null,
match: null
};
const r = n ?? t;
const i = r === t ? e.segment.resolution : resolveCommandResolutionFromArgv(r, e.context.cwd, e.context.env, e.context.platform ?? void 0);
const a = r === e.segment.argv ? e.segment : {
...e.segment,
argv: r,
resolution: i
};
const o = resolvePolicyTargetResolution(i);
const s = resolveExecutionTargetResolution(e.segment.resolution);
const c = resolvePolicyTargetCandidatePath(i, e.context.cwd);
const l = resolvePolicyTargetTrustPath(i, e.context.cwd);
const u = c && o ? {
...o,
resolvedPath: c,
resolvedRealPath: l
} : o;
const d = resolveExecutionTargetResolution(i);
const f = extractBindableShellWrapperInlineCommand(a.argv);
const p = isOpaquePosixShellWrapperSegment(a);
const m = resolvePowerShellFileScriptArgv({
segment: a,
cwd: e.context.cwd
});
const h = isShellWrapperSegment(a);
const g = f !== null && isDirectShellPositionalCarrierCommand(f);
const _ = executableResolutionsReferToSameTarget(o, d ?? s);
let v = g ? null : matchAllowlist(e.context.allowlist, u, r, e.context.platform, e.context.cwd);
const y = typeof v?.argPattern === "string" && v.argPattern.trim().length > 0;
const b = v?.pattern?.trim() === "*" && !y;
if (_ && (f !== null || h && r.length > 1) && !y && !b) v = null;
const x = f !== null ? resolveShellWrapperPositionalArgvCandidate({
segment: a,
cwd: e.context.cwd,
env: e.context.env,
platform: e.context.platform
}) : void 0;
const matchShellPath = (t, n, r) => matchAllowlist(t, {
kind: "executable",
rawExecutable: n,
resolvedPath: n,
resolvedRealPath: resolveCandidateTrustPath(n),
executableName: path.basename(n)
}, r, e.context.platform, e.context.cwd);
const S = x ? matchShellPath(x.durable ? e.context.allowlist : e.context.allowlist.filter((e) => e.argPattern === void 0), x.path, x.argv) : null;
const C = m?.[0] ?? (f === null ? resolveShellWrapperScriptCandidatePath({
segment: a,
cwd: e.context.cwd
}) : void 0);
const w = C ? m ?? resolveShellWrapperScriptArgv({
shellScriptCandidatePath: C,
effectiveArgv: r,
cwd: e.context.cwd
}) : null;
const T = C && w ? matchShellPath(e.context.allowlist, C, w) : null;
return {
effectiveArgv: t,
inlineCommand: m || p ? null : f,
match: v ?? S ?? T
};
}
function resolveSegmentSatisfaction(e) {
if (e.match) return "allowlist";
if (isSafeBinUsage({
argv: e.effectiveArgv,
resolution: resolveExecutionTargetResolution(e.segment.resolution),
safeBins: e.context.safeBins,
safeBinProfiles: e.context.safeBinProfiles,
platform: e.context.platform,
trustedSafeBinDirs: e.context.trustedSafeBinDirs
})) return "safeBins";
if (e.context.allowShellBuiltins === true && isSafeBuiltinSegment({
segment: e.segment,
platform: e.context.platform
})) return "safeBuiltins";
return isSkillAutoAllowedSegment({
segment: e.segment,
allowSkills: e.allowSkills,
skillBinTrust: e.skillBinTrust
}) ? "skills" : null;
}
function evaluateShellWrapperInlineCommand(e) {
if (e.inlineDepth >= MAX_SHELL_WRAPPER_INLINE_EVAL_DEPTH) return null;
if (hasShellLineContinuation(e.inlineCommand)) return null;
const t = analyzeWindowsShellCommand({
command: e.inlineCommand,
cwd: e.context.cwd,
env: e.context.env,
platform: e.context.platform
});
if (!t.ok || t.segments.length === 0) return null;
const n = [];
for (const r of t.chains ?? [t.segments]) {
const t = evaluateSegments(r, e.context, e.inlineDepth);
if (!t.allowlistSatisfied) return null;
n.push(...t.allowlistMatches);
}
return n;
}
function emptyExecAllowlistEvaluation() {
return {
allowlistSatisfied: false,
allowlistMatches: [],
segmentAllowlistEntries: [],
segmentSatisfiedBy: []
};
}
function evaluateSegments(e, t, n = 0) {
const r = emptyExecAllowlistEvaluation();
const { allowlistMatches: i, segmentAllowlistEntries: a, segmentSatisfiedBy: o } = r;
const s = buildSkillBinTrustIndex(t.skillBins);
const c = t.autoAllowSkills === true && s.size > 0;
r.allowlistSatisfied = e.every((e) => {
if (e.resolution?.policyBlocked === true) {
a.push(null);
o.push(null);
return false;
}
const { effectiveArgv: r, inlineCommand: l, match: u } = resolveSegmentAllowlistMatch({
segment: e,
context: t
});
if (u) i.push(u);
a.push(u ?? null);
const d = resolveSegmentSatisfaction({
match: u,
segment: e,
effectiveArgv: r,
context: t,
allowSkills: c,
skillBinTrust: s
});
const f = d === null && l && isWindowsPlatform(t.platform) ? evaluateShellWrapperInlineCommand({
inlineCommand: l,
context: t,
inlineDepth: n + 1
}) : null;
if (f) {
i.push(...f);
o.push("allowlist");
return true;
}
o.push(d);
return Boolean(d);
});
return r;
}
function evaluateAuthorizationPlan(e) {
const t = {
...emptyExecAllowlistEvaluation(),
analysisOk: true,
allowlistSatisfied: true,
segments: [],
authorizationPlan: e.plan
};
const n = e.context.skillBins ?? [];
const r = e.context.autoAllowSkills === true && n.length > 0;
const i = buildSkillBinTrustIndex(n);
for (const n of e.plan.groups) for (const a of n.candidates) {
let n = null;
let o = null;
if (a.trustMode !== "prompt-only") {
const t = resolveSegmentAllowlistMatch({
segment: a.sourceSegment,
context: e.context
});
n = t.match;
o = resolveSegmentSatisfaction({
match: n,
segment: a.sourceSegment,
effectiveArgv: t.effectiveArgv,
context: e.context,
allowSkills: r,
skillBinTrust: i
});
}
if (n) t.allowlistMatches.push(n);
t.segments.push(a.sourceSegment);
t.segmentAllowlistEntries.push(n);
t.segmentSatisfiedBy.push(o);
if (!o) t.allowlistSatisfied = false;
}
return t;
}
function evaluateExecAllowlist(e) {
if (!e.analysis.ok || e.analysis.segments.length === 0) return emptyExecAllowlistEvaluation();
if (!e.analysis.chains) return evaluateSegments(e.analysis.segments, e);
const t = emptyExecAllowlistEvaluation();
for (const n of e.analysis.chains) {
const r = evaluateSegments(n, e);
if (!r.allowlistSatisfied) return emptyExecAllowlistEvaluation();
t.allowlistMatches.push(...r.allowlistMatches);
t.segmentAllowlistEntries.push(...r.segmentAllowlistEntries);
t.segmentSatisfiedBy.push(...r.segmentSatisfiedBy);
}
t.allowlistSatisfied = true;
return t;
}
function hasSegmentExecutableMatch(e, t) {
const n = resolveExecutionTargetResolution(e.resolution);
return [
n?.executableName,
n?.rawExecutable,
e.argv[0]
].some((e) => {
const n = normalizeOptionalString(e);
return n ? t(n) : false;
});
}
function isShellWrapperSegment(e) {
return hasSegmentExecutableMatch(e, isShellWrapperExecutable);
}
function isOpaquePosixShellWrapperSegment(e) {
return hasSegmentExecutableMatch(e, (e) => {
const t = normalizeExecutableToken(e);
return POSIX_SHELL_WRAPPERS.has(t) && !POSIX_PARSEABLE_SHELL_WRAPPERS.has(t);
});
}
const SHELL_WRAPPER_OPTIONS_WITH_VALUE = /* @__PURE__ */ new Set([
"-c",
"--command",
"-o",
"-O",
"+O",
"+o"
]);
const SHELL_WRAPPER_DISQUALIFYING_SCRIPT_OPTIONS = [
"--rcfile",
"--init-file",
"--startup-file"
];
function hasDisqualifyingShellWrapperScriptOption(e) {
return SHELL_WRAPPER_DISQUALIFYING_SCRIPT_OPTIONS.some((t) => e === t || e.startsWith(`${t}=`));
}
const POWERSHELL_OPTIONS_WITH_VALUE_RE = /^-(?:executionpolicy|ep|windowstyle|w|workingdirectory|wd|inputformat|outputformat|settingsfile|configurationfile|version|v|psconsolefile|pscf|encodedcommand|en|enc|encodedarguments|ea)$/i;
function resolveShellWrapperScriptCandidatePath(e) {
if (!isShellWrapperSegment(e.segment)) return;
if (isOpaquePosixShellWrapperSegment(e.segment)) return;
const t = e.segment.argv;
if (!Array.isArray(t) || t.length < 2) return;
const n = normalizeExecutableToken(t[0] ?? "");
const r = POWERSHELL_WRAPPERS.has(n);
const i = POSIX_SHELLS_WITH_PLUS_OPTIONS.has(n);
let a = 1;
while (a < t.length) {
const e = t[a]?.trim() ?? "";
if (!e) {
a += 1;
continue;
}
if (e === "--") {
a += 1;
break;
}
if (!r && POSIX_INLINE_COMMAND_FLAGS.has(e)) return;
if (!r && /^-[^-]*c[^-]*$/i.test(e)) return;
if (e === "-s" || !r && /^-[^-]*s[^-]*$/i.test(e)) return;
if (hasDisqualifyingShellWrapperScriptOption(e)) return;
if (SHELL_WRAPPER_OPTIONS_WITH_VALUE.has(e)) {
a += 2;
continue;
}
if (r && POWERSHELL_OPTIONS_WITH_VALUE_RE.test(e)) {
a += 2;
continue;
}
if (!r && (e.startsWith("-") || i && e.startsWith("+"))) {
a += advancePosixInlineOptionScan(e);
continue;
}
if (e.startsWith("-") || e.startsWith("+")) {
a += 1;
continue;
}
break;
}
const o = t[a]?.trim();
if (!o) return;
if (path.isAbsolute(o)) return o;
const s = o.startsWith("~") ? expandHomePrefix(o) : o;
const c = e.cwd && e.cwd.trim().length > 0 ? e.cwd : process.cwd();
return path.resolve(c, s);
}
function isDurableShellPositionalCarrierCommand(e, t) {
const n = e.trim();
if (n.length === 0) return false;
const r = String.raw`[^\S\r\n]+`;
const i = String.raw`(?:\$(?:0|\{0\})|"\$(?:0|\{0\})")`;
if (t.length === 0) return new RegExp(`^(?:exec${r}(?:--${r})?)?${i}$`, "u").test(n);
const a = String.raw`(?:\$(?:@|\{@\})|"\$(?:@|\{@\})")`;
return new RegExp(`^(?:exec${r}(?:--${r})?)?${i}${r}${a}$`, "u").test(n);
}
function resolveShellWrapperPositionalArgvCandidate(e) {
if (!isShellWrapperSegment(e.segment)) return;
const t = e.segment.argv;
if (!Array.isArray(t) || t.length < 4) return;
const n = normalizeExecutableToken(t[0] ?? "");
if (![
"ash",
"bash",
"dash",
"fish",
"ksh",
"sh",
"zsh"
].includes(n)) return;
const r = resolveInlineCommandMatch(t, POSIX_INLINE_COMMAND_FLAGS, { allowCombinedC: true });
if (r.valueTokenIndex === null || !r.command) return;
if (!isDirectShellPositionalCarrierCommand(r.command)) return;
const i = t.slice(r.valueTokenIndex + 1).findIndex((e) => e.trim().length > 0);
if (i === -1) return;
const a = r.valueTokenIndex + 1 + i;
const o = t[a]?.trim() ?? "";
if (!o) return;
const s = t.slice(a + 1);
const c = isDurableShellPositionalCarrierCommand(r.command, s);
const l = normalizeExecutableToken(o);
if (isDispatchWrapperExecutable(l) || isShellWrapperExecutable(l)) return;
const u = resolveCommandResolutionFromArgv([o], e.cwd, e.env, e.platform ?? void 0);
const d = resolveExecutionTargetCandidatePath(u, e.cwd);
if (!d) return;
return {
path: d,
argv: [resolveCandidateTrustPath(d) ?? d, ...s],
durable: c
};
}
function addAllowAlwaysPattern(e, t, n) {
if (!e.some((e) => e.pattern === t && (e.argPattern ?? void 0) === (n ?? void 0))) e.push({
pattern: t,
argPattern: n
});
}
function resolveCandidateTrustPath(e) {
if (!e) return;
return resolveExecutableTrustPath({
kind: "executable",
rawExecutable: e,
resolvedPath: e,
executableName: path.basename(e)
});
}
function collectAllowAlwaysPatterns(e, t, n, r) {
if (n >= 3) return;
const i = resolvePackageManagerTrustTargetArgv(e.argv, t.platform ?? void 0);
if (i.kind === "blocked") return;
const a = resolveExecWrapperTrustPlan(i.argv, void 0, t.platform ?? void 0);
if (a.policyBlocked) return;
const o = a.argv === e.argv ? e : {
raw: a.argv.join(" "),
argv: a.argv,
sourceArgv: e.sourceArgv,
resolution: resolveCommandResolutionFromArgv(a.argv, t.cwd, t.env, t.platform ?? void 0)
};
const s = resolveExecutionTargetTrustPath(o.resolution, t.cwd);
if (!s) return;
if (isInterpreterLikeAllowlistPattern(s)) {
const e = o.resolution?.effectiveArgv ?? o.argv;
if (t.strictInlineEval !== true || detectInlineEvalArgv(e) !== null) return;
}
if (!a.shellWrapperExecutable) {
addAllowAlwaysPattern(r, s, buildCwdBoundHashedArgPattern(o.argv, t.cwd ?? process.cwd(), t.platform));
return;
}
const c = resolvePowerShellFileScriptArgv({
segment: o,
cwd: t.cwd
});
const l = c ? null : a.shellInlineCommand;
if (l && isOpaquePosixShellWrapperSegment(o)) return;
const u = l !== null ? resolveShellWrapperPositionalArgvCandidate({
segment: o,
cwd: t.cwd,
env: t.env,
platform: t.platform
}) : void 0;
if (u) {
if (!u.durable) return;
addAllowAlwaysPattern(r, resolveCandidateTrustPath(u.path) ?? u.path, buildCwdBoundHashedArgPattern(u.argv, t.cwd ?? process.cwd(), t.platform));
return;
}
if (!l) {
const e = c?.[0] ?? resolveShellWrapperScriptCandidatePath({
segment: o,
cwd: t.cwd
});
if (e) {
const n = resolveCandidateTrustPath(e) ?? e;
const i = resolveShellWrapperScriptArgv({
shellScriptCandidatePath: e,
effectiveArgv: c ?? o.argv,
cwd: t.cwd
});
addAllowAlwaysPattern(r, n, buildCwdBoundHashedArgPattern(i, t.cwd && t.cwd.trim() ? t.cwd : process.cwd(), t.platform));
}
return;
}
if (!isWindowsPlatform(t.platform) || POSIX_SHELL_WRAPPERS.has(normalizeExecutableToken(o.argv[0] ?? ""))) return;
const d = analyzeWindowsShellCommand({
command: l,
cwd: t.cwd,
env: t.env,
platform: t.platform
});
if (!d.ok || !canUseReusableWrapperPayloadCandidates(d.segments)) return;
for (const e of d.segments) collectAllowAlwaysPatterns(e, t, n + 1, r);
}
/** Derive persisted allowlist patterns for an "allow always" decision. */
function resolveAllowAlwaysPatternEntries(e) {
const t = [];
for (const n of e.segments) collectAllowAlwaysPatterns(n, e, 0, t);
return t;
}
async function evaluateShellAllowlistWithAuthorization(e) {
if (isWindowsPlatform(e.platform)) {
const t = hasShellLineContinuation(e.command) ? void 0 : analyzeWindowsShellCommand(e);
if (!t?.ok) return {
analysisOk: false,
...emptyExecAllowlistEvaluation(),
segments: []
};
return {
analysisOk: true,
...evaluateExecAllowlist({
...e,
analysis: t,
allowShellBuiltins: true
}),
segments: t.segments
};
}
const t = {
...e,
allowShellBuiltins: true
};
const n = await planShellAuthorization({ ...e });
if (!n.ok) return {
analysisOk: false,
...emptyExecAllowlistEvaluation(),
segments: await explainShellPolicySegments({ ...e }),
authorizationPlan: n
};
return evaluateAuthorizationPlan({
plan: n,
context: t
});
}
//#endregion
export { analyzeWindowsShellCommand as _, PNPM_CASE_SENSITIVE_OPTIONS_WITH_VALUE as a, PNPM_OPTIONS_WITH_VALUE as c, unwrapKnownPackageManagerExecInvocation as d, planExecAuthorization as f, analyzeArgvCommand as g, resolvePlannedSegmentArgv as h, resolveSafeBins as i, normalizePackageManagerExecToken as l, buildEnforcedShellCommand as m, evaluateShellAllowlistWithAuthorization as n, PNPM_DLX_OPTIONS_WITH_VALUE as o, planShellAuthorization as p, resolveAllowAlwaysPatternEntries as r, PNPM_FLAG_OPTIONS as s, evaluateExecAllowlist as t, resolveKnownPackageManagerExecInvocation as u, isWindowsPlatform as v };