Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 修复第 8 轮 review 批 A——快照父段遏制/停用两阶段/迁移瞬时错重试/市场投影全字段比对
Yuewei-LLca8b781f5bc6
diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.tsindex 4904e4bfea..3641f01aa6 100644Binary files a/apps/desktop/src/main/cindy-brain/GhostManager.ts and b/apps/desktop/src/main/cindy-brain/GhostManager.ts differdiff --git a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.tsindex 323c8d52a9..656b96fb7e 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts@@ -273,7 +273,7 @@ describe('GhostManager · 存量插件一次性迁移(§5 升级无感)', () =>// 安装目录重建授权"这条路被这道门堵死。await writeLegacyInstall('second', goodManifest('second'));const outcome = await manager.migrateLegacyApprovalsOnce();- expect(outcome).toEqual({ migrated: [], skipped: [], failed: [] });+ expect(outcome).toEqual({ migrated: [], skipped: [], failed: [], retryPending: [] });expect(manager.list().find((g) => g.manifest.id === 'second')?.approval.state).toBe('legacy-unapproved',);@@ -310,11 +310,46 @@ describe('GhostManager · 存量插件一次性迁移(§5 升级无感)', () =>});await writeLegacyInstall('hello', goodManifest());const outcome = await seededManager.migrateLegacyApprovalsOnce();- expect(outcome).toEqual({ migrated: [], skipped: ['hello'], failed: [] });+ expect(outcome).toEqual({ migrated: [], skipped: ['hello'], failed: [], retryPending: [] });// 没有替它写 receipt:provisioning 才是随包插件的批准入口。expect(fs.existsSync(path.join(workDir, 'ghosts-install-state', 'hello.json'))).toBe(false);});+ it('瞬时状态根 IO 不封门:台账停在 in-progress,下次启动自动续跑治愈', async () => {+ await writeLegacyInstall('hello', goodManifest());+ // 第一轮:receipt 落盘的 rename 吃一次 EACCES(模拟杀软/句柄占用的环境抖动)。+ const realRename = fs.promises.rename;+ const renameSpy = vi.spyOn(fs.promises, 'rename').mockImplementation(async (from, to) => {+ if (String(to).endsWith(`${path.sep}hello.json`)) {+ renameSpy.mockRestore();+ const err = new Error('EACCES: permission denied') as NodeJS.ErrnoException;+ err.code = 'EACCES';+ throw err;+ }+ return realRename(from, to);+ });+ const first = await manager.migrateLegacyApprovalsOnce();+ // 瞬时错不算"内容无效":不进 failed(那会写进 completed 台账永久封门),+ // 记 retryPending、台账停在 in-progress。+ expect(first.retryPending).toEqual(['hello']);+ expect(first.failed).toEqual([]);+ const ledger = JSON.parse(await fs.promises.readFile(migrationLedgerPath(), 'utf8')) as {+ state?: string;+ pendingIds?: string[];+ };+ expect(ledger.state).toBe('in-progress');+ expect(ledger.pendingIds).toEqual(['hello']);++ // 第二轮(下次启动):环境恢复,自动续跑治愈,不需要用户操作。+ const second = await manager.migrateLegacyApprovalsOnce();+ expect(second.migrated).toEqual(['hello']);+ expect(manager.list()[0]).toMatchObject({ enabled: true, approval: { state: 'approved' } });+ const finalLedger = JSON.parse(+ await fs.promises.readFile(migrationLedgerPath(), 'utf8'),+ ) as { state?: string };+ expect(finalLedger.state).toBe('completed');+ });+it('首轮迁移治愈损坏/旧 schema 的 receipt(格式升级不落到用户重新确认)', async () => {// issue #1243 验收第 4 条的实现形态:schema/编码 bump 后的旧 receipt 判 invalid,// 但**首轮迁移**会把它当"已判损坏"从安装目录 backfill 重建 —— 一次内部格式变更@@ -454,7 +489,7 @@ describe('GhostManager · 迁移崩溃安全(in-progress 状态机)与隔离命await fs.promises.writeFile(migrationLedgerPath(), '{ not valid json');const outcome = await manager.migrateLegacyApprovalsOnce();- expect(outcome).toEqual({ migrated: [], skipped: [], failed: [] });+ expect(outcome).toEqual({ migrated: [], skipped: [], failed: [], retryPending: [] });expect(manager.list()[0].approval.state).toBe('legacy-unapproved');expect(await fs.promises.readFile(migrationLedgerPath(), 'utf8')).toBe('{ not valid json');});@@ -693,6 +728,7 @@ describe('GhostManager · review 第 6 轮回归(P0/P1 修复钉住)', () => {migrated: [],skipped: [],failed: [],+ retryPending: [],});expect(fs.existsSync(migrationLedgerPath())).toBe(false);// 恢复流程把旧布局目录搬进来 → 门还开着,照常迁移。@@ -717,7 +753,7 @@ describe('GhostManager · review 第 6 轮回归(P0/P1 修复钉住)', () => {);await fs.promises.rm(path.join(workDir, 'ghosts-install-state', 'hello.json'));const outcome = await manager.migrateLegacyApprovalsOnce();- expect(outcome).toEqual({ migrated: [], skipped: [], failed: [] });+ expect(outcome).toEqual({ migrated: [], skipped: [], failed: [], retryPending: [] });expect(manager.list()[0].approval.state).toBe('legacy-unapproved');});@@ -1400,6 +1436,30 @@ describe('GhostManager · Host approval receipt', () => {]);});+ it('快照回收/重建绝不穿透被换成 junction 的父段删外部目录内容', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const idDir = path.join(workDir, 'ghosts-install-state', 'skill-snapshots', 'skilled');+ // 外部目录里放一个"看起来像旧 revision"的子目录 + 哨兵文件。+ const external = path.join(workDir, 'external-data');+ await fs.promises.mkdir(path.join(external, 'stale-revision'), { recursive: true });+ await fs.promises.writeFile(path.join(external, 'stale-revision', 'sentinel.txt'), 'keep');+ // 把 `<id>` 父段整个换成指向外部目录的 junction(同权限进程可做到)。+ await fs.promises.rm(idDir, { recursive: true, force: true });+ try {+ await fs.promises.symlink(external, idDir, process.platform === 'win32' ? 'junction' : 'dir');+ } catch {+ return; // 环境建不了链接则跳过;判定逻辑平台同源。+ }++ // 触发一次 receipt 写(启停翻转):修复前 ensureSkillSnapshot 会沿 junction 把+ // 快照发布到外部目录,prune 的 readdir + 逐项 recursive rm 更会把外部目录里的+ // "旧 revision"整个删掉(sentinel 消失)。修复后父段遏制先行:可疑父段整体跳过。+ await manager.setEnabled('skilled', false);+ expect(fs.existsSync(path.join(external, 'stale-revision', 'sentinel.txt'))).toBe(true);+ // 外部目录里也不应多出任何被"发布"进去的快照字节。+ expect(await fs.promises.readdir(external)).toEqual(['stale-revision']);+ });+it('holds the install-time SKILL.md size ceiling when rebuilding from mutable install bytes', async () => {await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));const snapshotRoot = manager.list()[0].approvedSkillRoot!;@@ -1781,6 +1841,33 @@ describe('GhostManager · Host approval receipt', () => {});describe('GhostManager · setEnabled(启用/停用)', () => {+ it('停用镜像本身写失败 → 如实报错,不谎报"已停用"(此刻什么都没落盘)', async () => {+ await manager.install(await makeCindy('a.cindy', goodManifest()));+ // 故障注入:.disabled 镜像写入抛 EACCES(receipt 还没轮到写)。+ const realWriteFile = fs.promises.writeFile;+ const spy = vi.spyOn(fs.promises, 'writeFile').mockImplementation(async (file, ...rest) => {+ if (String(file).endsWith('.disabled')) {+ const err = new Error('EACCES: permission denied') as NodeJS.ErrnoException;+ err.code = 'EACCES';+ throw err;+ }+ return realWriteFile(file, ...(rest as [Parameters<typeof realWriteFile>[1]]));+ });+ try {+ const result = await manager.setEnabled('hello', false);+ // 修复前这里返回 {ok:true}:catch 分不清失败的是镜像写还是 receipt 写,按+ // "镜像已就位"降级 —— 但镜像根本没写成,receipt.enabled 仍为 true,重启即复活。+ expect('rejection' in result && result.rejection.code).toBe('io');+ expect(manager.list()[0].enabled).toBe(true); // 如实:停用没有生效+ expect(fs.existsSync(path.join(rootDir, 'hello', '.disabled'))).toBe(false);+ } finally {+ spy.mockRestore();+ }+ // 环境恢复后停用照常成功。+ expect('ok' in (await manager.setEnabled('hello', false))).toBe(true);+ expect(manager.list()[0].enabled).toBe(false);+ });+it('停用:目录里出现 .disabled 标记、list 报 enabled=false、onChanged 广播;启用即恢复', async () => {await manager.install(await makeCindy('a.cindy', goodManifest()));onChanged.mockClear();diff --git a/apps/desktop/src/main/cindy-brain/__tests__/skillSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/skillSlot.test.tsindex 0fae16869b..3e6f904cf3 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/skillSlot.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/skillSlot.test.ts@@ -303,6 +303,32 @@ describe('skillSlot · reconcileGhostSkillLinks', () => {expect(fs.existsSync(managedLink)).toBe(false);});+ it('用户自建悬空链接不因目标路径里恰有 cindy-brain 段而被删(布局 id 必须对上链接名)', async () => {+ await fs.promises.mkdir(sharedDir(), { recursive: true });+ // 用户把自己项目目录(路径里恰好有一段叫 cindy-brain)链进技能根,随后目标没了。+ // 链接名 `foo--notes` 拆出的 id 是 `foo`,与目标里 cindy-brain 后面的段(`missing`)+ // 对不上 —— 不是我们铺的布局,绝不能删。+ const foreignLink = path.join(sharedDir(), 'foo--notes');+ await fs.promises.symlink(+ path.join(workDir, 'projects', 'cindy-brain', 'missing'),+ foreignLink,+ process.platform === 'win32' ? 'junction' : 'dir',+ );+ await reconcileGhostSkillLinks({ ghosts: [], brainRoot, approvalStateRoot, homeDir });+ expect(fs.lstatSync(foreignLink).isSymbolicLink()).toBe(true);++ // 对照:同样悬空、但布局 id 与链接名对得上的旧模型链接(cindy-brain/<id>/...)+ // 是我们自己的存量,要回收。+ const legacyLink = path.join(sharedDir(), 'my-ghost--foo');+ await fs.promises.symlink(+ path.join(workDir, 'anywhere', 'cindy-brain', 'my-ghost', 'skills', 'foo'),+ legacyLink,+ process.platform === 'win32' ? 'junction' : 'dir',+ );+ await reconcileGhostSkillLinks({ ghosts: [], brainRoot, approvalStateRoot, homeDir });+ expect(fs.existsSync(legacyLink)).toBe(false);+ });+it('他 owner 的活链接不碰(多账号隔离);他 owner 的断链回收(防积尘)', async () => {// 另一个 owner 的 brainRoot 与真实技能const otherBrainRoot = path.join(workDir, 'owners', 'bbb', 'cindy-brain');diff --git a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.tsindex 97fe4dc073..9f76ca4d18 100644--- a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts+++ b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts@@ -19,6 +19,7 @@ import {isRegularGhostDirEntry,resolveGhostContentPath,} from './ghostContentTree.js';+import { isPathInsideDir } from './dirDeposit.js';import { checkSkillMdConsistency } from './skillSlot.js';// v2 pairs receipts with the unambiguous ghostContentTree framing. Keeping v1@@ -110,6 +111,9 @@ export interface GhostLegacyMigrationLedger {/** Host-owned receipt store:严格读取、同目录临时文件 + rename 原子提交。 */export class GhostInstallReceiptStore {+ /** receipt 首写后的自动落账写失败(进程内关门标志,见 migrationDoorClosed)。 */+ private autoLedgerWriteFailed = false;+constructor(private readonly getRootDir: () => string) {}rootDir(): string {@@ -199,14 +203,31 @@ export class GhostInstallReceiptStore {migratedIds: [],state: 'completed',})- .catch(() => undefined);+ .catch(() => {+ // 不作 best-effort 吞掉:置进程内关门标志(migrationDoorClosed 优先读它),+ // 消除"落账失败 + 同会话删 receipt → 骗重铸"的窗口。批准本身不回滚 ——+ // receipt 刚写进同一目录,此处失败面极窄,且下次启动会经 hasAnyValidReceipt+ // 判据补写台账。+ this.autoLedgerWriteFailed = true;+ });}await this.pruneStaleSkillSnapshots(receipt);}async remove(id: string): Promise<void> {await fs.promises.rm(this.receiptPath(id), { force: true });- await fs.promises.rm(path.join(this.rootDir(), 'skill-snapshots', id), {+ // `skill-snapshots` 段必须是真目录才能递归删 `<id>`:该段被换成 junction 时,+ // recursive rm 会穿透删外部目录内容。`<id>` 自身是链接没关系 —— rm 按 lstat+ // 语义只摘链接本体,不进目标。段可疑/缺失就跳过(receipt 已删,批准已失效)。+ const snapshotsDir = path.join(this.rootDir(), 'skill-snapshots');+ let kind: string;+ try {+ kind = await classifyGhostDirEntry(snapshotsDir);+ } catch {+ return;+ }+ if (kind !== 'directory') return;+ await fs.promises.rm(path.join(snapshotsDir, id), {recursive: true,force: true,});@@ -219,6 +240,58 @@ export class GhostInstallReceiptStore {return path.join(this.rootDir(), 'skill-snapshots', id, revision);}+ /**+ * 快照父路径(`<状态根>/skill-snapshots/<id>`)的逐段遏制断言。+ *+ * 任何 readdir / mkdir / rename / rm 之前都必须过这道:父段被同权限进程换成+ * junction/链接时,这些操作会**穿透**到状态根之外 —— 把 §7 登记的「状态根可写→+ * 可伪造批准」升级成「任意外部目录删除/写入」,是一次真实的权限升级(已在+ * Windows 上实测复现)。判据与 ghostContentTree 同源:逐段 lstat、链接一律拒,+ * 最后再 realpath 对账"物理路径仍在状态根内"(状态根自身的祖先允许是链接 ——+ * relocated home 场景,所以以 realpath(root) 为基准而不是词法路径)。+ *+ * `createMissing`:装入/更新路径按需补建缺失段;prune/remove 等回收路径不建,+ * 段缺失(ENOENT)返回 null 表示"没有可回收对象"。段存在但不是真目录一律抛错,+ * 由调用方决定 fail closed 还是跳过 —— 绝不带着可疑父段继续动盘。+ */+ private async assertManagedSnapshotParent(+ id: string,+ opts: { createMissing: boolean },+ ): Promise<string | null> {+ if (!isValidGhostId(id)) throw new Error('invalid ghost id for snapshot path');+ const root = this.rootDir();+ let current = root;+ for (const segment of ['skill-snapshots', id]) {+ current = path.join(current, segment);+ let kind: Awaited<ReturnType<typeof classifyGhostDirEntry>> | null;+ try {+ kind = await classifyGhostDirEntry(current);+ } catch (error) {+ if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ kind = null;+ }+ if (kind === null) {+ if (!opts.createMissing) return null;+ // 非 recursive:上一段刚验证过是真目录,逐段建才不会静默沿着链接铺路。+ await fs.promises.mkdir(current);+ continue;+ }+ if (kind !== 'directory') {+ throw new Error(+ `skill snapshot path segment is not a real directory: ${segment} (${kind})`,+ );+ }+ }+ const [realRoot, realParent] = await Promise.all([+ fs.promises.realpath(root),+ fs.promises.realpath(current),+ ]);+ if (!isPathInsideDir(realRoot, realParent)) {+ throw new Error('skill snapshot parent escaped the approval state root');+ }+ return current;+ }+/** 迁移台账路径。点开头,不会与任何合法 ghost id 的 `<id>.json` receipt 撞名。 */private migrationLedgerPath(): string {return path.join(this.rootDir(), '.legacy-migration.json');@@ -277,6 +350,11 @@ export class GhostInstallReceiptStore {* 给这类进程送一条重铸授权的路。调用方发现"存在但读不出"应记 error 日志。*/migrationDoorClosed(): boolean {+ // 进程内保险门:receipt 首写后的自动落账写失败时置位(见 write())。没有它,+ // "落账失败 + 同会话内 receipt 又被删"的组合会让 hasAnyValidReceipt 判据也+ // 失效,可变 manifest 就能骗一次重铸 —— 状态根刚成功写过 receipt,门在本进程+ // 内必须视为已关;下次启动 hasAnyValidReceipt 或补写成功的台账接棒。+ if (this.autoLedgerWriteFailed) return true;if (!this.hasMigrationLedger()) return false;const ledger = this.readMigrationLedger();return ledger === null || ledger.state !== 'in-progress';@@ -325,6 +403,10 @@ export class GhostInstallReceiptStore {const items = receipt.manifest.skill?.items ?? [];if (items.length === 0) return;const target = this.skillSnapshotRoot(receipt.id, receipt.revision);+ // 父段遏制必须先于**任何**对 target 的操作:lstat/rm/rename 都会穿透被换成+ // junction 的父段,读写到状态根之外(见 assertManagedSnapshotParent 头注释)。+ const parent = await this.assertManagedSnapshotParent(receipt.id, { createMissing: true });+ if (!parent) throw new Error('skill snapshot parent unavailable');let existing: fs.Stats | null;try {existing = await fs.promises.lstat(target);@@ -347,12 +429,10 @@ export class GhostInstallReceiptStore {if (!skillSourceDir) {throw new Error('approved skill snapshot is missing');}- const parent = path.dirname(target);const temp = path.join(parent,`.${receipt.revision}-${process.pid}-${crypto.randomBytes(6).toString('hex')}.tmp`,);- await fs.promises.mkdir(parent, { recursive: true });try {await fs.promises.mkdir(temp, { recursive: false });@@ -490,7 +570,16 @@ export class GhostInstallReceiptStore {* best-effort:批准事实已经落盘,回收失败只记为待清理状态,不回滚安装。*/private async pruneStaleSkillSnapshots(receipt: GhostInstallReceipt): Promise<void> {- const parent = path.join(this.rootDir(), 'skill-snapshots', receipt.id);+ // 父段遏制先行:`<id>` 段被换成 junction 时,readdir 会列出外部目录的条目、+ // 随后的逐项 recursive rm 就会把**外部目录的内容**删掉(Windows 实测可复现)。+ // 回收是 best-effort:父段可疑就整体跳过,绝不带着可疑父段动盘。+ let parent: string | null;+ try {+ parent = await this.assertManagedSnapshotParent(receipt.id, { createMissing: false });+ } catch {+ return;+ }+ if (!parent) return;let entries: fs.Dirent[];try {entries = await fs.promises.readdir(parent, { withFileTypes: true });diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex cadf561024..94ea5483cc 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -18,6 +18,7 @@ import {isCindyAccountGhostId,isOfficialGhostId,ghostPermissionItems,+ ghostPermissionProjectionFingerprint,isValidGhostId,layoutWithGhostPanel,type GhostHostNoticeKey,@@ -2970,16 +2971,13 @@ export async function installOrUpdateMarketGhostPackage(rejectUnauthorizedTokenBroker(inspected.manifest);if (expected.expectedManifest) {// 权限投影 + 指令逐项比对,而不是整卡 deep-equal:服务端清单允许存在展示性- // 差异(字段顺序/补充元数据),但用户批准的权限集与指令名必须就是包里的那份。- const wanted = ghostPermissionItems(expected.expectedManifest)- .map((item) => item.key)- .sort();- const got = ghostPermissionItems(inspected.manifest)- .map((item) => item.key)- .sort();+ // 差异(字段顺序/补充元数据),但用户批准的权限内容必须就是包里的那份。+ // 指纹覆盖 key + kind + labelArgs + detail/detailKey/detailArgs —— 只比 key+ // 会漏掉同 key 下的安全语义字段(preview 的 hosts、OAuth scopes、node secret+ // 绑定方式、工具描述都在这些字段里),用户看 A、receipt 钉 B。const sameProjection =- wanted.length === got.length &&- wanted.every((key, index) => key === got[index]) &&+ ghostPermissionProjectionFingerprint(expected.expectedManifest) ===+ ghostPermissionProjectionFingerprint(inspected.manifest) &&(expected.expectedManifest.command ?? null) === (inspected.manifest.command ?? null);if (!sameProjection) {throwIpcError(diff --git a/apps/desktop/src/main/cindy-brain/skillSlot.ts b/apps/desktop/src/main/cindy-brain/skillSlot.tsindex 3703a02abf..99d692b758 100644--- a/apps/desktop/src/main/cindy-brain/skillSlot.ts+++ b/apps/desktop/src/main/cindy-brain/skillSlot.ts@@ -41,7 +41,12 @@ import path from 'node:path';import matter from 'gray-matter';-import type { GhostSkillItem, InstalledGhost } from '../../shared/ghost.js';+import {+ GHOST_SKILL_NAME_RE,+ isValidGhostId,+ type GhostSkillItem,+ type InstalledGhost,+} from '../../shared/ghost.js';import { parseAndValidateFrontmatter } from '../skillhub/frontmatterValidation.js';import {prepareSharedGlobalSkillLinks,@@ -142,13 +147,30 @@ function targetLooksGhostManaged(linkName: string,approvalStateDirName: string,): boolean {- if (!linkName.includes('--')) return false;+ // 链接名必须完整符合我们自己的命名契约:`<合法 ghostId>--<合法技能名>`+ // (按最后一个 `--` 拆分,与 ghostSkillLinkName 同规)。只看 includes('--')+ // 会把用户自建的 `foo--notes` 之类当成候选。+ const splitAt = linkName.lastIndexOf('--');+ if (splitAt <= 0) return false;+ const ghostId = linkName.slice(0, splitAt);+ const skillName = linkName.slice(splitAt + 2);+ if (!isValidGhostId(ghostId) || !GHOST_SKILL_NAME_RE.test(skillName)) return false;++ // 目标结构必须命中**我们铺过的两种布局之一**,且布局里的 id 段必须等于链接名里+ // 的 ghostId —— 单看"路径里有个段叫 cindy-brain"会把用户指向自己项目目录+ // (如 D:/projects/cindy-brain/...)的悬空链接误删,违背"外来链接绝不动"。+ // 两种布局(id 段可核对,这就是可验证的布局标识):+ // 旧模型(pre-receipt,线上存量): .../cindy-brain/<ghostId>/<skillDir...>+ // 新模型: .../<状态根名>/skill-snapshots/<ghostId>/<revision>/...const segments = target.split(/[\\/]/).map((segment) => segment.toLowerCase());const stateDirName = approvalStateDirName.toLowerCase();+ const idLower = ghostId.toLowerCase();return segments.some((segment, index) =>- segment === 'cindy-brain' ||- (segment === stateDirName && segments[index + 1] === 'skill-snapshots'),+ (segment === 'cindy-brain' && segments[index + 1] === idLower) ||+ (segment === stateDirName &&+ segments[index + 1] === 'skill-snapshots' &&+ segments[index + 2] === idLower),);}diff --git a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts b/apps/desktop/src/main/plugin-market/__tests__/service.test.tsindex 47359606e0..639c803614 100644--- a/apps/desktop/src/main/plugin-market/__tests__/service.test.ts+++ b/apps/desktop/src/main/plugin-market/__tests__/service.test.ts@@ -947,3 +947,25 @@ function recordForTest(item: VisiblePluginSummary) {updatedAt: '2026-07-23T00:00:00.000Z',};}++describe('market detail 响应身份绑定', () => {+ it('detail 自报的 id/ghostId 与请求不一致 → 拒,不把 A 的确认导向 B 的内容', async () => {+ const item = summary();+ const h = harness([item]);+ // 服务端异常/恶意响应:返回另一个插件的 detail(id 与 ghostId 都换了)。+ h.api.detail.mockImplementation(async () =>+ detail({ ...item, id: 'plg_other', ghostId: 'cindy-other' }),+ );+ await expect(+ h.service.install(item.id, { expectedReleaseId: item.currentRelease.id }),+ ).rejects.toThrow('[GHOST_FILE_INVALID]');+ // 只换 ghostId、id 相同也要拒:可见性与 ghostId 冲突判定都基于目录 summary。+ h.api.detail.mockImplementation(async () => detail({ ...item, ghostId: 'cindy-other' }));+ await expect(+ h.service.install(item.id, { expectedReleaseId: item.currentRelease.id }),+ ).rejects.toThrow('[GHOST_FILE_INVALID]');+ await expect(h.service.detail(item.id)).resolves.toBeTruthy(); // detail() 只绑 id+ h.api.detail.mockImplementation(async () => detail({ ...item, id: 'plg_other' }));+ await expect(h.service.detail(item.id)).rejects.toThrow('[GHOST_FILE_INVALID]');+ });+});diff --git a/apps/desktop/src/main/plugin-market/service.ts b/apps/desktop/src/main/plugin-market/service.tsindex db99e458c3..3218d1812b 100644--- a/apps/desktop/src/main/plugin-market/service.ts+++ b/apps/desktop/src/main/plugin-market/service.ts@@ -204,6 +204,23 @@ export class PluginMarketService {return { items: this.toItems(plugins, ledger), unavailableReason: null };}+ /**+ * detail 响应必须与请求身份一致:后续下载、安装、ledger 全都信 detail 的自报+ * 字段,不绑定的话异常/恶意服务端响应可以把 A 的确认导向 B 的内容,并绕过+ * 调用方基于目录 summary 做过的可见性与 ghostId 冲突判断。+ */+ private requireDetailIdentity(+ detail: { id: string; ghostId: string },+ expected: { pluginId: string; ghostId?: string },+ ): void {+ if (+ detail.id !== expected.pluginId ||+ (expected.ghostId !== undefined && detail.ghostId !== expected.ghostId)+ ) {+ throwIpcError('GHOST_FILE_INVALID', 'Market detail response does not match the requested Plugin');+ }+ }+async detail(pluginId: string): Promise<PluginMarketDetail> {if (!isValidPluginResourceId(pluginId)) {throwIpcError('INVALID_PARAMS', 'Invalid Plugin ID');@@ -212,6 +229,7 @@ export class PluginMarketService {const owner = captureMarketOwner();const plugin = await this.api.detail(pluginId);requireSameMarketOwner(owner);+ this.requireDetailIdentity(plugin, { pluginId });if (owner.mode === 'local' && plugin.scope !== 'public') {throwIpcError('PERMISSION_DENIED', 'Local mode can only access public Plugins');}@@ -260,6 +278,9 @@ export class PluginMarketService {}const plugin = await this.api.detail(pluginId);requireSameMarketOwner(owner);+ // 绑定到用户确认时看的那份目录 summary:id 与 ghostId 都必须一致 —— 可见性+ // 判定与 ghostId 唯一性判定都是基于 selected 做的,detail 换身份就全绕过了。+ this.requireDetailIdentity(plugin, { pluginId, ghostId: selected.ghostId });if (plugin.currentRelease.id !== options.expectedReleaseId) {throwIpcError('PRECONDITION_FAILED',@@ -596,6 +617,7 @@ export class PluginMarketService {await this.withMutation(summary.id, async () => {requireSameMarketOwner(owner);const detail = await this.api.detail(summary.id);+ this.requireDetailIdentity(detail, { pluginId: summary.id, ghostId: summary.ghostId });// 装完即开语义已收敛进市场安装入口本身,这里无需再显式声明。await this.installDetail(detail,diff --git a/apps/desktop/src/shared/__tests__/ghost.test.ts b/apps/desktop/src/shared/__tests__/ghost.test.tsindex 9a88fe5390..bd701177a2 100644--- a/apps/desktop/src/shared/__tests__/ghost.test.ts+++ b/apps/desktop/src/shared/__tests__/ghost.test.ts@@ -14,6 +14,7 @@ import {parseGhostNodeChildToHostMessage,ghostPartition,ghostPermissionItems,+ ghostPermissionProjectionFingerprint,ghostWebviewEntryPaths,isGhostCallToolName,isValidGhostId,@@ -2914,3 +2915,55 @@ describe('ghost · skill 槽(捆绑 Agent Skills,2026-07-25)', () => {expect(diff.unchanged.map((i) => i.key)).not.toContain('skill:alpha');});});++describe('ghostPermissionProjectionFingerprint', () => {+ it('same-key/different-detail 必须判不同(preview hosts / 工具描述都在 detail 侧)', () => {+ const base = {+ ...goodChipManifest(),+ slots: ['panel', 'preview'],+ preview: { hosts: ['*.example.dev', 'localhost'] },+ };+ const a = validateGhostManifest(base);+ // 同一个 key(preview 的 key 不随 hosts 变),hosts 换成别的域 —— 用户在确认卡+ // 看到的授权范围完全不同,只比 key 的旧判据放行,指纹必须拒。+ const b = validateGhostManifest({+ ...base,+ preview: { hosts: ['evil.example.com'] },+ });+ expect(a.ok && b.ok).toBe(true);+ if (!a.ok || !b.ok) return;+ const keysA = ghostPermissionItems(a.manifest).map((i) => i.key).sort();+ const keysB = ghostPermissionItems(b.manifest).map((i) => i.key).sort();+ expect(keysA).toEqual(keysB); // 前提成立:key 集相同+ expect(ghostPermissionProjectionFingerprint(a.manifest)).not.toBe(+ ghostPermissionProjectionFingerprint(b.manifest),+ );++ // 工具描述(作者自由文本,经 detail 展示)漂移同样必须判不同。+ const toolBase = {+ ...goodChipManifest(),+ slots: ['panel', 'model', 'tool'],+ tools: [{ name: 'do_thing', description: '做点事' }],+ };+ const toolA = validateGhostManifest(toolBase);+ const toolB = validateGhostManifest({+ ...toolBase,+ tools: [{ name: 'do_thing', description: '现在顺便读取你的邮箱' }],+ });+ expect(toolA.ok && toolB.ok).toBe(true);+ if (!toolA.ok || !toolB.ok) return;+ expect(ghostPermissionProjectionFingerprint(toolA.manifest)).not.toBe(+ ghostPermissionProjectionFingerprint(toolB.manifest),+ );+ });++ it('语义相同时指纹稳定(与字段/条目顺序无关)', () => {+ const a = validateGhostManifest(goodChipManifest());+ const b = validateGhostManifest(JSON.parse(JSON.stringify(goodChipManifest())));+ expect(a.ok && b.ok).toBe(true);+ if (!a.ok || !b.ok) return;+ expect(ghostPermissionProjectionFingerprint(a.manifest)).toBe(+ ghostPermissionProjectionFingerprint(b.manifest),+ );+ });+});diff --git a/apps/desktop/src/shared/ghost.ts b/apps/desktop/src/shared/ghost.tsindex 887f4d7a75..66adbdacc5 100644--- a/apps/desktop/src/shared/ghost.ts+++ b/apps/desktop/src/shared/ghost.ts@@ -1507,6 +1507,39 @@ function formatGhostQuotaSize(bytes: number): string {* 顺序即展示顺序:Cindy 代办 → 注册工具 → 聊天指令 → 面板 → 订阅/卡片 →* 可执行代码(先能力后载体,与权限展示契约一致)。*/+/**+ * 权限投影的规范化指纹:两份 manifest「用户在确认卡上看到的权限内容」是否逐字+ * 相同的唯一判据。+ *+ * **只比 `key` 是不够的**:同一个 key 下还有会呈现给用户、并构成授权语义的字段 ——+ * `labelArgs`(preview 的 hosts、工具名等)、`detail`(作者自由文本,OAuth scopes /+ * node secret 绑定方式等都经它展示)、`detailKey`/`detailArgs`。市场确认拿服务端+ * 清单给用户看、拿下载包装入,两份清单在这些字段上不同而 key 相同时,用户看的是 A、+ * receipt 钉的是 B。字段序列化按固定字段序 + labelArgs/detailArgs 键排序,与对象+ * 构造顺序无关。+ */+export function ghostPermissionProjectionFingerprint(manifest: GhostManifest): string {+ const sortRecord = (record: Record<string, string> | undefined): [string, string][] =>+ Object.entries(record ?? {}).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0));+ return JSON.stringify(+ ghostPermissionItems(manifest)+ .map((item) => [+ item.key,+ item.kind,+ item.labelKey,+ sortRecord(item.labelArgs),+ item.detail ?? null,+ item.detailKey ?? null,+ sortRecord(item.detailArgs),+ ])+ .sort((a, b) => {+ const ka = JSON.stringify(a);+ const kb = JSON.stringify(b);+ return ka < kb ? -1 : ka > kb ? 1 : 0;+ }),+ );+}+export function ghostPermissionItems(manifest: GhostManifest): GhostPermissionItem[] {const items: GhostPermissionItem[] = [];for (const [category, actions] of Object.entries(manifest.cindy ?? {})) {