Skip to content

Commit e0debe2

Browse files
committed
fix(oauth): restore OAuth mode after final key removal
1 parent 73aa7f2 commit e0debe2

2 files changed

Lines changed: 154 additions & 6 deletions

File tree

‎src/oauth/index.ts‎

Lines changed: 45 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -566,6 +566,42 @@ export function reconcileOAuthProviders(config: OcxConfig): boolean {
566566
return changed;
567567
}
568568

569+
/** Runtime guards: provider config is intentionally passthrough, so persisted fields may be malformed. */
570+
function normalizePreservableApiKey(value: unknown): string | undefined {
571+
if (typeof value !== "string") return undefined;
572+
const trimmed = value.trim();
573+
return trimmed && !/[\r\n]/.test(trimmed) ? trimmed : undefined;
574+
}
575+
576+
function preservableApiKeyPool(value: unknown): NonNullable<OcxProviderConfig["apiKeyPool"]> | undefined {
577+
if (!Array.isArray(value)) return undefined;
578+
const pool: NonNullable<OcxProviderConfig["apiKeyPool"]> = [];
579+
const ids = new Set<string>();
580+
const keys = new Set<string>();
581+
for (const entry of value as unknown[]) {
582+
if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
583+
const candidate = entry as Record<string, unknown>;
584+
const id = typeof candidate.id === "string" ? candidate.id.trim() : "";
585+
const key = normalizePreservableApiKey(candidate.key);
586+
if (!id || !key || ids.has(id) || keys.has(key)) continue;
587+
const label = typeof candidate.label === "string" ? candidate.label : undefined;
588+
const addedAt = typeof candidate.addedAt === "number" && Number.isFinite(candidate.addedAt)
589+
? candidate.addedAt
590+
: undefined;
591+
ids.add(id);
592+
keys.add(key);
593+
pool.push({
594+
id,
595+
key,
596+
...(label !== undefined ? { label } : {}),
597+
...(addedAt !== undefined ? { addedAt } : {}),
598+
});
599+
}
600+
// `apiKey` remains the routing source of truth. Keep valid alternate slots even when a
601+
// hand-edited config left the pool out of sync, rather than deleting usable credentials.
602+
return pool.length > 0 ? pool : undefined;
603+
}
604+
569605
/**
570606
* Add/refresh an OAuth provider's config entry on a config object (does not persist).
571607
*
@@ -574,8 +610,10 @@ export function reconcileOAuthProviders(config: OcxConfig): boolean {
574610
* `authMode: "key"` for them). A blind preset overwrite here deletes `apiKey`/`apiKeyPool`
575611
* on every OAuth login, silently destroying the stored key and forcing a re-paste — and it
576612
* flips billing back to the subscription without the user asking. Carry the key fields over
577-
* and keep an explicitly chosen `authMode: "key"`, so logging in never changes which
578-
* credential bills the request.
613+
* and keep an explicitly chosen `authMode: "key"` while an active stored key remains, so
614+
* logging in does not change which credential bills the request. If the final key was removed
615+
* and only the old key mode remains, let the OAuth preset restore `authMode: "oauth"` so the
616+
* newly saved OAuth credential can be used.
579617
*/
580618
export function upsertOAuthProvider(config: OcxConfig, provider: string): void {
581619
if (provider === "chatgpt") return;
@@ -584,9 +622,11 @@ export function upsertOAuthProvider(config: OcxConfig, provider: string): void {
584622
const existing = config.providers[provider];
585623
const next: OcxProviderConfig = { ...def.providerConfig };
586624
if (existing && getProviderRegistryEntry(provider)?.allowKeyAuthOverride === true) {
587-
if (existing.apiKey !== undefined) next.apiKey = existing.apiKey;
588-
if (existing.apiKeyPool !== undefined) next.apiKeyPool = existing.apiKeyPool;
589-
if (existing.authMode === "key") next.authMode = "key";
625+
const storedApiKey = normalizePreservableApiKey(existing.apiKey);
626+
const storedApiKeyPool = preservableApiKeyPool(existing.apiKeyPool);
627+
if (storedApiKey !== undefined) next.apiKey = storedApiKey;
628+
if (storedApiKeyPool !== undefined) next.apiKeyPool = storedApiKeyPool;
629+
if (existing.authMode === "key" && storedApiKey !== undefined) next.authMode = "key";
590630
}
591631
config.providers[provider] = next;
592632
}

‎tests/oauth-upsert-preserves-api-key.test.ts‎

Lines changed: 109 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,10 @@
11
import { describe, expect, test } from "bun:test";
2+
import { mkdtempSync, rmSync } from "node:fs";
3+
import { tmpdir } from "node:os";
4+
import { join } from "node:path";
25
import { upsertOAuthProvider } from "../src/oauth";
6+
import { removeProviderApiKey } from "../src/providers/api-keys";
7+
import { routeModel } from "../src/router";
38
import type { OcxConfig } from "../src/types";
49

510
/**
@@ -51,6 +56,106 @@ describe("upsertOAuthProvider credential preservation", () => {
5156
expect(provider.authMode).toBe("oauth");
5257
});
5358

59+
test("treats an API key environment reference as stored key material", () => {
60+
const config = configWithKey("xai", "openai-chat", "https://api.x.ai/v1");
61+
config.providers.xai!.apiKey = "${OCX_TEST_XAI_API_KEY}";
62+
config.providers.xai!.apiKeyPool = [{ id: "env-key", key: "${OCX_TEST_XAI_API_KEY}" }];
63+
upsertOAuthProvider(config, "xai");
64+
const provider = config.providers.xai!;
65+
expect(provider.apiKey).toBe("${OCX_TEST_XAI_API_KEY}");
66+
expect(provider.apiKeyPool).toEqual([{ id: "env-key", key: "${OCX_TEST_XAI_API_KEY}" }]);
67+
expect(provider.authMode).toBe("key");
68+
});
69+
70+
test("drops malformed stored key fields instead of breaking OAuth routing", () => {
71+
const config = {
72+
port: 10100,
73+
defaultProvider: "xai",
74+
providers: {
75+
xai: {
76+
adapter: "openai-chat",
77+
baseUrl: "https://api.x.ai/v1",
78+
authMode: "key",
79+
apiKey: 12345,
80+
apiKeyPool: [{ id: "bad-key", key: 67890 }],
81+
},
82+
},
83+
} as unknown as OcxConfig;
84+
upsertOAuthProvider(config, "xai");
85+
expect(config.providers.xai!.authMode).toBe("oauth");
86+
expect(config.providers.xai!.apiKey).toBeUndefined();
87+
expect(config.providers.xai!.apiKeyPool).toBeUndefined();
88+
expect(routeModel(config, "xai/grok-4.5").provider.authMode).toBe("oauth");
89+
});
90+
91+
test("rejects an unsafe active key but keeps valid alternate pool entries", () => {
92+
const config = {
93+
port: 10100,
94+
defaultProvider: "xai",
95+
providers: {
96+
xai: {
97+
adapter: "openai-chat",
98+
baseUrl: "https://api.x.ai/v1",
99+
authMode: "key",
100+
apiKey: "unsafe\r\nheader",
101+
apiKeyPool: [
102+
{ id: "safe", key: " safe-alternate " },
103+
{ id: "unsafe", key: "bad\r\nheader" },
104+
],
105+
},
106+
},
107+
} as OcxConfig;
108+
upsertOAuthProvider(config, "xai");
109+
const provider = config.providers.xai!;
110+
expect(provider.authMode).toBe("oauth");
111+
expect(provider.apiKey).toBeUndefined();
112+
expect(provider.apiKeyPool).toEqual([{ id: "safe", key: "safe-alternate" }]);
113+
expect(routeModel(config, "xai/grok-4.5").provider.authMode).toBe("oauth");
114+
});
115+
116+
test("filters malformed and duplicate pool data without deleting valid keys", () => {
117+
const config = configWithKey("xai", "openai-chat", "https://api.x.ai/v1");
118+
config.providers.xai!.apiKeyPool = [
119+
{ id: "primary", key: "stored-key-sentinel" },
120+
{ id: "alternate", key: " alternate-key " },
121+
{ id: "alternate", key: "duplicate-id" },
122+
{ id: "duplicate-key", key: "alternate-key" },
123+
{ id: "bad-added-at", key: "bad-metadata", addedAt: Number.NaN },
124+
];
125+
upsertOAuthProvider(config, "xai");
126+
const provider = config.providers.xai!;
127+
expect(provider.authMode).toBe("key");
128+
expect(provider.apiKey).toBe("stored-key-sentinel");
129+
expect(provider.apiKeyPool).toEqual([
130+
{ id: "primary", key: "stored-key-sentinel" },
131+
{ id: "alternate", key: "alternate-key" },
132+
{ id: "bad-added-at", key: "bad-metadata" },
133+
]);
134+
});
135+
136+
test("returns to oauth after the last stored API key is removed", () => {
137+
const config = configWithKey("xai", "openai-chat", "https://api.x.ai/v1");
138+
const previousHome = process.env.OPENCODEX_HOME;
139+
const testHome = mkdtempSync(join(tmpdir(), "ocx-oauth-upsert-"));
140+
process.env.OPENCODEX_HOME = testHome;
141+
try {
142+
expect(removeProviderApiKey(config, "xai", "aaaaaaaa")).toBe(true);
143+
expect(config.providers.xai!.authMode).toBe("key");
144+
expect(config.providers.xai!.apiKey).toBeUndefined();
145+
expect(config.providers.xai!.apiKeyPool).toBeUndefined();
146+
147+
upsertOAuthProvider(config, "xai");
148+
const provider = config.providers.xai!;
149+
expect(provider.authMode).toBe("oauth");
150+
expect(provider.apiKey).toBeUndefined();
151+
expect(provider.apiKeyPool).toBeUndefined();
152+
} finally {
153+
if (previousHome === undefined) delete process.env.OPENCODEX_HOME;
154+
else process.env.OPENCODEX_HOME = previousHome;
155+
rmSync(testHome, { recursive: true, force: true });
156+
}
157+
});
158+
54159
test("still applies the plain preset for oauth-only providers", () => {
55160
const config = {
56161
port: 10100,
@@ -59,7 +164,9 @@ describe("upsertOAuthProvider credential preservation", () => {
59164
anthropic: {
60165
adapter: "anthropic",
61166
baseUrl: "https://api.anthropic.com",
62-
authMode: "oauth",
167+
authMode: "key",
168+
apiKey: "stale-key",
169+
apiKeyPool: [{ id: "stale", key: "stale-key" }],
63170
note: "stale-note",
64171
},
65172
},
@@ -68,6 +175,7 @@ describe("upsertOAuthProvider credential preservation", () => {
68175
const provider = config.providers.anthropic!;
69176
expect(provider.authMode).toBe("oauth");
70177
expect(provider.apiKey).toBeUndefined();
178+
expect(provider.apiKeyPool).toBeUndefined();
71179
expect(provider.note).toBeUndefined();
72180
});
73181

0 commit comments

Comments
 (0)