@@ -10,8 +10,13 @@ import { resolveAgentDir, resolveDefaultAgentDir, listAgentIds } from "../agents
1010import { AUTH_STORE_VERSION } from "../agents/auth-profiles/constants.js" ;
1111import {
1212 clearAuthProfileMigrationDiagnostics ,
13+ listLegacyAuthProfileArchives ,
1314 resolveLegacyOAuthPath ,
1415} from "../agents/auth-profiles/legacy-source-diagnostic.js" ;
16+ import {
17+ areOAuthCredentialsEquivalent ,
18+ hasMatchingOAuthIdentity ,
19+ } from "../agents/auth-profiles/oauth-shared.js" ;
1520import {
1621 applyLegacyAuthStore ,
1722 coerceLegacyAuthStore ,
@@ -45,6 +50,7 @@ import type { AuthProfileConfig } from "../config/types.auth.js";
4550import type { OpenClawConfig } from "../config/types.openclaw.js" ;
4651import { coerceSecretRef } from "../config/types.secrets.js" ;
4752import { loadJsonFile } from "../infra/json-file.js" ;
53+ import { readLegacyMigrationReceipt } from "../infra/state-migrations.receipts.js" ;
4854import type { OpenClawAgentDatabase } from "../state/openclaw-agent-db.js" ;
4955import { shortenHomePath } from "../utils.js" ;
5056import {
@@ -974,6 +980,7 @@ export async function maybeMigrateAuthProfileJsonStoresToSqlite(params: {
974980 prompter : Pick < DoctorPrompter , "confirmAutoFix" > ;
975981 now ?: ( ) => number ;
976982 env ?: NodeJS . ProcessEnv ;
983+ openAICodexAuthProfileIdMap ?: ReadonlyMap < string , string > ;
977984 deps ?: {
978985 loadPersistedAuthProfileStore ?: typeof loadPersistedAuthProfileStore ;
979986 } ;
@@ -1053,7 +1060,11 @@ export async function maybeMigrateAuthProfileJsonStoresToSqlite(params: {
10531060 return result ;
10541061 }
10551062
1056- const openAIProfileIdMap = collectOpenAICodexAuthProfileStoreIdMap ( { cfg : params . cfg , env } ) ;
1063+ // Config, credential import, and session repair must share one collision
1064+ // decision; archived legacy JSON cannot recreate it after migration.
1065+ const openAIProfileIdMap =
1066+ params . openAICodexAuthProfileIdMap ??
1067+ collectOpenAICodexAuthProfileStoreIdMap ( { cfg : params . cfg , env } ) ;
10571068 for ( const candidate of detected ) {
10581069 let releaseSources : ( ( ) => void ) | undefined ;
10591070 try {
@@ -1761,7 +1772,100 @@ function canonicalizeLegacyOpenAIAuthStore(
17611772 : null ;
17621773}
17631774
1764- /** Collects deterministic legacy-to-canonical OpenAI profile ids across all agent stores. */
1775+ function recoverArchivedOpenAICodexAuthProfileIdMap ( params : {
1776+ candidates : readonly AuthProfileRepairCandidate [ ] ;
1777+ env : NodeJS . ProcessEnv ;
1778+ } ) : Map < string , string > {
1779+ const recovered = new Map < string , string > ( ) ;
1780+ const ambiguous = new Set < string > ( ) ;
1781+ const agentDirs = params . candidates . flatMap ( ( candidate ) =>
1782+ candidate . agentDir ? [ candidate . agentDir ] : [ ] ,
1783+ ) ;
1784+ const archives = listLegacyAuthProfileArchives ( { agentDirs, env : params . env } ) . filter (
1785+ ( archive ) => archive . kind === "auth-profiles" ,
1786+ ) ;
1787+ for ( const candidate of params . candidates ) {
1788+ const canonicalProfiles = loadPersistedAuthProfileStore ( candidate . agentDir ) ?. profiles ;
1789+ if ( ! canonicalProfiles ) {
1790+ continue ;
1791+ }
1792+ for ( const archive of archives . filter ( ( entry ) =>
1793+ entry . path . startsWith ( `${ candidate . authPath } .migrated-` ) ,
1794+ ) ) {
1795+ try {
1796+ const sourceBytes = fs . readFileSync ( archive . path ) ;
1797+ const sourceSha256 = createHash ( "sha256" ) . update ( sourceBytes ) . digest ( "hex" ) ;
1798+ const sourceKey = `auth-profile-v2:${ createHash ( "sha256" )
1799+ . update ( `${ path . resolve ( candidate . authPath ) } \0${ sourceSha256 } ` )
1800+ . digest ( "hex" ) } `;
1801+ const receipt = readLegacyMigrationReceipt ( sourceKey , params . env ) ;
1802+ if ( ! receipt ?. removedSource || receipt . sourceSha256 !== sourceSha256 ) {
1803+ continue ;
1804+ }
1805+ const report = JSON . parse ( receipt . reportJson ) as unknown ;
1806+ if (
1807+ ! isRecord ( report ) ||
1808+ report . format !== "auth-profile-json-to-sqlite-v2" ||
1809+ report . completionStatus !== "completed" ||
1810+ report . targetTable !== "auth_profile_store" ||
1811+ typeof report . archivePath !== "string" ||
1812+ path . resolve ( report . archivePath ) !== path . resolve ( archive . path ) ||
1813+ typeof report . targetDatabasePath !== "string" ||
1814+ path . resolve ( report . targetDatabasePath ) !==
1815+ path . resolve ( resolveAuthProfileDatabasePath ( candidate . agentDir ) ) ||
1816+ ! isRecord ( report . expectedProfileSha256 )
1817+ ) {
1818+ continue ;
1819+ }
1820+ const archivedStore = JSON . parse ( sourceBytes . toString ( "utf8" ) ) as unknown ;
1821+ if ( ! isRecord ( archivedStore ) || ! isRecord ( archivedStore . profiles ) ) {
1822+ continue ;
1823+ }
1824+ for ( const [ legacyProfileId , rawCredential ] of Object . entries ( archivedStore . profiles ) ) {
1825+ if ( ! isLegacyOpenAICodexProfileId ( legacyProfileId ) || ! isRecord ( rawCredential ) ) {
1826+ continue ;
1827+ }
1828+ const archivedCredential = parseLegacyCredentialEntry (
1829+ { ...rawCredential , provider : "openai" } ,
1830+ "openai" ,
1831+ ) ;
1832+ if ( archivedCredential ?. type !== "oauth" ) {
1833+ continue ;
1834+ }
1835+ const matches = Object . entries ( report . expectedProfileSha256 ) . flatMap (
1836+ ( [ canonicalProfileId , expectedSha256 ] ) => {
1837+ const credential = canonicalProfiles [ canonicalProfileId ] ;
1838+ return typeof expectedSha256 === "string" &&
1839+ credential ?. type === "oauth" &&
1840+ credential . provider === "openai" &&
1841+ ( hasMatchingOAuthIdentity ( archivedCredential , credential ) ||
1842+ areOAuthCredentialsEquivalent ( archivedCredential , credential ) )
1843+ ? [ canonicalProfileId ]
1844+ : [ ] ;
1845+ } ,
1846+ ) ;
1847+ if ( matches . length !== 1 ) {
1848+ continue ;
1849+ }
1850+ const canonicalProfileId = matches [ 0 ] ! ;
1851+ const previous = recovered . get ( legacyProfileId ) ;
1852+ if ( previous && previous !== canonicalProfileId ) {
1853+ recovered . delete ( legacyProfileId ) ;
1854+ ambiguous . add ( legacyProfileId ) ;
1855+ } else if ( ! ambiguous . has ( legacyProfileId ) ) {
1856+ recovered . set ( legacyProfileId , canonicalProfileId ) ;
1857+ }
1858+ }
1859+ } catch {
1860+ // Archives without a matching verified receipt or parseable identity
1861+ // cannot prove account ownership; leave their session pins untouched.
1862+ }
1863+ }
1864+ }
1865+ return recovered ;
1866+ }
1867+
1868+ /** Collects collision-safe OpenAI profile ids across config, SQLite, and legacy agent stores. */
17651869export function collectOpenAICodexAuthProfileStoreIdMap ( params : {
17661870 cfg : OpenClawConfig ;
17671871 env ?: NodeJS . ProcessEnv ;
@@ -1770,25 +1874,39 @@ export function collectOpenAICodexAuthProfileStoreIdMap(params: {
17701874 const occupiedProfileIds = new Set < string > ( ) ;
17711875 const legacyProfileIds = new Set < string > ( ) ;
17721876 const profileIdMap = new Map < string , string > ( ) ;
1773- for ( const candidate of listAuthProfileRepairCandidates ( params . cfg , env ) ) {
1877+ const candidates = listAuthProfileRepairCandidates ( params . cfg , env ) ;
1878+ const addProfileIds = ( profileIds : Iterable < string > ) : void => {
1879+ for ( const profileId of profileIds ) {
1880+ if ( isLegacyOpenAICodexProfileId ( profileId ) ) {
1881+ legacyProfileIds . add ( profileId ) ;
1882+ } else {
1883+ occupiedProfileIds . add ( profileId ) ;
1884+ }
1885+ }
1886+ } ;
1887+ addProfileIds ( Object . keys ( params . cfg . auth ?. profiles ?? { } ) ) ;
1888+ for ( const candidate of candidates ) {
1889+ addProfileIds ( Object . keys ( loadPersistedAuthProfileStore ( candidate . agentDir ) ?. profiles ?? { } ) ) ;
17741890 if ( ! fs . existsSync ( candidate . authPath ) ) {
17751891 continue ;
17761892 }
17771893 const raw = loadJsonFile ( candidate . authPath ) ;
17781894 if ( ! isRecord ( raw ) || ! isRecord ( raw . profiles ) ) {
17791895 continue ;
17801896 }
1781- for ( const profileId of Object . keys ( raw . profiles ) ) {
1782- if ( isLegacyOpenAICodexProfileId ( profileId ) ) {
1783- legacyProfileIds . add ( profileId ) ;
1784- } else {
1785- occupiedProfileIds . add ( profileId ) ;
1786- }
1787- }
1897+ addProfileIds ( Object . keys ( raw . profiles ) ) ;
17881898 }
17891899 for ( const profileId of [ ...legacyProfileIds ] . toSorted ( ( a , b ) => a . localeCompare ( b ) ) ) {
17901900 profileIdMap . set ( profileId , allocateOpenAIProfileId ( profileId , occupiedProfileIds ) ) ;
17911901 }
1902+ for ( const [ legacyProfileId , canonicalProfileId ] of recoverArchivedOpenAICodexAuthProfileIdMap ( {
1903+ candidates,
1904+ env,
1905+ } ) ) {
1906+ if ( ! profileIdMap . has ( legacyProfileId ) ) {
1907+ profileIdMap . set ( legacyProfileId , canonicalProfileId ) ;
1908+ }
1909+ }
17921910 return profileIdMap ;
17931911}
17941912
0 commit comments