openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
172 lines (171 loc) • 7.54 kB
JavaScript
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs";
import "./session-key-CqAyZeVk.mjs";
import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs";
import { a as executeSqliteQueryTakeFirstSync, i as executeSqliteQuerySync, s as getNodeSqliteKysely } from "./kysely-sync-YJo2lmGV.mjs";
import { n as sha256Hex } from "./node-crypto-B6yuTjmm.mjs";
import "./crypto-digest-B2m8wIBj.mjs";
import { a as LEGACY_EXEC_APPROVALS_DIAGNOSTIC, h as tryParsePersistedExecApprovals, l as parsePersistedExecApprovals, m as stripExecApprovalsSocketCredentials, o as createFailClosedExecApprovalsFallback, p as stripExecApprovalsRawSocketCredentials, s as normalizeExecApprovalsInternal, u as resolveExecApprovalsDisplayPath } from "./exec-approvals-config-BBzEUJlE.mjs";
import { t as assertExecApprovalsHostPolicyUnchanged } from "./exec-approvals-policy-BGzNHuNm.mjs";
import { n as assertNoPendingLegacyExecApprovals, r as resetExecApprovalsMigrationGateForTest, t as ExecApprovalsMigrationRequiredError } from "./exec-approvals-migration-gate-B5wo0WQB.mjs";
import { t as execApprovalsPublication } from "./exec-approvals-publication-CjvYUNZR.mjs";
import { isDeepStrictEqual } from "node:util";
//#region src/infra/exec-approvals-sqlite.ts
const EXEC_APPROVALS_CONFIG_KEY = "current";
var ExecApprovalsMutationFencedError = class extends Error {
constructor() {
super("Exec approvals cannot be changed while agent deletion is in progress; retry.");
this.name = "ExecApprovalsMutationFencedError";
}
};
function assertExecApprovalsMutationAllowed(e) {
const t = normalizeExecApprovalsInternal(e.current);
const n = normalizeExecApprovalsInternal(e.next);
const r = [.../* @__PURE__ */ new Set([...Object.keys(t.agents ?? {}), ...Object.keys(n.agents ?? {})])].filter((e) => !isDeepStrictEqual(t.agents?.[e], n.agents?.[e]));
const i = new Set(r.map(normalizeAgentId));
if (e.agentId) i.add(normalizeAgentId(e.agentId));
if (i.size === 0) return;
if (executeSqliteQueryTakeFirstSync(e.db, getNodeSqliteKysely(e.db).selectFrom("agent_deletion_journal").select("agent_id").where("agent_id", "in", [...i]).limit(1))) throw new ExecApprovalsMutationFencedError();
}
function hashExecApprovalsRaw(e) {
return e === null ? `missing:${sha256Hex("")}` : sha256Hex(e);
}
function serializeExecApprovals(e) {
return `${JSON.stringify(e, null, 2)}\n`;
}
function readExecApprovalsConfigRow(e) {
return executeSqliteQueryTakeFirstSync(e, getNodeSqliteKysely(e).selectFrom("exec_approvals_config").select("raw_json").where("config_key", "=", EXEC_APPROVALS_CONFIG_KEY));
}
function snapshotFromExecApprovalsRow(e) {
const t = e.row?.raw_json ?? null;
if (t === null) {
assertNoPendingLegacyExecApprovals({ env: e.env });
return {
path: e.path,
exists: false,
raw: null,
file: normalizeExecApprovalsInternal({
version: 1,
agents: {}
}),
hash: hashExecApprovalsRaw(null)
};
}
const n = parsePersistedExecApprovals(t);
if (!n.ok && n.error === "Legacy exec approval policy requires Doctor repair") throw new ExecApprovalsMigrationRequiredError(e.path, void 0, n.error);
const r = n.ok ? n.value : null;
if (!r) e.onMalformed?.();
return {
path: e.path,
exists: true,
raw: t,
file: r ?? createFailClosedExecApprovalsFallback(),
hash: hashExecApprovalsRaw(t)
};
}
function snapshotFromReadReply(e, t = process.env) {
return snapshotFromExecApprovalsRow({
path: resolveExecApprovalsDisplayPath(t),
env: t,
row: e?.row,
onMalformed: () => warnFailClosed("exec approvals SQLite row is malformed; denying host execution")
});
}
function projectionValues(e) {
const t = normalizeExecApprovalsInternal(e);
const n = Object.values(t.agents ?? {});
return {
socket_path: null,
has_socket_token: 0,
default_security: t.defaults?.security ?? null,
default_ask: t.defaults?.ask ?? null,
default_ask_fallback: t.defaults?.askFallback ?? null,
auto_allow_skills: t.defaults?.autoAllowSkills === void 0 ? null : t.defaults.autoAllowSkills ? 1 : 0,
agent_count: n.length,
allowlist_count: n.reduce((e, t) => e + (t.allowlist?.length ?? 0), 0)
};
}
function writeExecApprovalsConfigRow(e) {
const t = stripExecApprovalsSocketCredentials(e.file);
const n = normalizeExecApprovalsInternal(t);
const r = e.raw === void 0 ? serializeExecApprovals(t) : stripExecApprovalsRawSocketCredentials(e.raw);
const i = parsePersistedExecApprovals(r);
const a = e.raw === void 0 && !i.ok && i.error === "Legacy exec approval policy requires Doctor repair" ? serializeExecApprovals(n) : r;
const o = {
raw_json: a,
...projectionValues(n),
updated_at_ms: e.now ?? Date.now()
};
executeSqliteQuerySync(e.db, getNodeSqliteKysely(e.db).insertInto("exec_approvals_config").values({
config_key: EXEC_APPROVALS_CONFIG_KEY,
...o
}).onConflict((e) => e.column("config_key").doUpdateSet(o)));
const s = a === r ? i : parsePersistedExecApprovals(a);
const { socket: c, ...l } = s.ok ? s.value : createFailClosedExecApprovalsFallback();
execApprovalsPublication.stagePostimages(e.db, [{
file: l,
change: e.change ?? "policy"
}]);
return a;
}
function deleteExecApprovalsConfigRow(e) {
executeSqliteQuerySync(e, getNodeSqliteKysely(e).deleteFrom("exec_approvals_config").where("config_key", "=", EXEC_APPROVALS_CONFIG_KEY));
execApprovalsPublication.stageDeletions(e, [EXEC_APPROVALS_CONFIG_KEY]);
}
/** Called only inside the approval owner's winning resolution transaction. */
function mintMcpToolGrantLocked(e, t, n) {
const r = readExecApprovalsConfigRow(e);
const i = r ? tryParsePersistedExecApprovals(r.raw_json) : { version: 1 };
if (!i) throw new Error("Cannot save MCP tool grant: invalid exec approvals document");
const a = i.agents?.[t.agentId];
if (a?.mcpTools?.some((e) => e.server === t.server && e.tool === t.tool)) return;
const o = {
...i,
agents: {
...i.agents,
[t.agentId]: {
...a,
mcpTools: [...a?.mcpTools ?? [], {
server: t.server,
tool: t.tool,
source: "allow-always",
addedAt: n
}]
}
}
};
assertExecApprovalsHostPolicyUnchanged(i, o);
assertExecApprovalsMutationAllowed({
db: e,
current: i,
next: o
});
writeExecApprovalsConfigRow({
db: e,
file: o,
now: n
});
}
const log = createSubsystemLogger("infra/exec-approvals");
const WARN_INTERVAL_MS = 6e4;
let lastWarnAt;
function warnFailClosed(e, t) {
const n = Date.now();
if (lastWarnAt !== void 0 && n - lastWarnAt < WARN_INTERVAL_MS) return;
lastWarnAt = n;
log.warn(e, t === void 0 ? void 0 : { error: formatErrorMessage(t) });
}
function snapshotFromExecApprovalsDatabase(e, t = process.env) {
return snapshotFromExecApprovalsRow({
path: resolveExecApprovalsDisplayPath(t),
env: t,
row: readExecApprovalsConfigRow(e),
onMalformed: () => warnFailClosed("exec approvals SQLite row is malformed; denying host execution")
});
}
if (process.env.VITEST || false) Object.assign(globalThis, { [Symbol.for("openclaw.execApprovalsStoreTestApi")]: { reset() {
resetExecApprovalsMigrationGateForTest();
lastWarnAt = void 0;
} } });
//#endregion
export { projectionValues as a, snapshotFromExecApprovalsDatabase as c, warnFailClosed as d, writeExecApprovalsConfigRow as f, mintMcpToolGrantLocked as i, snapshotFromExecApprovalsRow as l, assertExecApprovalsMutationAllowed as n, readExecApprovalsConfigRow as o, deleteExecApprovalsConfigRow as r, serializeExecApprovals as s, ExecApprovalsMutationFencedError as t, snapshotFromReadReply as u };