UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

3 lines • 15.2 kB
import{a as getOpenClawDatabaseMaintenanceScope}from"./openclaw-state-maintenance-context-D-pYfco8.mjs";import{n as isPostgresSqlConnection}from"./sql-connection-nx8lLUJM.mjs";import{r as hasSqlitePostCommitScope,s as stageSqliteTransactionState}from"./sqlite-post-commit-CAVf6ZAG.mjs";import{a as executeSqliteQueryTakeFirstSync,i as executeSqliteQuerySync,s as getNodeSqliteKysely}from"./kysely-sync-R08Pt8qn.mjs";import{a as tableExists}from"./openclaw-state-db-schema-helpers-rYTimzjJ.mjs";import{t as CLIENT_CREDENTIAL_CUTOVER_SCHEMA_VERSION}from"./openclaw-state-db-contract-G6fQNIi2.mjs";import{r as assertStateDatabaseAccessAllowed}from"./gateway-state-owner-D_klysuh.mjs";import{a as runSqliteImmediateTransactionSync}from"./sqlite-transaction-CON-dGDv.mjs";import{i as getUpdateDoctorMigrationSource,n as beginUpdateSqliteCompanion,r as getDoctorMigrationBackup}from"./update-doctor-migration-context-DWFAKZNL.mjs";import{n as readEngineAnchor}from"./open-1OjrnB9v.mjs";import{o as readStateSchemaContentVersion}from"./openclaw-state-db-schema-version-DreEd78i.mjs";import{i as CLIENT_CREDENTIAL_SOURCE_TABLES,r as CLIENT_CREDENTIAL_SCHEMA_VERSION}from"./client-credential-schema-DfsAsx4-.mjs";import{t as chunkItems}from"./chunk-items-CsdD1uHV.mjs";import{a as validateSource,i as sourceRows,n as hashClientCredentialRows,r as resolveClientCredentialLegacyImportClaims,t as extractSocket}from"./client-credential-migration-data-CMSJJDjr.mjs";import{n as resolveStateClientCredentialEnvironment}from"./client-credential-paths-D__QHGyH.mjs";import{a as serializeClientCredentialReceipt,i as readClientCredentialFileIdentity,t as CLIENT_CREDENTIAL_LEGACY_KEYS}from"./client-credential-receipt-CEFy8dbp.mjs";import{d as writeClientCredentialReceipt,i as openClientCredentialCustodyAsync,r as openClientCredentialCustody,u as readClientCredentialReceipt}from"./client-credential-store-BZeU9erm.mjs";import path from"node:path"; //!src/infra/client-credential-migration.ts function postgresBootstrapProvenance(e){const t=isPostgresSqlConnection(e);const n=readEngineAnchor(t?e.anchor:e,`identity`,t);if(!n)return;const r=n[0];if(n.length!==1||!r||r.engine!==`postgres`||typeof r.store_id!==`string`||!r.store_id.trim()||typeof r.schema!==`string`||!r.schema.trim())throw new Error(`Invalid PostgreSQL anchor identity during client credential bootstrap.`);return{kind:`canonical`,engine:`postgres`,identity:r.store_id,generation:`bootstrap:${r.store_id}`,sha256:hashClientCredentialRows({identities:[],tokens:[],origins:[],approvals:[]}),destinationVersion:1}}function readClientCredentialBootstrapSource(e,t){const n=postgresBootstrapProvenance(e);if(n)return n;const r=e.prepare(`SELECT created_at FROM schema_meta WHERE meta_key = 'primary'`).get();if(!r)throw new Error(`Shared credential source identity was not published.`);return{kind:`canonical`,engine:`sqlite`,identity:`${t}:${String(r.created_at)}`,generation:`bootstrap:${String(r.created_at)}`,sha256:hashClientCredentialRows({identities:[],tokens:[],origins:[],approvals:[]}),destinationVersion:1}}function isPristineSqliteBootstrap(e,t){const n=t?.receipt.source;const r=t?.receipt.sharedFile;if(t?.phase!==`complete`||n?.kind!==`canonical`||n.engine!==`sqlite`||!r||!n.generation.startsWith(`bootstrap:`)||n.generation===`bootstrap:`||n.identity!==`${r.path}:${n.generation.slice(10)}`||n.sha256!==hashClientCredentialRows({identities:[],tokens:[],origins:[],approvals:[]})||Object.keys(t.receipt.legacyImports).length!==0)return false;const i=getNodeSqliteKysely(e);return[`device_identities`,`device_auth_tokens`,`gateway_origin_device_tokens`,`native_exec_socket_credentials`].every(t=>!executeSqliteQueryTakeFirstSync(e,i.selectFrom(t).selectAll().limit(1)))}async function prepareClientCredentialMigrationCustody(e){const t=resolveStateClientCredentialEnvironment(e);return t?openClientCredentialCustodyAsync(t,{createIfMissing:e.fromVersion<29,migration:true}):void 0}async function prepareClientCredentialRecoveryCustody(e){const t=resolveStateClientCredentialEnvironment(e);if(!t)return;const n=await openClientCredentialCustodyAsync(t,{migration:true});if(n)return{kind:`existing`,custody:n};if(!e.rebindMissing)return;const r=await openClientCredentialCustodyAsync(t,{createIfMissing:true,migration:true});if(!r?.created){r?.close();throw new Error(`Local credentials appeared during recovery; retry without rebinding.`)}return{kind:`replacement`,custody:r}}function bindFreshClientCredentialStore(e,t){if(!e.isTransaction||!hasSqlitePostCommitScope(e))throw new Error(`Client credential bootstrap has no source commit lifecycle.`);const n=resolveStateClientCredentialEnvironment(t);if(!n)return;const r=postgresBootstrapProvenance(e);const i=t.custody===void 0?openClientCredentialCustody(n,{createIfMissing:true,migration:true}):t.custody;if(!i)throw new Error(`Cannot acquire local credentials during shared bootstrap.`);const close=()=>{if(t.custody===void 0)i.close()};try{const n=beginUpdateSqliteCompanion(i.database,i.path,i.created);const a=readClientCredentialReceipt(i.database);const o=getNodeSqliteKysely(i.database);const s=executeSqliteQueryTakeFirstSync(i.database,o.selectFrom(`client_credential_migration`).selectAll().where(`version`,`=`,1));const c=readClientCredentialFileIdentity(t.path);if(!c)throw new Error(`Shared credential source is missing during bootstrap.`);const l=a?.receipt.source;const u=a?.receipt.sharedFile;const d=u?.path===c.path&&u.dev===c.dev&&u.ino===c.ino;const f=r&&l?.kind===r.kind&&l.engine===r.engine&&l.identity===r.identity&&l.generation===r.generation&&l.sha256===r.sha256&&l.destinationVersion===r.destinationVersion&&d;const p=!r&&isPristineSqliteBootstrap(i.database,a);if(l&&!f&&!p||u&&!d&&!p)throw new Error(`Existing client credentials belong to a previous shared database; run openclaw doctor --fix.`);const m={format:1,source:p&&!d?null:a?.receipt.source??null,sharedFile:c,legacyImports:a?.receipt.legacyImports??{}};runSqliteImmediateTransactionSync(i.database,()=>writeClientCredentialReceipt(i.database,m,`copied`));if(!stageSqliteTransactionState(e,{stage(){},commit(){try{m.source=readClientCredentialBootstrapSource(e,c.path);runSqliteImmediateTransactionSync(i.database,()=>writeClientCredentialReceipt(i.database,m,`complete`));n?.complete()}finally{close()}},rollback(){try{runSqliteImmediateTransactionSync(i.database,()=>{if(s)executeSqliteQuerySync(i.database,o.insertInto(`client_credential_migration`).values(s).onConflict(e=>e.column(`version`).doUpdateSet(s)));else executeSqliteQuerySync(i.database,o.deleteFrom(`client_credential_migration`).where(`version`,`=`,1))});n?.complete()}finally{close()}},invalidate:close}))throw new Error(`Client credential bootstrap has no source commit lifecycle.`)}catch(e){close();throw e}}function recoverClientCredentialStore(e,t){const n=e.prepare(`SELECT created_at FROM schema_meta WHERE meta_key = 'primary'`).get();if(readStateSchemaContentVersion(e)<29||CLIENT_CREDENTIAL_SOURCE_TABLES.slice(0,3).some(t=>tableExists(e,t)))throw new Error(`Shared credentials are still authoritative; complete their migration before using the local store.`);const r=resolveStateClientCredentialEnvironment(t);if(!r)return;const i=t.recovery?.kind===`replacement`?void 0:t.recovery?.custody??(t.custody===void 0?openClientCredentialCustody(r,{createIfMissing:false,migration:true}):t.custody);if(!i){if(t.rebindMissing===true&&isPostgresSqlConnection(e)&&(t.custody===void 0||t.recovery)){const n=readClientCredentialFileIdentity(t.path);if(!n)throw new Error(`Shared credential source is missing; restore its matching backup.`);const i={format:1,source:readClientCredentialBootstrapSource(e,n.path),sharedFile:n,legacyImports:{}};for(const e of CLIENT_CREDENTIAL_LEGACY_KEYS)i.legacyImports[e]={sha256:null};const a=t.recovery?.kind===`replacement`?t.recovery.custody:openClientCredentialCustody(r,{createIfMissing:true,migration:true});try{if(!a?.created)throw new Error(`Local credentials appeared during recovery; retry without rebinding.`);const e=beginUpdateSqliteCompanion(a.database,a.path,a.created);a.transaction(()=>writeClientCredentialReceipt(a.database,i,`complete`));e?.complete();return`rebound`}finally{if(!t.recovery)a?.close()}}throw new Error(isPostgresSqlConnection(e)?`Local credentials are missing; restore the matching client credential backup or run openclaw doctor --fix to create new local identities.`:`Local credentials are missing; restore the matching client credential backup.`)}try{const r=readClientCredentialReceipt(i.database);if(!r)throw new Error(`Local credential receipt is missing; restore its matching backup.`);const a=readClientCredentialFileIdentity(t.path);if(!a)throw new Error(`Shared credential source is missing; restore its matching backup.`);const o=r.receipt.source;const s=r.receipt.sharedFile;const c=s?.path===a.path&&s.dev===a.dev&&s.ino===a.ino;if(!o&&!c)throw new Error(`Local credentials do not match the shared database; restore their matched backup.`);if(o?.kind===`independent`)throw new Error(`Independent native credentials require copy admission, not canonical recovery.`);const l=o?.kind===`canonical`&&o.engine===`native-v0`&&c;if(o){const t=isPostgresSqlConnection(e)?String(readEngineAnchor(e.anchor,`identity`,true)?.[0]?.store_id):`${a.path}:${String(n?.created_at??0)}`;if(o.identity!==t&&!l)throw new Error(`Local credentials do not match the shared database; restore their matched backup.`);if(l){o.engine=isPostgresSqlConnection(e)?`postgres`:`sqlite`;o.identity=t}}if(r.phase===`complete`&&c&&!l&&o)return;r.receipt.source??=readClientCredentialBootstrapSource(e,a.path);r.receipt.sharedFile=a;i.transaction(()=>writeClientCredentialReceipt(i.database,r.receipt,`complete`))}finally{if(t.custody===void 0&&!t.recovery)i.close()}}function prepareClientCredentialMigration(e,t){if(t.fromVersion>=29||isPostgresSqlConnection(e)&&t.fromVersion!==29-1)return;if(!e.isTransaction)throw new Error(`Client credential migration requires the shared owner's transaction.`);const n=t.fromVersion===0;if(n&&!CLIENT_CREDENTIAL_SOURCE_TABLES.some(t=>tableExists(e,t))){bindFreshClientCredentialStore(e,t);return}const r=resolveStateClientCredentialEnvironment(t);const i=getOpenClawDatabaseMaintenanceScope();const a=t.capture??getUpdateDoctorMigrationSource(t.path)??(isPostgresSqlConnection(e)?void 0:getDoctorMigrationBackup(e,{path:t.path,env:r??t.env,tables:[...CLIENT_CREDENTIAL_SOURCE_TABLES,`sqlite_stat1`,`sqlite_stat4`]})?.capture);if(!i?.ownsSchemaMaintenance||!a||a.path!==t.path||!a.generation)throw new Error(`Client credentials require backed-up migration custody; stop the app and run openclaw doctor --fix.`);if(!r)throw new Error(`Client credentials in an auxiliary shared database require explicit recovery; preserve the source database.`);assertStateDatabaseAccessAllowed(t.path);i.assertAdmission();a.assertCurrent();const o=sourceRows(e,n||t.fromVersion<29-1);const s=!n||tableExists(e,`device_auth_tokens`);validateSource(o,n?`require-valid`:`preserve-for-doctor`);const c=extractSocket(o.approvals[0]);const l=readClientCredentialFileIdentity(t.path);if(!l)throw new Error(`Client credential source disappeared before migration.`);const u=tableExists(e,`schema_meta`);const d=t.fromVersion===1&&!u;const f=(n||d)&&!u?void 0:e.prepare(`SELECT created_at FROM schema_meta WHERE meta_key = 'primary'`).get();const p=isPostgresSqlConnection(e)?readEngineAnchor(e.anchor,`identity`,true)?.[0]:void 0;const m={format:1,source:{kind:`canonical`,engine:isPostgresSqlConnection(e)?`postgres`:n?`native-v0`:`sqlite`,identity:p?String(p.store_id):`${l.path}:${String(f?.created_at??0)}`,generation:a.generation,sha256:hashClientCredentialRows(o,n?{authTablePresent:s}:void 0),destinationVersion:1},sharedFile:l,legacyImports:resolveClientCredentialLegacyImportClaims(e,{identities:o.identities,nativeBootstrap:n,authTablePresent:s})};const h=t.custody===void 0?openClientCredentialCustody(r,{createIfMissing:true,migration:true}):t.custody;if(!h)throw new Error(`Client credential migration could not acquire local custody.`);const close=()=>{if(t.custody===void 0)h.close()};try{const t=beginUpdateSqliteCompanion(h.database,h.path,h.created);runSqliteImmediateTransactionSync(h.database,()=>{const e=h.database;const t=readClientCredentialReceipt(e);if(t)m.legacyImports={...m.legacyImports,...t.receipt.legacyImports};if(t?.phase===`complete`&&t.receipt.source?.kind===`independent`&&n&&t.receipt.source.identity===`${l.dev}:${l.ino}`&&t.receipt.source.sha256===m.source.sha256&&t.receipt.sharedFile?.path===l.path&&t.receipt.sharedFile.dev===l.dev&&t.receipt.sharedFile.ino===l.ino){writeClientCredentialReceipt(e,m,`copied`);return}const r=getNodeSqliteKysely(e);for(const t of[`device_identities`,`device_auth_tokens`,`gateway_origin_device_tokens`,`native_exec_socket_credentials`,`client_credential_migration`])executeSqliteQuerySync(e,r.deleteFrom(t));for(const t of chunkItems(o.identities,500))executeSqliteQuerySync(e,r.insertInto(`device_identities`).values(t));for(const t of chunkItems(o.tokens,500))executeSqliteQuerySync(e,r.insertInto(`device_auth_tokens`).values(t));for(const t of chunkItems(o.origins,500))executeSqliteQuerySync(e,r.insertInto(`gateway_origin_device_tokens`).values(t));if(c.socket)executeSqliteQuerySync(e,r.insertInto(`native_exec_socket_credentials`).values(c.socket));executeSqliteQuerySync(e,r.insertInto(`client_credential_migration`).values({version:1,source_store:serializeClientCredentialReceipt(m,path.dirname(path.dirname(h.path))),phase:`copied`,updated_at_ms:Date.now()}))});if(!stageSqliteTransactionState(e,{stage(){},prepareCommit(){if(!d)return;const t=e.prepare(`SELECT created_at FROM schema_meta WHERE meta_key = 'primary'`).get();if(!t||!m.source)throw new Error(`Historical client credential source identity was not published.`);m.source.identity=`${l.path}:${String(t.created_at)}`;runSqliteImmediateTransactionSync(h.database,()=>writeClientCredentialReceipt(h.database,m,`copied`))},commit(){try{if(n&&!isPostgresSqlConnection(e)&&tableExists(e,`schema_meta`)){const t=e.prepare(`SELECT created_at FROM schema_meta WHERE meta_key = 'primary'`).get();if(m.source){m.source.engine=`sqlite`;m.source.identity=`${l.path}:${String(t?.created_at??0)}`}}runSqliteImmediateTransactionSync(h.database,()=>writeClientCredentialReceipt(h.database,m,`complete`));t?.complete()}finally{close()}},rollback:close,invalidate:close}))throw new Error(`Client credential migration has no source commit lifecycle.`);i.assertAdmission();a.assertCurrent();if(o.approvals[0]&&c.policy!==void 0)executeSqliteQuerySync(e,getNodeSqliteKysely(e).updateTable(`exec_approvals_config`).set({raw_json:c.policy,socket_path:null,has_socket_token:0}).where(`config_key`,`=`,`current`));e.exec(`DROP TABLE IF EXISTS device_auth_tokens; DROP TABLE IF EXISTS device_identities; DROP TABLE IF EXISTS gateway_origin_device_tokens;`)}catch(e){close();throw e}}export{readClientCredentialBootstrapSource as a,prepareClientCredentialRecoveryCustody as i,prepareClientCredentialMigration as n,recoverClientCredentialStore as o,prepareClientCredentialMigrationCustody as r,bindFreshClientCredentialStore as t};