Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(auth): roll back unsafe account capability transitions

Chris6d81a540075f
diff --git a/apps/desktop/src/main/maker-host/__tests__/codex-account-auth.test.ts b/apps/desktop/src/main/maker-host/__tests__/codex-account-auth.test.ts
index a422087ce3..daebf2662a 100644
--- a/apps/desktop/src/main/maker-host/__tests__/codex-account-auth.test.ts
+++ b/apps/desktop/src/main/maker-host/__tests__/codex-account-auth.test.ts
@@ -98,10 +98,29 @@ beforeEach(() => {
setCodexAccountRetirement(async () => {});
});
afterEach(() => {
+ vi.restoreAllMocks();
fs.rmSync(state.root, { recursive: true, force: true });
});
describe('native Codex account credentials', () => {
+ it('keeps the original identity when its model cache cannot be removed', async () => {
+ await loginCodexAccount('account-a', () => true);
+ const home = codexAccountHome('account-a');
+ const files = ['auth.json', 'account.json', 'config.toml'];
+ const before = files.map(file => fs.readFileSync(path.join(home, file), 'utf8'));
+ const cache = path.join(home, 'models_cache.json');
+ fs.writeFileSync(cache, '{"models":[]}');
+ state.raw = credential('person-b');
+ const rm = fs.rmSync.bind(fs);
+ vi.spyOn(fs, 'rmSync').mockImplementation((target, options) => {
+ if (target === cache) throw Object.assign(new Error('cache busy'), { code: 'EPERM' });
+ rm(target, options);
+ });
+ await expect(loginCodexAccount('account-a', () => true)).rejects.toThrow('cache busy');
+ expect(files.map(file => fs.readFileSync(path.join(home, file), 'utf8'))).toEqual(before);
+ expect(codexAccountState('account-a').identity).toBe('[email protected]');
+ expect(fs.readFileSync(cache, 'utf8')).toBe('{"models":[]}');
+ });
it('signals explicit auth replacement before retirement and readiness immediately after commit', async () => {
const result = await loginCodexAccount('account-a', () => true);
expect(result.ok).toBe(true);
diff --git a/apps/desktop/src/main/maker-host/codex-account-auth.ts b/apps/desktop/src/main/maker-host/codex-account-auth.ts
index e7e57c5985..8c77fb5a67 100644
--- a/apps/desktop/src/main/maker-host/codex-account-auth.ts
+++ b/apps/desktop/src/main/maker-host/codex-account-auth.ts
@@ -287,6 +287,9 @@ export async function loginCodexAccount(
return false;
}
};
+ // Invalidation can fail (e.g. Windows delete sharing). Do it before changing
+ // credentials so failure leaves the original identity and grant intact.
+ if (identityChanged) fs.rmSync(path.join(home, 'models_cache.json'), { force: true });
// Synchronous commit after the final ownership check; no other request can interleave.
fs.writeFileSync(path.join(home, 'account.json'), JSON.stringify(identity), { mode: 0o600 });
fs.writeFileSync(path.join(home, 'config.toml'), 'cli_auth_credentials_store = "file"\n', {
@@ -295,8 +298,6 @@ export async function loginCodexAccount(
fs.renameSync(path.join(staging, 'auth.json'), path.join(home, 'auth.json'));
fs.rmSync(path.join(home, 'disconnected'), { force: true });
fs.rmSync(path.join(home, 'invalidated'), { force: true });
- // An old identity's model cache must not regrant its account-only tiers.
- if (identityChanged) fs.rmSync(path.join(home, 'models_cache.json'), { force: true });
broadcastCodexAccountAuthReady(providerId);
accountAuthReadySent = true;
return { ok: true, firstLogin: previous === null, previousIdentity: previous?.label, identityChanged, rollbackCredentials };
diff --git a/apps/desktop/src/main/maker-host/custom-provider-store.ts b/apps/desktop/src/main/maker-host/custom-provider-store.ts
index 42d4517ef6..a3af957b04 100644
--- a/apps/desktop/src/main/maker-host/custom-provider-store.ts
+++ b/apps/desktop/src/main/maker-host/custom-provider-store.ts
@@ -779,6 +779,17 @@ export function clearCodexAccountUltrafast(config: CustomProviderConfig): Custom
} } };
}
+/** A CAS miss/owner switch rejects the replacement login instead of keeping an old grant. */
+export async function revokeCodexAccountUltrafast(
+ providerId: string,
+ sameOwner: () => boolean,
+): Promise<boolean> {
+ if (!sameOwner()) return false;
+ const previous = await getCustomProvider(providerId);
+ if (!sameOwner() || !previous || previous.auth?.native !== 'codex') return false;
+ return updateCustomProviderIfUnchanged(providerId, previous, clearCodexAccountUltrafast(previous));
+}
+
/** 安全解析 auth 列 JSON(坏数据 / 结构不完整兜底为 undefined = API key 历史形态)。 */
function parseAuth(raw: string | null): CustomProviderConfig['auth'] {
if (!raw) return undefined;
diff --git a/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts b/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts
index 39e100e102..3f5bb74b0d 100644
--- a/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts
+++ b/apps/desktop/src/main/maker-ipc/__tests__/providerHandlers.test.ts
@@ -9,7 +9,7 @@ import { BUILTIN_REFRESHABLE_PROVIDER_IDS } from '../../../shared/providerModelR
import type { DbClient } from '../../localDb/client/DbClient.js';
import { clearCurrentDbClient, setCurrentDbClient } from '../../localDb/client/current.js';
import * as schema from '../../localDb/schema.js';
-import { createCustomProvider, getCustomProvider, listCustomProviders } from '../../maker-host/custom-provider-store.js';
+import { createCustomProvider, getCustomProvider, listCustomProviders, revokeCodexAccountUltrafast } from '../../maker-host/custom-provider-store.js';
import { codexCustomProviderConfigSignature } from '../../maker-host/codex-custom-provider-route.js';
import {
beginProviderRouteMutation,
@@ -4244,6 +4244,64 @@ describe('provider:oauth mutation ordering', () => {
expect(rollbackCredentials).toHaveBeenCalledOnce();
});
+ // Regression: a replacement login must not survive an interleaved settings
+ // write or owner switch before revocation. Use the real handler and SQLite CAS.
+ it.each(['settings-edit', 'owner-switch'] as const)('rolls replacement login back after %s during capability commit', async (interleaving) => {
+ mountDb();
+ const config: CustomProviderConfig = { ...validConfig,
+ auth: { method: 'oauth', native: 'codex' },
+ runtimes: { codex: { ...validConfig.runtimes.codex!,
+ baseUrl: 'https://chatgpt.com/backend-api/codex', wireProtocol: 'openai-responses',
+ models: [{ id: 'gpt-6.1-sol', name: 'GPT-6.1 Sol', supportsUltrafastMode: true }],
+ } },
+ };
+ await createCustomProvider(config);
+ const harness = new IpcHarness();
+ let owner = { dataOwnerId: 'owner-a', generation: 1 };
+ let identity = 'new-account';
+ let release!: () => void;
+ let read!: () => void;
+ const paused = new Promise<void>(resolve => { read = resolve; });
+ const resume = new Promise<void>(resolve => { release = resolve; });
+ const rollbackCredentials = vi.fn(() => { identity = 'old-account'; return true; });
+ const afterCommit = vi.fn(async () => {});
+ registerProviderHandlers(harness, makeDeps({
+ currentOwnerSession: () => owner,
+ oauthLogin: async () => ({ ok: true, rollbackCredentials, afterCommit,
+ commitAccountCapabilities: async () => {
+ // Delay only the first real row read; the concurrent settings IPC uses
+ // the same database normally and makes the original snapshot stale.
+ const select = client!.drizzle.select.bind(client!.drizzle);
+ vi.spyOn(client!.drizzle, 'select').mockImplementationOnce((...args: any[]) => {
+ const builder = (select as any)(...args);
+ const from = builder.from.bind(builder);
+ builder.from = (...fromArgs: any[]) => {
+ const query = from(...fromArgs);
+ const get = query.get.bind(query);
+ query.get = async () => { const row = get(); read(); await resume; return row; };
+ return query;
+ };
+ return builder;
+ });
+ return revokeCodexAccountUltrafast(config.id, () => owner.generation === 1);
+ },
+ }),
+ }));
+ const login = harness.invoke(MAKER_INVOKE.PROVIDER_OAUTH_LOGIN, config.id);
+ await paused;
+ if (interleaving === 'settings-edit') {
+ await harness.invoke(MAKER_INVOKE.PROVIDER_CUSTOM_UPDATE, { ...config, name: 'Edited while logging in' });
+ } else owner = { dataOwnerId: 'owner-b', generation: 2 };
+ release();
+ await expect(login).resolves.toEqual({ ok: false, reason: 'login_cancelled' });
+ expect(identity).toBe('old-account');
+ expect(rollbackCredentials).toHaveBeenCalledOnce();
+ expect(afterCommit).not.toHaveBeenCalled();
+ const saved = (await getCustomProvider(config.id))!;
+ expect(saved.runtimes.codex!.models[0].supportsUltrafastMode).toBe(true);
+ expect(saved.name).toBe(interleaving === 'settings-edit' ? 'Edited while logging in' : config.name);
+ });
+
it.each([false, true])('publishes login identity only after acceptance (cancelled=%s)', async (cancelled) => {
const harness = new IpcHarness();
type LoginResult = Awaited<ReturnType<ProviderHandlerDeps['oauthLogin']>>;
diff --git a/apps/desktop/src/main/maker-ipc/providerHandlers.ts b/apps/desktop/src/main/maker-ipc/providerHandlers.ts
index 4ff55184ba..d2eec38c50 100644
--- a/apps/desktop/src/main/maker-ipc/providerHandlers.ts
+++ b/apps/desktop/src/main/maker-ipc/providerHandlers.ts
@@ -357,6 +357,8 @@ export interface ProviderHandlerDeps {
ok: boolean;
reason?: string;
rollbackCredentials?: () => boolean;
+ /** Required account-state commit. False or failure must roll credentials back. */
+ commitAccountCapabilities?: () => Promise<boolean>;
/** Publish identity/model changes only after the login is accepted, outside rollback. */
afterCommit?: () => Promise<void>;
}>;
@@ -2482,6 +2484,17 @@ export function registerProviderHandlers(
});
if (isOAuthMutationCurrent(id, generation)) {
if (result.ok) {
+ if (result.commitAccountCapabilities) {
+ let committed = false;
+ try { committed = await result.commitAccountCapabilities(); } catch { /* Roll back below. */ }
+ if (!committed) {
+ if (!result.rollbackCredentials?.()) {
+ finishRouteMutation.commit?.();
+ throwIpcError('INTERNAL', 'failed to restore credentials after account capability update');
+ }
+ return { ok: false, reason: 'login_cancelled' };
+ }
+ }
finishRouteMutation.commit?.();
try {
await result.afterCommit?.();
diff --git a/apps/desktop/src/main/maker-ipc/register.ts b/apps/desktop/src/main/maker-ipc/register.ts
index 35c1d90191..39ad974be7 100644
--- a/apps/desktop/src/main/maker-ipc/register.ts
+++ b/apps/desktop/src/main/maker-ipc/register.ts
@@ -1187,7 +1187,7 @@ import {
runGenericOAuthLogin,
} from '../maker-host/generic-oauth.js';
import {
- clearCodexAccountUltrafast,
+ revokeCodexAccountUltrafast,
getCustomProvider,
mergeDiscoveredModelsIntoConfig,
updateCustomProviderIfUnchanged,
@@ -7378,23 +7378,23 @@ export function registerMakerIpc(maker: Maker, options: RegisterMakerIpcOptions)
const current = () => isCurrent() && sameOwner();
const result = await loginCodexAccount(providerId, isCurrent, onBrowserUrl);
if (!result.ok) return result;
- return { ...result, afterCommit: async () => {
- // Cancellation after acceptance keeps the new credentials, so it must
- // not interrupt invalidation of the old identity's entitlement.
+ return { ...result,
+ ...(result.identityChanged ? {
+ commitAccountCapabilities: () => revokeCodexAccountUltrafast(providerId, sameOwner),
+ } : {}),
+ afterCommit: async () => {
if (!sameOwner()) return;
+ if (result.identityChanged) await refreshCustomProvidersIntoCatalog();
+ if (!current()) return;
const previous = await getCustomProvider(providerId);
- if (!sameOwner()) return;
+ if (!current()) return;
const identity = codexAccountState(providerId).identity;
- if (previous) {
- // Cancellation before acceptance rolls credentials back without
- // invoking afterCommit or changing the saved capabilities.
- let next = result.identityChanged ? clearCodexAccountUltrafast(previous) : previous;
+ if (previous && identity) {
const names = new Set(getActiveCatalog().providers.filter((provider) => provider.id !== providerId).map((provider) => provider.name));
- const name = identity ? codexAccountLoginName(previous.name, result.previousIdentity, identity, names) : undefined;
- if (name !== undefined) next = { ...next, name };
- if (next !== previous) {
- await updateCustomProviderIfUnchanged(providerId, previous, next);
- if (!sameOwner()) return;
+ const name = codexAccountLoginName(previous.name, result.previousIdentity, identity, names);
+ if (name !== undefined) {
+ await updateCustomProviderIfUnchanged(providerId, previous, { ...previous, name });
+ if (!current()) return;
await refreshCustomProvidersIntoCatalog();
}
}
diff --git a/docs/product-rules/model-metadata-precedence.md b/docs/product-rules/model-metadata-precedence.md
index beedb11fcc..12ec308fb8 100644
--- a/docs/product-rules/model-metadata-precedence.md
+++ b/docs/product-rules/model-metadata-precedence.md
@@ -105,8 +105,9 @@ Codex 超快是账号发现能力:`service_tiers` / `additional_speed_tiers`
`serviceTiers` / `additionalSpeedTiers`)明确声明后,按连接保存 `supportsUltrafastMode`,
不进入可继承的 `ModelMetadata`,不按套餐名、型号或公共目录授予。
保存、重读和目录投影须保留该值;成功刷新该型号不再声明超快时清除旧资格。
-同一连接重新登录为不同身份或工作区时,提交登录后、刷新模型前清除旧资格,
-原生模型缓存随身份切换清除;取消登录回滚凭证与缓存,不提交资格变更。
+同一连接重新登录为不同身份或工作区时,接受登录前必须成功清除旧资格;
+CAS 冲突、所属用户切换或写入失败时回滚登录,不把撤权放进可忽略失败的展示刷新。
+原生模型缓存先于凭证提交清除,删除失败保留原身份;取消登录回滚凭证与缓存。
仅原生 Codex 账号的 Codex 入口可用,API 同名模型及其它引擎不继承。
回归见 `custom-provider-store.test.ts` 与 `modelDiscoveryChannels.test.ts`。