Skip to content

Commit dea0db6

Browse files
committed
fix(auth): preserve selected OAuth accounts during Codex migrations
1 parent b35b8e2 commit dea0db6

12 files changed

Lines changed: 1260 additions & 44 deletions

‎src/commands/doctor-auth-flat-profiles.test.ts‎

Lines changed: 715 additions & 0 deletions
Large diffs are not rendered by default.

‎src/commands/doctor-auth-flat-profiles.ts‎

Lines changed: 128 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,13 @@ import { resolveAgentDir, resolveDefaultAgentDir, listAgentIds } from "../agents
1010
import { AUTH_STORE_VERSION } from "../agents/auth-profiles/constants.js";
1111
import {
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";
1520
import {
1621
applyLegacyAuthStore,
1722
coerceLegacyAuthStore,
@@ -45,6 +50,7 @@ import type { AuthProfileConfig } from "../config/types.auth.js";
4550
import type { OpenClawConfig } from "../config/types.openclaw.js";
4651
import { coerceSecretRef } from "../config/types.secrets.js";
4752
import { loadJsonFile } from "../infra/json-file.js";
53+
import { readLegacyMigrationReceipt } from "../infra/state-migrations.receipts.js";
4854
import type { OpenClawAgentDatabase } from "../state/openclaw-agent-db.js";
4955
import { shortenHomePath } from "../utils.js";
5056
import {
@@ -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. */
17651869
export 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

‎src/commands/doctor-config-flow.test.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1953,6 +1953,28 @@ describe("doctor config flow", () => {
19531953
});
19541954
});
19551955

1956+
it("keeps the Codex session auth migration plan outside persisted config", async () => {
1957+
const openAICodexAuthProfileIdMap = new Map([
1958+
["openai-codex:default", "openai:chatgpt-default"],
1959+
]);
1960+
runDoctorRepairSequenceMock.mockImplementation(async (params: { state: unknown }) => ({
1961+
state: params.state,
1962+
changeNotes: [],
1963+
warningNotes: [],
1964+
authProfilesRepaired: false,
1965+
openAICodexAuthProfileIdMap,
1966+
}));
1967+
1968+
const result = await runDoctorConfigWithInput({
1969+
config: {},
1970+
repair: true,
1971+
run: loadAndMaybeMigrateDoctorConfig,
1972+
});
1973+
1974+
expect(result.openAICodexAuthProfileIdMap).toBe(openAICodexAuthProfileIdMap);
1975+
expect(result.cfg).not.toHaveProperty("openAICodexAuthProfileIdMap");
1976+
});
1977+
19561978
it("does not refresh gateway before writing a config-only auth repair", async () => {
19571979
runDoctorRepairSequenceMock.mockImplementation(
19581980
async (params: {

‎src/commands/doctor-config-flow.ts‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,6 +164,7 @@ export async function loadAndMaybeMigrateDoctorConfig(params: {
164164
};
165165
const explicitSetPaths: string[][] = [];
166166
let shouldRepairCronCodexModelRefsAfterConfigWrite = false;
167+
let openAICodexAuthProfileIdMap: ReadonlyMap<string, string> | undefined;
167168
const doctorFixCommand = formatCliCommand("openclaw doctor --fix");
168169
const applyConfigMutation = (
169170
mutation: DoctorConfigMutationResult & { warnings?: string[] },
@@ -410,6 +411,7 @@ export async function loadAndMaybeMigrateDoctorConfig(params: {
410411
blockedCodexProviderPlan,
411412
});
412413
state = repairSequence.state;
414+
openAICodexAuthProfileIdMap = repairSequence.openAICodexAuthProfileIdMap;
413415
if (repairSequence.authProfilesRepaired) {
414416
await refreshGatewayAuthStateAfterAuthProfileRepair();
415417
}
@@ -520,5 +522,6 @@ export async function loadAndMaybeMigrateDoctorConfig(params: {
520522
...(blockedCodexProviderPlan.blockedModelIdentities.length > 0
521523
? { blockedCodexModelIdentities: blockedCodexProviderPlan.blockedModelIdentities }
522524
: {}),
525+
...(openAICodexAuthProfileIdMap?.size ? { openAICodexAuthProfileIdMap } : {}),
523526
};
524527
}

‎src/commands/doctor/repair-sequencing.test.ts‎

Lines changed: 34 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -7,6 +7,7 @@ const mocks = vi.hoisted(() => ({
77
applyPluginAutoEnable: vi.fn(),
88
materializePluginAutoEnableCandidates: vi.fn(),
99
collectChannelDoctorCompatibilityMutations: vi.fn(),
10+
collectOpenAICodexAuthProfileStoreIdMap: vi.fn(),
1011
ensureAuthProfileStore: vi.fn(),
1112
evaluateStoredCredentialEligibility: vi.fn(),
1213
getInstalledPluginRecord: vi.fn(),
@@ -48,7 +49,7 @@ vi.mock("../../infra/state-migrations.onboarding-recommendations.js", () => ({
4849
}));
4950

5051
vi.mock("../doctor-auth-flat-profiles.js", () => ({
51-
collectOpenAICodexAuthProfileStoreIdMap: vi.fn(() => new Map()),
52+
collectOpenAICodexAuthProfileStoreIdMap: mocks.collectOpenAICodexAuthProfileStoreIdMap,
5253
maybeMigrateAuthProfileJsonStoresToSqlite: mocks.maybeMigrateAuthProfileJsonStoresToSqlite,
5354
maybeRepairOpenAICodexAuthConfig: mocks.maybeRepairOpenAICodexAuthConfig,
5455
}));
@@ -255,6 +256,7 @@ describe("doctor repair sequencing", () => {
255256
changes: [],
256257
warnings: [],
257258
});
259+
mocks.collectOpenAICodexAuthProfileStoreIdMap.mockReturnValue(new Map());
258260
mocks.maybeMigrateAuthProfileJsonStoresToSqlite.mockResolvedValue({
259261
detected: [],
260262
changes: [],
@@ -322,6 +324,37 @@ describe("doctor repair sequencing", () => {
322324
expect(result.warningNotes).toContain("Migration warning.");
323325
});
324326

327+
it("retains the exact auth profile map after import for later session-owner repair", async () => {
328+
const env = { OPENCLAW_STATE_DIR: "/tmp/openclaw-doctor-test" };
329+
const candidate = {} as OpenClawConfig;
330+
const profileIdMap = new Map([["openai-codex:default", "openai:chatgpt-default"]]);
331+
mocks.collectOpenAICodexAuthProfileStoreIdMap.mockReturnValue(profileIdMap);
332+
mocks.maybeMigrateAuthProfileJsonStoresToSqlite.mockResolvedValue({
333+
detected: ["auth-profiles.json"],
334+
changes: ["Migrated auth profile JSON into SQLite."],
335+
warnings: [],
336+
});
337+
const result = await runDoctorRepairSequence({
338+
state: { cfg: candidate, candidate, pendingChanges: false, fixHints: [] },
339+
doctorFixCommand: "openclaw doctor --fix",
340+
env,
341+
});
342+
343+
expect(mocks.maybeRepairOpenAICodexAuthConfig).toHaveBeenCalledWith(candidate, {
344+
profileIdMap,
345+
});
346+
expect(mocks.maybeMigrateAuthProfileJsonStoresToSqlite).toHaveBeenCalledWith({
347+
cfg: candidate,
348+
env,
349+
prompter: expect.objectContaining({ confirmAutoFix: expect.any(Function) }),
350+
openAICodexAuthProfileIdMap: profileIdMap,
351+
});
352+
expect(result.openAICodexAuthProfileIdMap).toBe(profileIdMap);
353+
expect(mocks.maybeRepairOpenAICodexAuthConfig.mock.invocationCallOrder[0]).toBeLessThan(
354+
mocks.maybeMigrateAuthProfileJsonStoresToSqlite.mock.invocationCallOrder[0]!,
355+
);
356+
});
357+
325358
it("sanitizes ordered plugin repair changes, warnings, notices, and migration notes", async () => {
326359
mocks.repairMissingConfiguredPluginInstalls.mockResolvedValueOnce({
327360
changes: ["Installed \u001B[31mplugin\u001B[0m\r\nnext."],

‎src/commands/doctor/repair-sequencing.ts‎

Lines changed: 16 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,7 @@ export async function runDoctorRepairSequence(params: {
5757
changeNotes: string[];
5858
warningNotes: string[];
5959
authProfilesRepaired: boolean;
60+
openAICodexAuthProfileIdMap?: ReadonlyMap<string, string>;
6061
}> {
6162
let state = params.state;
6263
const changeNotes: string[] = [];
@@ -141,12 +142,15 @@ export async function runDoctorRepairSequence(params: {
141142
changes: codexRouteRepair.changes,
142143
warnings: codexRouteRepair.warnings,
143144
});
145+
// Auth JSON is archived below; retain its exact collision-aware profile map
146+
// so durable session selections can follow the same account after import.
147+
const openAICodexAuthProfileIdMap = collectOpenAICodexAuthProfileStoreIdMap({
148+
cfg: state.candidate,
149+
env,
150+
});
144151
applyMutation(
145152
maybeRepairOpenAICodexAuthConfig(state.candidate, {
146-
profileIdMap: collectOpenAICodexAuthProfileStoreIdMap({
147-
cfg: state.candidate,
148-
env,
149-
}),
153+
profileIdMap: openAICodexAuthProfileIdMap,
150154
}),
151155
);
152156
applyMutation(
@@ -252,6 +256,7 @@ export async function runDoctorRepairSequence(params: {
252256
cfg: state.candidate,
253257
prompter: { confirmAutoFix: async () => true },
254258
env,
259+
openAICodexAuthProfileIdMap,
255260
});
256261
if (authProfileSqliteMigration.configChanged) {
257262
state = applyDoctorConfigMutation({
@@ -274,5 +279,11 @@ export async function runDoctorRepairSequence(params: {
274279
staleOAuthShadowRepair.changes.length > 0 ||
275280
authProfileSqliteMigration.changes.length > 0;
276281

277-
return { state, changeNotes, warningNotes, authProfilesRepaired };
282+
return {
283+
state,
284+
changeNotes,
285+
warningNotes,
286+
authProfilesRepaired,
287+
...(openAICodexAuthProfileIdMap.size > 0 ? { openAICodexAuthProfileIdMap } : {}),
288+
};
278289
}

‎src/commands/doctor/shared/codex-route-session-repair.test-support.ts‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@ type TestApi = {
88
store: Record<string, SessionEntry>;
99
now?: number;
1010
blockedModelIdentities?: ReadonlySet<LegacyCodexModelIdentity>;
11+
authProfileIdMap?: ReadonlyMap<string, string>;
1112
}): SessionRouteRepairResult;
1213
};
1314

0 commit comments

Comments
 (0)