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(desktop): harden OAuth client migration

liugaowei97e76ba4a616
diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.ts
index 2d65d685d6..b1bbcb60c3 100644
--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts
+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts
@@ -831,6 +831,8 @@ export class GhostManager {
opts?: {
expectedPackageSha256?: string;
trustOverride?: GhostHostTrustOverride;
+ /** 新目录已换位、旧目录仍可回滚时执行;抛错会恢复旧版本。 */
+ beforePackageCommit?: () => void;
/** 目录换位完成后、任何通知或运行时收尾前触发。 */
onPackagePlaced?: () => void;
},
@@ -921,6 +923,26 @@ export class GhostManager {
rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) },
};
}
+ try {
+ opts?.beforePackageCommit?.();
+ } catch (err) {
+ try {
+ await fs.promises.rename(finalDir, stagingDir);
+ await fs.promises.rename(backupDir, finalDir);
+ await fs.promises.rm(stagingDir, { recursive: true, force: true }).catch(() => {});
+ } catch (rollbackErr) {
+ this.options.log?.warn('ghost update pre-commit rollback failed', {
+ id: manifest.id,
+ error: rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr),
+ });
+ if (!(await pathExists(finalDir)) && (await pathExists(stagingDir))) {
+ await fs.promises.rename(stagingDir, finalDir).catch(() => {});
+ }
+ }
+ return {
+ rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) },
+ };
+ }
await fs.promises.rm(backupDir, { recursive: true, force: true }).catch(() => {});
const ghost: InstalledGhost = {
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
index 9991aad66e..c67c226d53 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
@@ -765,6 +765,27 @@ describe('GhostManager · update(原位换版)', () => {
expect(fs.existsSync(path.join(rootDir, 'hello', '.disabled'))).toBe(false);
});
+ it('提交前回调失败时恢复旧版本', async () => {
+ await manager.install(await makeCindy('v1.cindy', goodManifest(), { 'old.txt': 'v1' }));
+ const result = await manager.update(
+ await makeCindy(
+ 'v2.cindy',
+ { ...goodManifest(), version: '2.0.0' },
+ { 'new.txt': 'v2' },
+ ),
+ {
+ beforePackageCommit: () => {
+ throw new Error('migration write failed');
+ },
+ },
+ );
+
+ await expectRejection(result, 'io');
+ expect(manager.list()[0]?.manifest.version).toBe('1.0.0');
+ expect(fs.existsSync(path.join(rootDir, 'hello', 'old.txt'))).toBe(true);
+ expect(fs.existsSync(path.join(rootDir, 'hello', 'new.txt'))).toBe(false);
+ });
+
it('未装入 → not-installed 拒绝', async () => {
await expectRejection(
await manager.update(await makeCindy('a.cindy', goodManifest())),
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthAccounts.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthAccounts.test.ts
index 098bf8b7b2..c5ec161387 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthAccounts.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthAccounts.test.ts
@@ -192,6 +192,33 @@ describe('插件 OAuth clientId 迁移', () => {
expect(customized.listAccounts(GHOST, KEY)[0]?.status).toBe('connected');
expect(customized.clientMigrationExpiredAccountCount(GHOST, KEY)).toBe(0);
});
+
+ it('迁移状态写入失败时抛错并保留旧账号与 refresh token', () => {
+ const vault = memoryVault({
+ [`${KEY}-accounts`]: JSON.stringify({
+ defaultAccountId: 'acc-1',
+ accounts: [{ id: 'acc-1', label: '[email protected]', status: 'connected', createdAt: 1 }],
+ }),
+ [`${KEY}-rt-acc-1`]: 'rt-old-client',
+ });
+ const store = vault.store;
+ vault.store = (ghostId, key, value) =>
+ key === `${KEY}-accounts` ? false : store(ghostId, key, value);
+ const mgr = new GhostOauthAccountManager({
+ vault,
+ fetchImpl: vi.fn() as unknown as typeof fetch,
+ openExternal: vi.fn(),
+ });
+
+ expect(() =>
+ mgr.expireAccountsForChangedClients(
+ oauthManifest('old-client'),
+ oauthManifest('new-client'),
+ ),
+ ).toThrow('Unable to persist OAuth client migration state');
+ expect(mgr.listAccounts(GHOST, KEY)[0]?.status).toBe('connected');
+ expect(vault.read(GHOST, `${KEY}-rt-acc-1`)).toBe('rt-old-client');
+ });
});
describe('missingAuthScopes(快照推断)', () => {
@@ -803,6 +830,44 @@ describe('connectAccount', () => {
});
});
+ it('clientId 迁移重连未返回 refresh token 时移除旧 token', async () => {
+ const vault = memoryVault({
+ [`${KEY}-client-id`]: 'cid',
+ [`${KEY}-accounts`]: JSON.stringify({
+ defaultAccountId: 'acc-1',
+ accounts: [
+ {
+ id: 'acc-1',
+ label: '[email protected]',
+ status: 'expired',
+ expiredReason: 'oauth_client_changed',
+ createdAt: 1,
+ },
+ ],
+ }),
+ [`${KEY}-rt-acc-1`]: 'rt-old-client',
+ });
+ const fetchImpl = vi.fn(async (input: string | URL | Request) => {
+ if (String(input) === DECL.tokenUrl) {
+ return jsonResponse({ access_token: 'at-re', expires_in: 3600 });
+ }
+ return jsonResponse({ email: '[email protected]' });
+ });
+ const mgr = new GhostOauthAccountManager({
+ vault,
+ fetchImpl: fetchImpl as unknown as typeof fetch,
+ openExternal: autoBrowser(),
+ });
+
+ await expect(mgr.connectAccount(GHOST, KEY, DECL)).resolves.toMatchObject({ ok: true });
+ expect(vault.read(GHOST, `${KEY}-rt-acc-1`)).toBeNull();
+ expect(mgr.clientMigrationExpiredAccountCount(GHOST, KEY)).toBe(0);
+ await expect(mgr.getFreshAccessToken(GHOST, KEY, DECL, 'acc-1')).resolves.toMatchObject({
+ ok: true,
+ accessToken: 'at-re',
+ });
+ });
+
it('onAccountConnected 钩子:新连与同身份重连都触发(带标签);钩子抛错不影响连接结果', async () => {
// 新连:带身份标签触发一次
const onNew = vi.fn();
diff --git a/apps/desktop/src/main/cindy-brain/ghostOauthAccounts.ts b/apps/desktop/src/main/cindy-brain/ghostOauthAccounts.ts
index b4ad144576..6936ccbb0a 100644
--- a/apps/desktop/src/main/cindy-brain/ghostOauthAccounts.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostOauthAccounts.ts
@@ -703,6 +703,10 @@ export class GhostOauthAccountManager {
) {
return { ok: false, error: 'VAULT_WRITE_FAILED' };
}
+ } else if (existing.expiredReason === 'oauth_client_changed') {
+ // 新 client 的授权响应没有 refresh token 时,不能继续保留旧 client
+ // 签发的 token;当前 access token 过期后按无 refresh token 正常引导重连。
+ this.deps.vault.remove(ghostId, refreshTokenKey(secretKey, existing.id));
}
// 重连顺带刷新展示名:老账号(displayTemplate 上线前连的)或用户改过
// 显示名/workspace 名的,这里追上最新值。
@@ -1107,7 +1111,7 @@ export class GhostOauthAccountManager {
ghostId,
secretKey,
});
- return 0;
+ throw new Error('Unable to persist OAuth client migration state');
}
}
for (const key of this.tokenCache.keys()) {
diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.ts
index 824a138599..ca8ba3ccb5 100644
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@ -4039,6 +4039,12 @@ async function installOrUpdateMarketGhostPackageLocked(
result = await manager.update(cindyFilePath, {
expectedPackageSha256: inspected.packageSha256,
...(trustOverride ? { trustOverride } : {}),
+ beforePackageCommit: () => {
+ getGhostOauthAccountManager().expireAccountsForChangedClients(
+ withRuntimeFiloGoogleClient(installed.manifest),
+ withRuntimeFiloGoogleClient(inspected.canonicalManifest),
+ );
+ },
onPackagePlaced: () => {
packagePlaced = true;
expected.onPackagePlacedInLock?.();
@@ -4061,10 +4067,6 @@ async function installOrUpdateMarketGhostPackageLocked(
spawnIfResident(installed);
throwInstallError(result.rejection);
}
- getGhostOauthAccountManager().expireAccountsForChangedClients(
- withRuntimeFiloGoogleClient(installed.manifest),
- withRuntimeFiloGoogleClient(result.ghost.manifest),
- );
runtime.resetFuse(expected.ghostId);
const store = getLayoutStore();
const docked = layoutWithGhostPanel(store.getLayout(), result.ghost.manifest);
@@ -5401,6 +5403,16 @@ export function registerGhostIpc(): void {
try {
result = await manager.update(lizFilePath, {
expectedPackageSha256,
+ ...(previousGhost
+ ? {
+ beforePackageCommit: () => {
+ getGhostOauthAccountManager().expireAccountsForChangedClients(
+ withRuntimeFiloGoogleClient(previousGhost.manifest),
+ withRuntimeFiloGoogleClient(inspected.canonicalManifest),
+ );
+ },
+ }
+ : {}),
onPackagePlaced: () => {
packagePlaced = true;
},
@@ -5425,12 +5437,6 @@ export function registerGhostIpc(): void {
if (previousGhost) spawnIfResident(previousGhost);
throwInstallError(result.rejection);
}
- if (previousGhost) {
- getGhostOauthAccountManager().expireAccountsForChangedClients(
- withRuntimeFiloGoogleClient(previousGhost.manifest),
- withRuntimeFiloGoogleClient(result.ghost.manifest),
- );
- }
runtime.resetFuse(inspected.manifest.id); // 换了代码,给新版本干净的熔断记账
const store = getLayoutStore();
const docked = layoutWithGhostPanel(store.getLayout(), result.ghost.manifest);