openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
7 lines • 14.5 kB
JavaScript
import{s as normalizeNullableString}from"./string-coerce-CpTFcSwY.mjs";import{i as asOptionalObjectRecord,p as readStringField}from"./record-coerce-BTbqdJ3-.mjs";import{l as trackAsyncWork}from"./async-work-scope-DBcxYU4O.mjs";import{r as resolveStateDir}from"./state-dir-BwIClCab.mjs";import{a as redactSecrets}from"./redact-BT59pdZ_.mjs";import"./paths-D_FOvGon.mjs";import{n as executeExistingOpenClawStateRead}from"./openclaw-state-db-readonly-Cd5_cxBs.mjs";import{n as prepareSqliteAuditRecord}from"./sqlite-audit-record.kernel-BSKbkvEX.mjs";import{r as captureOpenClawStateWorkerContext}from"./openclaw-state-worker-context-Dx8YjqO2.mjs";import{i as runOpenClawStateWorkerOperation}from"./openclaw-state-worker-store-7se2aIrr.mjs";import{n as createSqliteAuditRecordWriter}from"./sqlite-audit-record-store.async-A8aF-EEi.mjs";import{t as createSqliteAuditRecordStore}from"./sqlite-audit-record-store-CI4WxhfZ.mjs";import{n as CONFIG_SNAPSHOT_SCOPE,t as CONFIG_SNAPSHOT_KEY}from"./config-journal-snapshot.kernel-ChySCljK.mjs";import{t as redactSensitiveArgv}from"./redact-argv-DyuaaIGr.mjs";import{t as isSensitiveConfigPath}from"./sensitive-paths-BrVSmum7.mjs";import{readFileSync}from"node:fs";import path from"node:path";import{createHmac,randomBytes,randomUUID}from"node:crypto";import fs$1 from"node:fs/promises";import{homedir}from"node:os";import{replaceFileAtomic}from"@openclaw/fs-safe/atomic";
//!src/config/config-journal-snapshot.ts
const CONFIG_JOURNAL_FINGERPRINT_KEY_FILENAME=`config-journal-fingerprint.key`;const CONFIG_JOURNAL_FINGERPRINT_KEY_BYTES=32;const CONFIG_JOURNAL_REDACTION_MARKER=`***`;const configJournalFingerprintKeys=/* @__PURE__ */ new Map;async function loadConfigJournalFingerprintKey(e){const t=resolveConfigAuditStoreContext(e);const n=resolveStateDir(t.env,t.homedir);const r=path.join(n,CONFIG_JOURNAL_FINGERPRINT_KEY_FILENAME);const i=configJournalFingerprintKeys.get(r);if(i)return i;const a=(async()=>{try{let e;try{e=await fs$1.readFile(r)}catch(t){if(t.code!==`ENOENT`)throw t;await fs$1.mkdir(n,{recursive:true,mode:448});const i=randomBytes(CONFIG_JOURNAL_FINGERPRINT_KEY_BYTES);try{await fs$1.writeFile(r,i,{flag:`wx`,mode:384});e=i}catch(t){if(t.code!==`EEXIST`)throw t;e=await fs$1.readFile(r)}}if(e.length!==CONFIG_JOURNAL_FINGERPRINT_KEY_BYTES)throw new Error(`Invalid config journal fingerprint key`);await fs$1.chmod(r,384);configJournalFingerprintKeys.set(r,e);return e}catch{configJournalFingerprintKeys.delete(r);return null}})();configJournalFingerprintKeys.set(r,a);return a}function fingerprintConfigSnapshotValue(e,t){if(!t)return CONFIG_JOURNAL_REDACTION_MARKER;const n=JSON.stringify(e);return`fp:${createHmac(`sha256`,t).update(n??String(e)).digest(`hex`).slice(0,12)}`}function fingerprintConfigSnapshotLeaves(e,t){if(Array.isArray(e))return e.map(e=>fingerprintConfigSnapshotLeaves(e,t));if(e&&typeof e===`object`)return Object.fromEntries(Object.entries(e).map(([e,n])=>[e,fingerprintConfigSnapshotLeaves(n,t)]));return fingerprintConfigSnapshotValue(e,t)}async function fingerprintConfigSnapshotAuthoredConfig(e,t){return fingerprintConfigSnapshotLeaves(e,await loadConfigJournalFingerprintKey(t))}function fingerprintConfigSnapshotAuthoredConfigReadOnlySync(e,t){const n=resolveConfigAuditStoreContext(t);let r=null;try{const e=readFileSync(path.join(resolveStateDir(n.env,n.homedir),CONFIG_JOURNAL_FINGERPRINT_KEY_FILENAME));if(e.length===CONFIG_JOURNAL_FINGERPRINT_KEY_BYTES)r=e}catch{}return fingerprintConfigSnapshotLeaves(e,r)}function resolveConfigAuditStoreContext(e){return{env:e?.env??process.env,homedir:e?.homedir??homedir}}function resolveConfigAuditStoreEnv(e){return{...e.env,OPENCLAW_STATE_DIR:resolveStateDir(e.env,e.homedir)}}function configSnapshotAuditRecordMatchesPath(e,t){return e?.configPath===path.resolve(t)}async function prepareConfigSnapshotAuditRecord(e){return{configPath:path.resolve(e.configPath),rawHash:e.rawHash,fingerprintedAuthoredConfig:await fingerprintConfigSnapshotAuthoredConfig(e.authoredConfig,e)}}async function readLatestConfigSnapshotAuditRecordAsync(e,t){t?.();try{const n=resolveConfigAuditStoreEnv(resolveConfigAuditStoreContext(e));const r=captureOpenClawStateWorkerContext({env:n});const i=await executeExistingOpenClawStateRead({env:n},{type:`config.snapshot.read`},{context:r,current:true});r.admission.assertCurrent();t?.();return i?.snapshot??null}catch{t?.();return null}}async function upsertConfigSnapshotAuditRecordAsync(e,t){t?.();try{const n=await prepareConfigSnapshotAuditRecord(e);return await writeConfigSnapshotAuditRecord({...e,snapshot:n},t)?n:null}catch{t?.();return null}}async function writeConfigSnapshotAuditRecord(e,t){t?.();try{const n=resolveConfigAuditStoreEnv(resolveConfigAuditStoreContext(e));const r=captureOpenClawStateWorkerContext({env:n});const i={record:e.snapshot===null?null:prepareSqliteAuditRecord(CONFIG_SNAPSHOT_SCOPE,{key:CONFIG_SNAPSHOT_KEY,value:e.snapshot,createdAt:Date.now()}),expectedPayloadJson:e.expectedSnapshot===null?null:JSON.stringify(e.expectedSnapshot)};const a=await runOpenClawStateWorkerOperation(r,e=>e.execute({type:`config.snapshot.upsert`,input:i}),{assertCurrent:t});r.admission.assertCurrent();t?.();return a}catch{t?.();return false}}async function restoreConfigSnapshotAuditRecordAsync(e,t){await writeConfigSnapshotAuditRecord(e,t)}
//!src/config/io.audit.ts
const CONFIG_AUDIT_ARGV_CAP=8;const CONFIG_AUDIT_PATH_CAP=64;const CONFIG_AUDIT_ISSUE_CAP=64;const CONFIG_SET_VALUE_OPTIONS=/* @__PURE__ */ new Set([`--batch-file`,`--batch-json`,`--container`,`--expect-current-json`,`--log-level`,`--profile`,`--provider-allowlist`,`--provider-arg`,`--provider-command`,`--provider-env`,`--provider-max-bytes`,`--provider-max-output-bytes`,`--provider-mode`,`--provider-no-output-timeout-ms`,`--provider-pass-env`,`--provider-path`,`--provider-source`,`--provider-timeout-ms`,`--provider-trusted-dir`,`--ref-id`,`--ref-provider`,`--ref-source`,`--section`]);function findConfigPositionals(e,t,n){const r=[];let i=false;for(let a=t;a<e.length&&r.length<n;a+=1){const t=e[a];if(t===void 0)break;if(!i&&t===`--`){i=true;continue}if(!i&&t.startsWith(`-`)){const e=t.indexOf(`=`);const n=e<0?t:t.slice(0,e);if(e<0&&CONFIG_SET_VALUE_OPTIONS.has(n))a+=1;continue}r.push(a)}return r}function redactConfigAuditArgv(e){const t=redactSensitiveArgv(e);let n=-1;for(let e=0;e<t.length;e+=1){if(t[e]!==`config`)continue;const[r]=findConfigPositionals(t,e+1,1);if(r!==void 0&&t[r]===`set`){n=r;break}}if(n<0)return t;for(let e=n+1;e<t.length;e+=1){const n=t[e];if(n===void 0)break;if(n===`--batch-json`&&e+1<t.length){t[e+1]=`***`;e+=1;continue}if(n.startsWith(`--batch-json=`))t[e]=`--batch-json=***`}const[r,i]=findConfigPositionals(t,n+1,2);if(r===void 0||i===void 0)return t;const a=t[r];if(a!==void 0&&isSensitiveConfigPath(a))t[i]=`***`;return t}function capArgv(e){if(!Array.isArray(e))return[];return e.slice(0,CONFIG_AUDIT_ARGV_CAP)}const CONFIG_AUDIT_SCOPE=`config-audit`;const CONFIG_AUDIT_MAX_ENTRIES=5e4;const CONFIG_AUDIT_STORE_LABEL=`SQLite diagnostic_events/config-audit state (latest 50000 rows)`;const LEGACY_CONFIG_AUDIT_LOG_FILENAME=[`config-audit`,`jsonl`].join(`.`);function createConfigObserveAuditRecord(e){const{current:t,lastKnownGood:n,backup:r}=e;return{ts:t.observedAt,source:`config-io`,event:`config.observe`,phase:`read`,configPath:e.configPath,...resolveConfigAuditProcessInfo(),exists:true,valid:e.valid,hash:t.hash,bytes:t.bytes,mtimeMs:t.mtimeMs,ctimeMs:t.ctimeMs,dev:t.dev,ino:t.ino,mode:t.mode,nlink:t.nlink,uid:t.uid,gid:t.gid,hasMeta:t.hasMeta,gatewayMode:t.gatewayMode,suspicious:e.suspicious,lastKnownGoodHash:n?.hash??null,lastKnownGoodBytes:n?.bytes??null,lastKnownGoodMtimeMs:n?.mtimeMs??null,lastKnownGoodCtimeMs:n?.ctimeMs??null,lastKnownGoodDev:n?.dev??null,lastKnownGoodIno:n?.ino??null,lastKnownGoodMode:n?.mode??null,lastKnownGoodNlink:n?.nlink??null,lastKnownGoodUid:n?.uid??null,lastKnownGoodGid:n?.gid??null,lastKnownGoodGatewayMode:n?.gatewayMode??null,backupHash:r?.hash??null,backupBytes:r?.bytes??null,backupMtimeMs:r?.mtimeMs??null,backupCtimeMs:r?.ctimeMs??null,backupDev:r?.dev??null,backupIno:r?.ino??null,backupMode:r?.mode??null,backupNlink:r?.nlink??null,backupUid:r?.uid??null,backupGid:r?.gid??null,backupGatewayMode:r?.gatewayMode??null,clobberedPath:e.clobberedPath??null,restoredFromBackup:e.restoredFromBackup??false,restoredBackupPath:e.restoredBackupPath??null,restoreErrorCode:e.restoreErrorCode??null,restoreErrorMessage:e.restoreErrorMessage??null}}function resolveConfigAuditProcessInfo(e){const t=e||{pid:process.pid,ppid:process.ppid,cwd:process.cwd(),argv:process.argv,execArgv:process.execArgv};return{...t,argv:redactConfigAuditArgv(capArgv(t.argv)),execArgv:redactConfigAuditArgv(capArgv(t.execArgv))}}function resolveLegacyConfigAuditLogPath(e,t){return path.join(resolveStateDir(e,t),`logs`,LEGACY_CONFIG_AUDIT_LOG_FILENAME)}function formatConfigOverwriteLogMessage(e){const t=typeof e.changedPathCount===`number`?`, changedPaths=${e.changedPathCount}`:``;return`Config overwrite: ${e.configPath} (sha256 ${e.previousHash??`unknown`} -> ${e.nextHash}, backup=${e.configPath}.bak${t})`}function createConfigWriteAuditRecordBase(e){const t=resolveConfigAuditProcessInfo(e.processInfo);return{ts:e.now??(/* @__PURE__ */ new Date()).toISOString(),source:`config-io`,event:`config.write`,configPath:e.configPath,pid:t.pid,ppid:t.ppid,cwd:t.cwd,argv:t.argv,execArgv:t.execArgv,watchMode:e.env.OPENCLAW_WATCH_MODE===`1`,watchSession:normalizeNullableString(e.env.OPENCLAW_WATCH_SESSION),watchCommand:normalizeNullableString(e.env.OPENCLAW_WATCH_COMMAND),existsBefore:e.existsBefore,previousHash:e.previousHash,nextHash:e.nextHash,previousBytes:e.previousBytes,nextBytes:e.nextBytes,previousDev:e.previousMetadata.dev,previousIno:e.previousMetadata.ino,previousMode:e.previousMetadata.mode,previousNlink:e.previousMetadata.nlink,previousUid:e.previousMetadata.uid,previousGid:e.previousMetadata.gid,changedPathCount:typeof e.changedPathCount===`number`?e.changedPathCount:null,...e.changedPaths?{changedPaths:capConfigAuditPaths(e.changedPaths)}:{},...e.origin?{origin:e.origin}:{},hasMetaBefore:e.hasMetaBefore,hasMetaAfter:e.hasMetaAfter,gatewayModeBefore:e.gatewayModeBefore,gatewayModeAfter:e.gatewayModeAfter,suspicious:e.suspicious}}function capConfigAuditEntries(e,t){if(e.length<=t)return[...e];const n=Math.max(0,t-1);return[...e.slice(0,n),`…+${e.length-n} more`]}function capConfigAuditPaths(e){return capConfigAuditEntries([...new Set(e)].toSorted(),CONFIG_AUDIT_PATH_CAP)}function capConfigAuditIssues(e){return capConfigAuditEntries(e,CONFIG_AUDIT_ISSUE_CAP)}function finalizeConfigWriteAuditRecord(e){const t=asOptionalObjectRecord(e.err);const n=readStringField(t,`code`);const r=readStringField(t,`message`);const i=e.result!==`failed`&&e.result!==`rejected`;const a=i?e.nextMetadata:void 0;return{...e.base,result:e.result,nextHash:i?e.base.nextHash:null,nextBytes:i?e.base.nextBytes:null,nextDev:a==null?null:a.dev,nextIno:a==null?null:a.ino,nextMode:a==null?null:a.mode,nextNlink:a==null?null:a.nlink,nextUid:a==null?null:a.uid,nextGid:a==null?null:a.gid,...n!==void 0?{errorCode:n}:{},...r!==void 0?{errorMessage:r}:{}}}async function scrubConfigAuditLog(e){const t=resolveLegacyConfigAuditLogPath(e.env,e.homedir);let n;try{n=await fs$1.readFile(t,`utf-8`)}catch(e){if(e?.code===`ENOENT`)return{scanned:0,rewritten:0,skipped:0,aborted:false};throw e}const r=Buffer.byteLength(n,`utf-8`);let i=0;let a=0;let o=0;const s=[];const c=n.split(`
`);for(const e of c){if(e.length===0){s.push(e);continue}i+=1;let t;try{t=JSON.parse(e)}catch{s.push(e);o+=1;continue}if(!t||typeof t!==`object`||Array.isArray(t)){s.push(e);o+=1;continue}const n=t;let r=false;for(const e of[`argv`,`execArgv`]){const t=n[e];if(!Array.isArray(t))continue;if(!t.every(e=>typeof e===`string`))continue;const i=redactConfigAuditArgv(t);if(i.some((e,n)=>e!==t[n])){n[e]=i;r=true}}if(r){a+=1;s.push(JSON.stringify(n))}else s.push(e)}if(a===0||e.dryRun)return{scanned:i,rewritten:a,skipped:o,aborted:false};const l=/* @__PURE__ */ new Error(`Config audit log changed before scrub publication`);try{const e=await fs$1.realpath(path.dirname(t));await replaceFileAtomic({filePath:path.join(e,path.basename(t)),content:s.join(`
`),mode:384&~process.umask(),dirMode:`preserve`,beforeRename:async({filePath:e})=>{if(await fs$1.stat(e).then(e=>e.size,()=>void 0)!==r)throw l}})}catch(e){if(e===l)return{scanned:i,rewritten:a,skipped:o,aborted:true};throw e}return{scanned:i,rewritten:a,skipped:o,aborted:false}}function openConfigAuditStore(e){return createSqliteAuditRecordStore({scope:CONFIG_AUDIT_SCOPE,maxEntries:CONFIG_AUDIT_MAX_ENTRIES,env:e})}function readRecentConfigAuditRecords(e){try{return openConfigAuditStore(resolveConfigAuditStoreEnv(e)).latest({limit:e.limit}).map(({value:e})=>e)}catch{return[]}}function configAuditEntryKey(e){return`${e.ts}:${e.event}:${randomUUID()}`}function sanitizeConfigAuditRecord(e){const t={...e};if(t.event!==`config.external`){t.argv=redactConfigAuditArgv(capArgv(t.argv));t.execArgv=redactConfigAuditArgv(capArgv(t.execArgv))}return redactSecrets(t)}function captureConfigAuditAppender(e,t){let n;try{n={writer:createSqliteAuditRecordWriter({scope:CONFIG_AUDIT_SCOPE,maxEntries:CONFIG_AUDIT_MAX_ENTRIES,env:resolveConfigAuditStoreEnv(e),assertCurrent:t})}}catch(e){n={error:e}}return async e=>{t?.();try{if(`error`in n)throw n.error;const t=sanitizeConfigAuditRecord(e);await n.writer.register(configAuditEntryKey(t),t,Date.parse(t.ts))}catch{t?.()}}}async function appendConfigAuditRecord(e,t){await captureConfigAuditAppender(e,t)(e.record)}function enqueueConfigAuditRecord(e){trackAsyncWork(()=>appendConfigAuditRecord(e)).catch(()=>{})}export{upsertConfigSnapshotAuditRecordAsync as S,configSnapshotAuditRecordMatchesPath as _,capConfigAuditIssues as a,readLatestConfigSnapshotAuditRecordAsync as b,createConfigObserveAuditRecord as c,finalizeConfigWriteAuditRecord as d,formatConfigOverwriteLogMessage as f,scrubConfigAuditLog as g,sanitizeConfigAuditRecord as h,appendConfigAuditRecord as i,createConfigWriteAuditRecordBase as l,resolveLegacyConfigAuditLogPath as m,CONFIG_AUDIT_SCOPE as n,capConfigAuditPaths as o,readRecentConfigAuditRecords as p,CONFIG_AUDIT_STORE_LABEL as r,captureConfigAuditAppender as s,CONFIG_AUDIT_MAX_ENTRIES as t,enqueueConfigAuditRecord as u,fingerprintConfigSnapshotAuthoredConfig as v,restoreConfigSnapshotAuditRecordAsync as x,fingerprintConfigSnapshotAuthoredConfigReadOnlySync as y};