Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): surface plugin OAuth client migrations
liugaowei8f0598a6f851
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthAccounts.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthAccounts.test.tsindex cbbdcf7d1a..098bf8b7b2 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthAccounts.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostOauthAccounts.test.ts@@ -5,6 +5,8 @@import * as http from 'node:http';import { describe, expect, it, vi } from 'vitest';+import type { GhostManifest } from '../../../shared/ghost.js';+import {GHOST_OAUTH_INVALID_GRANT_RECHECK_DELAY_MS,GHOST_OAUTH_MAX_ACCOUNTS,@@ -79,6 +81,119 @@ function seededVault(rt = 'rt-seed'): ReturnType<typeof memoryVault> {});}+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 },+ },+ ],+ },+ };+}++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'),+ ),+ ).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);+ });+});+describe('missingAuthScopes(快照推断)', () => {it.each([['全量快照没有新增 scope', ['scope.a'], { authFace: 'full', authScopes: ['scope.a'] }, false],@@ -643,7 +758,13 @@ describe('connectAccount', () => {[`${KEY}-accounts`]: JSON.stringify({defaultAccountId: 'acc-1',accounts: [- { id: 'acc-1', label: '[email protected]', status: 'expired', createdAt: 1 },+ {+ id: 'acc-1',+ label: '[email protected]',+ status: 'expired',+ expiredReason: 'oauth_client_changed',+ createdAt: 1,+ },{ id: 'acc-2', label: '[email protected]', status: 'connected', createdAt: 2 },],}),@@ -669,6 +790,7 @@ describe('connectAccount', () => {expect(result.account.isDefault).toBe(true);const listed = mgr.listAccounts(GHOST, KEY);expect(listed).toHaveLength(2);+ expect(mgr.clientMigrationExpiredAccountCount(GHOST, KEY)).toBe(0);expect(vault.read(GHOST, `${KEY}-rt-acc-1`)).toBe('rt-fresh');expect(JSON.parse(vault.read(GHOST, `${KEY}-accounts`) ?? '{}').accounts[0]).toMatchObject({authScopes: ['scope.a'],@@ -887,6 +1009,7 @@ describe('getFreshAccessToken', () => {error: 'AUTH_EXPIRED',});expect(mgr.listAccounts(GHOST, KEY)[0]).toMatchObject({ status: 'expired' });+ expect(mgr.clientMigrationExpiredAccountCount(GHOST, KEY)).toBe(0);expect(vault.read(GHOST, `${KEY}-rt-acc-1`)).toBeNull();expect(onAccountStatusChanged).toHaveBeenCalledWith({ghostId: GHOST,diff --git a/apps/desktop/src/main/cindy-brain/ghostOauthAccounts.ts b/apps/desktop/src/main/cindy-brain/ghostOauthAccounts.tsindex faf33872eb..b4ad144576 100644--- a/apps/desktop/src/main/cindy-brain/ghostOauthAccounts.ts+++ b/apps/desktop/src/main/cindy-brain/ghostOauthAccounts.ts@@ -44,7 +44,12 @@ import {type GhostOauthFlowError,type GhostOauthLogger,} from './ghostOauthFlow.js';-import { isOfficialGhostId, type GhostSecretOauthDecl } from '../../shared/ghost.js';+import {+ changedBuiltinOauthClientSecretKeys,+ isOfficialGhostId,+ type GhostManifest,+ type GhostSecretOauthDecl,+} from '../../shared/ghost.js';/** 每个 oauth 凭证槽最多可连账号数(防清单无限膨胀;超出连接被拒)。 */export const GHOST_OAUTH_MAX_ACCOUNTS = 8;@@ -177,6 +182,8 @@ interface AccountRow {/** 人类可读展示名(identity.displayTemplate 渲染;纯展示,不参与合并判定)。 */displayLabel: string | null;status: GhostOauthAccountStatus;+ /** 仅标记由插件内置 OAuth clientId 迁移触发的过期,供宿主精确提示。 */+ expiredReason?: 'oauth_client_changed';createdAt: number;/** 本次浏览器授权 URL 实际携带的 scope 面;旧账号没有该快照。 */authScopes?: string[];@@ -227,6 +234,9 @@ function parseManifest(raw: string | null): AccountsManifest {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 }+ : {}),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 @@ 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);+ }+ return expiredCount;+ }++ /** 返回仍未完成重新授权的 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',+ ).length;+ }+/*** client 凭证解析链:用户自填 > 清单内置(cindy-google 等开箱即用意识* 把凭证写在包里)。**成对语义**:自填了 clientId 就用自填的整对@@ -672,6 +711,10 @@ export class GhostOauthAccountManager {existing.status = 'connected';manifestDirty = true;}+ if (existing.expiredReason !== undefined) {+ delete existing.expiredReason;+ manifestDirty = true;+ }if (display !== null && existing.displayLabel !== display) {existing.displayLabel = display;manifestDirty = true;@@ -805,6 +848,11 @@ export class GhostOauthAccountManager {if (!resolvedId) return { ok: false, error: 'NO_ACCOUNT' };const row = manifest.accounts.find((a) => a.id === resolvedId);if (!row) return { ok: false, error: 'NO_ACCOUNT' };+ // 旧 refresh token 与新的内置 clientId 不成对;必须重新走浏览器授权,+ // 不能先拿新 client 尝试刷新再把仍需保留的旧 token 当 invalid_grant 删除。+ if (row.status === 'expired' && row.expiredReason === 'oauth_client_changed') {+ return { ok: false, error: 'AUTH_EXPIRED' };+ }const key = this.cacheKey(ghostId, secretKey, resolvedId);const cached = this.tokenCache.get(key);@@ -1046,10 +1094,41 @@ export class GhostOauthAccountManager {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,+ });+ return 0;+ }+ }+ 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;return true;});if (changed) this.notifyStatusChanged(ghostId, secretKey, 'connected');diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex fbc022b536..824a138599 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -732,9 +732,22 @@ function availableGhosts(): InstalledGhost[] {function projectGhostForRenderer(ghost: InstalledGhost): InstalledGhost {try {- const suggest = getGhostOauthReauthSuggest(withRuntimeFiloGoogleClient(ghost.manifest));+ const runtimeManifest = withRuntimeFiloGoogleClient(ghost.manifest);+ const oauthManager = getGhostOauthAccountManager();+ const expiredAccountCount = (runtimeManifest.network?.secrets ?? []).reduce(+ (count, secret) =>+ secret.source === 'oauth' && secret.oauth+ ? count ++ oauthManager.clientMigrationExpiredAccountCount(runtimeManifest.id, secret.key)+ : count,+ 0,+ );+ const suggest = getGhostOauthReauthSuggest(runtimeManifest);return {...ghost,+ ...(expiredAccountCount > 0+ ? { oauthAuthorizationExpired: { expiredAccountCount } }+ : {}),...(suggest? {oauthScopeStale: {@@ -745,8 +758,8 @@ function projectGhostForRenderer(ghost: InstalledGhost): InstalledGhost {: {}),};} catch (error) {- // 详情页角标是提示面,保险库异常不能让插件清单整体消失。- log.warn('ghost oauth scope stale projection omitted', {+ // OAuth 展示投影是提示面,保险库异常不能让插件清单整体消失。+ log.warn('ghost oauth renderer projection omitted', {ghostId: ghost.manifest.id,errorType: error instanceof Error ? error.name : typeof error,});@@ -3381,9 +3394,13 @@ function getGhostOauthReauthSuggest(runtimeManifest: GhostManifest,): GhostSetupReauthSuggest | undefined {const oauthManager = getGhostOauthAccountManager();- return findGhostOauthReauthSuggest(runtimeManifest, (secretKey, decl) =>- oauthManager.defaultMissingScopes(runtimeManifest.id, secretKey, decl),- );+ return findGhostOauthReauthSuggest(runtimeManifest, (secretKey, decl) => {+ const defaultAccount = oauthManager+ .listAccounts(runtimeManifest.id, secretKey)+ .find((account) => account.isDefault);+ if (defaultAccount?.status === 'expired') return [];+ return oauthManager.defaultMissingScopes(runtimeManifest.id, secretKey, decl);+ });}/**@@ -3952,9 +3969,10 @@ async function installOrUpdateMarketGhostPackageLocked(): [];const needsReview =- expected.permissionPolicy.mode === 'manual'+ permissionDiff?.builtinOauthClientChanged === true ||+ (expected.permissionPolicy.mode === 'manual'? permissionDiff === null || permissionDiff.added.length > 0- : unreviewed.length > 0;+ : unreviewed.length > 0);if (needsReview && expected.approvedPackageSha256 === undefined) {const reviewKeys =expected.permissionPolicy.mode === 'manual'@@ -3972,6 +3990,7 @@ async function installOrUpdateMarketGhostPackageLocked(ghostId: expected.ghostId,mode: expected.permissionPolicy.mode,keys: reviewKeys,+ builtinOauthClientChanged: permissionDiff?.builtinOauthClientChanged === true,});throw new GhostPackagePermissionReviewRequiredError(review);}@@ -4042,6 +4061,10 @@ 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);@@ -5402,6 +5425,12 @@ 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);diff --git a/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx b/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsxindex a0f7c262b7..ed011fdc02 100644--- a/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx+++ b/apps/desktop/src/renderer/cindy-brain/GhostPermissionList.tsx@@ -417,10 +417,27 @@ export function GhostUpdateReview({trust?: GhostTrustInfo;diff: GhostPermissionDiff;}) {+ const { t } = useTranslation();return (<div>{trust && <GhostTrustSummary trust={trust} />}- <div className={cn(trust && 'mt-3')}>+ {diff.builtinOauthClientChanged ? (+ <div+ role="alert"+ className={cn(+ trust && 'mt-3',+ 'flex items-start gap-2 rounded-lg bg-[var(--warning-bg-soft)] px-3 py-2 text-13 leading-5 text-[var(--text-secondary)]',+ )}+ >+ <ShieldAlert+ size={16}+ className="mt-0.5 shrink-0 text-[var(--warning-fg)]"+ aria-hidden="true"+ />+ <span>{t('settings.ghosts.updateConfirm.oauthClientChanged')}</span>+ </div>+ ) : null}+ <div className={cn((trust || diff.builtinOauthClientChanged) && 'mt-3')}><GhostPermissionDiffView diff={diff} /></div></div>diff --git a/apps/desktop/src/renderer/cindy-brain/__tests__/GhostPermissionList.test.tsx b/apps/desktop/src/renderer/cindy-brain/__tests__/GhostPermissionList.test.tsxindex eb33f92613..2147add31b 100644--- a/apps/desktop/src/renderer/cindy-brain/__tests__/GhostPermissionList.test.tsx+++ b/apps/desktop/src/renderer/cindy-brain/__tests__/GhostPermissionList.test.tsx@@ -273,6 +273,14 @@ describe('GhostUpdateReview(更新确认内容区,两个入口共用)', () => {expect(screen.getByText(/perm\.networkHost:.*api\.example\.com/)).toBeTruthy();});+ it('内置 OAuth clientId 变化时提示更新后需要重新连接', () => {+ const diff = diffGhostPermissionItems(chip(), next());+ render(<GhostUpdateReview diff={{ ...diff, builtinOauthClientChanged: true }} />);+ expect(screen.getByRole('alert').textContent).toBe(+ 'settings.ghosts.updateConfirm.oauthClientChanged',+ );+ });+it('不自套限高滚动区(高度归共享 ConfirmDialog)', () => {const { container } = render(<GhostUpdateReview diff={diffGhostPermissionItems(chip(), next())} />,diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsxindex 6b8df45bcd..4c59eeab41 100644--- a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx@@ -19,6 +19,7 @@ import {} from 'react';import { useNavigate, useSearchParams } from 'react-router-dom';import {+ AlertTriangle,ArrowUp,Bot,Check,@@ -2004,7 +2005,13 @@ export function GhostPluginCard({</span><span className="mt-1 block min-w-0 truncate text-11 text-[var(--text-tertiary)]">{sourceLabel ? `${sourceLabel} · ` : ''}v{item.version}- {!updateVersion ? (+ {item.oauthAuthorizationExpired ? (+ <span className="inline-flex items-center gap-1 text-[var(--warning-fg)]">+ {' · '}+ <AlertTriangle size={11} className="inline" aria-hidden="true" />+ <span>{t('settings.ghosts.page.oauthAuthorizationExpired')}</span>+ </span>+ ) : !updateVersion ? (<span className="inline-flex items-center gap-1">{' · '}<Check size={11} className="inline" aria-hidden="true" />diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsxindex 9c49fc889a..91c7005b25 100644--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginCard.test.tsx@@ -56,6 +56,7 @@ const commandPlugin: GhostPluginListItem = {canUse: true,tabPanel: false,hostCapability: null,+ oauthAuthorizationExpired: false,};const panelPlugin: GhostPluginListItem = {@@ -161,6 +162,19 @@ describe('GhostPluginCard', () => {expect(screen.queryByText(/upToDate/)).toBeNull();});+ it('shows an expired OAuth status instead of the up-to-date status', () => {+ render(+ <GhostPluginCard+ item={{ ...commandPlugin, oauthAuthorizationExpired: true }}+ onPrimary={vi.fn()}+ onManage={vi.fn()}+ />,+ );++ expect(screen.getByText('settings.ghosts.page.oauthAuthorizationExpired')).toBeTruthy();+ expect(screen.queryByText(/upToDate/)).toBeNull();+ });+it('blocks the update pill while a market operation is running', () => {render(<GhostPluginCarddiff --git a/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts b/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.tsindex 0b4733afea..32b4a65f9c 100644--- a/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts+++ b/apps/desktop/src/renderer/features/plugin/lib/ghostPluginViewModel.ts@@ -38,6 +38,7 @@ export interface GhostPluginListItem {tabPanel: boolean;/** 声明了由 Host 承载、但可从插件 UI 主动进入的能力。 */hostCapability: 'ios-simulator' | null;+ oauthAuthorizationExpired?: boolean;trust?: GhostTrustInfo;iconDataUrl?: string;}@@ -265,6 +266,7 @@ export function toGhostPluginListItem(canUse: Boolean(manifest.command),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 --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex 87d5f49a29..3c03950032 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -3315,6 +3315,7 @@"manageAria": "Manage {{name}}","agentInvoked": "Invoked by Agent","upToDate": "Up to date",+ "oauthAuthorizationExpired": "Authorization expired — reconnect required","installAria": "Install {{name}}"},"market": {@@ -3740,6 +3741,7 @@"updateConfirm": {"title": "Update plugin \"{{name}}\"?","body": "Version {{from}} → {{to}}. This replaces the installed version; enabled state and panel position are preserved.",+ "oauthClientChanged": "This update changes the OAuth client. Connected accounts using the plugin's built-in authorization will expire after the update and must be reconnected.","confirm": "Update","cancel": "Cancel"},diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 183fc4d1f8..3c4e3d6d10 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -3314,6 +3314,7 @@"manageAria": "{{name}} を管理","agentInvoked": "Agent が自動で呼び出し","upToDate": "最新です",+ "oauthAuthorizationExpired": "認証期限切れ・再接続が必要","installAria": "{{name}} をインストール"},"market": {@@ -3739,6 +3740,7 @@"updateConfirm": {"title": "プラグイン「{{name}}」を更新しますか?","body": "バージョン {{from}} → {{to}}。既存バージョンを置き換えます。有効状態とパネル位置は保持されます。",+ "oauthClientChanged": "この更新で OAuth クライアントが変更されます。プラグイン内蔵の認証を使用している接続済みアカウントは更新後に無効となり、再接続が必要です。","confirm": "更新","cancel": "キャンセル"},diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex 76679f8b1c..c0556f9a25 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -3314,6 +3314,7 @@"manageAria": "{{name}} 관리","agentInvoked": "Agent가 자동 호출","upToDate": "최신 상태",+ "oauthAuthorizationExpired": "인증 만료 · 다시 연결 필요","installAria": "{{name}} 설치"},"market": {@@ -3739,6 +3740,7 @@"updateConfirm": {"title": "플러그인 \"{{name}}\"을(를) 업데이트할까요?","body": "버전 {{from}} → {{to}}. 설치된 버전을 교체합니다. 활성 상태와 패널 위치는 유지됩니다.",+ "oauthClientChanged": "이번 업데이트에서 OAuth 클라이언트가 변경됩니다. 플러그인의 기본 인증을 사용하는 연결된 계정은 업데이트 후 만료되며 다시 연결해야 합니다.","confirm": "업데이트","cancel": "취소"},diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex c406f0cae9..e231128b96 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -3310,6 +3310,7 @@"manageAria": "管理 {{name}}","agentInvoked": "Agent 自动调用","upToDate": "已是最新",+ "oauthAuthorizationExpired": "授权已失效,需重新连接","installAria": "安装 {{name}}"},"market": {@@ -3735,6 +3736,7 @@"updateConfirm": {"title": "更新插件「{{name}}」?","body": "版本 {{from}} → {{to}}。将替换现有版本;生效状态与面板位置保持不变。",+ "oauthClientChanged": "本次更新更换了 OAuth 客户端。使用插件内置授权的已连接账号将在更新后失效,需要重新连接。","confirm": "更新","cancel": "取消"},diff --git a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.jsonindex 598c18fc68..d4f2e53a1f 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-TW/common.json@@ -3313,6 +3313,7 @@"manageAria": "管理 {{name}}","agentInvoked": "Agent 自動呼叫","upToDate": "已是最新",+ "oauthAuthorizationExpired": "授權已失效,需重新連線","installAria": "安裝 {{name}}"},"market": {@@ -3738,6 +3739,7 @@"updateConfirm": {"title": "更新插件「{{name}}」?","body": "版本 {{from}} → {{to}}。將替換現有版本;生效狀態與面板位置保持不變。",+ "oauthClientChanged": "本次更新更換了 OAuth 用戶端。使用插件內建授權的已連線帳號將在更新後失效,需要重新連線。","confirm": "更新","cancel": "取消"},diff --git a/apps/desktop/src/shared/__tests__/ghost.test.ts b/apps/desktop/src/shared/__tests__/ghost.test.tsindex 7e6bde70c3..36424421c8 100644--- a/apps/desktop/src/shared/__tests__/ghost.test.ts+++ b/apps/desktop/src/shared/__tests__/ghost.test.ts@@ -6,6 +6,7 @@ import {GHOST_CINDY_EMBED_MAX_TEXTS,GHOST_MANIFEST_SUMMARY_MAX_CHARS,GHOST_SLOTS,+ changedBuiltinOauthClientSecretKeys,deriveGhostSessionContext,diffGhostPermissionItems,ghostAppContextLocale,@@ -2237,6 +2238,41 @@ describe('ghost · 逐项权限清单', () => {expect(d.added).toEqual([]);expect(d.removed).toEqual([]);expect(d.unchanged.length).toBe(7);+ expect(d.builtinOauthClientChanged).toBe(false);+ });++ it('diff:同一凭证槽的内置直连 OAuth clientId 变化会标记授权失效风险', () => {+ const oauthManifest = (clientId: string): GhostManifest => ({+ schemaVersion: 2,+ id: 'oauth-plugin',+ name: 'OAuth Plugin',+ version: '1.0.0',+ kind: 'chip',+ entry: 'main.js',+ slots: ['network'],+ network: {+ hosts: ['api.example.com'],+ secrets: [+ {+ key: 'account',+ label: 'Account',+ source: 'oauth',+ inject: { header: 'Authorization', format: 'Bearer {value}' },+ oauth: {+ authorizeUrl: 'https://accounts.example.com/authorize',+ tokenUrl: 'https://accounts.example.com/token',+ clientId,+ },+ },+ ],+ },+ });+ const previous = oauthManifest('old-client');+ const current = oauthManifest('new-client');++ expect(changedBuiltinOauthClientSecretKeys(previous, current)).toEqual(['account']);+ expect(diffGhostPermissionItems(previous, current).builtinOauthClientChanged).toBe(true);+ expect(changedBuiltinOauthClientSecretKeys(oauthManifest(''), current)).toEqual([]);});});diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.tsindex b416e71738..18a008d7d1 100644--- a/apps/desktop/src/shared/ghost.ts+++ b/apps/desktop/src/shared/ghost.ts@@ -1468,6 +1468,10 @@ export interface InstalledGhost {secretKey: string;missingScopeCount: number;};+ /** 插件列表所需的失效授权投影;不暴露账号身份或凭证内容。 */+ oauthAuthorizationExpired?: {+ expiredAccountCount: number;+ };}/**@@ -2069,6 +2073,38 @@ export interface GhostPermissionDiff {added: GhostPermissionItem[];removed: GhostPermissionItem[];unchanged: GhostPermissionItem[];+ /** 同一凭证槽的内置直连 OAuth clientId 发生变化。 */+ builtinOauthClientChanged: boolean;+}++/**+ * 返回同一插件内置直连 OAuth clientId 发生变化的凭证槽。+ * tokenBroker 可能按区域选择不同 clientId,仅凭 manifest 无法判断账号实际+ * 使用哪一个,因此不把 broker 默认值变化判成确定失效。+ */+export function changedBuiltinOauthClientSecretKeys(+ previousManifest: GhostManifest,+ currentManifest: GhostManifest,+): string[] {+ if (previousManifest.id !== currentManifest.id) return [];+ const previousSecrets = new Map(+ (previousManifest.network?.secrets ?? []).map((secret) => [secret.key, secret]),+ );+ const changed: string[] = [];+ for (const current of currentManifest.network?.secrets ?? []) {+ if (current.source !== 'oauth' || !current.oauth) continue;+ const previous = previousSecrets.get(current.key);+ if (previous?.source !== 'oauth' || !previous.oauth) continue;+ if (current.oauth.tokenBroker || previous.oauth.tokenBroker) continue;+ const previousClientId = previous.oauth.clientId?.trim() || null;+ const currentClientId = current.oauth.clientId?.trim() || null;+ // 旧版没有内置 clientId 时,存量账号只能来自用户自定义配置;新增默认值+ // 不会让这些令牌失效。只有旧内置客户端真实存在时才属于迁移。+ if (previousClientId !== null && previousClientId !== currentClientId) {+ changed.push(current.key);+ }+ }+ return changed;}/**@@ -2148,7 +2184,12 @@ export function diffGhostPermissionItems(removed.push(item);}}- return { added, removed, unchanged };+ return {+ added,+ removed,+ unchanged,+ builtinOauthClientChanged: changedBuiltinOauthClientSecretKeys(prev, next).length > 0,+ };}/** 返回真实包中既未在安装前展示、也未被当前已装版本覆盖的权限。 */