Skip to content

Commit 8e584f5

Browse files
committed
feat(codex): add account namespace foundation
1 parent 461de39 commit 8e584f5

32 files changed

Lines changed: 2185 additions & 75 deletions

‎gui/src/components/use-add-provider-oauth.ts‎

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,8 @@ import { useCallback } from "react";
22
import type { TFn } from "../i18n/shared";
33
import { readJsonIfOk } from "../fetch-json";
44

5+
export const OAUTH_LOGIN_POLL_INTERVAL_MS = 2_000;
6+
57
export function useAddProviderOAuth({
68
apiBase,
79
t,
@@ -52,17 +54,17 @@ export function useAddProviderOAuth({
5254
if (data.url) { setOauthUrl(data.url, providerId); setOauthMsg(t("modal.waitingLogin")); }
5355
else { setOauthMsg(data.instructions || t("modal.loggingIn")); }
5456
for (let i = 0; i < 100; i++) {
55-
await new Promise(r => setTimeout(r, 2000));
57+
await new Promise(r => setTimeout(r, OAUTH_LOGIN_POLL_INTERVAL_MS));
5658
if (!aliveRef.current) return;
5759
const sRes = await fetch(`${apiBase}/api/oauth/status?provider=${providerId}`).catch(() => null);
5860
const s = sRes ? await readJsonIfOk<{ loggedIn?: boolean; error?: string }>(sRes) : null;
5961
if (!aliveRef.current) return;
60-
if (s?.loggedIn) { onAdded(providerId); return; }
6162
if (s?.error) {
6263
setOauthMsgTone("warn");
6364
setOauthMsg(t("modal.loginError", { error: s.error }));
6465
return;
6566
}
67+
if (s?.loggedIn) { onAdded(providerId); return; }
6668
}
6769
setOauthMsgTone("warn");
6870
setOauthMsg(t("modal.loginTimeout"));

‎gui/tests/add-provider-oauth-url-leak.test.tsx‎

Lines changed: 50 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,9 +1,10 @@
1-
import { afterEach, beforeEach, expect, test } from "bun:test";
1+
import { afterEach, beforeEach, expect, spyOn, test } from "bun:test";
22
import { Window } from "happy-dom";
33
import { act } from "react";
44
import type { Root } from "react-dom/client";
55
import { LanguageProvider } from "../src/i18n/provider";
66
import AddProviderModal from "../src/components/AddProviderModal";
7+
import { OAUTH_LOGIN_POLL_INTERVAL_MS } from "../src/components/use-add-provider-oauth";
78

89
/**
910
* The add-provider OAuth pane renders the authorization URL so a user whose
@@ -23,6 +24,7 @@ let host: HTMLElement;
2324
let root: Root | null = null;
2425
let originalFetch: typeof globalThis.fetch;
2526
let pendingLogins: Array<(url: string) => void> = [];
27+
let oauthStatus: { loggedIn: boolean; error?: string } = { loggedIn: false };
2628

2729
const PRESETS = [
2830
{ id: "claude", label: "Claude", adapter: "anthropic", baseUrl: "https://api.anthropic.com", auth: "oauth", oauthProvider: "claude" },
@@ -43,6 +45,7 @@ beforeEach(() => {
4345
(globalThis as typeof globalThis & { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
4446

4547
pendingLogins = [];
48+
oauthStatus = { loggedIn: false };
4649
Object.defineProperty(globalThis, "fetch", {
4750
configurable: true,
4851
value: async (input: RequestInfo | URL, init?: RequestInit) => {
@@ -56,7 +59,7 @@ beforeEach(() => {
5659
pendingLogins.push((authUrl: string) => resolve(Response.json({ url: authUrl })));
5760
});
5861
}
59-
if (url.pathname === "/api/oauth/status") return Response.json({ loggedIn: false });
62+
if (url.pathname === "/api/oauth/status") return Response.json(oauthStatus);
6063
return Response.json({});
6164
},
6265
});
@@ -78,13 +81,13 @@ afterEach(async () => {
7881
await win.happyDOM?.close?.();
7982
});
8083

81-
async function mountModal() {
84+
async function mountModal(onAdded: (name: string) => void = () => {}) {
8285
const { createRoot } = await import("react-dom/client");
8386
await act(async () => {
8487
root = createRoot(host);
8588
root.render(
8689
<LanguageProvider>
87-
<AddProviderModal apiBase="" existingNames={[]} initialTier="paid" onClose={() => {}} onAdded={() => {}} />
90+
<AddProviderModal apiBase="" existingNames={[]} initialTier="paid" onClose={() => {}} onAdded={onAdded} />
8891
</LanguageProvider>,
8992
);
9093
});
@@ -167,3 +170,46 @@ test("a late URL for an abandoned provider cannot overwrite the one already show
167170
expect(host.querySelector(".login-url-block-text")?.textContent).toBe(B_URL);
168171
expect(host.textContent).not.toContain(A_URL);
169172
});
173+
174+
test("a login error wins over a retained OAuth credential", async () => {
175+
const added: string[] = [];
176+
oauthStatus = {
177+
loggedIn: true,
178+
error: "The credential was saved, but the provider entry was not written.",
179+
};
180+
const realSetTimeout = globalThis.setTimeout;
181+
const timeoutSpy = spyOn(globalThis, "setTimeout").mockImplementation(((
182+
callback: (...args: unknown[]) => void,
183+
delay?: number,
184+
...args: unknown[]
185+
) => {
186+
if (delay === OAUTH_LOGIN_POLL_INTERVAL_MS) {
187+
queueMicrotask(() => callback(...args));
188+
return 0 as unknown as ReturnType<typeof setTimeout>;
189+
}
190+
return realSetTimeout(callback, delay, ...args);
191+
}) as typeof setTimeout);
192+
193+
try {
194+
await mountModal(name => added.push(name));
195+
await act(async () => {
196+
clickByText("Claude");
197+
await new Promise((r) => setTimeout(r, 20));
198+
});
199+
await act(async () => {
200+
clickByText("Log in with Claude");
201+
await new Promise((r) => setTimeout(r, 20));
202+
});
203+
204+
expect(pendingLogins).toHaveLength(1);
205+
await act(async () => {
206+
pendingLogins.shift()!(A_URL);
207+
await new Promise((r) => setTimeout(r, 40));
208+
});
209+
210+
expect(added).toEqual([]);
211+
expect(host.textContent).toContain("provider entry was not written");
212+
} finally {
213+
timeoutSpy.mockRestore();
214+
}
215+
});

‎src/cli/account-auth.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -137,11 +137,11 @@ async function login(argv: string[], deps: RuntimeApiDeps): Promise<void> {
137137
for (let attempt = 0; attempt < 100; attempt++) {
138138
await Bun.sleep(2_000);
139139
const state = await runtimeRequest<Record<string, unknown>>(`/api/oauth/status?provider=${encodeURIComponent(provider)}`, {}, deps);
140+
if (state.error) throw new CliUsageError(String(state.error));
140141
if (state.loggedIn === true) {
141142
printData(state, wantsJson, [`Logged in to ${provider}.`]);
142143
return;
143144
}
144-
if (state.error) throw new CliUsageError(String(state.error));
145145
}
146146
throw new CliUsageError("login timed out");
147147
}

‎src/cli/provider.ts‎

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import { providerConfigSeed } from "../providers/derive";
1515
import type { OcxProviderConfig } from "../types";
1616
import { findLiveProxy } from "../server/proxy-liveness";
1717
import { syncModelsToCodex } from "../codex/sync";
18+
import { codexAccountNamespaceProviderCollisionError } from "../codex/account-namespace-match";
1819

1920
// ---------------------------------------------------------------------------
2021
// Arg helpers
@@ -152,6 +153,12 @@ async function handleAdd(args: string[]): Promise<void> {
152153

153154
const config = loadConfig();
154155

156+
const namespaceCollision = codexAccountNamespaceProviderCollisionError(config.codexAccountNamespaces, name);
157+
if (namespaceCollision) {
158+
console.error(`Error: ${namespaceCollision}.`);
159+
process.exit(1);
160+
}
161+
155162
if (hasOwnProvider(config.providers, name) && !force) {
156163
console.error(`Provider "${name}" already exists. Use --force to overwrite.`);
157164
process.exit(1);

‎src/codex/account-id.ts‎

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/** Canonical persisted Codex pool-account id format. */
2+
export const CODEX_ACCOUNT_ID_RE = /^[A-Za-z0-9._-]{1,64}$/;
3+
4+
// Account credentials are persisted in JSON object maps. These names have
5+
// special meaning on ordinary JavaScript objects and must never be admitted as
6+
// user-controlled keys.
7+
const RESERVED_CODEX_ACCOUNT_IDS = new Set(["__proto__", "prototype", "constructor"]);
8+
9+
/**
10+
* Stable internal id under which the Codex Desktop login participates in account rotation.
11+
* It is reserved and must never be used as a public namespace target or pool-account id.
12+
*/
13+
export const MAIN_CODEX_ACCOUNT_ID = "__main__";
14+
15+
export function isValidCodexAccountId(accountId: unknown): accountId is string {
16+
return typeof accountId === "string"
17+
&& accountId !== MAIN_CODEX_ACCOUNT_ID
18+
&& CODEX_ACCOUNT_ID_RE.test(accountId)
19+
&& !RESERVED_CODEX_ACCOUNT_IDS.has(accountId.toLowerCase());
20+
}
21+
22+
type CodexAccountIdentityRow = { id: string; isMain: boolean };
23+
24+
/** Legacy invalid rows remain loadable for cleanup, but never participate in routing. */
25+
export function isSelectableCodexPoolAccount(account: CodexAccountIdentityRow): boolean {
26+
return !account.isMain && isValidCodexAccountId(account.id);
27+
}
28+
29+
/** A pre-validation pool row that collides with the internal Desktop-account sentinel. */
30+
export function hasLegacyMainCodexPoolAccount(
31+
accounts: readonly CodexAccountIdentityRow[] | undefined,
32+
): boolean {
33+
return accounts?.some(account => !account.isMain && account.id === MAIN_CODEX_ACCOUNT_ID) ?? false;
34+
}

‎src/codex/account-lifecycle.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,8 @@ export function resetMainCodexAccountIdentityTrackingForTests(): void {
4545

4646
export function deleteCodexAccount(runtimeConfig: OcxConfig, accountId: string): void {
4747
removeCodexAccountCredential(accountId);
48-
runtimeConfig.codexAccounts = (runtimeConfig.codexAccounts ?? []).filter(account => account.id !== accountId);
48+
runtimeConfig.codexAccounts = (runtimeConfig.codexAccounts ?? [])
49+
.filter(account => account.isMain || account.id !== accountId);
4950
if (runtimeConfig.activeCodexAccountId === accountId) runtimeConfig.activeCodexAccountId = undefined;
5051
purgeCodexAccountRuntimeState(accountId);
5152
invalidateCodexWebSocketsForAccount(accountId);
Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
import { isValidCodexAccountId } from "./account-id";
2+
3+
/** Config-only sentinel for the Codex Desktop account; outside the pool-account id grammar. */
4+
export const MAIN_CODEX_ACCOUNT_NAMESPACE_TARGET = "@main";
5+
6+
export const CODEX_ACCOUNT_NAMESPACE_COMBO_ALIAS_COLLISION_ERROR =
7+
"combo alias must not use a configured Codex account namespace";
8+
9+
const CODEX_ACCOUNT_ID_NAMESPACE_COLLISION_ERROR =
10+
"account id must not collide with a configured Codex account namespace";
11+
12+
/** Provider ids are compared case-insensitively at namespace admission boundaries. */
13+
export function codexProviderNamespaceKey(value: string): string {
14+
return value.toLowerCase();
15+
}
16+
17+
export function hasCodexAccountNamespace(
18+
namespaces: unknown,
19+
namespace: string,
20+
): boolean {
21+
return !!namespaces
22+
&& typeof namespaces === "object"
23+
&& !Array.isArray(namespaces)
24+
&& Object.hasOwn(namespaces, namespace);
25+
}
26+
27+
export function codexAccountNamespaceProviderCollisionError(
28+
namespaces: unknown,
29+
providerName: string,
30+
): string | undefined {
31+
const normalizedProvider = codexProviderNamespaceKey(providerName);
32+
const collides = !!namespaces
33+
&& typeof namespaces === "object"
34+
&& !Array.isArray(namespaces)
35+
&& Object.keys(namespaces)
36+
.some(namespace => codexProviderNamespaceKey(namespace) === normalizedProvider);
37+
return collides
38+
? "provider name must not collide with a configured Codex account namespace"
39+
: undefined;
40+
}
41+
42+
export function codexAccountIdNamespaceCollisionError(
43+
namespaces: unknown,
44+
accountId: string,
45+
): string | undefined {
46+
return hasCodexAccountNamespace(namespaces, accountId)
47+
? CODEX_ACCOUNT_ID_NAMESPACE_COLLISION_ERROR
48+
: undefined;
49+
}
50+
51+
export function codexAccountNamespaceForModel(
52+
namespaces: unknown,
53+
modelId: string,
54+
): string | undefined {
55+
const slash = modelId.indexOf("/");
56+
if (slash <= 0) return undefined;
57+
const namespace = modelId.slice(0, slash);
58+
return hasCodexAccountNamespace(namespaces, namespace) ? namespace : undefined;
59+
}
60+
61+
export function isValidCodexAccountNamespaceTarget(accountId: unknown): accountId is string {
62+
return accountId === MAIN_CODEX_ACCOUNT_NAMESPACE_TARGET || isValidCodexAccountId(accountId);
63+
}

0 commit comments

Comments
 (0)