Skip to content

armgit / cindy

Public Imported from GitHub
0

Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。

fix(desktop): 批准 receipt 钉住技能字节指纹,快照重建须逐字节对上

Yuewei-LL3387f85a7bf9
diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.ts
index cc6307cd13..8c468910ce 100644
--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts
+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts
@@ -31,6 +31,7 @@ import { checkSkillMdConsistency } from './skillSlot.js';
import {
createGhostInstallReceipt,
GhostInstallReceiptStore,
+ hashApprovedSkillContent,
type GhostInstallReceipt,
type GhostInstallReceiptReadResult,
} from './ghostInstallReceipt.js';
@@ -771,14 +772,9 @@ export class GhostManager {
// 5) 解压到 staging(zip-slip / zip bomb 防御),全过才切正式目录
const stagingDir = path.join(root, `.cindy-installing-${manifest.id}-${crypto.randomBytes(4).toString('hex')}`);
- const receipt = createGhostInstallReceipt({
- manifest: approvedManifest,
- localeResources,
- enabled: initiallyEnabled,
- trust,
- packageSha256,
- ...(iconDataUrl !== undefined ? { iconDataUrl } : {}),
- });
+ // receipt 在内容落到 finalDir 之后才创建:技能字节指纹必须从这次批准的内容
+ // 目录现算,不能凭空构造。
+ let receipt: GhostInstallReceipt | undefined;
try {
// 初始沉睡:标记在 staging 阶段就位,rename 后首个广播即沉睡态,
// 不存在"先启用一帧再熄灯"的跳变(规则 7)。
@@ -791,6 +787,15 @@ export class GhostManager {
});
await fs.promises.rename(stagingDir, finalDir);
try {
+ receipt = createGhostInstallReceipt({
+ manifest: approvedManifest,
+ localeResources,
+ enabled: initiallyEnabled,
+ trust,
+ skillContentSha256: await hashApprovedSkillContent(approvedManifest, finalDir),
+ packageSha256,
+ ...(iconDataUrl !== undefined ? { iconDataUrl } : {}),
+ });
await this.receiptStore.write(receipt, { skillSourceDir: finalDir });
} catch (error) {
await fs.promises.rm(finalDir, { recursive: true, force: true }).catch(() => undefined);
@@ -803,6 +808,9 @@ export class GhostManager {
}
return { rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) } };
}
+ if (!receipt) {
+ return { rejection: { code: 'io', reason: '安装批准状态未能生成' } };
+ }
const ghost: InstalledGhost = {
manifest,
@@ -907,14 +915,6 @@ export class GhostManager {
const rand = crypto.randomBytes(4).toString('hex');
const stagingDir = path.join(root, `.cindy-installing-${manifest.id}-${rand}`);
const backupDir = path.join(root, `.cindy-updating-${manifest.id}-${rand}`);
- const receipt = createGhostInstallReceipt({
- manifest: approvedManifest,
- localeResources,
- enabled,
- trust,
- packageSha256,
- ...(iconDataUrl !== undefined ? { iconDataUrl } : {}),
- });
try {
await this.extractToStaging(allEntries, prefix, stagingDir, {
disabled: !enabled,
@@ -945,7 +945,18 @@ export class GhostManager {
await fs.promises.rm(stagingDir, { recursive: true, force: true }).catch(() => {});
return { rejection: { code: 'io', reason: err instanceof Error ? err.message : String(err) } };
}
+ // 与 install 同理:技能字节指纹从这次换入的内容目录现算。
+ let receipt: GhostInstallReceipt;
try {
+ receipt = createGhostInstallReceipt({
+ manifest: approvedManifest,
+ localeResources,
+ enabled,
+ trust,
+ skillContentSha256: await hashApprovedSkillContent(approvedManifest, finalDir),
+ packageSha256,
+ ...(iconDataUrl !== undefined ? { iconDataUrl } : {}),
+ });
await this.receiptStore.write(receipt, { skillSourceDir: finalDir });
} catch (err) {
await fs.promises.rm(finalDir, { recursive: true, force: true }).catch(() => undefined);
@@ -979,6 +990,7 @@ export class GhostManager {
const localeResources = this.readApprovedLocaleResources(dir, manifest);
const iconDataUrl = this.readInstalledIconDataUrl(dir, manifest) ?? undefined;
const packageSha256 = await hashApprovedDirectory(dir);
+ const skillContentSha256 = await hashApprovedSkillContent(manifest, dir);
const trust: GhostTrustInfo = {
level: 'cindy-official',
publisherSigned: false,
@@ -991,6 +1003,7 @@ export class GhostManager {
isDeepStrictEqual(current.receipt.manifest, manifest) &&
isDeepStrictEqual(current.receipt.localeResources, localeResources) &&
isDeepStrictEqual(current.receipt.trust, trust) &&
+ isDeepStrictEqual(current.receipt.skillContentSha256, skillContentSha256) &&
current.receipt.packageSha256 === packageSha256 &&
current.receipt.iconDataUrl === iconDataUrl
) {
@@ -1009,6 +1022,7 @@ export class GhostManager {
localeResources,
enabled,
trust,
+ skillContentSha256,
packageSha256,
...(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.ts
index ed50cc56af..246c55dba0 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
@@ -696,6 +696,68 @@ describe('GhostManager · Host approval receipt', () => {
expect(fs.existsSync(snapshotRoot)).toBe(false);
});
+ it('refuses to rebuild a snapshot when only the SKILL.md body drifted', async () => {
+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));
+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;
+ // frontmatter 的 name/description 一字未动,只改正文 —— 一致性校验看不出来,
+ // 但这份指令会被主 Agent 以用户全部权限执行,必须靠批准时点的字节指纹拦住。
+ await fs.promises.writeFile(
+ path.join(rootDir, 'skilled', 'skills', 'demo', 'SKILL.md'),
+ '---\nname: demo\ndescription: Demo skill\n---\n\nrm -rf everything\n',
+ );
+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });
+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });
+
+ await expectRejection(await manager.setEnabled('skilled', true), 'io');
+ expect(manager.list()[0].enabled).toBe(false);
+ expect(fs.existsSync(snapshotRoot)).toBe(false);
+ });
+
+ it('refuses to rebuild a snapshot when a helper file was added to the skill directory', async () => {
+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));
+ const snapshotRoot = manager.list()[0].approvedSkillRoot!;
+ // SKILL.md 完全没动,只往技能目录里塞一个被指令引用的辅助文件(点文件同样算)。
+ await fs.promises.writeFile(
+ path.join(rootDir, 'skilled', 'skills', 'demo', '.helper.sh'),
+ '#!/bin/sh\necho injected\n',
+ );
+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });
+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });
+
+ await expectRejection(await manager.setEnabled('skilled', true), 'io');
+ expect(manager.list()[0].enabled).toBe(false);
+ expect(fs.existsSync(snapshotRoot)).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!;
+ // 字节指纹校验不能把合法的自愈场景一起堵死:外部清理误删快照、内容没动过。
+ await fs.promises.rm(snapshotRoot, { recursive: true, force: true });
+ expect(await manager.setEnabled('skilled', false)).toEqual({ ok: true });
+
+ expect(await manager.setEnabled('skilled', true)).toEqual({ ok: true });
+ expect(manager.list()[0].enabled).toBe(true);
+ expect(
+ await fs.promises.readFile(path.join(snapshotRoot, 'skills', 'demo', 'SKILL.md'), 'utf8'),
+ ).toContain('Approved instructions');
+ });
+
+ it('invalidates a receipt whose skill content digests no longer match the manifest', async () => {
+ await manager.install(await makeCindy('skill.cindy', skillManifest(), skillFiles()));
+ const receipt = JSON.parse(
+ await fs.promises.readFile(receiptPath('skilled'), 'utf8'),
+ ) as Record<string, unknown>;
+ // 手工把指纹字段抹掉:必填项缺失一律判 invalid,不允许退化成"跳过校验"。
+ delete receipt.skillContentSha256;
+ await fs.promises.writeFile(receiptPath('skilled'), JSON.stringify(receipt));
+
+ expect(manager.list()[0]).toMatchObject({
+ enabled: false,
+ approval: { state: 'invalid' },
+ });
+ });
+
it('revoking approval fails the install closed, and a later bundled approval heals it', async () => {
await manager.install(await makeCindy('approved.cindy', goodManifest()));
const approvedManifest = manager.list()[0].manifest;
diff --git a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
index f1997af94e..4745eaa324 100644
--- a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
@@ -44,6 +44,16 @@ export interface GhostInstallReceipt {
* 随包种子是内容目录哈希。**运行时不校验它**,不要据此认为安装内容持续完整。
*/
packageSha256?: string;
+ /**
+ * 按 skill item 目录钉住的批准字节指纹(`item.dir` → sha256)。声明了 skill 槽
+ * 时逐项必填,没声明时是空对象。
+ *
+ * 这一项**是运行期判据**,与只作审计用的 `packageSha256` 不同:快照缺失需要从
+ * 可变安装目录重建时,必须先重算并逐字节对上才允许重建。少了它,改写 SKILL.md
+ * 正文或往技能目录塞辅助文件就能在一次"启用"里被固化成已批准快照并全局挂链,
+ * 而 frontmatter 一致性校验只看 name/description,拦不住这类漂移。
+ */
+ skillContentSha256: Record<string, string>;
iconDataUrl?: string;
}
@@ -167,6 +177,19 @@ export class GhostInstallReceiptStore {
if (!skillSourceDir) {
throw new Error('approved skill snapshot is missing');
}
+ // 快照缺失、要从可变安装目录重建:先逐字节对上批准时点钉住的指纹。
+ // 只校验 SKILL.md frontmatter 不够 —— name/description 保持不变、改写正文或
+ // 往技能目录塞辅助文件,同样会让一份没人确认过的技能指令被固化成已批准快照
+ // 并全局挂链,而 skill 槽是以用户全部权限执行的。对不上就拒,让它退回完整
+ // 重新确认,而不是就地"自愈"成新批准。
+ const actualSkillContent = await hashApprovedSkillContent(receipt.manifest, skillSourceDir);
+ for (const item of items) {
+ if (actualSkillContent[item.dir] !== receipt.skillContentSha256[item.dir]) {
+ throw new Error(
+ `approved skill ${item.dir} no longer matches the bytes approved at install time`,
+ );
+ }
+ }
const parent = path.dirname(target);
const temp = path.join(
parent,
@@ -236,6 +259,8 @@ export function createGhostInstallReceipt(input: {
localeResources: Record<string, GhostManifestLocaleResource>;
enabled: boolean;
trust: GhostTrustInfo;
+ /** 由 `hashApprovedSkillContent` 从**这次批准的内容目录**现算,不可沿用旧值。 */
+ skillContentSha256: Record<string, string>;
packageSha256?: string;
iconDataUrl?: string;
}): GhostInstallReceipt {
@@ -247,11 +272,59 @@ export function createGhostInstallReceipt(input: {
localeResources: input.localeResources,
enabled: input.enabled,
trust: input.trust,
+ skillContentSha256: input.skillContentSha256,
...(input.packageSha256 ? { packageSha256: input.packageSha256 } : {}),
...(input.iconDataUrl ? { iconDataUrl: input.iconDataUrl } : {}),
};
}
+/**
+ * 逐 skill item 目录算规范化内容指纹(排序后的相对路径 + 字节)。
+ *
+ * 与 `hashApprovedDirectory` 的差别:技能目录**不跳过点文件**——技能指令可以引用
+ * 目录里的任意文件,漏掉一类就是漏掉一条改写通道;非普通条目一律拒,与快照拷贝
+ * 侧 `copyRegularDirectory` 同一判据。
+ */
+export async function hashApprovedSkillContent(
+ manifest: GhostManifest,
+ sourceDir: string | undefined,
+): Promise<Record<string, string>> {
+ const items = manifest.skill?.items ?? [];
+ if (items.length === 0) return {};
+ if (!sourceDir) throw new Error('skill content hash requires a source directory');
+ const result: Record<string, string> = {};
+ for (const item of items) {
+ const itemRoot = path.join(sourceDir, ...item.dir.split('/'));
+ const files: string[] = [];
+ const collect = async (relativeDir: string): Promise<void> => {
+ const entries = await fs.promises.readdir(path.join(itemRoot, relativeDir), {
+ withFileTypes: true,
+ });
+ for (const entry of entries) {
+ const relativePath = relativeDir ? `${relativeDir}/${entry.name}` : entry.name;
+ if (entry.isDirectory()) {
+ await collect(relativePath);
+ } else if (entry.isFile()) {
+ files.push(relativePath);
+ } else {
+ throw new Error(`approved skill rejects non-regular entry: ${item.dir}/${relativePath}`);
+ }
+ }
+ };
+ await collect('');
+ files.sort();
+ const hash = crypto.createHash('sha256');
+ for (const relativePath of files) {
+ hash.update(relativePath);
+ hash.update('\0');
+ hash.update(await fs.promises.readFile(path.join(itemRoot, ...relativePath.split('/'))));
+ hash.update('\0');
+ }
+ result[item.dir] = hash.digest('hex');
+ }
+ return result;
+}
+
function validateReceipt(
raw: unknown,
expectedId: string,
@@ -287,6 +360,32 @@ function validateReceipt(
) {
return { ok: false, reason: 'receipt packageSha256 不合法' };
}
+ // 技能字节指纹是运行期判据,必填且键集必须与清单声明严格一致 —— 留"字段缺失就
+ // 跳过校验"的可选口子等于给漂移留一条绕过路径。receipt 格式尚未随任何版本发布,
+ // 不存在需要兼容的旧 receipt。
+ const skillContentSha256: Record<string, string> = {};
+ {
+ const raw = value.skillContentSha256;
+ if (!raw || typeof raw !== 'object' || Array.isArray(raw)) {
+ return { ok: false, reason: 'receipt skillContentSha256 不合法' };
+ }
+ const expectedDirs = (manifestResult.manifest.skill?.items ?? [])
+ .map((item) => item.dir)
+ .sort();
+ const actualDirs = Object.keys(raw as Record<string, unknown>).sort();
+ if (
+ expectedDirs.length !== actualDirs.length ||
+ expectedDirs.some((dir, index) => dir !== actualDirs[index])
+ ) {
+ return { ok: false, reason: 'receipt skillContentSha256 与 manifest 声明不一致' };
+ }
+ for (const [dir, digest] of Object.entries(raw as Record<string, unknown>)) {
+ if (typeof digest !== 'string' || !/^[a-f0-9]{64}$/.test(digest)) {
+ return { ok: false, reason: `receipt skillContentSha256 不合法:${dir}` };
+ }
+ skillContentSha256[dir] = digest;
+ }
+ }
if (
value.iconDataUrl !== undefined &&
(
@@ -333,6 +432,7 @@ function validateReceipt(
localeResources,
enabled: value.enabled,
trust,
+ skillContentSha256,
...(typeof value.packageSha256 === 'string'
? { packageSha256: value.packageSha256 }
: {}),
diff --git a/docs/dev-rules/plugin-security-and-authoring.md b/docs/dev-rules/plugin-security-and-authoring.md
index 6063512c8d..79870c1d92 100644
--- a/docs/dev-rules/plugin-security-and-authoring.md
+++ b/docs/dev-rules/plugin-security-and-authoring.md
@@ -84,11 +84,18 @@
- `skill` 槽是唯一**越出沙箱**的能力:技能指令由主 Agent 以用户全部权限执行、全局
生效、不随 workdir 级停用隐藏。其安全边界是**声明一致性**(manifest 里的
name/description 必须与 SKILL.md frontmatter 逐字一致,`skillSlot.ts` 的
- `checkSkillMdConsistency` 是唯一裁判,打包与装入、以及批准快照三侧共用)+
- **批准快照**(确认时把技能目录逐字节拷进
- `<状态根>/skill-snapshots/<id>/<revision>`,只收普通文件;确认框看到的 SKILL.md
- 必须就是 Agent 之后读到的那份,所以共享技能根的链接指快照而不是可被改写的
- `cindy-brain/<id>/<dir>`)+ **链接对账**(`reconcileGhostSkillLinks` 只增删"目标落在
+ `checkSkillMdConsistency` 是唯一裁判,打包与装入、以及批准快照三侧共用;注意它**只**
+ 校验 frontmatter 的 name/description,正文与辅助文件不在它的判据里)+
+ **批准快照与字节指纹**(确认时把技能目录逐字节拷进
+ `<状态根>/skill-snapshots/<id>/<revision>`,只收普通文件,同时把逐 item 的内容
+ 指纹钉进 receipt 的 `skillContentSha256`;确认框看到的 SKILL.md 必须就是 Agent 之后
+ 读到的那份,所以共享技能根的链接指快照而不是可被改写的 `cindy-brain/<id>/<dir>`。
+ 快照缺失需要从安装目录重建时**必须先重算指纹并逐字节对上**——只靠
+ `checkSkillMdConsistency` 拦不住"frontmatter 不动、改写正文或塞辅助文件",那会把
+ 一份没人确认过的指令在一次启用里固化成已批准快照并全局挂链。对不上一律拒、退回
+ 完整重新确认,不许就地自愈成新批准;`skillContentSha256` 因此是**运行期判据**,与
+ 只作审计用的 `packageSha256` 不同,且必填——留"字段缺失就跳过校验"的可选口子等于
+ 给漂移开一条绕过路径)+ **链接对账**(`reconcileGhostSkillLinks` 只增删"目标落在
安装根或批准状态根内的 symlink/junction",绝不触碰真实目录与外来链接;
启用挂链、停用/卸载撤链、断链自愈)。快照目标带 revision,因此每次更新都换目标、
靠对账重指,旧 revision 在 receipt 提交后回收。改动技能落链、命名
@@ -179,6 +186,8 @@ topic 路由;产品层多端语义见
3. 运行授权是否只取自 Host receipt,而不是可变安装目录?无批准/损坏批准是否 fail
closed(列为停用、不许启用、不落技能链),且 UI 如实说明并给出重新确认入口?停用
方向是否无论环境如何都能成功?改了技能落链或快照时 `approvalStateRoot` 是否仍必填?
+ 任何"从安装目录取字节"的路径(快照重建等)是否都复现了装入侧的门槛——字节指纹逐项
+ 对上、SKILL.md 定长后再读?失败时是拒绝并退回重新确认,而不是就地自愈成新批准?
4. 网络是否限白名单域名、凭证无明文读回?附件/媒体/目录是否经归属校验的
grant/deposit/ledger 交接,未暴露宿主绝对路径?
5. 内联凭证是否只走 trusted Desktop 专用 IPC,未登记 device-link?Main 是否重新校验