UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

184 lines (183 loc) • 9.41 kB
import { o as registerSecretValueForRedaction } from "./secret-redaction-registry-Cy0acctn.mjs"; import { s as stageSqliteTransactionState } from "./sqlite-post-commit-BrUVQObC.mjs"; import { a as executeSqliteQueryTakeFirstSync, i as executeSqliteQuerySync, s as getNodeSqliteKysely } from "./kysely-sync-YJo2lmGV.mjs"; import { a as tableExists } from "./openclaw-state-db-schema-helpers-nImZNMq_.mjs"; import "./sqlite-number-D8n3srri.mjs"; import { l as runOpenClawStateWriteTransaction, r as openOpenClawStateDatabase } from "./openclaw-state-db-ARhwdPJg.mjs"; import { t as createOpenClawStateSchemaEnsurer } from "./openclaw-state-feature-schema-ensure-DcloJsFG.mjs"; import { t as validateDecisionReceiptV1 } from "./audit-run-validators-DQArxEAR.mjs"; import { createHmac, randomBytes } from "node:crypto"; //#region src/audit/audit-identity.ts /** Stable installation-local pseudonyms for sensitive audit identifiers. */ const AUDIT_IDENTITY_SINGLETON_ID = 1; const AUDIT_IDENTITY_KEY_BYTES = 32; const AUDIT_IDENTITY_KEY_ID_BYTES = 16; const AUDIT_IDENTITY_KEY_ID_RE = /^[a-f0-9]{32}$/u; const AUDIT_IDENTITY_DOMAIN = "openclaw.audit.identity.v1"; const identityByDatabase = /* @__PURE__ */ new WeakMap(); function registerAuditIdentityKeyForRedaction(e) { const t = Buffer.from(e); registerSecretValueForRedaction(t.toString("hex")); registerSecretValueForRedaction(t.toString("base64url")); } function parseAuditIdentityKey(e) { if (typeof e.key_id !== "string" || !AUDIT_IDENTITY_KEY_ID_RE.test(e.key_id) || !(e.key instanceof Uint8Array) || e.key.byteLength !== AUDIT_IDENTITY_KEY_BYTES) throw new Error("audit identity key is corrupt"); const t = Buffer.from(e.key); registerAuditIdentityKeyForRedaction(t); return { keyId: e.key_id, key: t }; } /** Load the stable audit identity key or create it on first use. */ function loadOrCreateAuditIdentityKey(e) { const t = identityByDatabase.get(e); if (t) return t; const n = getNodeSqliteKysely(e); const r = executeSqliteQueryTakeFirstSync(e, n.selectFrom("audit_identity_keys").select(["key_id", "key"]).where("id", "=", AUDIT_IDENTITY_SINGLETON_ID)); if (r) { const t = parseAuditIdentityKey(r); identityByDatabase.set(e, t); return t; } const i = executeSqliteQueryTakeFirstSync(e, n.selectFrom("audit_events").select("sequence").where("kind", "=", "message").limit(1)); const a = tableExists(e, "execution_identity_contexts") ? executeSqliteQueryTakeFirstSync(e, n.selectFrom("execution_identity_contexts").select("context_id").limit(1)) : void 0; if (i || a) throw new Error("audit identity key is missing"); const o = { id: AUDIT_IDENTITY_SINGLETON_ID, key_id: randomBytes(AUDIT_IDENTITY_KEY_ID_BYTES).toString("hex"), key: randomBytes(AUDIT_IDENTITY_KEY_BYTES), created_at: Date.now() }; executeSqliteQuerySync(e, n.insertInto("audit_identity_keys").values(o)); const s = { keyId: o.key_id, key: o.key }; registerAuditIdentityKeyForRedaction(s.key); stageSqliteTransactionState(e, { commit: () => {}, rollback: () => identityByDatabase.delete(e), invalidate: () => identityByDatabase.delete(e) }); identityByDatabase.set(e, s); return s; } /** Forget transaction-local key state after a failed or rolled-back write. */ function clearAuditIdentityKeyCacheForDatabase(e) { identityByDatabase.delete(e); } /** Produce a stable, domain-separated pseudonym without retaining raw identity bytes. */ function pseudonymizeAuditIdentity(e) { if (e.value === void 0 || e.value.length === 0) return; const t = createHmac("sha256", e.identity.key).update(JSON.stringify([ AUDIT_IDENTITY_DOMAIN, e.kind, e.channel, e.accountId ?? null, e.kind === "message" ? e.conversationId ?? null : null, e.value ]), "utf8").digest("hex"); return `hmac-sha256:v1:${e.identity.keyId}:${t}`; } /** Project one execution-identity ref without retaining its raw owner value. */ function pseudonymizeExecutionIdentityRef(e) { if (!e.scope || !e.value) throw new Error("execution identity HMAC scope and value must be non-empty"); const t = loadOrCreateAuditIdentityKey(e.db); const n = createHmac("sha256", t.key).update(JSON.stringify([ "openclaw.audit.execution-identity.v1", e.kind, e.scope, e.value ]), "utf8").digest("hex"); return `hmac-sha256:v1:${t.keyId}:${n}`; } //#endregion //#region src/audit/execution-decision-facts.ts const EXECUTION_DECISION_FACT_MAX_BYTES = 16384; const EXECUTION_DECISION_FACT_RETENTION_MS = 2592e6; const EXECUTION_DECISION_FACT_MAX_ROWS = 25e4; const EXECUTION_DECISION_FACT_PRUNE_BATCH_ROWS = 1024; const ensureExecutionDecisionFactSchema = createOpenClawStateSchemaEnsurer({ table: "execution_decision_facts", indexes: [ "execution_decision_facts_cursor_id_idx", "execution_decision_facts_context_occurred_idx", "execution_decision_facts_run_occurred_idx" ], endMarker: " ON execution_decision_facts (run_id, occurred_at, receipt_id);\n", operationLabel: "audit.execution-decision.schema.ensure" }); function decisionDb(e) { return getNodeSqliteKysely(e); } function hasExactExecutionContext(e, t) { if (!tableExists(e, "execution_identity_contexts")) return false; return Boolean(executeSqliteQueryTakeFirstSync(e, decisionDb(e).selectFrom("execution_identity_contexts").select("context_id").where("context_id", "=", t.contextId).where("execution_id", "=", t.executionId).where("run_id", "=", t.runId))); } function deleteExpiredDecisionFacts(e, t, n) { const r = decisionDb(e); const i = r.selectFrom("execution_decision_facts").select("receipt_id").where("occurred_at", "<", t - EXECUTION_DECISION_FACT_RETENTION_MS).orderBy("occurred_at", "asc").orderBy("receipt_id", "asc").limit(n); return executeSqliteQuerySync(e, r.deleteFrom("execution_decision_facts").where("receipt_id", "in", i)); } function pruneDecisionFactsAfterInsert(e, t, n) { const r = decisionDb(e); const i = deleteExpiredDecisionFacts(e, t, n.pruneBatchRows); const a = Math.max(0, n.pruneBatchRows - Number(i.numAffectedRows ?? 0n)); if (a === 0) return; const o = r.selectFrom("execution_decision_facts").select(["occurred_at", "receipt_id"]).orderBy("occurred_at", "desc").orderBy("receipt_id", "desc").offset(n.maxRows).limit(1).$asTuple("occurred_at", "receipt_id"); const s = r.selectFrom("execution_decision_facts").select("receipt_id").where((e) => e(e.refTuple("occurred_at", "receipt_id"), "<=", o)).orderBy("occurred_at", "asc").orderBy("receipt_id", "asc").limit(a); executeSqliteQuerySync(e, r.deleteFrom("execution_decision_facts").where("receipt_id", "in", s)); } /** Record one immutable fact only when its action owner has no native durable record. */ function recordExecutionDecisionFactInDatabase(e, t) { if (!validateDecisionReceiptV1(e)) throw new Error("execution decision fact must match DecisionReceiptV1"); if (e.source.owner === "operator_approvals") throw new Error("operator approvals must be read from their owner-native table"); if (!hasExactExecutionContext(openOpenClawStateDatabase(t).db, e)) throw new Error("execution decision fact requires an exact retained execution context"); const n = JSON.stringify(e); const r = Buffer.byteLength(n, "utf8"); if (r > EXECUTION_DECISION_FACT_MAX_BYTES) throw new Error("execution decision fact exceeds 16 KiB"); ensureExecutionDecisionFactSchema(t); return runOpenClawStateWriteTransaction(({ db: i }) => { const a = decisionDb(i); const o = executeSqliteQueryTakeFirstSync(i, a.selectFrom("execution_decision_facts").select(["receipt_json"]).where("receipt_id", "=", e.receiptId)); if (o) { if (o.receipt_json !== n) throw new Error("execution decision fact id conflicts with retained state"); return "existing"; } executeSqliteQuerySync(i, a.insertInto("execution_decision_facts").values((t) => ({ cursor_id: t.selectFrom("execution_decision_facts").select((e) => e(e.fn.coalesce(e.fn.max("cursor_id"), e.val(0)), "+", 1).as("cursor_id")), receipt_id: e.receiptId, context_id: e.contextId, execution_id: e.executionId, run_id: e.runId, action_id: e.actionId ?? null, action_family: e.action.family, decision_outcome: e.decision.outcome, coverage_state: e.enforcement.coverageState, reason_code: e.decision.reasonCode, owner: e.source.owner, source_ref: e.source.recordRef, occurred_at: e.occurredAt, receipt_bytes: r, receipt_json: n }))); pruneDecisionFactsAfterInsert(i, t.now ?? Date.now(), t.limits ?? { maxRows: EXECUTION_DECISION_FACT_MAX_ROWS, pruneBatchRows: EXECUTION_DECISION_FACT_PRUNE_BATCH_ROWS }); return "inserted"; }, t, { operationLabel: "audit.execution-decision.record" }); } /** Delete one bounded batch without creating the optional table. */ function pruneExpiredExecutionDecisionFactsInDatabase(e) { const t = e.database; const n = openOpenClawStateDatabase(t); if (!tableExists(n.db, "execution_decision_facts")) return 0; return runOpenClawStateWriteTransaction(({ db: t }) => Number(deleteExpiredDecisionFacts(t, e.now ?? Date.now(), EXECUTION_DECISION_FACT_PRUNE_BATCH_ROWS).numAffectedRows ?? 0n), { ...t, database: n }, { operationLabel: "audit.execution-decision.maintenance" }); } //#endregion export { pseudonymizeAuditIdentity as a, loadOrCreateAuditIdentityKey as i, recordExecutionDecisionFactInDatabase as n, pseudonymizeExecutionIdentityRef as o, clearAuditIdentityKeyCacheForDatabase as r, pruneExpiredExecutionDecisionFactsInDatabase as t };