Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(plugin): 支持真实包权限变化后重新确认 (#1648)
GaoWei Liu2db5c6280641
diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.tsindex e13774adf9..735dc6e5bd 100644--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts@@ -316,6 +316,8 @@ export class GhostManager {): Promise<| {manifest: GhostManifest;+ /** 包内原始清单,仅供 Main 安全比较。 */+ canonicalManifest: GhostManifest;trust: GhostTrustInfo;packageSha256: string;iconDataUrl?: string;@@ -326,6 +328,7 @@ export class GhostManager {if ('rejection' in parsed) return parsed;return {manifest: parsed.manifest,+ canonicalManifest: parsed.canonicalManifest,trust: parsed.trust,packageSha256: parsed.packageSha256,...(parsed.iconDataUrl !== undefined ? { iconDataUrl: parsed.iconDataUrl } : {}),@@ -338,6 +341,7 @@ export class GhostManager {): Promise<| {manifest: GhostManifest;+ canonicalManifest: GhostManifest;trust: GhostTrustInfo;packageSha256: string;iconDataUrl?: string;@@ -614,6 +618,7 @@ export class GhostManager {return {manifest: localizedManifest,+ canonicalManifest: v.manifest,trust: signature.trust,packageSha256: crypto.createHash('sha256').update(buf).digest('hex'),...(iconDataUrl !== undefined ? { iconDataUrl } : {}),diff --git a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.tsindex 396768c2a3..2c152c3a5a 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts@@ -535,6 +535,37 @@ describe('GhostManager · inspect(只验不装)', () => {expect(onChanged).not.toHaveBeenCalled();});+ it('本地化展示清单与包内 canonical 清单分离', async () => {+ hostLocale = 'zh-CN';+ const base = {+ ...goodManifest(),+ name: 'Base name',+ locales: {+ en: 'locales/en.json',+ 'zh-CN': 'locales/zh-CN.json',+ },+ };+ const cindy = await makeCindy('canonical.cindy', base, {+ 'locales/en.json': JSON.stringify({ name: 'English name' }),+ 'locales/zh-CN.json': JSON.stringify({+ name: '中文名称',+ tools: { do_thing: { description: '中文工具说明' } },+ }),+ });++ const inspected = await manager.inspect(cindy);+ expect(inspected).toMatchObject({+ manifest: {+ name: '中文名称',+ tools: [{ name: 'do_thing', description: '中文工具说明' }],+ },+ canonicalManifest: {+ name: 'Base name',+ tools: [{ name: 'do_thing', description: '做点事' }],+ },+ });+ });+it('确认后源文件被替换时,整包指纹不一致会拒绝安装', async () => {const cindy = await makeCindy('swap.cindy', goodManifest(), { 'payload.txt': 'before' });const inspected = await manager.inspect(cindy);diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex bb563f3f30..689450c216 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -14,6 +14,7 @@ import {GHOST_NETWORK_MAX_CONNECTIONS_PER_DECL,GHOST_NOTIFY_MIN_INTERVAL_MS,diffGhostPermissionItems,+ ghostPermissionBaselineKey,ghostWebviewEntryPaths,isCindyAccountGhostId,isOfficialGhostId,@@ -28,6 +29,7 @@ import {type GhostVideoResultParams,type InstalledGhost,} from '../../shared/ghost.js';+import type { PluginMarketPackageReview } from '../../shared/pluginMarket.js';import { getAppCapabilities } from '../appCapabilities.js';import {activeOwnerScopeKey,@@ -41,6 +43,7 @@ import { GhostManager, type InstallRejection, type UninstallRejection } from './import { exportGhostPackage } from './exportGhostPackage.js';import { GhostMutationCoordinator } from './ghostMutationCoordinator.js';import { withGhostInstallLock } from './ghostInstallLock.js';+import { GhostPackagePermissionReviewRequiredError } from './packagePermissionReview.js';import {clearBuiltinTombstone,listEligibleBuiltinCommands,@@ -3167,10 +3170,13 @@ export async function installOrUpdateMarketGhostPackage(version: string;/*** 装入确认框实际展示给用户的那份 manifest(来源方给的)。给了就逐项比对:- * 包里多出来的权限一律拒装(见 Locked 版里的说明)。两条市场路径都必须给;+ * 包里多出来的权限会暂停落位并交由上层复核。两条市场路径都必须给;* 本地 `.cindy` 装入不经此出口,确认框读的就是包本身,没有这层漂移。*/reviewedManifest?: GhostManifest;+ /** 用户确认过的真实下载包 SHA 与确认时的已装权限基线。 */+ approvedPackageSha256?: string;+ reviewedBaseline?: string;},): Promise<InstalledGhost> {// 卡点:按 ghostId 上锁,覆盖 inspect → 落位整段。服务端与自定义两条市场路径@@ -3187,6 +3193,8 @@ async function installOrUpdateMarketGhostPackageLocked(ghostId: string;version: string;reviewedManifest?: GhostManifest;+ approvedPackageSha256?: string;+ reviewedBaseline?: string;},): Promise<InstalledGhost> {const mutationOwner = captureGhostMutationOwner();@@ -3196,8 +3204,8 @@ async function installOrUpdateMarketGhostPackageLocked(const inspected = await manager.inspect(cindyFilePath);if ('rejection' in inspected) throwInstallError(inspected.rejection);if (- inspected.manifest.id !== expected.ghostId ||- inspected.manifest.version !== expected.version+ inspected.canonicalManifest.id !== expected.ghostId ||+ inspected.canonicalManifest.version !== expected.version) {throwIpcError('GHOST_FILE_INVALID',@@ -3215,29 +3223,49 @@ async function installOrUpdateMarketGhostPackageLocked(* 未知槽名,投影时会被丢掉或整份拒绝。结果:确认框漏列该项权限,包却原样带着* 它装进来,用户**从没审过就多出一个常驻能力面**。*- * 这里按权限项逐项比对,包里多出来的一律拒装——不是只挡 badge,是把这一整类- * 「来源投影漏字段」的洞一次封死。落在 inspect 之后、任何落地动作之前,所以- * 拒绝时磁盘上什么都没动,不需要回滚。+ * 这里按权限项逐项比对。包里多出来的权限先暂停落位,由 Renderer 按真实包+ * 重新展示;用户批准后携带包 SHA 和已装权限基线重试。+ * 卡点落在 inspect 之后、任何落地动作之前,所以等待复核时磁盘上什么都没动。*/+ const installed = manager.list().find((ghost) => ghost.manifest.id === expected.ghostId);if (expected.reviewedManifest) {- const unreviewed = diffGhostPermissionItems(- expected.reviewedManifest,- inspected.manifest,- ).added;- if (unreviewed.length > 0) {- log.warn('market package declares unreviewed permissions', {- ghostId: expected.ghostId,- keys: unreviewed.map((item) => item.key),- });+ const installedBaseline = installed+ ? ghostPermissionBaselineKey(installed.manifest)+ : null;+ // 真实包复核的批准必须始终绑定当时那份包与已装权限面,不能只在+ // 当前仍存在来源清单差异时才校验。否则两次请求间包字节发生变化、+ // 新包恰好不再多权限时,会绕过旧批准的 SHA/基线绑定直接落位。+ if (+ expected.approvedPackageSha256 !== undefined &&+ (expected.approvedPackageSha256 !== inspected.packageSha256 ||+ (expected.reviewedBaseline ?? null) !== installedBaseline)+ ) {throwIpcError('PRECONDITION_FAILED',- '下载包申请的权限多于安装确认框展示的内容,已阻止安装(请向插件来源反馈)',+ 'Downloaded Plugin package changed after permission review',);}+ const added = diffGhostPermissionItems(+ expected.reviewedManifest,+ inspected.canonicalManifest,+ ).added;+ if (added.length > 0) {+ const review: PluginMarketPackageReview = {+ manifest: inspected.manifest,+ packageSha256: inspected.packageSha256,+ installedBaseline,+ };+ if (expected.approvedPackageSha256 === undefined) {+ log.warn('market package declares unreviewed permissions', {+ ghostId: expected.ghostId,+ keys: added.map((item) => item.key),+ });+ throw new GhostPackagePermissionReviewRequiredError(review);+ }+ }}- rejectUnauthorizedTokenBroker(inspected.manifest);+ rejectUnauthorizedTokenBroker(inspected.canonicalManifest);- const installed = manager.list().find((ghost) => ghost.manifest.id === expected.ghostId);// Node 高风险条目由 renderer 装入确认卡权限清单如实展示;// 2026-07-24 Lizi 定案:不再有 Main 侧原生二次确认弹窗(PR #333,本处为其// 漏删的市场安装路径调用点,一并对齐)。@@ -4522,7 +4550,12 @@ export function registerGhostIpc(): void {// 官方前缀在 inspect 就拒(确认弹窗都不该弹出来),install/update 双保险再拦。rejectReservedGhostId(result.manifest.id);rejectUnauthorizedTokenBroker(result.manifest);- return result;+ return {+ manifest: result.manifest,+ trust: result.trust,+ packageSha256: result.packageSha256,+ ...(result.iconDataUrl !== undefined ? { iconDataUrl: result.iconDataUrl } : {}),+ };});ipcMain.handle('ghosts:uninstall', async (_event, id: unknown) => {diff --git a/apps/desktop/src/main/cindy-brain/packagePermissionReview.ts b/apps/desktop/src/main/cindy-brain/packagePermissionReview.tsnew file mode 100644index 0000000000..c6a74e75d9--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/packagePermissionReview.ts@@ -0,0 +1,8 @@+import type { PluginMarketPackageReview } from '../../shared/pluginMarket.js';++/** 安装包权限与市场展示不一致时,交给 PluginMarketService 转成可恢复结果。 */+export class GhostPackagePermissionReviewRequiredError extends Error {+ constructor(readonly review: PluginMarketPackageReview) {+ super('The downloaded Plugin package requires permission review');+ }+}diff --git a/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts b/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.tsindex 7f4108f9df..d896916d71 100644--- a/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/service-custom-sources.test.ts@@ -412,7 +412,7 @@ describe('PluginMarketService 自定义市场 detail/install', () => {expectedReleaseId: customMarketReleaseId('team-lib', 'alpha', '1.0.0'),expectedManifest: reviewed.manifest,});- expect(result.ghost.manifest.id).toBe('alpha');+ expect(result.ghost?.manifest.id).toBe('alpha');expect(runtime.install).toHaveBeenCalledTimes(1);// 打包产物是临时文件,装完即删expect(runtime.install.mock.calls[0]?.[0]).toMatch(/cindy-custom-market-alpha-.*\.cindy$/);diff --git a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts b/apps/desktop/src/main/plugin-market/__tests__/service.test.tsindex 36a1db7780..d8bd711687 100644--- a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts@@ -60,6 +60,7 @@ vi.mock('../download.js', () => ({import type { VisiblePluginDetail, VisiblePluginSummary } from '@cindy/plugin-protocol';import { withGhostInstallLock } from '../../cindy-brain/ghostInstallLock';+import { GhostPackagePermissionReviewRequiredError } from '../../cindy-brain/packagePermissionReview';import { PluginMarketLedger } from '../ledger';import { PluginMarketService } from '../service';import type { PluginMarketApi } from '../api';@@ -423,14 +424,14 @@ describe('PluginMarketService migration and defaultInstall', () => {},);// 锁定装完即开的最终结果:装入入口返回的 ghost 必须是启用态。- expect(ghost.enabled).toBe(true);+ expect(ghost?.enabled).toBe(true);});// 装入确认框渲染的是**服务端给的** manifest,真正落地的是 .cindy 包里的// ghost.json。服务端投影层与客户端清单契约漂移时(cindy-protocol 那份平行// 校验器已经缺了 confirm 槽,新字段按「忽略未知字段」被静默丢掉),包会带着// 用户没审过的权限装进来。出口处需要这份 reviewedManifest 才能逐项比对拦下。- it('passes the reviewed server manifest to the install entry so unreviewed package permissions can be blocked', async () => {+ it('passes the reviewed server manifest to the install entry so package permissions can be re-reviewed', async () => {const item = summary();runtime.install.mockResolvedValue({manifest: manifest(),@@ -450,6 +451,63 @@ describe('PluginMarketService migration and defaultInstall', () => {});});+ it('returns a recoverable package review result and forwards the bound approval on retry', async () => {+ const item = summary();+ const review = {+ manifest: manifest('cindy-test', '1.0.0', ['notify', 'fs']),+ packageSha256: 'a'.repeat(64),+ installedBaseline: null,+ };+ runtime.install.mockRejectedValueOnce(+ new GhostPackagePermissionReviewRequiredError(review),+ );+ const h = harness([item]);++ await expect(+ h.service.install(item.id, { expectedReleaseId: item.currentRelease.id }),+ ).resolves.toEqual({ reviewRequired: review });+ expect(h.ledger.installationForGhost(item.ghostId)).toBeNull();++ runtime.install.mockResolvedValueOnce({+ manifest: manifest(),+ dir: '/userData/cindy-brain/cindy-test',+ enabled: true,+ });+ await expect(+ h.service.install(item.id, {+ expectedReleaseId: item.currentRelease.id,+ approvedPackageSha256: review.packageSha256,+ }),+ ).resolves.toMatchObject({ ghost: { manifest: { id: item.ghostId } } });+ expect(runtime.install).toHaveBeenLastCalledWith(+ expect.stringMatching(/\.cindy$/),+ expect.objectContaining({ approvedPackageSha256: review.packageSha256 }),+ );+ });++ it('does not return package review details after the active owner changes', async () => {+ const item = summary();+ const review = {+ manifest: manifest('cindy-test', '1.0.0', ['notify', 'fs']),+ packageSha256: 'a'.repeat(64),+ installedBaseline: null,+ };+ runtime.install.mockImplementationOnce(async () => {+ runtime.session = {+ mode: 'cloud',+ dataOwnerId: 'user-2',+ generation: 2,+ };+ throw new GhostPackagePermissionReviewRequiredError(review);+ });+ const h = harness([item]);++ await expect(+ h.service.install(item.id, { expectedReleaseId: item.currentRelease.id }),+ ).rejects.toThrow('[PRECONDITION_FAILED]');+ expect(h.ledger.installationForGhost(item.ghostId)).toBeNull();+ });+it('installs and enables a public defaultInstall package in local mode', async () => {runtime.session = {mode: 'local',diff --git a/apps/desktop/src/main/plugin-market/registerIpc.ts b/apps/desktop/src/main/plugin-market/registerIpc.tsindex 2e4b4b5903..f46edc7c36 100644--- a/apps/desktop/src/main/plugin-market/registerIpc.ts+++ b/apps/desktop/src/main/plugin-market/registerIpc.ts@@ -80,6 +80,7 @@ export function registerPluginMarketIpc(): void {expectedManifest?: unknown;allowPermissionExpansion?: unknown;reviewedBaseline?: unknown;+ approvedPackageSha256?: unknown;}): null;const expectedReleaseId = requireString(obj?.expectedReleaseId, 'expectedReleaseId');@@ -91,12 +92,23 @@ export function registerPluginMarketIpc(): void {// 扩权批准的审阅基线:只收字符串,野值按缺席处理(缺席 = 保持旧行为)。const reviewedBaseline =typeof obj?.reviewedBaseline === 'string' ? obj.reviewedBaseline : undefined;+ const approvedPackageSha256 =+ typeof obj?.approvedPackageSha256 === 'string'+ ? obj.approvedPackageSha256+ : undefined;+ if (+ approvedPackageSha256 !== undefined &&+ !/^[a-f0-9]{64}$/.test(approvedPackageSha256)+ ) {+ throwIpcError('INVALID_PARAMS', 'approvedPackageSha256 is invalid');+ }return invokePluginMarket(() =>service().install(requireString(pluginId, 'pluginId'), {expectedReleaseId,...(expectedManifest ? { expectedManifest: expectedManifest as unknown as GhostManifest } : {}),allowPermissionExpansion,...(reviewedBaseline !== undefined ? { reviewedBaseline } : {}),+ ...(approvedPackageSha256 !== undefined ? { approvedPackageSha256 } : {}),}),);},diff --git a/apps/desktop/src/main/plugin-market/service.ts b/apps/desktop/src/main/plugin-market/service.tsindex 56ec2d4f84..c0f0720709 100644--- a/apps/desktop/src/main/plugin-market/service.ts+++ b/apps/desktop/src/main/plugin-market/service.ts@@ -21,6 +21,8 @@ import type {MarketSourceConfig,MarketSourceSummary,PluginMarketDetail,+ PluginMarketInstallOptions,+ PluginMarketInstallResult,PluginMarketItem,PluginMarketSnapshot,} from '../../shared/pluginMarket.js';@@ -52,6 +54,7 @@ import {readBoundedFileNoFollowSync,} from '../utils/readBoundedFile.js';import { withGhostInstallLock } from '../cindy-brain/ghostInstallLock.js';+import { GhostPackagePermissionReviewRequiredError } from '../cindy-brain/packagePermissionReview.js';import { PluginMarketApi } from './api.js';import { downloadVerifiedPlugin } from './download.js';import { installCustomMarketPlugin } from './install.js';@@ -405,23 +408,8 @@ export class PluginMarketService {async install(pluginId: string,- options: {- /** Renderer 确认框实际展示过的 release。Main 重拉详情后必须仍一致,- * 否则用户审阅 A、实际安装/启用 B(review P1)。 */- expectedReleaseId: string;- /** 自定义市场插件:Renderer 确认框实际审阅过的完整 manifest。 */- expectedManifest?: GhostManifest;- allowPermissionExpansion?: boolean;- /**- * 扩权批准所依据的**已装 manifest 权限指纹**- * (`ghostPermissionBaselineKey`)。带 allowPermissionExpansion 时应一并- * 传入:Main 在安装锁内用当前已装 manifest 重算比对,不一致说明审阅与- * 现实已经脱节(典型是审阅期间「从文件更新」换了包),此时拒绝这次批准- * 而不是拿旧批准放行相对新 manifest 的全部新增权限。- */- reviewedBaseline?: string;- },- ): Promise<{ ghost: InstalledGhost }> {+ options: PluginMarketInstallOptions,+ ): Promise<PluginMarketInstallResult> {const customRef = parseCustomMarketPluginId(pluginId);if (customRef) {if (!options.expectedManifest) {@@ -484,6 +472,9 @@ export class PluginMarketService {...(options.reviewedBaseline !== undefined? { reviewedBaseline: options.reviewedBaseline }: {}),+ ...(options.approvedPackageSha256 !== undefined+ ? { approvedPackageSha256: options.approvedPackageSha256 }+ : {}),// 下载可能持续数分钟,提交副作用前按当前事实再算一次。recheckOwnership: assertOwnership,},@@ -491,6 +482,12 @@ export class PluginMarketService {ledger,),};+ }).catch((error: unknown) => {+ if (error instanceof GhostPackagePermissionReviewRequiredError) {+ requireSameMarketOwner(owner);+ return { reviewRequired: error.review };+ }+ throw error;});}@@ -1084,6 +1081,8 @@ export class PluginMarketService {allowPermissionExpansion?: boolean;/** 扩权批准所依据的已装权限指纹;安装锁内复核,详见 install() 的说明。 */reviewedBaseline?: string;+ /** 用户确认过的真实下载包 SHA。 */+ approvedPackageSha256?: string;/** 确认操作时的安装意图;下载窗口期目标被另一窗口卸载时拒绝滑入首装。 */expectedInstalled: boolean;/**@@ -1188,10 +1187,16 @@ export class PluginMarketService {const installed = await installOrUpdateMarketGhostPackage(tempPath, {ghostId: plugin.ghostId,version: plugin.currentRelease.version,- // 确认框渲染的就是这份服务端 manifest;包里若多出权限项,出口处拒装- // ——服务端投影层与客户端清单契约漂移时,用户会在没审过的情况下多拿- // 一个能力面(codex review P1)。+ // 确认框渲染的就是这份服务端 manifest;包里若多出权限项,出口处先+ // 暂停落位并返回真实包权限——服务端投影层与客户端清单契约漂移时,+ // 必须让用户按实际要安装的能力面重新确认。reviewedManifest: compatible.manifest,+ ...(options.approvedPackageSha256 !== undefined+ ? {+ approvedPackageSha256: options.approvedPackageSha256,+ reviewedBaseline: options.reviewedBaseline,+ }+ : {}),});// Once the package directory is committed, finish provenance against// the owner captured at operation start even if the active sessiondiff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex 095f8032f3..0463747eb8 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -1083,14 +1083,8 @@ contextBridge.exposeInMainWorld('electronAPI', {ipcRenderer.invoke('plugin-market:detail', pluginId),install: (pluginId: string,- options: {- expectedReleaseId: string;- expectedManifest?: import('../shared/ghost').GhostManifest;- allowPermissionExpansion?: boolean;- /** 扩权批准所依据的已装权限指纹;Main 在安装锁内复核后才放行扩权。 */- reviewedBaseline?: string;- },- ): Promise<{ ghost: import('../shared/ghost').InstalledGhost }> =>+ options: import('../shared/pluginMarket').PluginMarketInstallOptions,+ ): Promise<import('../shared/pluginMarket').PluginMarketInstallResult> =>ipcRenderer.invoke('plugin-market:install', pluginId, options),uninstall: (pluginId: string): Promise<{ ok: true }> =>ipcRenderer.invoke('plugin-market:uninstall', pluginId),diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsxindex 2624b49bf5..87ba7be792 100644--- a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx@@ -68,9 +68,11 @@ import {ghostPermissionItems,isOfficialGhostId,type GhostSetupStatus,+ type InstalledGhost,} from '../../../shared/ghost';import type {PluginMarketDetail,+ PluginMarketInstallOptions,PluginMarketItem,PluginMarketSnapshot,} from '../../../shared/pluginMarket';@@ -652,6 +654,57 @@ export function GhostPluginPage() {[t],);+ /**+ * 市场详情与真实下载包权限不一致时,展示 Main 验证后的真实权限并绑定重试。+ * Renderer 只负责确认;包 SHA 和已装权限基线均由 Main 重新核对。+ */+ const installReviewedMarketPackage = useCallback(+ async (input: {+ detail: PluginMarketDetail;+ lease: { pluginId: string };+ options: PluginMarketInstallOptions;+ }): Promise<InstalledGhost | null> => {+ const initial = await window.electronAPI.pluginMarket.install(+ input.detail.pluginId,+ input.options,+ );+ if (initial.ghost !== undefined) return initial.ghost;+ if (!isMarketBusyLeaseActive(input.lease)) return null;++ const review = initial.reviewRequired;+ if (!review) return null;+ const approved = await confirm({+ title: t('settings.ghosts.market.installConfirmTitle', {+ name: input.detail.name,+ }),+ description: t('settings.ghosts.market.installConfirmDescription'),+ content: <GhostPermissionList items={ghostPermissionItems(review.manifest)} />,+ maxWidth: 520,+ confirmText: t('settings.ghosts.market.install'),+ cancelText: t('settings.ghosts.installConfirm.cancel'),+ autoFocusConfirm: true,+ });+ if (!approved || !isMarketBusyLeaseActive(input.lease)) return null;++ const retried = await window.electronAPI.pluginMarket.install(+ input.detail.pluginId,+ {+ ...input.options,+ allowPermissionExpansion: review.installedBaseline !== null,+ reviewedBaseline: review.installedBaseline ?? undefined,+ approvedPackageSha256: review.packageSha256,+ },+ );+ if (retried.ghost !== undefined) return retried.ghost;++ // 同一 release 的真实包不应漂移;再次要求复核说明已装基线在往返窗口内变化。+ toast.error(t('settings.ghosts.market.errors.stateChanged'));+ await refreshMarket();+ return null;+ },+ [confirm, isMarketBusyLeaseActive, refreshMarket, t],+ );+// 市场更新流程由列表卡片和详情页共用:先取目标 release 的完整 manifest 做// 权限 diff,经用户确认后才安装,不做静默升级。const handleMarketUpdate = useCallback(@@ -681,21 +734,26 @@ export function GhostPluginPage() {cancelText: t('settings.ghosts.updateConfirm.cancel'),});if (!approved || !isMarketBusyLeaseActive(marketBusyLease)) return;- const result = await window.electronAPI.pluginMarket.install(marketItem.pluginId, {- expectedReleaseId: next.releaseId,- ...(next.sourceType !== 'server' ? { expectedManifest: next.manifest } : {}),- allowPermissionExpansion: diff.added.length > 0,- // 用户看确认框这段时间里已装 manifest 可能被换掉(如从文件更新);- // 把审阅基线交给 Main,在安装锁内复核后才放行扩权。- ...(installedGhost- ? { reviewedBaseline: ghostPermissionBaselineKey(installedGhost.manifest) }- : {}),+ const ghost = await installReviewedMarketPackage({+ detail: next,+ lease: marketBusyLease,+ options: {+ expectedReleaseId: next.releaseId,+ ...(next.sourceType !== 'server' ? { expectedManifest: next.manifest } : {}),+ allowPermissionExpansion: diff.added.length > 0,+ // 用户看确认框这段时间里已装 manifest 可能被换掉(如从文件更新);+ // 把审阅基线交给 Main,在安装锁内复核后才放行扩权。+ ...(installedGhost+ ? { reviewedBaseline: ghostPermissionBaselineKey(installedGhost.manifest) }+ : {}),+ },});+ if (!ghost) return;if (!isMarketBusyLeaseActive(marketBusyLease)) return;toast.success(t('settings.ghosts.toast.updated', {- name: result.ghost.manifest.name,- version: result.ghost.manifest.version,+ name: ghost.manifest.name,+ version: ghost.manifest.version,}),);await refreshMarket();@@ -712,6 +770,7 @@ export function GhostPluginPage() {confirm,ghosts,isMarketBusyLeaseActive,+ installReviewedMarketPackage,marketByGhostId,refreshMarket,releaseMarketBusy,@@ -1056,39 +1115,44 @@ export function GhostPluginPage() {autoFocusConfirm: true,});if (!confirmed || !isMarketBusyLeaseActive(marketBusyLease)) return;- const result = await window.electronAPI.pluginMarket.install(marketDetail.pluginId, {- expectedReleaseId: marketDetail.releaseId,- ...(marketDetail.sourceType !== 'server'- ? { expectedManifest: marketDetail.manifest }- : {}),- ...(isUpdate && diff!.added.length > 0- ? {- allowPermissionExpansion: true,- // 确认框展示期间已装 manifest 可能被换掉;基线交由 Main 在- // 安装锁内复核,不一致就拒绝这次批准而不是沿用旧同意。- ...(installedGhost- ? { reviewedBaseline: ghostPermissionBaselineKey(installedGhost.manifest) }- : {}),- }- : {}),+ const ghost = await installReviewedMarketPackage({+ detail: marketDetail,+ lease: marketBusyLease,+ options: {+ expectedReleaseId: marketDetail.releaseId,+ ...(marketDetail.sourceType !== 'server'+ ? { expectedManifest: marketDetail.manifest }+ : {}),+ ...(isUpdate && diff!.added.length > 0+ ? {+ allowPermissionExpansion: true,+ // 确认框展示期间已装 manifest 可能被换掉;基线交由 Main 在+ // 安装锁内复核,不一致就拒绝这次批准而不是沿用旧同意。+ ...(installedGhost+ ? { reviewedBaseline: ghostPermissionBaselineKey(installedGhost.manifest) }+ : {}),+ }+ : {}),+ },});+ if (!ghost) return;if (!isMarketBusyLeaseActive(marketBusyLease)) return;// 市场首装装完即开(2026-07-26 定案),toast 用"已安装";更新路径如实// 用"已更新"(生效状态未被改变)。toast.success(isUpdate? t('settings.ghosts.toast.updated', {- name: result.ghost.manifest.name,- version: result.ghost.manifest.version,+ name: ghost.manifest.name,+ version: ghost.manifest.version,}): t('settings.ghosts.toast.installed', {- name: result.ghost.manifest.name,+ name: ghost.manifest.name,}),);setMarketDetail((current) =>current?.pluginId === marketDetail.pluginId ? null : current,);- setSelectedId(result.ghost.manifest.id);+ setSelectedId(ghost.manifest.id);await refreshMarket();} catch (error) {if (isMarketBusyLeaseActive(marketBusyLease)) {@@ -1102,6 +1166,7 @@ export function GhostPluginPage() {confirm,ghosts,isMarketBusyLeaseActive,+ installReviewedMarketPackage,refreshMarket,releaseMarketBusy,t,diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/updateAllController.test.ts b/apps/desktop/src/renderer/features/plugin/__tests__/updateAllController.test.tsindex 8098208dd4..f3bf806e55 100644--- a/apps/desktop/src/renderer/features/plugin/__tests__/updateAllController.test.ts+++ b/apps/desktop/src/renderer/features/plugin/__tests__/updateAllController.test.ts@@ -1,7 +1,7 @@/*** Regression coverage for the module-level update-all batch controller:- * uninstall guards, reviewed-manifest passthrough on approval, and batch- * state surviving page unmount (review 定稿 2026-08-02).+ * uninstall guards, reviewed-manifest passthrough, package-review baseline+ * drift recovery, and batch state surviving page unmount (review 定稿 2026-08-04).* [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md* @vitest-environment jsdom*/@@ -21,7 +21,7 @@ import {setDataOwnerGeneration,} from '@/contexts/dataOwnerGeneration';import { toast } from '@/lib/toast';-import type { GhostManifest } from '../../../../shared/ghost';+import { ghostPermissionBaselineKey, type GhostManifest } from '../../../../shared/ghost';import type { PluginMarketDetail, PluginMarketItem } from '../../../../shared/pluginMarket';import {__resetUpdateAllBatchForTest,@@ -114,6 +114,62 @@ describe('updateAllController', () => {expect(installMock).not.toHaveBeenCalled();});+ it('holds actual package permissions for approval', async () => {+ stubDetail({ manifest: manifest({}), sourceType: 'server' });+ const review = {+ manifest: manifest({ network: { hosts: ['api.example.com'] } }),+ packageSha256: 'a'.repeat(64),+ installedBaseline: ghostPermissionBaselineKey(installedGhosts[0].manifest),+ };+ installMock.mockResolvedValueOnce({ reviewRequired: review } as never);++ startUpdateAllBatch([marketItem({})]);+ await waitForSettledBatch();+ expect(getUpdateAllBatchState().rows?.[0]).toMatchObject({+ status: 'needs-confirm',+ releaseId: 'release-2',+ packageReview: review,+ });++ await approveUpdateExpansion('plugin-a');+ expect(installMock).toHaveBeenLastCalledWith(+ 'plugin-a',+ expect.objectContaining({+ approvedPackageSha256: review.packageSha256,+ }),+ );+ });++ it('keeps package review recoverable when the installed baseline drifts in flight', async () => {+ stubDetail({ manifest: manifest({}), sourceType: 'server' });+ const review = {+ manifest: manifest({ network: { hosts: ['api.example.com'] } }),+ packageSha256: 'a'.repeat(64),+ installedBaseline: ghostPermissionBaselineKey(installedGhosts[0].manifest),+ };+ installMock.mockImplementationOnce(async () => {+ installedGhosts = [{ manifest: manifest({ version: '1.0.5', slots: ['fs'] }) }];+ return { reviewRequired: review } as never;+ });++ startUpdateAllBatch([marketItem({})]);+ await waitForSettledBatch();++ expect(getUpdateAllBatchState().rows?.[0]).toMatchObject({+ status: 'needs-confirm',+ staleReview: true,+ releaseId: 'release-2',+ fromVersion: '1.0.5',+ toVersion: '1.1.0',+ });++ await approveUpdateExpansion('plugin-a');+ expect(installMock).toHaveBeenLastCalledWith('plugin-a', {+ expectedReleaseId: 'release-2',+ });+ expect(getUpdateAllBatchState().rows?.[0]?.status).toBe('done');+ });+it('passes the reviewed manifest back when approving a non-server expansion', async () => {const nextManifest = manifest({ network: { hosts: ['api.example.com'] } });stubDetail({ manifest: nextManifest, sourceType: 'git-market' });diff --git a/apps/desktop/src/renderer/features/plugin/lib/updateAllController.ts b/apps/desktop/src/renderer/features/plugin/lib/updateAllController.tsindex c12e4e01f6..ca60567571 100644--- a/apps/desktop/src/renderer/features/plugin/lib/updateAllController.ts+++ b/apps/desktop/src/renderer/features/plugin/lib/updateAllController.ts@@ -8,7 +8,8 @@* 为什么在组件外:批次可以在用户关掉弹窗、离开 /plugins 后继续跑* (「后台继续」语义),待确认的扩权项也必须在回到插件页后仍然保留* 批准/跳过入口——状态生命周期必须长于页面组件,所以照- * useInstalledGhosts 的先例做成模块级单例 store。+ * useInstalledGhosts 的先例做成模块级单例 store。真实包复核返回期间若+ * 已装权限基线漂移,保留目标 release 并退回可恢复的重新审阅状态。* [PROTOCOL]: 变更时更新此头部,然后检查 CLAUDE.md*/@@ -26,7 +27,10 @@ import {ghostPermissionBaselineKey,type GhostManifest,} from '../../../../shared/ghost';-import type { PluginMarketItem } from '../../../../shared/pluginMarket';+import type {+ PluginMarketItem,+ PluginMarketPackageReview,+} from '../../../../shared/pluginMarket';import { pluginMarketErrorKey } from './pluginMarketErrorKey';import {batchSummary,@@ -152,6 +156,7 @@ function holdRowForReReview(status: 'needs-confirm',staleReview: true,permissionDiff: undefined,+ packageReview: undefined,...patch,releaseId,});@@ -190,6 +195,43 @@ function installedManifestOf(ghostId: string): GhostManifest | null {);}+function holdPackageReview(+ generation: number,+ row: Pick<UpdateAllRow, 'pluginId' | 'ghostId'> & {+ releaseId: string;+ toVersion: string;+ expectedManifest?: GhostManifest;+ },+ review: PluginMarketPackageReview,+): void {+ const installed = installedManifestOf(row.ghostId);+ if (!installed) {+ patchRow(generation, row.pluginId, { status: 'skipped' });+ return;+ }+ const reviewedBaseline = ghostPermissionBaselineKey(installed);+ if (reviewedBaseline !== review.installedBaseline) {+ holdRowForReReview(generation, row.pluginId, {+ releaseId: row.releaseId,+ fromVersion: installed.version,+ toVersion: row.toVersion,+ expectedManifest: undefined,+ });+ return;+ }+ patchRow(generation, row.pluginId, {+ status: 'needs-confirm',+ fromVersion: installed.version,+ toVersion: row.toVersion,+ releaseId: row.releaseId,+ permissionDiff: diffGhostPermissionItems(installed, review.manifest),+ staleReview: false,+ reviewedBaseline,+ packageReview: review,+ expectedManifest: row.expectedManifest,+ });+}+async function refreshMarketIfMounted(): Promise<void> {try {await hooks.refreshMarket?.();@@ -285,10 +327,24 @@ async function runQueue(generation: number): Promise<void> {});continue;}- await window.electronAPI.pluginMarket.install(next.pluginId, {+ const result = await window.electronAPI.pluginMarket.install(next.pluginId, {expectedReleaseId: detail.releaseId,...(detail.sourceType !== 'server' ? { expectedManifest: detail.manifest } : {}),});+ if (result.reviewRequired) {+ holdPackageReview(+ generation,+ {+ pluginId: next.pluginId,+ ghostId: next.ghostId,+ releaseId: detail.releaseId,+ toVersion: detail.version,+ ...(detail.sourceType !== 'server' ? { expectedManifest: detail.manifest } : {}),+ },+ result.reviewRequired,+ );+ continue;+ }patchRow(generation, next.pluginId, { status: 'done' });} catch (error) {if (batchGeneration !== generation) return;@@ -440,6 +496,7 @@ async function runApprovalBody(pluginId: string, generation: number): Promise<vopermissionDiff: diffGhostPermissionItems(installed, detail.manifest),staleReview: false,reviewedBaseline: ghostPermissionBaselineKey(installed),+ packageReview: undefined,expectedManifest: detail.sourceType !== 'server' ? detail.manifest : undefined,});};@@ -478,7 +535,21 @@ async function runApprovalBody(pluginId: string, generation: number): Promise<vooptions: Parameters<typeof window.electronAPI.pluginMarket.install>[1],): Promise<boolean> => {try {- await window.electronAPI.pluginMarket.install(pluginId, options);+ const result = await window.electronAPI.pluginMarket.install(pluginId, options);+ if (result.reviewRequired) {+ holdPackageReview(+ generation,+ {+ pluginId,+ ghostId: row.ghostId,+ releaseId: detail.releaseId,+ toVersion: detail.version,+ ...(detail.sourceType !== 'server' ? { expectedManifest: detail.manifest } : {}),+ },+ result.reviewRequired,+ );+ return false;+ }return true;} catch (error) {if (batchGeneration !== generation) return false;@@ -509,6 +580,9 @@ async function runApprovalBody(pluginId: string, generation: number): Promise<vo...(row.reviewedBaseline !== undefined? { reviewedBaseline: row.reviewedBaseline }: {}),+ ...(row.packageReview+ ? { approvedPackageSha256: row.packageReview.packageSha256 }+ : {}),});if (!didInstall) return;patchRow(generation, pluginId, { status: 'done' });@@ -586,6 +660,7 @@ export function reconcileUpdateAllBatch(marketItems: readonly PluginMarketItem[]fromVersion: installed.version,permissionDiff: undefined,staleReview: true,+ packageReview: undefined,});changed = true;} else if (installed.version !== row.fromVersion) {diff --git a/apps/desktop/src/renderer/features/plugin/lib/updateAllModel.ts b/apps/desktop/src/renderer/features/plugin/lib/updateAllModel.tsindex 8d3964abdf..02b137c640 100644--- a/apps/desktop/src/renderer/features/plugin/lib/updateAllModel.ts+++ b/apps/desktop/src/renderer/features/plugin/lib/updateAllModel.ts@@ -8,7 +8,10 @@*/import type { GhostManifest, GhostPermissionDiff } from '../../../../shared/ghost';-import type { PluginMarketItem } from '../../../../shared/pluginMarket';+import type {+ PluginMarketItem,+ PluginMarketPackageReview,+} from '../../../../shared/pluginMarket';/*** 批量更新策略(设计定稿):权限无变化的自动串行完成;权限有扩张的@@ -51,6 +54,8 @@ export interface UpdateAllRow {* 传回同一份 reviewed manifest,approve 必须原样带上,否则 INVALID_PARAMS。*/expectedManifest?: GhostManifest;+ /** 实际下载包等待用户确认的权限事实。 */+ packageReview?: PluginMarketPackageReview;/** status 为 failed 时的用户可读错误(已经过 i18n 映射)。 */errorText?: string;}diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 8ed949b0ea..df661fdfd1 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -1411,12 +1411,8 @@ interface ElectronAPI {) => Promise<import('../shared/pluginMarket').PluginMarketDetail>;install: (pluginId: string,- options: {- expectedReleaseId: string;- expectedManifest?: import('../shared/ghost').GhostManifest;- allowPermissionExpansion?: boolean;- },- ) => Promise<{ ghost: import('../shared/ghost').InstalledGhost }>;+ options: import('../shared/pluginMarket').PluginMarketInstallOptions,+ ) => Promise<import('../shared/pluginMarket').PluginMarketInstallResult>;uninstall: (pluginId: string) => Promise<{ ok: true }>;listSources: () => Promise<import('../shared/pluginMarket').MarketSourceSummary[]>;pickLocalSource: (diff --git a/apps/desktop/src/shared/pluginMarket.ts b/apps/desktop/src/shared/pluginMarket.tsindex bcbc5fca79..2b946bac98 100644--- a/apps/desktop/src/shared/pluginMarket.ts+++ b/apps/desktop/src/shared/pluginMarket.ts@@ -1,4 +1,4 @@-import type { GhostManifest } from './ghost';+import type { GhostManifest, InstalledGhost } from './ghost';import type { PluginIconMetadata } from '@cindy/plugin-protocol';export type PluginMarketScope = 'public' | 'organization' | 'personal';@@ -45,6 +45,32 @@ export interface PluginMarketDetail extends PluginMarketItem {manifest: GhostManifest;}+/** Main 验证真实下载包后,交给 Renderer 展示的权限复核事实。 */+export interface PluginMarketPackageReview {+ /** 已按当前界面语言本地化,仅用于展示;安全指纹由 Main 基于原始清单计算。 */+ manifest: GhostManifest;+ packageSha256: string;+ /** 产生复核结果时的已装权限基线;null 表示当时尚未安装。 */+ installedBaseline: string | null;+}++export interface PluginMarketInstallOptions {+ /** 用户审阅时看到的目标 release;Main 会在下载前重新核对。 */+ expectedReleaseId: string;+ /** 自定义市场审阅过的完整清单;服务端市场由 Main 读取 release 清单。 */+ expectedManifest?: GhostManifest;+ allowPermissionExpansion?: boolean;+ /** 用户审阅扩权时的已装权限基线。 */+ reviewedBaseline?: string;+ /** 用户确认过的真实下载包;Main 会重新下载并核对 SHA。 */+ approvedPackageSha256?: string;+}++/** 安装成功,或真实包权限与市场展示不一致而需要用户复核。 */+export type PluginMarketInstallResult =+ | { ghost: InstalledGhost; reviewRequired?: never }+ | { ghost?: never; reviewRequired: PluginMarketPackageReview };+/* ------------------------------------------------------------------------ *//* 自定义市场源(Git / 本地文件夹) *//* ------------------------------------------------------------------------ */