Skip to content

Commit dcc3e43

Browse files
committed
fix(doctor): converge missing OAuth sidecar migration
Persist missing-sidecar OAuth profiles as cold SQLite rows and make startup migration warnings deterministic.
1 parent 7235943 commit dcc3e43

4 files changed

Lines changed: 124 additions & 155 deletions

File tree

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

Lines changed: 95 additions & 45 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,8 @@ import fs from "node:fs";
33
import path from "node:path";
44
import { DatabaseSync } from "node:sqlite";
55
import { afterEach, describe, expect, it, vi } from "vitest";
6+
import { listAuthProfileStoresRequiringMigration } from "../agents/auth-profiles/legacy-source-diagnostic.js";
7+
import { resolveAuthProfileEligibility } from "../agents/auth-profiles/order.js";
68
import { loadPersistedAuthProfileStore } from "../agents/auth-profiles/persisted.js";
79
import { clearRuntimeAuthProfileStoreSnapshots } from "../agents/auth-profiles/runtime-snapshots.js";
810
import {
@@ -285,8 +287,9 @@ describe("maybeMigrateAuthProfileJsonStoresToSqlite", () => {
285287
type: "oauth",
286288
provider: "openai",
287289
oauthRef: {
290+
source: "openclaw-credentials",
288291
id: "0123456789abcdef0123456789abcdef",
289-
provider: "openai",
292+
provider: "openai-codex",
290293
},
291294
},
292295
},
@@ -305,16 +308,21 @@ describe("maybeMigrateAuthProfileJsonStoresToSqlite", () => {
305308
env: state.env,
306309
});
307310

308-
expect(result.warnings).toEqual([
309-
expect.stringContaining("legacy OAuth sidecar profile"),
310-
expect.stringContaining("no importable auth profiles or state"),
311-
expect.stringContaining("Deferred shared legacy OAuth migration"),
312-
]);
313-
expect(loadPersistedAuthProfileStore(state.agentDir())).toBeNull();
314-
expect(fs.existsSync(authPath)).toBe(true);
315-
expect(fs.existsSync(oauthPath)).toBe(true);
316-
expectNoMigratedArchive(authPath);
317-
expectNoMigratedArchive(oauthPath);
311+
expect(result.warnings).toEqual([expect.stringContaining("legacy OAuth sidecar profile")]);
312+
expect(
313+
loadPersistedAuthProfileStore(state.agentDir())?.profiles["openai:default"],
314+
).toMatchObject({
315+
type: "oauth",
316+
provider: "openai",
317+
oauthRef: {
318+
source: "openclaw-credentials",
319+
provider: "openai-codex",
320+
},
321+
});
322+
expect(fs.existsSync(authPath)).toBe(false);
323+
expect(fs.existsSync(oauthPath)).toBe(false);
324+
expectMigratedArchive(authPath);
325+
expectMigratedArchive(oauthPath);
318326
});
319327

320328
it("preserves state-only profile IDs while migrating shared OAuth", async () => {
@@ -701,7 +709,7 @@ describe("maybeMigrateAuthProfileJsonStoresToSqlite", () => {
701709
expect(fs.existsSync(authPath)).toBe(false);
702710
});
703711

704-
it("leaves unresolved legacy OAuth sidecar refs in JSON", async () => {
712+
it("migrates unresolved legacy OAuth sidecar refs so startup can proceed cold", async () => {
705713
const state = await makeTestState();
706714
const authPath = await writeLegacyAuthProfilesJson(state, {
707715
version: 1,
@@ -711,8 +719,9 @@ describe("maybeMigrateAuthProfileJsonStoresToSqlite", () => {
711719
provider: "openai",
712720
713721
oauthRef: {
722+
source: "openclaw-credentials",
714723
id: "0123456789abcdef0123456789abcdef",
715-
provider: "openai",
724+
provider: "openai-codex",
716725
},
717726
},
718727
},
@@ -725,14 +734,36 @@ describe("maybeMigrateAuthProfileJsonStoresToSqlite", () => {
725734
});
726735

727736
expect(result.detected).toEqual([authPath]);
728-
expect(result.changes).toEqual([]);
737+
expect(result.changes).toEqual([expect.stringContaining("Migrated auth profile JSON")]);
729738
expect(result.warnings).toEqual([
730-
expect.stringContaining("legacy OAuth sidecar profile"),
731-
expect.stringContaining("no importable auth profiles or state"),
739+
expect.stringContaining("Migrated 1 legacy OAuth sidecar profile"),
732740
]);
733-
expect(loadPersistedAuthProfileStore(state.agentDir())).toBeNull();
734-
expect(fs.existsSync(authPath)).toBe(true);
735-
expectNoMigratedArchive(authPath);
741+
expect(result.warnings[0]).toContain("re-authenticate");
742+
const store = loadPersistedAuthProfileStore(state.agentDir());
743+
expect(store?.profiles["openai:[email protected]"]).toMatchObject({
744+
type: "oauth",
745+
provider: "openai",
746+
747+
oauthRef: {
748+
source: "openclaw-credentials",
749+
provider: "openai-codex",
750+
},
751+
});
752+
expect(
753+
resolveAuthProfileEligibility({
754+
store: store!,
755+
provider: "openai",
756+
profileId: "openai:[email protected]",
757+
}),
758+
).toEqual({ eligible: false, reasonCode: "unresolved_ref" });
759+
expect(fs.existsSync(authPath)).toBe(false);
760+
expectMigratedArchive(authPath);
761+
expect(
762+
listAuthProfileStoresRequiringMigration({
763+
agentDirs: [state.agentDir()],
764+
env: state.env,
765+
}),
766+
).toEqual([]);
736767
});
737768

738769
it("imports valid profiles when one legacy OAuth sidecar ref is unresolved", async () => {
@@ -750,8 +781,8 @@ describe("maybeMigrateAuthProfileJsonStoresToSqlite", () => {
750781
provider: "openai",
751782
752783
oauthRef: {
753-
id: "0123456789abcdef0123456789abcdef",
754-
provider: "openai",
784+
source: "openclaw-credentials",
785+
provider: "openai-codex",
755786
},
756787
},
757788
},
@@ -774,19 +805,28 @@ describe("maybeMigrateAuthProfileJsonStoresToSqlite", () => {
774805
provider: "openai",
775806
key: "sk-imported",
776807
},
808+
"openai:[email protected]": {
809+
type: "oauth",
810+
provider: "openai",
811+
812+
oauthRef: {
813+
source: "openclaw-credentials",
814+
id: "0123456789abcdef0123456789abcdef",
815+
provider: "openai-codex",
816+
},
817+
},
777818
},
778-
order: { openai: ["openai:default"] },
819+
order: { openai: ["openai:default", "openai:[email protected]"] },
779820
lastGood: { openai: "openai:default" },
780821
});
781-
expect(fs.existsSync(authPath)).toBe(true);
782-
expectNoMigratedArchive(authPath);
783-
const remaining = JSON.parse(fs.readFileSync(authPath, "utf8"));
784-
expect(remaining.profiles).toHaveProperty("openai:default");
785-
expect(remaining.profiles).toHaveProperty("openai:[email protected]");
786-
expect(remaining.order).toEqual({
787-
openai: ["openai:default", "openai:[email protected]"],
788-
});
789-
expect(remaining.lastGood).toEqual({ openai: "openai:default" });
822+
expect(fs.existsSync(authPath)).toBe(false);
823+
expectMigratedArchive(authPath);
824+
expect(
825+
listAuthProfileStoresRequiringMigration({
826+
agentDirs: [state.agentDir()],
827+
env: state.env,
828+
}),
829+
).toEqual([]);
790830
});
791831

792832
it("keeps existing SQLite credentials when importing stale JSON", async () => {
@@ -2031,7 +2071,7 @@ describe("legacy OpenAI auth profiles through the canonical migration owner", ()
20312071
});
20322072
});
20332073

2034-
it("does not rebind unresolved sidecar accounts when another Codex account migrates", async () => {
2074+
it("canonicalizes unresolved sidecar accounts while keeping them cold", async () => {
20352075
const state = await makeTestState();
20362076
const storePath = path.join(state.sessionsDir(), "sessions.json");
20372077
const readySessionKey = "agent:main:main";
@@ -2089,7 +2129,7 @@ describe("legacy OpenAI auth profiles through the canonical migration owner", ()
20892129
authProfileIdMap: profileIdMap,
20902130
});
20912131

2092-
expect(result.repairedSessions).toBe(1);
2132+
expect(result.repairedSessions).toBe(2);
20932133
expect(
20942134
loadSessionEntry({ storePath, sessionKey: readySessionKey, env: state.env }),
20952135
).toMatchObject({
@@ -2098,9 +2138,17 @@ describe("legacy OpenAI auth profiles through the canonical migration owner", ()
20982138
expect(
20992139
loadSessionEntry({ storePath, sessionKey: pendingSessionKey, env: state.env }),
21002140
).toMatchObject({
2101-
authProfileOverride: "openai-codex:pending",
2141+
authProfileOverride: "openai:pending",
21022142
authProfileOverrideSource: "user",
21032143
});
2144+
const coldStore = loadPersistedAuthProfileStore(state.agentDir());
2145+
expect(
2146+
resolveAuthProfileEligibility({
2147+
store: coldStore!,
2148+
provider: "openai",
2149+
profileId: "openai:pending",
2150+
}),
2151+
).toEqual({ eligible: false, reasonCode: "missing_credential" });
21042152
});
21052153

21062154
it("repairs an already-migrated selected account from its verified auth archive", async () => {
@@ -2265,6 +2313,7 @@ describe("legacy OpenAI auth profiles through the canonical migration owner", ()
22652313
provider: "openai-codex",
22662314
accountId: "failed-different-account",
22672315
oauthRef: {
2316+
source: "openclaw-credentials",
22682317
id: "0123456789abcdef0123456789abcdef",
22692318
provider: "openai-codex",
22702319
},
@@ -2326,8 +2375,8 @@ describe("legacy OpenAI auth profiles through the canonical migration owner", ()
23262375
shouldRepair: true,
23272376
authProfileIdMap: profileIdMap,
23282377
});
2329-
expect(repair.repairedSessions).toBe(3);
2330-
for (const agentId of ["main", "inherited", "dedup"]) {
2378+
expect(repair.repairedSessions).toBe(4);
2379+
for (const agentId of ["main", "failed", "inherited", "dedup"]) {
23312380
expect(
23322381
loadSessionEntry({
23332382
storePath: path.join(state.sessionsDir(agentId), "sessions.json"),
@@ -2339,15 +2388,16 @@ describe("legacy OpenAI auth profiles through the canonical migration owner", ()
23392388
authProfileOverrideSource: "user",
23402389
});
23412390
}
2342-
expect(
2343-
loadSessionEntry({
2344-
storePath: path.join(state.sessionsDir("failed"), "sessions.json"),
2345-
sessionKey: "agent:failed:main",
2346-
env: state.env,
2347-
}),
2348-
).toMatchObject({
2349-
authProfileOverride: "openai-codex:shared",
2350-
authProfileOverrideSource: "user",
2391+
expect(loadPersistedAuthProfileStore(state.agentDir("failed"))?.profiles).toMatchObject({
2392+
"openai:shared": {
2393+
type: "oauth",
2394+
provider: "openai",
2395+
accountId: "failed-different-account",
2396+
oauthRef: {
2397+
source: "openclaw-credentials",
2398+
provider: "openai-codex",
2399+
},
2400+
},
23512401
});
23522402
});
23532403

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

Lines changed: 11 additions & 91 deletions
Original file line numberDiff line numberDiff line change
@@ -618,80 +618,6 @@ function formatMissingAuthProfileSqliteVerification(params: {
618618
return parts.length > 0 ? parts.join("; ") : null;
619619
}
620620

621-
function filterRawAuthProfileState(
622-
raw: Record<string, unknown>,
623-
shouldKeepProfileId: (profileId: string) => boolean,
624-
): void {
625-
if (isRecord(raw.order)) {
626-
for (const [provider, profileIds] of Object.entries(raw.order)) {
627-
if (!Array.isArray(profileIds)) {
628-
continue;
629-
}
630-
const kept = profileIds.filter(
631-
(profileId): profileId is string =>
632-
typeof profileId === "string" && shouldKeepProfileId(profileId),
633-
);
634-
if (kept.length > 0) {
635-
raw.order[provider] = kept;
636-
} else {
637-
delete raw.order[provider];
638-
}
639-
}
640-
if (Object.keys(raw.order).length === 0) {
641-
delete raw.order;
642-
}
643-
}
644-
if (isRecord(raw.lastGood)) {
645-
for (const [provider, profileId] of Object.entries(raw.lastGood)) {
646-
if (typeof profileId !== "string" || !shouldKeepProfileId(profileId)) {
647-
delete raw.lastGood[provider];
648-
}
649-
}
650-
if (Object.keys(raw.lastGood).length === 0) {
651-
delete raw.lastGood;
652-
}
653-
}
654-
if (isRecord(raw.usageStats)) {
655-
for (const profileId of Object.keys(raw.usageStats)) {
656-
if (!shouldKeepProfileId(profileId)) {
657-
delete raw.usageStats[profileId];
658-
}
659-
}
660-
if (Object.keys(raw.usageStats).length === 0) {
661-
delete raw.usageStats;
662-
}
663-
}
664-
}
665-
666-
function pruneRawAuthProfileIds(raw: unknown, profileIds: ReadonlySet<string>): void {
667-
if (!isRecord(raw) || !isRecord(raw.profiles)) {
668-
return;
669-
}
670-
for (const profileId of profileIds) {
671-
delete raw.profiles[profileId];
672-
}
673-
filterRawAuthProfileState(raw, (profileId) => !profileIds.has(profileId));
674-
}
675-
676-
function pickRawAuthProfileIds(
677-
raw: unknown,
678-
profileIds: ReadonlySet<string>,
679-
): Record<string, unknown> | null {
680-
if (!isRecord(raw) || !isRecord(raw.profiles)) {
681-
return null;
682-
}
683-
const profiles = Object.fromEntries(
684-
Object.entries(raw.profiles).filter(([profileId]) => profileIds.has(profileId)),
685-
);
686-
if (Object.keys(profiles).length === 0) {
687-
return null;
688-
}
689-
const next = structuredClone(raw);
690-
next.profiles = profiles;
691-
filterRawAuthProfileState(next, (profileId) => profileIds.has(profileId));
692-
return next;
693-
}
694-
695621
function collectUnresolvedLegacyOAuthSidecarProfileIds(raw: unknown): string[] {
696622
if (!isRecord(raw) || !isRecord(raw.profiles)) {
697623
return [];
@@ -971,7 +897,7 @@ function migrateLockedLegacyOAuthFile(params: {
971897
* Imports legacy auth profile JSON and state files into the per-agent SQLite store.
972898
*
973899
* JSON files are verified and atomically renamed to timestamped archives only after import.
974-
* OAuth profiles that still depend on unresolved sidecar secrets remain as a migration input.
900+
* OAuth profiles that still depend on missing sidecar secrets migrate as unavailable ref-only rows.
975901
*/
976902
export async function maybeMigrateAuthProfileJsonStoresToSqlite(params: {
977903
cfg: OpenClawConfig;
@@ -1099,17 +1025,10 @@ export async function maybeMigrateAuthProfileJsonStoresToSqlite(params: {
10991025
const unresolvedSidecarProfileIds = new Set(
11001026
collectUnresolvedLegacyOAuthSidecarProfileIds(rawStore),
11011027
);
1102-
const unresolvedSidecarRawStore =
1028+
const unresolvedSidecarWarning =
11031029
unresolvedSidecarProfileIds.size > 0
1104-
? pickRawAuthProfileIds(rawStore, unresolvedSidecarProfileIds)
1105-
: null;
1106-
if (unresolvedSidecarProfileIds.size > 0) {
1107-
// Sidecar-backed OAuth entries cannot move into SQLite until their secret material exists.
1108-
pruneRawAuthProfileIds(rawStore, unresolvedSidecarProfileIds);
1109-
result.warnings.push(
1110-
`Left ${unresolvedSidecarProfileIds.size} legacy OAuth sidecar profile${unresolvedSidecarProfileIds.size === 1 ? "" : "s"} in ${shortenHomePath(candidate.authPath)}; rerun ${formatCliCommand("openclaw doctor --fix")} after sidecar migration or re-authenticate those profiles.`,
1111-
);
1112-
}
1030+
? `Migrated ${unresolvedSidecarProfileIds.size} legacy OAuth sidecar profile${unresolvedSidecarProfileIds.size === 1 ? "" : "s"} from ${shortenHomePath(candidate.authPath)} into SQLite as configured-unavailable without credentials; re-authenticate ${unresolvedSidecarProfileIds.size === 1 ? "this profile" : "these profiles"} to restore access.`
1031+
: undefined;
11131032
const awsSdkMarkerStore =
11141033
isRecord(rawStore) && isRecord(rawStore.profiles)
11151034
? resolveAwsSdkAuthProfileMarkerStore(candidate)
@@ -1154,15 +1073,16 @@ export async function maybeMigrateAuthProfileJsonStoresToSqlite(params: {
11541073
!hasAuthProfileState(state) &&
11551074
!awsSdkMarkerStore
11561075
) {
1157-
if (!unresolvedSidecarRawStore && sourceReceipts.length > 0) {
1076+
if (sourceReceipts.length > 0) {
11581077
const archived = sourceReceipts.map((receipt) => {
11591078
finalizeAuthProfileMigrationSource(receipt, "archived-unparsed", {
11601079
sourceLocked: true,
11611080
});
11621081
return receipt.archivePath;
11631082
});
11641083
result.warnings.push(
1165-
`Archived unparseable auth profile input without import for ${shortenHomePath(candidate.authPath)} (${archived.map(shortenHomePath).join(", ")}).`,
1084+
unresolvedSidecarWarning ??
1085+
`Archived unparseable auth profile input without import for ${shortenHomePath(candidate.authPath)} (${archived.map(shortenHomePath).join(", ")}).`,
11661086
);
11671087
continue;
11681088
}
@@ -1354,11 +1274,8 @@ export async function maybeMigrateAuthProfileJsonStoresToSqlite(params: {
13541274
receipt.expectedStateSha256 = expectedStateSha256;
13551275
}
13561276
}
1357-
const archivalReceipts = unresolvedSidecarRawStore
1358-
? sourceReceipts.filter((receipt) => receipt.sourcePath !== candidate.authPath)
1359-
: sourceReceipts;
13601277
assertAuthProfileMigrationSourcesUnchanged(candidate, sourceReceipts);
1361-
const archives = archivalReceipts.map((receipt) =>
1278+
const archives = sourceReceipts.map((receipt) =>
13621279
archiveVerifiedAuthProfileSource(receipt, true),
13631280
);
13641281
const archiveText =
@@ -1368,6 +1285,9 @@ export async function maybeMigrateAuthProfileJsonStoresToSqlite(params: {
13681285
result.changes.push(
13691286
`Migrated auth profile JSON for ${shortenHomePath(candidate.authPath)} into SQLite (${archiveText}).`,
13701287
);
1288+
if (unresolvedSidecarWarning) {
1289+
result.warnings.push(unresolvedSidecarWarning);
1290+
}
13711291
if (openAIProviderRepair !== null) {
13721292
result.changes.push(
13731293
`Migrated ${openAIProviderRepair} OpenAI Codex auth profile(s) in ${shortenHomePath(candidate.authPath)} to provider "openai".`,

0 commit comments

Comments
 (0)