Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
fix(desktop): 批准技能快照在每次写入与对账时都逐字节核对 receipt
Yuewei-LL7545bc1e7c4e
diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.tsindex 55723f9e9c..5dc2d21512 100644--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts@@ -168,6 +168,38 @@ export class GhostManager {return this.receiptStore.read(id);}+ /**+ * 技能链接对账前重新核验批准快照。+ *+ * `list()` 是首帧同步 API,不能在里面流式重算目录摘要;因此由异步 reconciler+ * 对每个准备挂链的插件调用本入口。receipt revision 若已变化、快照缺失/不可读、+ * 含非普通条目或字节不符一律 false,让对账器撤掉已有链接并拒绝新建。+ */+ async verifyApprovedSkillSnapshot(ghost: InstalledGhost): Promise<boolean> {+ if (+ ghost.approval.state !== 'approved' ||+ !ghost.manifest.skill?.items.length ||+ !ghost.approvedSkillRoot+ ) {+ return false;+ }+ const current = this.readApproval(ghost.manifest.id);+ if (+ current.state !== 'approved' ||+ current.receipt.revision !== ghost.approval.revision+ ) {+ return false;+ }+ const expectedRoot = this.receiptStore.skillSnapshotRoot(+ current.receipt.id,+ current.receipt.revision,+ );+ if (path.resolve(ghost.approvedSkillRoot) !== path.resolve(expectedRoot)) {+ return false;+ }+ return this.receiptStore.skillSnapshotMatchesReceipt(current.receipt, expectedRoot);+ }+/** Serialize content-directory and approval-receipt mutations as one Host transaction lane. */async runExclusiveMutation<T>(operation: () => Promise<T>): Promise<T> {const previous = this.mutationTail;diff --git a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.tsindex 26de748b4a..326e69ab1f 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts@@ -912,6 +912,39 @@ describe('GhostManager · Host approval receipt', () => {await expectRejection(await manager.setEnabled('hello', true), 'approval-required');});+ it('does not trust an already-present snapshot whose bytes were rewritten in place', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ const snapshotSkillMd = path.join(snapshotRoot, 'skills', 'demo', 'SKILL.md');+ // 快照就位后被就地改写(状态根没有写保护)。主 Agent 是顺着共享链接持续读它的,+ // 所以"快照已存在"不能当成"仍是被批准的那份字节"直接早退信任。+ await fs.promises.writeFile(+ snapshotSkillMd,+ '---\nname: demo\ndescription: Demo skill\n---\n\nrm -rf everything\n',+ );++ // 安装目录里的字节没动过 → 删掉坏快照后能按批准字节重建,自愈。+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });+ expect(await manager.setEnabled('skilled', true)).toEqual({ ok: true });+ expect(await fs.promises.readFile(snapshotSkillMd, 'utf8')).toContain('Approved instructions');+ });++ it('refuses to keep a rewritten snapshot when the installed bytes drifted too', async () => {+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;+ const tampered = '---\nname: demo\ndescription: Demo skill\n---\n\nrm -rf everything\n';+ // 快照与安装目录都被改成同一份未批准内容:此时没有任何可信来源可重建,必须拒。+ await fs.promises.writeFile(path.join(snapshotRoot, 'skills', 'demo', 'SKILL.md'), tampered);+ await fs.promises.writeFile(+ path.join(rootDir, 'skilled', 'skills', 'demo', 'SKILL.md'),+ tampered,+ );++ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });+ await expectRejection(await manager.setEnabled('skilled', true), 'io');+ expect(manager.list()[0].enabled).toBe(false);+ });+it('still heals a deleted snapshot when the installed skill bytes are untouched', async () => {await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));const snapshotRoot = manager.list()[0].approvedSkillRoot!;diff --git a/apps/desktop/src/main/cindy-brain/__tests__/skillSlot.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/skillSlot.test.tsindex debbce0723..0fae16869b 100644--- a/apps/desktop/src/main/cindy-brain/__tests__/skillSlot.test.ts+++ b/apps/desktop/src/main/cindy-brain/__tests__/skillSlot.test.ts@@ -10,7 +10,7 @@ import { GhostManager } from '../GhostManager';import {checkSkillMdConsistency,ghostSkillLinkName,- reconcileGhostSkillLinks,+ reconcileGhostSkillLinks as reconcileGhostSkillLinksRaw,} from '../skillSlot';/** 规则 23:测试路径一律 os.tmpdir;伪 home + 伪 brainRoot,互不污染。 */@@ -36,6 +36,22 @@ afterEach(async () => {const sharedDir = () => path.join(homeDir, '.agents', 'skills');const claudeDir = () => path.join(homeDir, '.claude', 'skills');+/**+ * 结构对账用例默认把夹具视为已经过完整快照摘要校验;摘要失配的安全回归单独+ * 调 raw reconciler,避免每个链接行为用例重复搭 receipt。+ */+function reconcileGhostSkillLinks(+ options: Omit<+ Parameters<typeof reconcileGhostSkillLinksRaw>[0],+ 'validateApprovedSkillSnapshot'+ >,+) {+ return reconcileGhostSkillLinksRaw({+ ...options,+ validateApprovedSkillSnapshot: async () => true,+ });+}+/** reconciler 只消费 manifest 数据,不跑校验——手工拼最小清单即可。 */function ghost(id: string,@@ -203,11 +219,38 @@ describe('skillSlot · reconcileGhostSkillLinks', () => {});it('漏传批准状态根在类型层就被挡住(否则指向快照的活链接会被判成外来链接而永不撤链)', () => {- // @ts-expect-error approvalStateRoot 必填:这行编译不报错就说明保护没了。- const missingStateRoot = () => reconcileGhostSkillLinks({ ghosts: [], brainRoot, homeDir });+ const missingStateRoot = () =>+ // @ts-expect-error approvalStateRoot 必填:这行编译不报错就说明保护没了。+ reconcileGhostSkillLinksRaw({+ ghosts: [],+ brainRoot,+ homeDir,+ validateApprovedSkillSnapshot: async () => true,+ });expect(typeof missingStateRoot).toBe('function');});+ it('完整摘要校验不通过时撤掉已有托管链接,不因目标未变而 kept', async () => {+ await writeSkillDir('my-ghost', 'skills/foo', 'foo');+ const ghosts = [ghost('my-ghost', [{ dir: 'skills/foo', name: 'foo' }])];+ await reconcileGhostSkillLinks({ ghosts, brainRoot, approvalStateRoot, homeDir });+ const linkName = ghostSkillLinkName('my-ghost', 'foo');+ expect(fs.existsSync(path.join(sharedDir(), linkName))).toBe(true);++ const result = await reconcileGhostSkillLinksRaw({+ ghosts,+ brainRoot,+ approvalStateRoot,+ homeDir,+ validateApprovedSkillSnapshot: async () => false,+ });++ expect(result.changed).toBe(true);+ expect(result.warnings.some((warning) => warning.includes('字节不可信'))).toBe(true);+ expect(fs.existsSync(path.join(sharedDir(), linkName))).toBe(false);+ expect(fs.existsSync(path.join(claudeDir(), linkName))).toBe(false);+ });+it('外来链接(目标不在任何受管根内)→ 活链断链都不碰', async () => {const foreignTarget = path.join(workDir, 'foreign-skill');await fs.promises.mkdir(foreignTarget, { recursive: true });@@ -358,12 +401,14 @@ describe('skillSlot · 全链路(打包 → 装入 → 对账 → 双端可见)'const installed = await manager.install(packed.cindyPath);expect('ghost' in installed, JSON.stringify(installed)).toBe(true);- // 3) 对账:共享根与 .claude 双端可见,realpath 落在安装目录- await reconcileGhostSkillLinks({+ // 3) 对账:共享根与 .claude 双端可见,realpath 落在批准快照目录+ await reconcileGhostSkillLinksRaw({ghosts: manager.list(),brainRoot,approvalStateRoot: manager.approvalStateRoot(),homeDir,+ validateApprovedSkillSnapshot: (candidate) =>+ manager.verifyApprovedSkillSnapshot(candidate),});const linkName = ghostSkillLinkName('e2e-ghost', 'demo');const approvedSkillRoot = manager.list()[0].approvedSkillRoot;@@ -383,6 +428,24 @@ describe('skillSlot · 全链路(打包 → 装入 → 对账 → 双端可见)'await fs.promises.readFile(path.join(sharedDir(), linkName, 'SKILL.md'), 'utf8'),).not.toContain('篡改后的指令');+ // 改写批准状态根里的快照正文,保持 frontmatter 不变。下一轮正常对账必须重算+ // 整棵快照摘要并撤链,不能因链接目标没变而直接 kept。+ await fs.promises.writeFile(+ path.join(target, 'SKILL.md'),+ '---\nname: demo\ndescription: 演示技能\n---\n\n篡改批准快照\n',+ );+ const tampered = await reconcileGhostSkillLinksRaw({+ ghosts: manager.list(),+ brainRoot,+ approvalStateRoot: manager.approvalStateRoot(),+ homeDir,+ validateApprovedSkillSnapshot: (candidate) =>+ manager.verifyApprovedSkillSnapshot(candidate),+ });+ expect(tampered.warnings.some((warning) => warning.includes('字节不可信'))).toBe(true);+ expect(fs.existsSync(path.join(sharedDir(), linkName))).toBe(false);+ expect(fs.existsSync(path.join(claudeDir(), linkName))).toBe(false);+// 4) 卸载 → 对账 → 双端链接消失const removed = await manager.uninstall('e2e-ghost');expect(removed).toMatchObject({ ok: true });diff --git a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.tsindex ac5aa65bf0..606abf4779 100644--- a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts+++ b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts@@ -179,11 +179,24 @@ export class GhostInstallReceiptStore {const items = receipt.manifest.skill?.items ?? [];if (items.length === 0) return;const target = this.skillSnapshotRoot(receipt.id, receipt.revision);+ let existing: fs.Stats | null;try {- if ((await fs.promises.lstat(target)).isDirectory()) return;- throw new Error('approved skill snapshot target is not a directory');+ existing = await fs.promises.lstat(target);} catch (error) {if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;+ existing = null;+ }+ if (existing) {+ if (!existing.isDirectory()) {+ throw new Error('approved skill snapshot target is not a directory');+ }+ // 快照已存在**不等于**它还是被批准的那份字节:状态根里的目录同样可被同权限+ // 进程改写,而主 Agent 是顺着共享技能链接持续读它的。所以这里必须重算,+ // 不能像上一版那样直接早退信任它。+ if (await this.skillSnapshotMatchesReceipt(receipt, target)) return;+ // 对不上的快照一律不可信:删掉,退回下面的重建路径 —— 重建本身仍要过安装+ // 目录的字节校验,所以"损坏快照"能自愈,"安装字节已漂移"仍然拒。+ await fs.promises.rm(target, { recursive: true, force: true });}if (!skillSourceDir) {throw new Error('approved skill snapshot is missing');@@ -247,13 +260,14 @@ export class GhostInstallReceiptStore {);}}- const copiedSkillContent = await hashApprovedSkillContent(receipt.manifest, temp);+ // 指纹判定走与"接受既有快照""发布后复核"同一个 helper:同一判据只有一份实现,+ // 否则三处各写一遍、日后只改其中一处,就是这条链路前几轮反复出问题的形态。+ if (!(await this.skillSnapshotMatchesReceipt(receipt, temp))) {+ throw new Error(+ `approved skill content for ${receipt.id} no longer matches the bytes approved at install time`,+ );+ }for (const item of items) {- if (copiedSkillContent[item.dir] !== receipt.skillContentSha256[item.dir]) {- throw new Error(- `approved skill ${item.dir} no longer matches the bytes approved at install time`,- );- }// 指纹相符已经蕴含 frontmatter 一致(批准时点那份过过这道校验),这里重跑一遍// 是防止钉指纹那条路径本身有 bug,并给出更具体的错误。const consistencyError = checkSkillMdConsistency(@@ -265,17 +279,45 @@ export class GhostInstallReceiptStore {}}- // 残留窗口(已知、未关):rename 之前 temp 位于状态根内,同权限进程仍可改写它。- // 本地校验能保证"被校验的就是被复制的",保证不到"rename 的就是被校验的"。这属于- // 「批准状态根自身没有写保护」那一类,已正式登记在- // docs/dev-rules/plugin-security-and-authoring.md 第 6 节(与"内容根字节可变"- // 是两条并列的不同缺口),不在本函数能关掉的范围内。await fs.promises.rename(temp, target);++ // rename 之前 temp 位于状态根内、同权限进程仍可改写它,所以就位之后再核一遍:+ // 这一步把"校验通过 → rename"之间那段窗口收掉 —— 在那段里被换过的字节到这里+ // 会暴露,并且不会留在盘上。+ //+ // 残留窗口(已知、未关):这次核对之后、主 Agent 顺着共享技能链接读取之前,快照+ // 仍可被改写。要真正关掉需要给状态根写保护或在消费侧校验,都不在本函数范围内;+ // 该缺口已正式登记在 docs/dev-rules/plugin-security-and-authoring.md 第 6 节+ // (与"内容根字节可变"是两条并列的不同缺口)。+ if (!(await this.skillSnapshotMatchesReceipt(receipt, target))) {+ await fs.promises.rm(target, { recursive: true, force: true }).catch(() => undefined);+ throw new Error('approved skill snapshot changed while being published');+ }} finally {await fs.promises.rm(temp, { recursive: true, force: true }).catch(() => undefined);}}+ /**+ * 快照目录里的字节是否仍等于 receipt 钉住的批准指纹。+ *+ * 三处调用共用同一判据(接受既有快照 / 复制后发布前 / 发布后复核) —— 这类判定散落+ * 多处再各写一遍,就是本 PR 前几轮反复出问题的成因。读不动或含非普通条目一律按+ * 不匹配处理:调用方对"不匹配"的收敛动作都是删掉重建或拒绝,始终 fail closed。+ */+ async skillSnapshotMatchesReceipt(+ receipt: GhostInstallReceipt,+ snapshotDir: string,+ ): Promise<boolean> {+ const actual = await hashApprovedSkillContent(receipt.manifest, snapshotDir).catch(+ () => null,+ );+ if (!actual) return false;+ return (receipt.manifest.skill?.items ?? []).every(+ (item) => actual[item.dir] === receipt.skillContentSha256[item.dir],+ );+ }+/*** 回收同一插件下非当前 revision 的技能快照与崩溃残留的 `.tmp` 目录。*diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex 40b0e85aed..f99a4afc9c 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -4264,6 +4264,8 @@ function scheduleGhostSkillReconcile(): void {ghosts: getGhostManager().list(),brainRoot: brainRootDir(),approvalStateRoot: getGhostManager().approvalStateRoot(),+ validateApprovedSkillSnapshot: (ghost) =>+ getGhostManager().verifyApprovedSkillSnapshot(ghost),});if (result.warnings.length > 0) {log.warn('ghost skill reconcile warnings', { warnings: result.warnings });diff --git a/apps/desktop/src/main/cindy-brain/skillSlot.ts b/apps/desktop/src/main/cindy-brain/skillSlot.tsindex 80a71c8199..3703a02abf 100644--- a/apps/desktop/src/main/cindy-brain/skillSlot.ts+++ b/apps/desktop/src/main/cindy-brain/skillSlot.ts@@ -101,6 +101,11 @@ interface ReconcileOptions {* 必填:漏给会让指向快照的活链接被判成外来链接而永不撤链(见头注释)。*/approvalStateRoot: string;+ /**+ * 在把批准快照投影成共享链接前重算其完整内容摘要。必填:只检查 SKILL.md+ * frontmatter 拦不住正文/辅助文件被改写,而已有链接目标不变时也不能直接 kept。+ */+ validateApprovedSkillSnapshot: (ghost: InstalledGhost) => Promise<boolean>;/** 覆盖 home 目录(仅测试)。 */homeDir?: string;}@@ -189,6 +194,20 @@ export async function reconcileGhostSkillLinks().sort((a, b) => a.manifest.id.localeCompare(b.manifest.id));for (const ghost of eligible) {+ let snapshotValid = false;+ try {+ snapshotValid = await opts.validateApprovedSkillSnapshot(ghost);+ } catch (err) {+ warnings.push(+ `批准技能快照校验失败 ${ghost.manifest.id}:${+ err instanceof Error ? err.message : String(err)+ }`,+ );+ }+ if (!snapshotValid) {+ warnings.push(`批准技能快照字节不可信,撤链并等待修复:${ghost.manifest.id}`);+ continue;+ }const sortedItems = [...(ghost.manifest.skill?.items ?? [])].sort((a, b) =>a.name.localeCompare(b.name),);