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。

Merge origin/main into plugin approval receipt migration

Yuewei-LL0615bb31002f
diff --cc apps/desktop/src/main/bootstrap-electron.ts
index ed80cefde7,7ad0338e23..1a8a4e9369
--- a/apps/desktop/src/main/bootstrap-electron.ts
+++ b/apps/desktop/src/main/bootstrap-electron.ts
@@@ -746,8 -746,7 +746,9 @@@ import
getGhostCindySlot,
getGhostManager,
getGhostSessionActivityTracker,
+ interruptGhostCallsForAccountBoundary,
isGhostAvailableForActiveSession,
++ reconcileGhostOauthAccountsForActiveOwner,
refreshGhostLocalization,
registerGhostIpc,
setGhostsChangedObserver,
@@@ -3081,6 -3004,6 +3082,15 @@@ function syncDefaultPluginsForActiveOwn
});
}
++function reconcileGhostOauthForActiveOwner(): void {
++ void reconcileGhostOauthAccountsForActiveOwner().catch((error) => {
++ createLogger('ghost-oauth-owner-reconcile').warn(
++ 'OAuth account reconciliation for active owner failed',
++ { error: error instanceof Error ? error.message : String(error) },
++ );
++ });
++}
++
function parseOptionalDeviceLinkDeviceId(value: unknown): string | null | undefined {
if (value === undefined) return undefined;
if (value === null) return null;
@@@ -5203,9 -5145,9 +5213,13 @@@ const registerIpcHandlers = () =>
// 复用市场快照;云端登录/切号的通知可能早于 owner boundary 释放,因此
// 延迟到当前调用栈结束后再按已提交的新 owner 补跑一次。
disposePluginMarketAuthListener = authManager.onAuthStateChange(() => {
-- queueMicrotask(syncDefaultPluginsForActiveOwner);
++ queueMicrotask(() => {
++ syncDefaultPluginsForActiveOwner();
++ reconcileGhostOauthForActiveOwner();
++ });
});
syncDefaultPluginsForActiveOwner();
++ reconcileGhostOauthForActiveOwner();
// ── Dialog: 目录选择器(v0.6 新增,与旧 show-open-directory-dialog 并存) ──
ipcMain.handle(
diff --cc apps/desktop/src/main/cindy-brain/GhostManager.ts
index 4e562ff51f,b1bbcb60c3..f2c219d253
--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts
+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts
@@@ -193,17 -119,8 +193,27 @@@ export type InstallRejection
| { code: 'already-installed'; reason: string }
| { code: 'not-installed'; reason: string }
| { code: 'command-conflict'; reason: string }
- | { code: 'io'; reason: string };
+ | { code: 'state-changed'; reason: string }
+ | {
+ code: 'io';
+ reason: string;
+ /**
+ * 更新失败后连旧版本目录都没能滚回原位(Windows 文件锁/AV 等):此时安装目录
+ * 可能是新字节或缺失,调用方**不得**按"旧版本还在"重启运行时。
+ */
+ rollbackFailed?: boolean;
+ };
+
++/**
++ * Reversible side effect prepared after the new package directory is in place.
++ * Durable writes happen before this object is returned; `commit` only publishes
++ * best-effort notifications after the receipt has committed.
++ */
++export interface GhostPackageCommitPreparation {
++ commit(): void;
++ rollback(): void;
++}
+
export type UninstallRejection =
| { code: 'invalid-id'; reason: string }
| { code: 'not-installed'; reason: string }
@@@ -2933,23 -828,11 +2943,26 @@@ export class GhostManager
*/
async update(
lizFilePath: string,
- opts?: {
+ opts: {
+ expectedInstalledApproval: string;
+ expectedPackageSha256?: string;
+ trustOverride?: GhostHostTrustOverride;
++ beforePackageCommit?: () => GhostPackageCommitPreparation | void;
+ /** 目录换位完成后、任何通知或运行时收尾前触发。 */
+ onPackagePlaced?: () => void;
+ },
+ ) {
+ return this.runExclusiveMutation(() => this.updateUnlocked(lizFilePath, opts));
+ }
+
+ private async updateUnlocked(
+ lizFilePath: string,
+ opts: {
+ expectedInstalledApproval: string;
expectedPackageSha256?: string;
trustOverride?: GhostHostTrustOverride;
+ /** 新目录已换位、旧目录仍可回滚时执行;抛错会恢复旧版本。 */
- beforePackageCommit?: () => void;
++ beforePackageCommit?: () => GhostPackageCommitPreparation | void;
/** 目录换位完成后、任何通知或运行时收尾前触发。 */
onPackagePlaced?: () => void;
},
@@@ -3122,85 -917,32 +3135,134 @@@
try {
await fs.promises.rename(stagingDir, finalDir);
} catch (err) {
- await fs.promises.rename(backupDir, finalDir).catch(() => {});
+ let rolledBack = true;
+ await fs.promises.rename(backupDir, finalDir).catch((rollbackErr) => {
+ rolledBack = false;
+ (this.options.log?.error ?? this.options.log?.warn)?.call(
+ this.options.log,
+ 'ghost update rollback failed; install dir left inconsistent',
+ {
+ id: manifest.id,
+ backupDir,
+ error: rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr),
+ },
+ );
+ });
await fs.promises.rm(stagingDir, { recursive: true, force: true }).catch(() => {});
+ // 只有回滚成功时才能清标记。回滚失败必须保留 journal,让下次启动继续收敛;
+ // 清掉它会让 orphan-backup 启发式把新字节与旧 receipt 固化在一起。
+ if (rolledBack) {
+ await clearUpdateQuarantineAfterRollback();
+ }
return {
- rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) },
+ rejection: {
+ code: 'io',
+ reason: err instanceof Error ? err.message : String(err),
+ ...(rolledBack ? {} : { rollbackFailed: true }),
+ },
};
}
- // 与 install 同理:技能字节指纹从这次换入的内容目录现算。
++ // Durable side effects (currently OAuth client migration) join the package
++ // transaction after the new manifest is in place but before its receipt is
++ // committed. Later failures compensate both this side effect and the
++ // directory swap; either rollback failure keeps journal + quarantine.
++ let packageCommitPreparation: GhostPackageCommitPreparation | undefined;
+ let receipt: GhostInstallReceipt;
try {
- opts?.beforePackageCommit?.();
++ packageCommitPreparation = opts.beforePackageCommit?.() ?? undefined;
+ receipt = createGhostInstallReceipt({
+ manifest: approvedManifest,
+ localeResources,
+ enabled,
+ trust,
+ // 同 install:指纹取自包投影,发布后的目录漂移在快照对账时 fail closed(P0-8)。
+ skillContentSha256: await this.hashSkillContentFromPackage(
+ approvedManifest,
+ allEntries,
+ prefix,
+ ),
+ packageSha256,
+ revision: receiptRevision,
+ ...(iconDataUrl !== undefined ? { iconDataUrl } : {}),
+ });
+ await this.receiptStore.write(receipt, { skillSourceDir: finalDir });
} catch (err) {
- let rolledBack = true;
- await fs.promises.rm(finalDir, { recursive: true, force: true }).catch(() => undefined);
- await fs.promises.rename(backupDir, finalDir).catch((rollbackErr) => {
- rolledBack = false;
- 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(() => {});
++ let sideEffectRolledBack = !(
++ err instanceof Error &&
++ 'rollbackFailed' in err &&
++ err.rollbackFailed === true
++ );
++ if (packageCommitPreparation) {
++ try {
++ packageCommitPreparation.rollback();
++ } catch (rollbackErr) {
++ sideEffectRolledBack = false;
++ (this.options.log?.error ?? this.options.log?.warn)?.call(
++ this.options.log,
++ 'ghost update side-effect rollback failed',
++ {
++ id: manifest.id,
++ error: rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr),
++ },
++ );
+ }
+ }
++ let directoryRolledBack = false;
++ if (sideEffectRolledBack) {
++ directoryRolledBack = true;
++ await fs.promises.rm(finalDir, { recursive: true, force: true }).catch(() => undefined);
++ await fs.promises.rename(backupDir, finalDir).catch((rollbackErr) => {
++ directoryRolledBack = false;
++ (this.options.log?.error ?? this.options.log?.warn)?.call(
++ this.options.log,
++ 'ghost update rollback failed after receipt write failure',
++ {
++ id: manifest.id,
++ backupDir,
++ error: rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr),
++ },
++ );
++ });
++ } else {
++ // Preserve the normal interrupted-update shape (new final + old backup)
++ // when the side effect cannot be compensated. Startup first restores the
++ // old package from this journal, then OAuth reconciliation can safely
++ // restore only accounts tagged for that rolled-back client transition.
+ (this.options.log?.error ?? this.options.log?.warn)?.call(
+ this.options.log,
- 'ghost update rollback failed after receipt write failure',
- {
- id: manifest.id,
- backupDir,
- error: rollbackErr instanceof Error ? rollbackErr.message : String(rollbackErr),
- },
++ 'ghost update left package swap for startup recovery after side-effect rollback failure',
++ { id: manifest.id, backupDir },
+ );
- });
++ }
++ const rolledBack = sideEffectRolledBack && directoryRolledBack;
+ if (rolledBack) {
+ await clearUpdateQuarantineAfterRollback();
+ }
return {
- rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) },
+ rejection: {
+ code: 'io',
+ reason: err instanceof Error ? err.message : String(err),
+ ...(rolledBack ? {} : { rollbackFailed: true }),
+ },
};
}
+ // receipt 已就位 = 事务提交,清标记后再回收 backup;顺序保证"标记在 ⟺ 可能未提交"。
+ try {
+ await this.receiptStore.clearPendingMutation(manifest.id);
+ this.untrustedApprovals.delete(this.isolationKey(manifest.id));
+ } catch {
+ // Keep quarantine while the durable journal remains; recovery retries it.
+ }
++ try {
++ packageCommitPreparation?.commit();
++ } catch (err) {
++ // Receipt and package bytes are already committed. Notification failure
++ // must not report a false update rollback to the caller.
++ this.options.log?.warn('ghost update side-effect commit notification failed', {
++ id: manifest.id,
++ error: err instanceof Error ? err.message : String(err),
++ });
++ }
await fs.promises.rm(backupDir, { recursive: true, force: true }).catch(() => {});
const ghost: InstalledGhost = {
diff --cc apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
index be3b0d6a6e,c67c226d53..b491cff143
--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
@@@ -4408,8 -765,32 +4408,116 @@@ 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' },
+ ),
+ {
++ expectedInstalledApproval: ghostInstallApprovalToken(manager.list()[0]?.approval),
+ 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())),
- 'not-installed',
++ it('receipt 提交失败时补偿副作用并恢复旧版本', async () => {
++ await manager.install(await makeCindy('v1.cindy', goodManifest(), { 'old.txt': 'v1' }));
++ const rollback = vi.fn();
++ const commit = vi.fn();
++ const store = (
++ manager as unknown as {
++ receiptStore: { write(...args: unknown[]): Promise<void> };
++ }
++ ).receiptStore;
++ const writeSpy = vi.spyOn(store, 'write').mockRejectedValueOnce(new Error('receipt blocked'));
++ try {
++ const result = await manager.update(
++ await makeCindy('v2.cindy', { ...goodManifest(), version: '2.0.0' }, { 'new.txt': 'v2' }),
++ {
++ expectedInstalledApproval: ghostInstallApprovalToken(manager.list()[0]?.approval),
++ beforePackageCommit: () => ({ commit, rollback }),
++ },
++ );
++ await expectRejection(result, 'io');
++ } finally {
++ writeSpy.mockRestore();
++ }
++ expect(rollback).toHaveBeenCalledTimes(1);
++ expect(commit).not.toHaveBeenCalled();
++ expect(manager.list()[0]?.manifest.version).toBe('1.0.0');
++ expect(fs.existsSync(path.join(rootDir, 'hello', 'old.txt'))).toBe(true);
++ });
++
++ it('副作用补偿失败时保留 journal、隔离和可恢复的目录交换现场', async () => {
++ await manager.install(await makeCindy('v1.cindy', goodManifest(), { 'old.txt': 'v1' }));
++ const store = (
++ manager as unknown as {
++ receiptStore: { write(...args: unknown[]): Promise<void> };
++ }
++ ).receiptStore;
++ const writeSpy = vi.spyOn(store, 'write').mockRejectedValueOnce(new Error('receipt blocked'));
++ try {
++ const result = await manager.update(
++ await makeCindy('v2.cindy', { ...goodManifest(), version: '2.0.0' }, { 'new.txt': 'v2' }),
++ {
++ expectedInstalledApproval: ghostInstallApprovalToken(manager.list()[0]?.approval),
++ beforePackageCommit: () => ({
++ commit: vi.fn(),
++ rollback: () => {
++ throw new Error('vault blocked');
++ },
++ }),
++ },
++ );
++ expect(result).toMatchObject({ rejection: { code: 'io', rollbackFailed: true } });
++ } finally {
++ writeSpy.mockRestore();
++ }
++ expect(manager.list()[0]).toMatchObject({ approval: { state: 'invalid' }, enabled: false });
++ expect(fs.existsSync(path.join(rootDir, 'hello', 'new.txt'))).toBe(true);
++ expect(fs.readdirSync(rootDir).some((name) => name.startsWith('.cindy-updating-hello-'))).toBe(true);
++ expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', '.pending-hello.json'))).toBe(true);
++
++ const recovered = new GhostManager({
++ getRootDir: () => rootDir,
++ getLocale: () => hostLocale,
++ onChanged,
++ });
++ expect(recovered.list()[0]?.manifest.version).toBe('1.0.0');
++ expect(fs.existsSync(path.join(rootDir, 'hello', 'old.txt'))).toBe(true);
++ });
++
++ it('副作用只在 receipt 提交后 commit', async () => {
++ await manager.install(await makeCindy('v1.cindy', goodManifest()));
++ const events: string[] = [];
++ const result = await manager.update(
++ await makeCindy('v2.cindy', { ...goodManifest(), version: '2.0.0' }),
++ {
++ expectedInstalledApproval: ghostInstallApprovalToken(manager.list()[0]?.approval),
++ beforePackageCommit: () => ({
++ rollback: vi.fn(),
++ commit: () => {
++ events.push(manager.list()[0]?.manifest.version ?? 'missing');
++ },
++ }),
++ },
+ );
++ expect('ghost' in result).toBe(true);
++ expect(events).toEqual(['2.0.0']);
++ });
++
+ it('未装入 → not-installed 拒绝', async () => {
+ await expectRejection(await updateGhost(await makeCindy('a.cindy', goodManifest())), 'not-installed');
});
it('指令查重豁免自己,但仍拦别人的指令', async () => {
diff --cc apps/desktop/src/main/cindy-brain/__tests__/ghostOauthAccounts.test.ts
index cbbdcf7d1a,c5ec161387..35b034115b
--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthAccounts.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthAccounts.test.ts
@@@ -79,6 -81,146 +81,372 @@@ function seededVault(rt = 'rt-seed'): R
});
}
+ function oauthManifest(clientId: string): GhostManifest {
+ return {
+ schemaVersion: 2,
+ kind: 'chip',
+ id: GHOST,
+ name: 'Google',
+ description: 'test',
+ whenToUse: 'test',
+ version: '1.0.0',
+ author: 'test',
+ entry: 'main.js',
+ slots: ['network'],
+ network: {
+ hosts: ['api.example.com'],
+ secrets: [
+ {
+ key: KEY,
+ label: 'Google account',
+ source: 'oauth',
+ inject: {
+ header: 'Authorization',
+ format: 'Bearer {value}',
+ hosts: ['api.example.com'],
+ },
+ oauth: { ...DECL, clientId },
+ },
+ ],
+ },
+ };
+ }
+
++function oauthManifestWithoutBuiltinClient(): GhostManifest {
++ const manifest = oauthManifest('placeholder');
++ const secret = manifest.network?.secrets?.[0];
++ if (secret?.source === 'oauth' && secret.oauth) delete secret.oauth.clientId;
++ return manifest;
++}
++
+ describe('插件 OAuth clientId 迁移', () => {
+ it('仅内置 clientId 变化时标记迁移过期,保留且不再消费旧 refresh token', async () => {
+ 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 onAccountStatusChanged = vi.fn();
+ const fetchImpl = vi.fn();
+ const mgr = new GhostOauthAccountManager({
+ vault,
+ fetchImpl: fetchImpl as unknown as typeof fetch,
+ openExternal: vi.fn(),
+ onAccountStatusChanged,
+ });
+
+ expect(
- mgr.expireAccountsForChangedClients(
- oauthManifest('old-client'),
- oauthManifest('new-client'),
- ),
++ mgr.expireAccountsForChangedClients(oauthManifest('old-client'), oauthManifest('new-client')),
+ ).toBe(1);
+ expect(mgr.listAccounts(GHOST, KEY)[0]?.status).toBe('expired');
+ expect(mgr.clientMigrationExpiredAccountCount(GHOST, KEY)).toBe(1);
+ await expect(
+ mgr.getFreshAccessToken(GHOST, KEY, { ...DECL, clientId: 'new-client' }),
+ ).resolves.toMatchObject({ ok: false, error: 'AUTH_EXPIRED' });
+ expect(fetchImpl).not.toHaveBeenCalled();
+ expect(vault.read(GHOST, `${KEY}-rt-acc-1`)).toBe('rt-old-client');
+ expect(onAccountStatusChanged).toHaveBeenCalledWith({
+ ghostId: GHOST,
+ secretKey: KEY,
+ status: 'expired',
+ });
+ });
+
+ it('clientId 未变化或用户使用自定义 clientId 时不改变账号状态', () => {
+ const unchangedVault = memoryVault({
+ [`${KEY}-accounts`]: JSON.stringify({
+ defaultAccountId: 'acc-1',
+ accounts: [{ id: 'acc-1', label: '[email protected]', status: 'connected', createdAt: 1 }],
+ }),
+ });
+ const unchanged = new GhostOauthAccountManager({
+ vault: unchangedVault,
+ fetchImpl: vi.fn() as unknown as typeof fetch,
+ openExternal: vi.fn(),
+ });
+ expect(
+ unchanged.expireAccountsForChangedClients(
+ oauthManifest('same-client'),
+ oauthManifest('same-client'),
+ ),
+ ).toBe(0);
+ expect(unchanged.listAccounts(GHOST, KEY)[0]?.status).toBe('connected');
+ expect(unchanged.clientMigrationExpiredAccountCount(GHOST, KEY)).toBe(0);
+
+ const customizedVault = memoryVault({
+ [`${KEY}-client-id`]: 'custom-client',
+ [`${KEY}-accounts`]: JSON.stringify({
+ defaultAccountId: 'acc-1',
+ accounts: [{ id: 'acc-1', label: '[email protected]', status: 'connected', createdAt: 1 }],
+ }),
+ });
+ const customized = new GhostOauthAccountManager({
+ vault: customizedVault,
+ fetchImpl: vi.fn() as unknown as typeof fetch,
+ openExternal: vi.fn(),
+ });
+ expect(
+ customized.expireAccountsForChangedClients(
+ oauthManifest('old-client'),
+ oauthManifest('new-client'),
+ ),
+ ).toBe(0);
+ expect(customized.listAccounts(GHOST, KEY)[0]?.status).toBe('connected');
+ expect(customized.clientMigrationExpiredAccountCount(GHOST, KEY)).toBe(0);
+ });
+
++ it('prepare 延迟通知,rollback 恢复账号,commit 才发布过期状态', () => {
++ const vault = memoryVault({
++ [`${KEY}-accounts`]: JSON.stringify({
++ defaultAccountId: 'acc-1',
++ accounts: [{ id: 'acc-1', label: '[email protected]', status: 'connected', createdAt: 1 }],
++ }),
++ });
++ const onAccountStatusChanged = vi.fn();
++ const mgr = new GhostOauthAccountManager({
++ vault,
++ fetchImpl: vi.fn() as unknown as typeof fetch,
++ openExternal: vi.fn(),
++ onAccountStatusChanged,
++ });
++
++ const rolledBack = mgr.prepareAccountsForChangedClients(
++ oauthManifest('old-client'),
++ oauthManifest('new-client'),
++ );
++ expect(mgr.listAccounts(GHOST, KEY)[0]?.status).toBe('expired');
++ expect(onAccountStatusChanged).not.toHaveBeenCalled();
++ rolledBack.rollback();
++ expect(mgr.listAccounts(GHOST, KEY)[0]?.status).toBe('connected');
++ expect(onAccountStatusChanged).not.toHaveBeenCalled();
++
++ const committed = mgr.prepareAccountsForChangedClients(
++ oauthManifest('old-client'),
++ oauthManifest('new-client'),
++ );
++ committed.commit();
++ expect(mgr.listAccounts(GHOST, KEY)[0]?.status).toBe('expired');
++ expect(onAccountStatusChanged).toHaveBeenCalledWith({
++ ghostId: GHOST,
++ secretKey: KEY,
++ status: 'expired',
++ });
++ });
++
++ it('rollback 不覆盖并发重连写入', () => {
++ const vault = memoryVault({
++ [`${KEY}-accounts`]: JSON.stringify({
++ defaultAccountId: 'acc-1',
++ accounts: [{ id: 'acc-1', label: '[email protected]', status: 'connected', createdAt: 1 }],
++ }),
++ });
++ const mgr = new GhostOauthAccountManager({
++ vault,
++ fetchImpl: vi.fn() as unknown as typeof fetch,
++ openExternal: vi.fn(),
++ });
++ const migration = mgr.prepareAccountsForChangedClients(
++ oauthManifest('old-client'),
++ oauthManifest('new-client'),
++ );
++ const concurrent = JSON.parse(vault.read(GHOST, `${KEY}-accounts`) ?? '{}') as {
++ accounts: Array<Record<string, unknown>>;
++ };
++ concurrent.accounts[0].status = 'connected';
++ delete concurrent.accounts[0].expiredReason;
++ concurrent.accounts[0].displayLabel = 'reconnected';
++ vault.store(GHOST, `${KEY}-accounts`, JSON.stringify(concurrent));
++
++ migration.rollback();
++ expect(JSON.parse(vault.read(GHOST, `${KEY}-accounts`) ?? '{}').accounts[0]).toMatchObject({
++ status: 'connected',
++ displayLabel: 'reconnected',
++ });
++ });
++
++ it('启动对账只恢复已回滚到签发 client 的迁移账号', () => {
++ const vault = memoryVault({
++ [`${KEY}-accounts`]: JSON.stringify({
++ defaultAccountId: 'acc-1',
++ accounts: [
++ {
++ id: 'acc-1',
++ label: '[email protected]',
++ status: 'expired',
++ expiredReason: 'oauth_client_changed',
++ expiredFromClientId: 'old-client',
++ expiredForClientId: 'new-client',
++ createdAt: 1,
++ },
++ ],
++ }),
++ });
++ const onAccountStatusChanged = vi.fn();
++ const mgr = new GhostOauthAccountManager({
++ vault,
++ fetchImpl: vi.fn() as unknown as typeof fetch,
++ openExternal: vi.fn(),
++ onAccountStatusChanged,
++ });
++
++ expect(mgr.reconcileAccountsForInstalledManifest(oauthManifest('new-client'))).toBe(0);
++ expect(mgr.listAccounts(GHOST, KEY)[0]?.status).toBe('expired');
++ expect(mgr.reconcileAccountsForInstalledManifest(oauthManifest('third-client'))).toBe(0);
++ expect(mgr.listAccounts(GHOST, KEY)[0]?.status).toBe('expired');
++ expect(mgr.reconcileAccountsForInstalledManifest(oauthManifest('old-client'))).toBe(1);
++ expect(mgr.listAccounts(GHOST, KEY)[0]?.status).toBe('connected');
++ expect(onAccountStatusChanged).toHaveBeenCalledWith({
++ ghostId: GHOST,
++ secretKey: KEY,
++ status: 'connected',
++ });
++ });
++
++ it('插件切回签发 client 时只在 commit 后复活旧 token,不误复活新 client 账号', () => {
++ const vault = memoryVault({
++ [`${KEY}-accounts`]: JSON.stringify({
++ defaultAccountId: 'old-account',
++ accounts: [
++ {
++ id: 'old-account',
++ label: '[email protected]',
++ status: 'expired',
++ expiredReason: 'oauth_client_changed',
++ expiredFromClientId: 'old-client',
++ expiredForClientId: 'new-client',
++ createdAt: 1,
++ },
++ { id: 'new-account', label: '[email protected]', status: 'connected', createdAt: 2 },
++ ],
++ }),
++ });
++ const onAccountStatusChanged = vi.fn();
++ const mgr = new GhostOauthAccountManager({
++ vault,
++ fetchImpl: vi.fn() as unknown as typeof fetch,
++ openExternal: vi.fn(),
++ onAccountStatusChanged,
++ });
++
++ const migration = mgr.prepareAccountsForChangedClients(
++ oauthManifest('new-client'),
++ oauthManifest('old-client'),
++ );
++ const preparedAccounts = mgr.listAccounts(GHOST, KEY);
++ expect(preparedAccounts.find((account) => account.id === 'old-account')?.status).toBe(
++ 'expired',
++ );
++ expect(preparedAccounts.find((account) => account.id === 'new-account')?.status).toBe(
++ 'expired',
++ );
++ migration.commit();
++ const committedAccounts = mgr.listAccounts(GHOST, KEY);
++ expect(committedAccounts.find((account) => account.id === 'old-account')?.status).toBe(
++ 'connected',
++ );
++ expect(committedAccounts.find((account) => account.id === 'new-account')?.status).toBe(
++ 'expired',
++ );
++ expect(onAccountStatusChanged).toHaveBeenCalledWith({
++ ghostId: GHOST,
++ secretKey: KEY,
++ status: 'connected',
++ });
++ expect(onAccountStatusChanged).toHaveBeenCalledWith({
++ ghostId: GHOST,
++ secretKey: KEY,
++ status: 'expired',
++ });
++ });
++
++ it('A → 无内置 client → A 时在第二次 receipt commit 后无需重启即可恢复', () => {
++ const vault = memoryVault({
++ [`${KEY}-accounts`]: JSON.stringify({
++ defaultAccountId: 'acc-1',
++ accounts: [{ id: 'acc-1', label: '[email protected]', status: 'connected', createdAt: 1 }],
++ }),
++ });
++ const mgr = new GhostOauthAccountManager({
++ vault,
++ fetchImpl: vi.fn() as unknown as typeof fetch,
++ openExternal: vi.fn(),
++ });
++
++ const removed = mgr.prepareAccountsForChangedClients(
++ oauthManifest('client-a'),
++ oauthManifestWithoutBuiltinClient(),
++ );
++ removed.commit();
++ expect(mgr.listAccounts(GHOST, KEY)[0]?.status).toBe('expired');
++
++ const restored = mgr.prepareAccountsForChangedClients(
++ oauthManifestWithoutBuiltinClient(),
++ oauthManifest('client-a'),
++ );
++ expect(mgr.listAccounts(GHOST, KEY)[0]?.status).toBe('expired');
++ restored.commit();
++ expect(mgr.listAccounts(GHOST, KEY)[0]?.status).toBe('connected');
++ });
++
++ it('切回签发 client 后 receipt 失败时 rollback 不会提前复活 token', () => {
++ const vault = memoryVault({
++ [`${KEY}-accounts`]: JSON.stringify({
++ defaultAccountId: 'acc-1',
++ accounts: [
++ {
++ id: 'acc-1',
++ label: '[email protected]',
++ status: 'expired',
++ expiredReason: 'oauth_client_changed',
++ expiredFromClientId: 'old-client',
++ expiredForClientId: 'new-client',
++ createdAt: 1,
++ },
++ ],
++ }),
++ });
++ const mgr = new GhostOauthAccountManager({
++ vault,
++ fetchImpl: vi.fn() as unknown as typeof fetch,
++ openExternal: vi.fn(),
++ });
++
++ const migration = mgr.prepareAccountsForChangedClients(
++ oauthManifest('new-client'),
++ oauthManifest('old-client'),
++ );
++ expect(mgr.listAccounts(GHOST, KEY)[0]?.status).toBe('expired');
++ migration.rollback();
++ expect(mgr.listAccounts(GHOST, KEY)[0]?.status).toBe('expired');
++ });
++
+ 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'),
- ),
++ 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(快照推断)', () => {
it.each([
['全量快照没有新增 scope', ['scope.a'], { authFace: 'full', authScopes: ['scope.a'] }, false],
diff --cc apps/desktop/src/main/cindy-brain/__tests__/ghostOauthMutationLock.test.ts
index 0000000000,0000000000..04421e88ce
new file mode 100644
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthMutationLock.test.ts
@@@ -1,0 -1,0 +1,86 @@@
++import { beforeEach, describe, expect, it, vi } from 'vitest';
++
++const { withSecurityBoundaryLock } = vi.hoisted(() => ({
++ withSecurityBoundaryLock: vi.fn(),
++}));
++
++vi.mock('../../device-link/crossProcessLock.js', () => ({
++ withSecurityBoundaryLock,
++}));
++
++import {
++ resetGhostOauthMutationLocksForTest,
++ withGhostOauthMutationLock,
++} from '../ghostOauthMutationLock.js';
++
++describe('ghost OAuth mutation lock', () => {
++ beforeEach(() => {
++ resetGhostOauthMutationLocksForTest();
++ withSecurityBoundaryLock.mockReset();
++ withSecurityBoundaryLock.mockImplementation(
++ async (_path: string, _opts: unknown, task: (status: { held: true }) => Promise<unknown>) =>
++ task({ held: true }),
++ );
++ });
++
++ it('fails closed when the security-boundary lock cannot be acquired', async () => {
++ withSecurityBoundaryLock.mockImplementationOnce(
++ async (
++ _path: string,
++ _opts: unknown,
++ task: (status: { held: false; reason: 'busy' }) => Promise<unknown>,
++ ) => task({ held: false, reason: 'busy' }),
++ );
++
++ await expect(
++ withGhostOauthMutationLock('owner-a', 'plugin-a', 'C:/locks/plugin-a.lock', vi.fn()),
++ ).rejects.toThrow('Plugin OAuth mutation lock is busy or unavailable');
++ });
++
++ it('is reentrant for the same owner and plugin without reacquiring cross-process state', async () => {
++ const result = await withGhostOauthMutationLock(
++ 'owner-a',
++ 'plugin-a',
++ 'C:/locks/plugin-a.lock',
++ () =>
++ withGhostOauthMutationLock('owner-a', 'plugin-a', 'C:/locks/plugin-a.lock', () => 'done'),
++ );
++
++ expect(result).toBe('done');
++ expect(withSecurityBoundaryLock).toHaveBeenCalledTimes(1);
++ });
++
++ it('serializes same-key work before acquiring the next strict lock', async () => {
++ let releaseFirst!: () => void;
++ const firstGate = new Promise<void>((resolve) => {
++ releaseFirst = resolve;
++ });
++ const events: string[] = [];
++
++ const first = withGhostOauthMutationLock(
++ 'owner-a',
++ 'plugin-a',
++ 'C:/locks/plugin-a.lock',
++ async () => {
++ events.push('first-start');
++ await firstGate;
++ events.push('first-end');
++ },
++ );
++ const second = withGhostOauthMutationLock(
++ 'owner-a',
++ 'plugin-a',
++ 'C:/locks/plugin-a.lock',
++ async () => {
++ events.push('second');
++ },
++ );
++
++ await vi.waitFor(() => expect(events).toEqual(['first-start']));
++ releaseFirst();
++ await Promise.all([first, second]);
++
++ expect(events).toEqual(['first-start', 'first-end', 'second']);
++ expect(withSecurityBoundaryLock).toHaveBeenCalledTimes(2);
++ });
++});
diff --cc apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts
index cbfd56d52a,b01e3136a0..9fdcae8de1
--- a/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/marketGhostSessionBoundary.test.ts
@@@ -96,7 -83,7 +96,10 @@@ describe('market Ghost session boundary
const stopAndWaitIndex = body.indexOf(
'await getGhostNodeRuntimeBroker().stopAndWait(inspected.manifest.id);',
);
-- const managerUpdateIndex = body.indexOf('result = await manager.update(');
++ const oauthLockIndex = body.indexOf(
++ 'result = await withActiveOwnerGhostOauthMutationLock(inspected.manifest.id',
++ );
++ const managerUpdateIndex = body.indexOf('manager.update(lizFilePath,');
const detachIndex = body.indexOf(
'marketLedger.markRemoved(inspected.manifest.id, marketInstallSubject)',
);
@@@ -112,7 -99,7 +115,8 @@@
// 只有确认旧进程退出,才切断旧市场的自动更新路由;等待失败时保留原路由,
// 也不会尝试恢复第二份 resident 进程。
expect(detachIndex).toBeGreaterThan(stopAndWaitIndex);
-- expect(managerUpdateIndex).toBeGreaterThan(detachIndex);
++ expect(oauthLockIndex).toBeGreaterThan(detachIndex);
++ expect(managerUpdateIndex).toBeGreaterThan(oauthLockIndex);
expect(body).toContain('marketLedger.isDefaultInstallSuppressed(');
expect(body).toContain('marketLedger.restoreInstallation(');
expect(body).toContain('suppressed: marketRecordWasSuppressed');
@@@ -146,10 -133,10 +150,14 @@@
const waitIndex = body.indexOf(
'await getGhostNodeRuntimeBroker().stopAndWait(expected.ghostId);',
);
-- const updateIndex = body.indexOf('await manager.update(cindyFilePath,');
++ const oauthLockIndex = body.indexOf(
++ 'await withActiveOwnerGhostOauthMutationLock(expected.ghostId',
++ );
++ const updateIndex = body.indexOf('manager.update(cindyFilePath,');
expect(waitIndex).toBeGreaterThan(-1);
-- expect(waitIndex).toBeLessThan(updateIndex);
++ expect(waitIndex).toBeLessThan(oauthLockIndex);
++ expect(oauthLockIndex).toBeLessThan(updateIndex);
const restoreIndex = body.indexOf('spawnIfResident(installed);');
expect(restoreIndex).toBeGreaterThan(updateIndex);
});
@@@ -162,20 -149,18 +170,24 @@@
const waitIndex = body.indexOf(
'await getGhostNodeRuntimeBroker().stopAndWait(inspected.manifest.id);',
);
- const tryIndex = body.indexOf('try {\n runtime.stop(inspected.manifest.id);');
-- const updateIndex = body.indexOf('result = await manager.update(lizFilePath');
++ const oauthLockIndex = body.indexOf(
++ 'result = await withActiveOwnerGhostOauthMutationLock(inspected.manifest.id',
++ );
++ const updateIndex = body.indexOf('manager.update(lizFilePath');
const restoreIndex = body.indexOf(
'if (previousGhost) spawnIfResident(previousGhost);',
);
- expect(tryIndex).toBeGreaterThan(-1);
- expect(tryIndex).toBeLessThan(waitIndex);
+ // stopAndWait must be called before manager.update (safe directory
+ // replacement on Windows). The owner lease is outside the per-id lock
+ // per the documented invariant (owner lease → per-id lock).
expect(waitIndex).toBeGreaterThan(-1);
-- expect(waitIndex).toBeLessThan(updateIndex);
++ expect(waitIndex).toBeLessThan(oauthLockIndex);
++ expect(oauthLockIndex).toBeLessThan(updateIndex);
+ // spawnIfResident is in the market-provenance catch block, after
+ // stopAndWait (rollback if provenance check fails).
expect(restoreIndex).toBeGreaterThan(waitIndex);
- expect(body).toContain('finally {\n releaseMutation();');
+ expect(body).toContain('finally {\n releaseMutation();');
expect(body).toContain("throwIpcError('INTERNAL', 'Unable to verify the installed Plugin source');");
expect(body).toContain("throwIpcError('INTERNAL', 'Unable to detach the installed Plugin source');");
});
diff --cc apps/desktop/src/main/cindy-brain/ghostOauthAccounts.ts
index faf33872eb,6936ccbb0a..2244d84a95
--- a/apps/desktop/src/main/cindy-brain/ghostOauthAccounts.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostOauthAccounts.ts
@@@ -141,10 -146,10 +146,26 @@@ export interface GhostOauthAccountManag
* before any callback result is persisted.
*/
isConnectTargetCurrent?: (ghostId: string, secretKey: string, decl: GhostOauthDecl) => boolean;
++ /**
++ * Serialize the final declaration check and every related vault mutation
++ * with plugin update migration. Browser authorization and identity requests
++ * intentionally remain outside this lock.
++ */
++ withMutationLock?: <T>(ghostId: string, task: () => Promise<T> | T) => Promise<T>;
/** 延时器(仅 invalid_grant 轮换探测用;测试注入即时假体,生产缺省 setTimeout)。 */
sleep?: (ms: number) => Promise<void>;
}
++/**
++ * Reversible part of an OAuth client migration. The plugin update transaction
++ * commits or rolls this back together with its receipt and directory swap.
++ */
++export interface GhostOauthClientMigration {
++ expiredCount: number;
++ commit(): number;
++ rollback(): void;
++}
++
export type GhostOauthConnectResult =
| { ok: true; account: GhostOauthAccountView }
| {
@@@ -177,6 -182,8 +198,12 @@@ interface AccountRow
/** 人类可读展示名(identity.displayTemplate 渲染;纯展示,不参与合并判定)。 */
displayLabel: string | null;
status: GhostOauthAccountStatus;
+ /** 仅标记由插件内置 OAuth clientId 迁移触发的过期,供宿主精确提示。 */
+ expiredReason?: 'oauth_client_changed';
++ /** The retained refresh token was issued to this previous builtin client. */
++ expiredFromClientId?: string;
++ /** The plugin update that expired the account introduced this builtin client. */
++ expiredForClientId?: string;
createdAt: number;
/** 本次浏览器授权 URL 实际携带的 scope 面;旧账号没有该快照。 */
authScopes?: string[];
@@@ -227,6 -234,9 +254,13 @@@ function parseManifest(raw: string | nu
displayLabel:
typeof r.displayLabel === 'string' && r.displayLabel.length > 0 ? r.displayLabel : null,
status: r.status === 'expired' ? 'expired' : 'connected',
- ...(r.expiredReason === 'oauth_client_changed'
- ? { expiredReason: r.expiredReason }
++ ...(r.expiredReason === 'oauth_client_changed' ? { expiredReason: r.expiredReason } : {}),
++ ...(typeof r.expiredFromClientId === 'string' && r.expiredFromClientId.length > 0
++ ? { expiredFromClientId: r.expiredFromClientId }
++ : {}),
++ ...(typeof r.expiredForClientId === 'string' && r.expiredForClientId.length > 0
++ ? { expiredForClientId: r.expiredForClientId }
+ : {}),
createdAt:
typeof r.createdAt === 'number' && Number.isFinite(r.createdAt) ? r.createdAt : 0,
...(Array.isArray(r.authScopes) && r.authScopes.every((scope) => typeof scope === 'string')
@@@ -375,6 -385,35 +409,253 @@@ export class GhostOauthAccountManager
}
}
+ /**
+ * 插件原位升级后,对比同一 OAuth 凭证槽的新旧内置 clientId。发生变化时
+ * 旧 refresh token 已不能由新客户端续期,因此保留凭证但将账号标为过期,
+ * 并清掉旧 access token 缓存,让设置页立即引导用户重新连接。
+ * 用户自定义了 clientId 时实际客户端未随 manifest 改变,不做处理。
+ */
+ expireAccountsForChangedClients(
+ previousManifest: GhostManifest,
+ currentManifest: GhostManifest,
+ ): number {
- let expiredCount = 0;
- for (const secretKey of changedBuiltinOauthClientSecretKeys(
- previousManifest,
- currentManifest,
- )) {
- if (this.clientCustomized(currentManifest.id, secretKey)) continue;
- expiredCount += this.expireAllAccounts(currentManifest.id, secretKey);
++ const migration = this.prepareAccountsForChangedClients(previousManifest, currentManifest);
++ migration.commit();
++ return migration.expiredCount;
++ }
++
++ /**
++ * Persist client-change expiry without publishing notifications yet. This
++ * method is called while the owner-scoped OAuth mutation lock is held, so
++ * prepare/rollback and account reconnect cannot interleave across processes.
++ * Accounts whose retained token matches the new client are only marked for
++ * restoration; `commit` restores them after the package receipt commits.
++ */
++ prepareAccountsForChangedClients(
++ previousManifest: GhostManifest,
++ currentManifest: GhostManifest,
++ ): GhostOauthClientMigration {
++ const ghostId = currentManifest.id;
++ const applied: Array<{
++ secretKey: string;
++ beforeRaw: string;
++ afterRaw: string;
++ expiredCount: number;
++ restoreOnCommitAccountIds: string[];
++ }> = [];
++ try {
++ const changedKeys = changedBuiltinOauthClientSecretKeys(previousManifest, currentManifest);
++ const currentDirectOauthKeys = (currentManifest.network?.secrets ?? [])
++ .filter(
++ (secret) =>
++ secret.source === 'oauth' &&
++ secret.oauth !== undefined &&
++ secret.oauth.tokenBroker === undefined &&
++ Boolean(secret.oauth.clientId?.trim()),
++ )
++ .map((secret) => secret.key);
++ for (const secretKey of new Set([...changedKeys, ...currentDirectOauthKeys])) {
++ if (this.clientCustomized(ghostId, secretKey)) continue;
++ const previousClientId = previousManifest.network?.secrets
++ ?.find((secret) => secret.key === secretKey && secret.source === 'oauth')
++ ?.oauth?.clientId?.trim();
++ const currentClientId =
++ currentManifest.network?.secrets
++ ?.find((secret) => secret.key === secretKey && secret.source === 'oauth')
++ ?.oauth?.clientId?.trim() || null;
++ const clientChanged =
++ previousClientId !== undefined && previousClientId !== currentClientId;
++ const beforeRaw = this.deps.vault.read(ghostId, accountsKey(secretKey));
++ const manifest = parseManifest(beforeRaw);
++ if (beforeRaw === null) {
++ this.clearCachedTokens(ghostId, secretKey);
++ continue;
++ }
++ let expiredCount = 0;
++ const restoreOnCommitAccountIds: string[] = [];
++ for (const account of manifest.accounts) {
++ if (
++ currentClientId !== null &&
++ account.status === 'expired' &&
++ account.expiredReason === 'oauth_client_changed' &&
++ account.expiredFromClientId === currentClientId &&
++ account.expiredForClientId !== currentClientId
++ ) {
++ restoreOnCommitAccountIds.push(account.id);
++ continue;
++ }
++ if (!clientChanged || !previousClientId) continue;
++ if (account.status !== 'connected') continue;
++ account.status = 'expired';
++ account.expiredReason = 'oauth_client_changed';
++ account.expiredFromClientId = previousClientId;
++ if (currentClientId !== null) account.expiredForClientId = currentClientId;
++ expiredCount += 1;
++ }
++ if (expiredCount === 0 && restoreOnCommitAccountIds.length === 0) continue;
++ const afterRaw = JSON.stringify(manifest);
++ if (
++ afterRaw !== beforeRaw &&
++ !this.deps.vault.store(ghostId, accountsKey(secretKey), afterRaw)
++ ) {
++ throw new Error('Unable to persist OAuth client migration state');
++ }
++ this.clearCachedTokens(ghostId, secretKey);
++ applied.push({
++ secretKey,
++ beforeRaw,
++ afterRaw,
++ expiredCount,
++ restoreOnCommitAccountIds,
++ });
++ }
++ } catch (error) {
++ let rollbackFailed = false;
++ for (const change of [...applied].reverse()) {
++ const current = this.deps.vault.read(ghostId, accountsKey(change.secretKey));
++ if (current !== change.afterRaw) continue;
++ if (!this.deps.vault.store(ghostId, accountsKey(change.secretKey), change.beforeRaw)) {
++ rollbackFailed = true;
++ }
++ }
++ if (rollbackFailed) {
++ const failure = new Error('Unable to roll back OAuth client migration state');
++ Object.assign(failure, { rollbackFailed: true, cause: error });
++ throw failure;
++ }
++ throw error;
+ }
- return expiredCount;
++
++ let settled = false;
++ return {
++ expiredCount: applied.reduce((count, change) => count + change.expiredCount, 0),
++ commit: () => {
++ if (settled) return 0;
++ settled = true;
++ let restoredCount = 0;
++ for (const change of applied) {
++ let restoredForSecret = 0;
++ if (change.restoreOnCommitAccountIds.length > 0) {
++ const fresh = parseManifest(
++ this.deps.vault.read(ghostId, accountsKey(change.secretKey)),
++ );
++ const restoreIds = new Set(change.restoreOnCommitAccountIds);
++ for (const account of fresh.accounts) {
++ if (
++ restoreIds.has(account.id) &&
++ account.status === 'expired' &&
++ account.expiredReason === 'oauth_client_changed'
++ ) {
++ account.status = 'connected';
++ delete account.expiredReason;
++ delete account.expiredFromClientId;
++ delete account.expiredForClientId;
++ restoredForSecret += 1;
++ }
++ }
++ if (
++ restoredForSecret > 0 &&
++ !this.deps.vault.store(ghostId, accountsKey(change.secretKey), JSON.stringify(fresh))
++ ) {
++ this.deps.logger?.warn?.(
++ 'ghost oauth client migration post-commit recovery write failed',
++ {
++ ghostId,
++ secretKey: change.secretKey,
++ },
++ );
++ restoredForSecret = 0;
++ }
++ }
++ restoredCount += restoredForSecret;
++ if (change.expiredCount > 0) {
++ this.notifyStatusChanged(ghostId, change.secretKey, 'expired');
++ }
++ if (restoredForSecret > 0) {
++ this.notifyStatusChanged(ghostId, change.secretKey, 'connected');
++ }
++ this.deps.logger?.info?.('ghost oauth accounts reconciled for client change', {
++ ghostId,
++ secretKey: change.secretKey,
++ expiredCount: change.expiredCount,
++ restoredCount: restoredForSecret,
++ });
++ }
++ return restoredCount;
++ },
++ rollback: () => {
++ if (settled) return;
++ for (const change of [...applied].reverse()) {
++ const current = this.deps.vault.read(ghostId, accountsKey(change.secretKey));
++ if (current !== change.afterRaw) continue;
++ if (!this.deps.vault.store(ghostId, accountsKey(change.secretKey), change.beforeRaw)) {
++ throw new Error('Unable to roll back OAuth client migration state');
++ }
++ }
++ // Expiry notifications are delayed until commit, so compensation is
++ // silent. Settle only after every restore succeeds so a partial vault
++ // failure remains safely retryable.
++ settled = true;
++ },
++ };
++ }
++
++ /**
++ * Finish crash recovery after GhostManager has selected the committed package
++ * directory. An account is revived only when the installed builtin client is
++ * exactly the client that issued its retained refresh token. This avoids both
++ * the update-crash half state and incorrectly reusing that token for a third
++ * client introduced by a later update.
++ */
++ reconcileAccountsForInstalledManifest(currentManifest: GhostManifest): number {
++ const ghostId = currentManifest.id;
++ let restoredCount = 0;
++ for (const secret of currentManifest.network?.secrets ?? []) {
++ if (secret.source !== 'oauth' || secret.oauth?.tokenBroker) continue;
++ if (this.clientCustomized(ghostId, secret.key)) continue;
++ const currentClientId = secret.oauth?.clientId?.trim();
++ if (!currentClientId) continue;
++ const beforeRaw = this.deps.vault.read(ghostId, accountsKey(secret.key));
++ if (beforeRaw === null) continue;
++ const manifest = parseManifest(beforeRaw);
++ let changed = 0;
++ for (const account of manifest.accounts) {
++ if (
++ account.status !== 'expired' ||
++ account.expiredReason !== 'oauth_client_changed' ||
++ account.expiredFromClientId !== currentClientId ||
++ account.expiredForClientId === currentClientId
++ ) {
++ continue;
++ }
++ account.status = 'connected';
++ delete account.expiredReason;
++ delete account.expiredFromClientId;
++ delete account.expiredForClientId;
++ changed += 1;
++ }
++ if (changed === 0) continue;
++ if (!this.deps.vault.store(ghostId, accountsKey(secret.key), JSON.stringify(manifest))) {
++ this.deps.logger?.warn?.('ghost oauth client migration recovery write failed', {
++ ghostId,
++ secretKey: secret.key,
++ });
++ continue;
++ }
++ restoredCount += changed;
++ this.clearCachedTokens(ghostId, secret.key);
++ this.notifyStatusChanged(ghostId, secret.key, 'connected');
++ }
++ return restoredCount;
+ }
+
+ /** 返回仍未完成重新授权的 clientId 迁移账号数;普通撤销授权不计入。 */
+ clientMigrationExpiredAccountCount(ghostId: string, secretKey: string): number {
+ return parseManifest(this.deps.vault.read(ghostId, accountsKey(secretKey))).accounts.filter(
- (account) =>
- account.status === 'expired' && account.expiredReason === 'oauth_client_changed',
++ (account) => account.status === 'expired' && account.expiredReason === 'oauth_client_changed',
+ ).length;
+ }
+
/**
* client 凭证解析链:用户自填 > 清单内置(cindy-google 等开箱即用意识
* 把凭证写在包里)。**成对语义**:自填了 clientId 就用自填的整对
@@@ -634,144 -673,152 +915,171 @@@
}
}
-- // Identity/avatar fetches are asynchronous as well. Recheck immediately
-- // before the first vault read/write so uninstall or manifest replacement
-- // during those requests cannot resurrect stale credentials.
-- if (this.deps.isConnectTargetCurrent?.(ghostId, secretKey, decl) === false) {
-- return {
-- ok: false,
-- error: 'INVALID_CONFIG',
-- detail: '插件或授权声明已变更',
-- };
-- }
++ return this.withMutationLock(ghostId, async () => {
++ // Identity/avatar fetches are asynchronous as well. Recheck inside the
++ // same strict mutation lock as the first vault read/write so a package
++ // update cannot replace the declaration between validation and commit.
++ if (this.deps.isConnectTargetCurrent?.(ghostId, secretKey, decl) === false) {
++ return {
++ ok: false,
++ error: 'INVALID_CONFIG',
++ detail: '插件或授权声明已变更',
++ };
++ }
-- // 清单在授权**之后**才读:授权流可长达数分钟,期间清单可能被并发写
-- // (断开其它账号 / 刷新 invalidGrant 标过期),以新鲜清单为准收窄
-- // 陈旧写回窗口。
-- const manifest = parseManifest(this.deps.vault.read(ghostId, accountsKey(secretKey)));
++ // 清单在授权**之后**才读:授权流可长达数分钟,期间清单可能被并发写
++ // (断开其它账号 / 刷新 invalidGrant 标过期),以新鲜清单为准收窄
++ // 陈旧写回窗口。
++ const manifest = parseManifest(this.deps.vault.read(ghostId, accountsKey(secretKey)));
++
++ // 同身份合并:复用既有账号 id(默认位 / 意识侧记住的 account id 全部
++ // 保持有效),只换令牌与状态。
++ const existing =
++ label !== null ? manifest.accounts.find((a) => a.label === label) : undefined;
++ if (existing) {
++ if (flow.bundle.refreshToken !== null) {
++ if (
++ !this.deps.vault.store(
++ ghostId,
++ refreshTokenKey(secretKey, existing.id),
++ flow.bundle.refreshToken,
++ )
++ ) {
++ 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 名的,这里追上最新值。
++ let manifestDirty = false;
++ if (existing.status !== 'connected') {
++ existing.status = 'connected';
++ manifestDirty = true;
++ }
++ if (existing.expiredReason !== undefined) {
++ delete existing.expiredReason;
++ manifestDirty = true;
++ }
++ if (existing.expiredFromClientId !== undefined) {
++ delete existing.expiredFromClientId;
++ manifestDirty = true;
++ }
++ if (existing.expiredForClientId !== undefined) {
++ delete existing.expiredForClientId;
++ manifestDirty = true;
++ }
++ if (display !== null && existing.displayLabel !== display) {
++ existing.displayLabel = display;
++ manifestDirty = true;
++ }
++ if (existing.authScopes === undefined || !sameScopeFace(existing.authScopes, authScopes)) {
++ existing.authScopes = authScopes;
++ manifestDirty = true;
++ }
++ if (existing.authFace !== authFace) {
++ existing.authFace = authFace;
++ manifestDirty = true;
++ }
++ if (existing.insufficientScopes !== undefined) {
++ delete existing.insufficientScopes;
++ manifestDirty = true;
++ }
++ if (
++ manifestDirty &&
++ !this.deps.vault.store(ghostId, accountsKey(secretKey), JSON.stringify(manifest))
++ ) {
++ return { ok: false, error: 'VAULT_WRITE_FAILED' };
++ }
++ // 重连顺带刷新头像(用户可能换过头像;写失败不影响连接结果)。
++ if (avatar !== null) {
++ this.deps.vault.store(ghostId, avatarKey(secretKey, existing.id), avatar);
++ }
++ this.tokenCache.set(this.cacheKey(ghostId, secretKey, existing.id), {
++ accessToken: flow.bundle.accessToken,
++ expiresAt: flow.bundle.expiresAt,
++ });
++ this.deps.logger?.info('ghost oauth 账号已重连(同身份合并)', {
++ ghostId,
++ secretKey,
++ accountId: existing.id,
++ });
++ this.notifyConnected(ghostId, secretKey, existing.displayLabel ?? existing.label);
++ return {
++ ok: true,
++ account: toView(
++ existing,
++ manifest.defaultAccountId,
++ avatar ?? this.readAvatar(ghostId, secretKey, existing.id),
++ decl.scopes,
++ ),
++ };
++ }
++
++ // 上限只拦"真新增":检查放在合并判定之后——满员时重连既有账号仍然要放行
++ // (代价是满员 + 真新账号会白跑一趟授权才报 ACCOUNT_LIMIT,8 个上限极少命中)。
++ if (manifest.accounts.length >= GHOST_OAUTH_MAX_ACCOUNTS) {
++ return { ok: false, error: 'ACCOUNT_LIMIT' };
++ }
++
++ const account: AccountRow = {
++ id: randomUUID(),
++ label,
++ displayLabel: display,
++ status: 'connected',
++ createdAt: Date.now(),
++ authScopes,
++ authFace,
++ };
-- // 同身份合并:复用既有账号 id(默认位 / 意识侧记住的 account id 全部
-- // 保持有效),只换令牌与状态。
-- const existing = label !== null ? manifest.accounts.find((a) => a.label === label) : undefined;
-- if (existing) {
++ // refresh token 先落库再挂清单:清单是"账号存在"的事实源,顺序反了
++ // 可能出现"清单有账号但无 rt"的半身位。没有 rt 的服务商(罕见)照样
++ // 挂账号,access token 走内存缓存,过期后 AUTH_EXPIRED 引导重连。
if (flow.bundle.refreshToken !== null) {
if (
!this.deps.vault.store(
ghostId,
-- refreshTokenKey(secretKey, existing.id),
++ refreshTokenKey(secretKey, account.id),
flow.bundle.refreshToken,
)
) {
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 名的,这里追上最新值。
- let manifestDirty = false;
- if (existing.status !== 'connected') {
- existing.status = 'connected';
- manifestDirty = true;
- }
- if (existing.expiredReason !== undefined) {
- delete existing.expiredReason;
- manifestDirty = true;
}
- // 重连顺带刷新展示名:老账号(displayTemplate 上线前连的)或用户改过
- // 显示名/workspace 名的,这里追上最新值。
- let manifestDirty = false;
- if (existing.status !== 'connected') {
- existing.status = 'connected';
- manifestDirty = true;
- }
-- if (display !== null && existing.displayLabel !== display) {
-- existing.displayLabel = display;
-- manifestDirty = true;
-- }
-- if (existing.authScopes === undefined || !sameScopeFace(existing.authScopes, authScopes)) {
-- existing.authScopes = authScopes;
-- manifestDirty = true;
-- }
-- if (existing.authFace !== authFace) {
-- existing.authFace = authFace;
-- manifestDirty = true;
-- }
-- if (existing.insufficientScopes !== undefined) {
-- delete existing.insufficientScopes;
-- manifestDirty = true;
-- }
-- if (
-- manifestDirty &&
-- !this.deps.vault.store(ghostId, accountsKey(secretKey), JSON.stringify(manifest))
-- ) {
++ const nextManifest: AccountsManifest = {
++ defaultAccountId: manifest.defaultAccountId ?? account.id,
++ accounts: [...manifest.accounts, account],
++ };
++ if (!this.deps.vault.store(ghostId, accountsKey(secretKey), JSON.stringify(nextManifest))) {
++ this.deps.vault.remove(ghostId, refreshTokenKey(secretKey, account.id));
return { ok: false, error: 'VAULT_WRITE_FAILED' };
}
-- // 重连顺带刷新头像(用户可能换过头像;写失败不影响连接结果)。
++ // 头像最后落(清单已是事实源;写失败只是没头像,不回滚账号)。
if (avatar !== null) {
-- this.deps.vault.store(ghostId, avatarKey(secretKey, existing.id), avatar);
++ this.deps.vault.store(ghostId, avatarKey(secretKey, account.id), avatar);
}
-- this.tokenCache.set(this.cacheKey(ghostId, secretKey, existing.id), {
++
++ this.tokenCache.set(this.cacheKey(ghostId, secretKey, account.id), {
accessToken: flow.bundle.accessToken,
expiresAt: flow.bundle.expiresAt,
});
-- this.deps.logger?.info('ghost oauth 账号已重连(同身份合并)', {
++ this.deps.logger?.info('ghost oauth 账号已连接', {
ghostId,
secretKey,
-- accountId: existing.id,
++ accountId: account.id,
});
-- this.notifyConnected(ghostId, secretKey, existing.displayLabel ?? existing.label);
++ this.notifyConnected(ghostId, secretKey, account.displayLabel ?? account.label);
return {
ok: true,
-- account: toView(
-- existing,
-- manifest.defaultAccountId,
-- avatar ?? this.readAvatar(ghostId, secretKey, existing.id),
-- decl.scopes,
-- ),
++ account: toView(account, nextManifest.defaultAccountId, avatar, decl.scopes),
};
-- }
--
-- // 上限只拦"真新增":检查放在合并判定之后——满员时重连既有账号仍然要放行
-- // (代价是满员 + 真新账号会白跑一趟授权才报 ACCOUNT_LIMIT,8 个上限极少命中)。
-- if (manifest.accounts.length >= GHOST_OAUTH_MAX_ACCOUNTS) {
-- return { ok: false, error: 'ACCOUNT_LIMIT' };
-- }
--
-- const account: AccountRow = {
-- id: randomUUID(),
-- label,
-- displayLabel: display,
-- status: 'connected',
-- createdAt: Date.now(),
-- authScopes,
-- authFace,
-- };
--
-- // refresh token 先落库再挂清单:清单是"账号存在"的事实源,顺序反了
-- // 可能出现"清单有账号但无 rt"的半身位。没有 rt 的服务商(罕见)照样
-- // 挂账号,access token 走内存缓存,过期后 AUTH_EXPIRED 引导重连。
-- if (flow.bundle.refreshToken !== null) {
-- if (
-- !this.deps.vault.store(
-- ghostId,
-- refreshTokenKey(secretKey, account.id),
-- flow.bundle.refreshToken,
-- )
-- ) {
-- return { ok: false, error: 'VAULT_WRITE_FAILED' };
-- }
-- }
-- const nextManifest: AccountsManifest = {
-- defaultAccountId: manifest.defaultAccountId ?? account.id,
-- accounts: [...manifest.accounts, account],
-- };
-- if (!this.deps.vault.store(ghostId, accountsKey(secretKey), JSON.stringify(nextManifest))) {
-- this.deps.vault.remove(ghostId, refreshTokenKey(secretKey, account.id));
-- return { ok: false, error: 'VAULT_WRITE_FAILED' };
-- }
-- // 头像最后落(清单已是事实源;写失败只是没头像,不回滚账号)。
-- if (avatar !== null) {
-- this.deps.vault.store(ghostId, avatarKey(secretKey, account.id), avatar);
-- }
--
-- this.tokenCache.set(this.cacheKey(ghostId, secretKey, account.id), {
-- accessToken: flow.bundle.accessToken,
-- expiresAt: flow.bundle.expiresAt,
});
-- this.deps.logger?.info('ghost oauth 账号已连接', { ghostId, secretKey, accountId: account.id });
-- this.notifyConnected(ghostId, secretKey, account.displayLabel ?? account.label);
-- return {
-- ok: true,
-- account: toView(account, nextManifest.defaultAccountId, avatar, decl.scopes),
-- };
++ }
++
++ private withMutationLock<T>(ghostId: string, task: () => Promise<T> | T): Promise<T> {
++ return this.deps.withMutationLock?.(ghostId, task) ?? Promise.resolve(task());
}
/** 授权成功通知(自兜异常:提示挂了不影响连接结果)。 */
@@@ -842,7 -894,7 +1155,10 @@@
let refreshToken = this.deps.vault.read(ghostId, refreshTokenKey(secretKey, accountId));
if (!refreshToken) {
// 无 rt 且缓存已失效:只能重新授权。
-- this.markExpired(ghostId, secretKey, accountId);
++ await this.withMutationLock(ghostId, () => {
++ if (this.deps.isConnectTargetCurrent?.(ghostId, secretKey, decl) === false) return;
++ this.markExpired(ghostId, secretKey, accountId);
++ });
return { ok: false, error: 'AUTH_EXPIRED' };
}
@@@ -858,29 -910,29 +1174,37 @@@
logger: this.deps.logger,
});
if (result.ok) {
-- // 轮换型服务商:新 rt 覆盖落库(丢了下一次刷新必 invalid_grant)。
-- // 写失败无法当场补救(新 RT 只在内存),但必须大声留痕:重启后旧 RT
-- // 已被服务商作废,下一次刷新注定 invalid_grant → 重新授权。
-- if (result.bundle.refreshToken !== null && result.bundle.refreshToken !== refreshToken) {
-- if (
-- !this.deps.vault.store(
-- ghostId,
-- refreshTokenKey(secretKey, accountId),
-- result.bundle.refreshToken,
-- )
-- ) {
-- this.deps.logger?.warn(
-- 'ghost oauth 轮换后的新 refresh token 落库失败——新令牌仅存内存,重启后需要重新授权',
-- { ghostId, secretKey, accountId },
-- );
++ const committed = await this.withMutationLock(ghostId, () => {
++ if (this.deps.isConnectTargetCurrent?.(ghostId, secretKey, decl) === false) return false;
++ const currentRefreshToken = this.deps.vault.read(
++ ghostId,
++ refreshTokenKey(secretKey, accountId),
++ );
++ if (currentRefreshToken !== refreshToken) return false;
++ // 轮换型服务商:新 rt 覆盖落库(丢了下一次刷新必 invalid_grant)。
++ if (result.bundle.refreshToken !== null && result.bundle.refreshToken !== refreshToken) {
++ if (
++ !this.deps.vault.store(
++ ghostId,
++ refreshTokenKey(secretKey, accountId),
++ result.bundle.refreshToken,
++ )
++ ) {
++ this.deps.logger?.warn(
++ 'ghost oauth 轮换后的新 refresh token 落库失败——新令牌仅存内存,重启后需要重新授权',
++ { ghostId, secretKey, accountId },
++ );
++ }
}
-- }
-- this.tokenCache.set(cacheKey, {
-- accessToken: result.bundle.accessToken,
-- expiresAt: result.bundle.expiresAt,
++ this.tokenCache.set(cacheKey, {
++ accessToken: result.bundle.accessToken,
++ expiresAt: result.bundle.expiresAt,
++ });
++ // 曾标 expired 的账号刷新成功即复活(用户在别处重授权后 rt 又有效的边角)。
++ this.markConnected(ghostId, secretKey, accountId);
++ return true;
});
-- // 曾标 expired 的账号刷新成功即复活(用户在别处重授权后 rt 又有效的边角)。
-- this.markConnected(ghostId, secretKey, accountId);
++ if (!committed) return { ok: false, error: 'AUTH_EXPIRED' };
// 展示名/头像回填(fire-and-forget,不拖累令牌热路径):displayTemplate /
// avatarPath 上线前连的老账号缺这些,借下一次令牌刷新顺路补上,无需重连。
void this.backfillIdentityExtras(
@@@ -919,12 -971,12 +1243,17 @@@
// 真失效:标 expired 引导重新授权。删除走 compare-and-delete——只删
// 仍等于自己最后用过的这枚;若期间有并发实例写入了更新的 RT,留给它。
-- this.markExpired(ghostId, secretKey, accountId);
-- const current = this.deps.vault.read(ghostId, refreshTokenKey(secretKey, accountId));
-- if (current === refreshToken) {
-- this.deps.vault.remove(ghostId, refreshTokenKey(secretKey, accountId));
-- }
-- this.tokenCache.delete(cacheKey);
++ await this.withMutationLock(ghostId, () => {
++ // 插件可能在 provider 请求期间换版。旧声明的 invalid_grant 不得
++ // 删除为包事务保留的旧 client token。
++ if (this.deps.isConnectTargetCurrent?.(ghostId, secretKey, decl) === false) return;
++ this.markExpired(ghostId, secretKey, accountId);
++ const current = this.deps.vault.read(ghostId, refreshTokenKey(secretKey, accountId));
++ if (current === refreshToken) {
++ this.deps.vault.remove(ghostId, refreshTokenKey(secretKey, accountId));
++ }
++ this.tokenCache.delete(cacheKey);
++ });
return { ok: false, error: 'AUTH_EXPIRED', detail: result.detail };
}
}
@@@ -988,11 -1040,11 +1317,14 @@@
if (needDisplay && identity.display !== null) {
// 拉取期间清单可能被并发写(断开/设默认/新连接):用 patchAccount 做
// 定向字段写入——只改目标行的 displayLabel/label,不覆盖清单其它状态。
-- this.patchAccount(ghostId, secretKey, accountId, (fresh) => {
-- if (fresh.displayLabel !== null) return false;
-- fresh.displayLabel = identity.display;
-- if (fresh.label === null && identity.label !== null) fresh.label = identity.label;
-- return true;
++ await this.withMutationLock(ghostId, () => {
++ if (this.deps.isConnectTargetCurrent?.(ghostId, secretKey, decl) === false) return;
++ this.patchAccount(ghostId, secretKey, accountId, (fresh) => {
++ if (fresh.displayLabel !== null) return false;
++ fresh.displayLabel = identity.display;
++ if (fresh.label === null && identity.label !== null) fresh.label = identity.label;
++ return true;
++ });
});
this.deps.logger?.info('ghost oauth 账号展示名已回填', { ghostId, secretKey, accountId });
}
@@@ -1003,11 -1055,11 +1335,18 @@@
});
// 存前重验账号仍在清单(拉取期间可能被断开;断开后不再写孤儿头像键)。
if (avatar !== null) {
-- const fresh = parseManifest(this.deps.vault.read(ghostId, accountsKey(secretKey)));
-- if (fresh.accounts.some((a) => a.id === accountId)) {
-- this.deps.vault.store(ghostId, avatarKey(secretKey, accountId), avatar);
-- this.deps.logger?.info('ghost oauth 账号头像已回填', { ghostId, secretKey, accountId });
-- }
++ await this.withMutationLock(ghostId, () => {
++ if (this.deps.isConnectTargetCurrent?.(ghostId, secretKey, decl) === false) return;
++ const fresh = parseManifest(this.deps.vault.read(ghostId, accountsKey(secretKey)));
++ if (fresh.accounts.some((a) => a.id === accountId)) {
++ this.deps.vault.store(ghostId, avatarKey(secretKey, accountId), avatar);
++ this.deps.logger?.info('ghost oauth 账号头像已回填', {
++ ghostId,
++ secretKey,
++ accountId,
++ });
++ }
++ });
}
}
} catch (err) {
@@@ -1046,10 -1098,41 +1385,19 @@@
if (changed) this.notifyStatusChanged(ghostId, secretKey, 'expired');
}
- private expireAllAccounts(ghostId: string, secretKey: string): number {
- const manifest = parseManifest(this.deps.vault.read(ghostId, accountsKey(secretKey)));
- const connected = manifest.accounts.filter((account) => account.status === 'connected');
- if (connected.length > 0) {
- for (const account of connected) {
- account.status = 'expired';
- account.expiredReason = 'oauth_client_changed';
- }
- if (!this.deps.vault.store(ghostId, accountsKey(secretKey), JSON.stringify(manifest))) {
- this.deps.logger?.warn?.('ghost oauth client 变化后账号状态写入失败', {
- ghostId,
- secretKey,
- });
- throw new Error('Unable to persist OAuth client migration state');
- }
- }
++ private clearCachedTokens(ghostId: string, secretKey: string): void {
+ for (const key of this.tokenCache.keys()) {
+ if (key.startsWith(`${ghostId} ${secretKey} `)) this.tokenCache.delete(key);
+ }
- if (connected.length > 0) {
- this.notifyStatusChanged(ghostId, secretKey, 'expired');
- this.deps.logger?.info?.('ghost oauth client 已变化,旧账号需要重新连接', {
- ghostId,
- secretKey,
- accountCount: connected.length,
- });
- }
- return connected.length;
+ }
+
private markConnected(ghostId: string, secretKey: string, accountId: string): void {
const changed = this.patchAccount(ghostId, secretKey, accountId, (row) => {
- if (row.status === 'connected') return false;
+ if (row.status === 'connected' && row.expiredReason === undefined) return false;
row.status = 'connected';
+ delete row.expiredReason;
++ delete row.expiredFromClientId;
++ delete row.expiredForClientId;
return true;
});
if (changed) this.notifyStatusChanged(ghostId, secretKey, 'connected');
diff --cc apps/desktop/src/main/cindy-brain/ghostOauthMutationLock.ts
index 0000000000,0000000000..d2fa20400e
new file mode 100644
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/ghostOauthMutationLock.ts
@@@ -1,0 -1,0 +1,63 @@@
++/**
++ * OAuth credential mutations share one authorization-boundary lock with
++ * plugin package updates. The existing install lock remains the in-process
++ * package/lifecycle lock; this layer adds owner-scoped cross-process exclusion
++ * for vault read-modify-write sequences that must agree with the committed
++ * plugin manifest.
++ *
++ * Lock order is fixed: owner lease -> ghost install lock -> OAuth mutation
++ * lock. Callers must never acquire an install/source lock from inside `task`.
++ */
++import { AsyncLocalStorage } from 'node:async_hooks';
++import fs from 'node:fs';
++import path from 'node:path';
++
++import { withSecurityBoundaryLock } from '../device-link/crossProcessLock.js';
++
++const heldKeys = new AsyncLocalStorage<ReadonlySet<string>>();
++const inProcessTails = new Map<string, Promise<void>>();
++
++export async function withGhostOauthMutationLock<T>(
++ ownerScopeKey: string,
++ ghostId: string,
++ lockPath: string,
++ task: () => Promise<T> | T,
++): Promise<T> {
++ const key = `${ownerScopeKey}\u0000${ghostId}`;
++ const held = heldKeys.getStore();
++ if (held?.has(key)) return task();
++
++ const previous = inProcessTails.get(key) ?? Promise.resolve();
++ let release!: () => void;
++ const gate = new Promise<void>((resolve) => {
++ release = resolve;
++ });
++ const mine = previous.then(() => gate);
++ inProcessTails.set(key, mine);
++ await previous.catch(() => undefined);
++
++ const nextHeld = new Set(held ?? []);
++ nextHeld.add(key);
++ try {
++ return await heldKeys.run(nextHeld, async () => {
++ fs.mkdirSync(path.dirname(lockPath), { recursive: true });
++ return withSecurityBoundaryLock(
++ lockPath,
++ { label: 'ghost-oauth-mutation', waitMs: 12_000 },
++ async (status) => {
++ if (!status.held) {
++ throw new Error('Plugin OAuth mutation lock is busy or unavailable');
++ }
++ return task();
++ },
++ );
++ });
++ } finally {
++ release();
++ if (inProcessTails.get(key) === mine) inProcessTails.delete(key);
++ }
++}
++
++export function resetGhostOauthMutationLocksForTest(): void {
++ inProcessTails.clear();
++}
diff --cc apps/desktop/src/main/cindy-brain/index.ts
index 2b3722656b,ca8ba3ccb5..e3c86cf4a7
--- a/apps/desktop/src/main/cindy-brain/index.ts
+++ b/apps/desktop/src/main/cindy-brain/index.ts
@@@ -143,7 -126,6 +143,8 @@@ import { handleGhostSecretsRequest } fr
import { handleGhostOauthRequest } from './runtime/ghostOauthEndpoint.js';
import { handleGhostConnectionsRequest } from './runtime/ghostConnectionsEndpoint.js';
import { GhostOauthAccountManager, type GhostOauthDecl } from './ghostOauthAccounts.js';
++import { withGhostOauthMutationLock } from './ghostOauthMutationLock.js';
+import { cancelActiveGhostOauthFlow } from './ghostOauthFlow.js';
import {
appendReadyGhostOauthReauthSuggest,
findGhostOauthReauthSuggest,
@@@ -3596,6 -3287,6 +3610,62 @@@ export function getGhostCindySlot(): Gh
* removeGhostSecrets 的前缀清扫天然连带)。
*/
let ghostOauthManagerSingleton: GhostOauthAccountManager | null = null;
++let ghostOauthReconciledOwnerScope: string | null = null;
++let ghostOauthReconcileInFlight: Promise<void> | null = null;
++
++function ghostOauthMutationLockPath(ghostId: string): string {
++ return ownerScopedUserDataPath('ghost-install-state', '.oauth-locks', `${ghostId}.lock`);
++}
++
++function withActiveOwnerGhostOauthMutationLock<T>(
++ ghostId: string,
++ task: () => Promise<T> | T,
++): Promise<T> {
++ const ownerScope = activeOwnerScopeKey();
++ return withGhostOauthMutationLock(
++ ownerScope,
++ ghostId,
++ ghostOauthMutationLockPath(ghostId),
++ async () => {
++ if (isAppSessionBoundaryPending() || activeOwnerScopeKey() !== ownerScope) {
++ throw new Error('Plugin OAuth owner boundary changed before mutation');
++ }
++ return task();
++ },
++ );
++}
++
++/** Reconcile migration markers once for every committed owner scope. */
++export async function reconcileGhostOauthAccountsForActiveOwner(): Promise<void> {
++ const ownerScope = activeOwnerScopeKey();
++ if (ghostOauthReconciledOwnerScope === ownerScope) return;
++ if (ghostOauthReconcileInFlight) await ghostOauthReconcileInFlight;
++ if (ghostOauthReconciledOwnerScope === ownerScope) return;
++ const reconcileTask = (async () => {
++ if (isAppSessionBoundaryPending() || activeOwnerScopeKey() !== ownerScope) return;
++ const oauthManager = getGhostOauthAccountManager();
++ for (const ghost of getGhostManager().list()) {
++ await withActiveOwnerGhostOauthMutationLock(ghost.manifest.id, () => {
++ if (activeOwnerScopeKey() !== ownerScope) {
++ throw new Error('Plugin OAuth owner changed during reconciliation');
++ }
++ oauthManager.reconcileAccountsForInstalledManifest(
++ withRuntimeFiloGoogleClient(ghost.manifest),
++ );
++ });
++ }
++ if (!isAppSessionBoundaryPending() && activeOwnerScopeKey() === ownerScope) {
++ ghostOauthReconciledOwnerScope = ownerScope;
++ }
++ })();
++ ghostOauthReconcileInFlight = reconcileTask;
++ try {
++ await reconcileTask;
++ } finally {
++ if (ghostOauthReconcileInFlight === reconcileTask) ghostOauthReconcileInFlight = null;
++ }
++}
++
function getGhostOauthAccountManager(): GhostOauthAccountManager {
if (!ghostOauthManagerSingleton) {
ghostOauthManagerSingleton = new GhostOauthAccountManager({
@@@ -3670,6 -3361,6 +3740,14 @@@
: undefined;
return currentDecl !== undefined && isDeepStrictEqual(currentDecl, decl);
},
++ withMutationLock: withActiveOwnerGhostOauthMutationLock,
++ });
++ queueMicrotask(() => {
++ void reconcileGhostOauthAccountsForActiveOwner().catch((error) => {
++ log.warn('ghost oauth startup reconciliation failed', {
++ error: error instanceof Error ? error.message : String(error),
++ });
++ });
});
}
return ghostOauthManagerSingleton;
@@@ -4362,23 -4035,21 +4446,32 @@@ async function installOrUpdateMarketGho
// 必须确认旧 utilityProcess 已离开,否则入口文件仍可能被占用而报 EPERM。
getGhostAgentSlot().clearGhost(expected.ghostId);
getGhostErrandSlot().clearGhost(expected.ghostId);
- // 与首装分支同一口径:钉住 inspect 时校验过的包字节(见上)。
- result = await manager.update(cindyFilePath, {
- expectedPackageSha256: inspected.packageSha256,
- ...(trustOverride ? { trustOverride } : {}),
- beforePackageCommit: () => {
- getGhostOauthAccountManager().expireAccountsForChangedClients(
- withRuntimeFiloGoogleClient(installed.manifest),
- withRuntimeFiloGoogleClient(inspected.canonicalManifest),
- );
- },
- onPackagePlaced: () => {
- packagePlaced = true;
- expected.onPackagePlacedInLock?.();
- },
- });
+ // receipt 模型下更新必须绑定 receipt token(决策 A:与 main 的 sha 钉扎叠加),
+ // 否则并发批准变更绕不过去。
+ if (!expected.expectedInstalledApproval) {
+ throwIpcError(
+ 'PRECONDITION_FAILED',
+ 'Plugin approval state was not bound to the market update',
+ );
+ }
- result = await manager.update(cindyFilePath, {
- expectedPackageSha256: inspected.packageSha256,
- expectedInstalledApproval: expected.expectedInstalledApproval,
- ...(trustOverride ? { trustOverride } : {}),
- onPackagePlaced: () => {
- packagePlaced = true;
- expected.onPackagePlacedInLock?.();
- },
- });
++ // Lock order: owner lease -> install lock -> OAuth security lock. Keep
++ // the strict lock through package swap, receipt commit, and compensation.
++ result = await withActiveOwnerGhostOauthMutationLock(expected.ghostId, () =>
++ manager.update(cindyFilePath, {
++ expectedPackageSha256: inspected.packageSha256,
++ expectedInstalledApproval: expected.expectedInstalledApproval!,
++ ...(trustOverride ? { trustOverride } : {}),
++ beforePackageCommit: () =>
++ getGhostOauthAccountManager().prepareAccountsForChangedClients(
++ withRuntimeFiloGoogleClient(installed.manifest),
++ withRuntimeFiloGoogleClient(inspected.canonicalManifest),
++ ),
++ onPackagePlaced: () => {
++ packagePlaced = true;
++ expected.onPackagePlacedInLock?.();
++ },
++ }),
++ );
} catch (error) {
if (!packagePlaced) {
spawnIfResident(installed);
@@@ -4442,7 -4109,7 +4535,9 @@@ export async function uninstallGhostAnd
): Promise<void> {
// 按 ghostId 与装入/更新互斥:卸载与同 id 的市场/本地装入不得交错,否则
// 市场装入的"目标是否已装"判定会被本卸载在其落位前抽走(反之亦然)。
-- return withGhostInstallLock(id, () => uninstallGhostAndCleanupLocked(id, options));
++ return withGhostInstallLock(id, () =>
++ withActiveOwnerGhostOauthMutationLock(id, () => uninstallGhostAndCleanupLocked(id, options)),
++ );
}
async function uninstallGhostAndCleanupLocked(
@@@ -4730,6 -4400,6 +4825,7 @@@ export function registerGhostIpc(): voi
networkHosts: runtimeManifest.network?.hosts,
manager: getGhostOauthAccountManager(),
ghostId,
++ withMutationLock: withActiveOwnerGhostOauthMutationLock,
onChanged: (secretKey) => {
getGhostSetupChangeBus().emit(ghostId, { source: 'oauth', ref: secretKey });
broadcastGhostsChanged(getGhostManager().list(), false, { projectionOnly: true });
@@@ -5756,13 -5401,22 +5852,24 @@@
let result: Awaited<ReturnType<typeof manager.update>>;
let packagePlaced = false;
try {
-- result = await manager.update(lizFilePath, {
-- expectedPackageSha256,
- expectedInstalledApproval,
- ...(previousGhost
- ? {
- beforePackageCommit: () => {
- getGhostOauthAccountManager().expireAccountsForChangedClients(
- withRuntimeFiloGoogleClient(previousGhost.manifest),
- withRuntimeFiloGoogleClient(inspected.canonicalManifest),
- );
- },
- }
- : {}),
-- onPackagePlaced: () => {
-- packagePlaced = true;
-- },
-- });
++ result = await withActiveOwnerGhostOauthMutationLock(inspected.manifest.id, () =>
++ manager.update(lizFilePath, {
++ expectedPackageSha256,
++ expectedInstalledApproval,
++ ...(previousGhost
++ ? {
++ beforePackageCommit: () =>
++ getGhostOauthAccountManager().prepareAccountsForChangedClients(
++ withRuntimeFiloGoogleClient(previousGhost.manifest),
++ withRuntimeFiloGoogleClient(inspected.canonicalManifest),
++ ),
++ }
++ : {}),
++ onPackagePlaced: () => {
++ packagePlaced = true;
++ },
++ }),
++ );
} catch (err) {
if (!packagePlaced) {
restoreMarketRecord();
diff --cc apps/desktop/src/main/cindy-brain/runtime/ghostOauthEndpoint.ts
index 0b216a6e24,0b216a6e24..f8d73563b7
--- a/apps/desktop/src/main/cindy-brain/runtime/ghostOauthEndpoint.ts
+++ b/apps/desktop/src/main/cindy-brain/runtime/ghostOauthEndpoint.ts
@@@ -90,12 -90,12 +90,16 @@@ export async function handleGhostOauthR
networkHosts?: readonly string[];
manager: GhostOauthEndpointManager;
ghostId: string;
++ /** Serialize credential/account persistence with package OAuth migration. */
++ withMutationLock?: <T>(ghostId: string, task: () => Promise<T> | T) => Promise<T>;
/** Successful semantic persistence only; never receives credential values. */
onChanged?: (secretKey: string) => void;
log?: { warn(message: string, meta?: Record<string, unknown>): void };
}): Promise<GhostOauthRequestOutcome> {
const { method, pathname, readBodyText, oauthSecrets, networkHosts, manager, ghostId, log } =
args;
++ const runMutation = <T>(task: () => Promise<T> | T): Promise<T> =>
++ args.withMutationLock?.(ghostId, task) ?? Promise.resolve(task());
const notifyChanged = (secretKey: string): void => {
try {
args.onChanged?.(secretKey);
@@@ -175,7 -175,7 +179,8 @@@
clientSecret = trimmed.length > 0 ? trimmed : undefined;
}
try {
-- if (!manager.setClientConfig(ghostId, secretKey, clientId, clientSecret)) {
++ if (!(await runMutation(() =>
++ manager.setClientConfig(ghostId, secretKey, clientId, clientSecret)))) {
return { status: 500 };
}
notifyChanged(secretKey);
@@@ -187,7 -187,7 +192,7 @@@
}
if (method === 'DELETE') {
try {
-- manager.clearClientConfig(ghostId, secretKey);
++ await runMutation(() => manager.clearClientConfig(ghostId, secretKey));
notifyChanged(secretKey);
return { status: 204 };
} catch (err) {
@@@ -295,11 -295,11 +300,8 @@@
scopes.push(scope);
}
try {
-- const stored = manager.reportInsufficientScopes(
-- ghostId,
-- secretKey,
-- scopes,
-- decl.scopes ?? [],
++ const stored = await runMutation(() =>
++ manager.reportInsufficientScopes(ghostId, secretKey, scopes, decl.scopes ?? []),
);
if (stored === false) return { status: 500 };
// 证据未变时不广播:插件在用户重连前会反复撞同一权限错误并 fire-and-forget
@@@ -317,7 -317,7 +319,7 @@@
const accountId = segments[2];
if (!accountId) return { status: 404 };
try {
-- manager.disconnectAccount(ghostId, secretKey, accountId);
++ await runMutation(() => manager.disconnectAccount(ghostId, secretKey, accountId));
notifyChanged(secretKey);
return { status: 204 };
} catch (err) {
@@@ -333,7 -333,7 +335,9 @@@
const accountId = parsed.body.accountId;
if (typeof accountId !== 'string' || accountId.length === 0) return { status: 400 };
try {
-- if (!manager.setDefaultAccount(ghostId, secretKey, accountId)) return { status: 404 };
++ if (!(await runMutation(() => manager.setDefaultAccount(ghostId, secretKey, accountId)))) {
++ return { status: 404 };
++ }
notifyChanged(secretKey);
return { status: 204 };
} catch (err) {
diff --cc apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts
index a5a7614544,a5a7614544..bf7cdbccc5
--- a/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts
+++ b/apps/desktop/src/main/plugin-market/__tests__/ipcErrorBoundary.test.ts
@@@ -126,12 -126,12 +126,16 @@@ describe('Plugin Market IPC error bound
'disposePluginMarketAuthListener = authManager.onAuthStateChange',
);
expect(listenerStart).toBeGreaterThan(-1);
-- expect(
-- bootstrapSource.indexOf(
-- 'queueMicrotask(syncDefaultPluginsForActiveOwner);',
-- listenerStart,
-- ),
-- ).toBeGreaterThan(listenerStart);
++ const listenerEnd = bootstrapSource.indexOf(
++ '\n syncDefaultPluginsForActiveOwner();',
++ listenerStart,
++ );
++ const listenerBody = bootstrapSource.slice(listenerStart, listenerEnd);
++ expect(listenerBody).toContain('queueMicrotask(() => {');
++ expect(listenerBody).toContain('syncDefaultPluginsForActiveOwner();');
++ expect(listenerBody).toContain('reconcileGhostOauthForActiveOwner();');
++ expect(bootstrapSource.slice(listenerEnd)).toContain('syncDefaultPluginsForActiveOwner();');
++ expect(bootstrapSource.slice(listenerEnd)).toContain('reconcileGhostOauthForActiveOwner();');
expect(bootstrapSource).toContain("'plugin-market-auth-listener'");
});
});
diff --cc apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx
index 2cf2e7db1c,91c7005b25..49cce776d7
--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx
+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx
@@@ -109,10 -54,9 +109,11 @@@ const commandPlugin: GhostPluginListIte
version: '1.0.0',
enabled: true,
canUse: true,
+ approvalState: 'approved',
+ builtin: false,
tabPanel: false,
hostCapability: null,
+ oauthAuthorizationExpired: false,
};
const panelPlugin: GhostPluginListItem = {
diff --cc apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts
index 7f0e0e3a08,32b4a65f9c..6b518c830f
--- a/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts
+++ b/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts
@@@ -271,10 -264,9 +272,11 @@@ export function toGhostPluginListItem
version: manifest.version,
enabled: ghost.enabled,
canUse: Boolean(manifest.command),
+ approvalState: ghost.approval.state,
+ builtin: ghost.builtin === true,
tabPanel: manifest.panel?.position === 'tab',
hostCapability: manifest.slots.includes('ios-simulator') ? 'ios-simulator' : null,
+ oauthAuthorizationExpired: ghost.oauthAuthorizationExpired !== undefined,
trust: ghost.trust ?? {
level: 'unverified',
publisherSigned: false,
diff --cc apps/desktop/src/shared/ghost.ts
index 64dc2175a5,18a008d7d1..82f698b0d6
--- a/apps/desktop/src/shared/ghost.ts
+++ b/apps/desktop/src/shared/ghost.ts
@@@ -2240,38 -2184,15 +2276,47 @@@ export function diffGhostPermissionItem
removed.push(item);
}
}
- return { added, removed, unchanged };
+ return {
+ added,
+ removed,
+ unchanged,
+ builtinOauthClientChanged: changedBuiltinOauthClientSecretKeys(prev, next).length > 0,
+ };
}
-/** 返回真实包中既未在安装前展示、也未被当前已装版本覆盖的权限。 */
+/**
+ * Compare an installed Plugin with a candidate package without trusting a
+ * mutable live manifest. Legacy or invalid installs have no approved baseline,
+ * so every permission in the candidate must be reviewed as newly requested.
+ */
+export function diffInstalledGhostPermissionItems(
+ installed: InstalledGhost,
+ next: GhostManifest,
+): GhostPermissionDiff {
+ if (installed.approval.state === 'approved') {
+ return diffGhostPermissionItems(installed.manifest, next);
+ }
+ return {
+ added: ghostPermissionItems(next),
+ removed: [],
+ unchanged: [],
++ // Legacy/invalid installs have no approved old manifest from which a
++ // builtin client transition can be proven. Their complete permission set
++ // is already forced through review via `added` above.
++ builtinOauthClientChanged: false,
+ };
+}
+
+/**
+ * 返回未被发布清单或已批准旧版本覆盖的包权限。
+ *
+ * 第二个来源用于兼容旧市场元数据:旧详情投影可能漏掉已存在的权限,
+ * 但这些权限此前已经被用户批准,更新时应继续保留。
+ *
+ * 注(receipt 模型整合):receipt 模型下"已批准的旧版本清单"即 receipt 的 manifest,
+ * 由整合任务①在 packagePermissionReview 落点用 receipt 已批准 manifest 作 baseline;
+ * 保留本函数以支持 main 现有 market 调用点,不额外引入 previouslyInstalled 认证路径。
+ */
export function unreviewedGhostPermissionItems(
reviewed: GhostManifest,
previouslyInstalled: GhostManifest | undefined,
diff --cc packages/lizi-im/src/telegram/__tests__/messageLifecycle.test.ts
index 0000000000,9171ee8ea5..245b184954
mode 000000,100644..100644
--- a/packages/lizi-im/src/telegram/__tests__/messageLifecycle.test.ts
+++ b/packages/lizi-im/src/telegram/__tests__/messageLifecycle.test.ts
@@@ -1,0 -1,48 +1,47 @@@
+ import { describe, expect, it } from 'vitest';
+
+ import { createTelegramMessageLifecycle } from '../messageLifecycle.js';
+
+ describe('telegram message lifecycle', () => {
+ it('终稿栅栏后拒绝迟到 progress,且发送后才能进入清理', () => {
+ const lifecycle = createTelegramMessageLifecycle('round-1');
+ expect(lifecycle.acceptProgress()).toBe(true);
+ const final = lifecycle.beginFinal();
+
+ expect(final).toMatchObject({ deliveryKey: 'round-1:final', sequence: 1, attempt: 1 });
+ expect(lifecycle.acceptProgress()).toBe(false);
+ expect(lifecycle.beginCleanup()).toBe(false);
+ expect(lifecycle.markFinalSent(final!)).toBe(true);
+ expect(lifecycle.beginCleanup()).toBe(true);
+ expect(lifecycle.finishCleanup()).toBe(true);
+ expect(lifecycle.phase).toBe('complete');
+ });
+
+ it('重复终态共享同一在途 intent,失败重试保持 delivery key', () => {
+ const lifecycle = createTelegramMessageLifecycle('round-2');
+ const first = lifecycle.beginFinal()!;
+ const duplicate = lifecycle.beginFinal()!;
+
+ expect(duplicate).toEqual(first);
+ expect(lifecycle.markFinalFailed(first)).toBe(true);
+ const retry = lifecycle.beginFinal()!;
+ expect(retry.deliveryKey).toBe(first.deliveryKey);
+ expect(retry.attempt).toBe(2);
+ // 旧尝试的迟到回执不能收口新尝试。
+ expect(lifecycle.markFinalSent(first)).toBe(false);
+ expect(lifecycle.markFinalSent(retry)).toBe(true);
+ });
+
+ it('取消冻结过程与终稿,但不删除已经确认的答案', () => {
+ const pending = createTelegramMessageLifecycle('pending');
+ expect(pending.cancel()).toBe(true);
+ expect(pending.acceptProgress()).toBe(false);
+ expect(pending.beginFinal()).toBeNull();
+
+ const sent = createTelegramMessageLifecycle('sent');
+ const final = sent.beginFinal()!;
+ expect(sent.markFinalSent(final)).toBe(true);
+ expect(sent.cancel()).toBe(false);
+ expect(sent.phase).toBe('final-sent');
+ });
+ });
-