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): 插件内容目录判据收敛到一处,内容摘要改无歧义编码

Yuewei-LLbce8faba6448
diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.ts
index 66dec923fc..55723f9e9c 100644
--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts
+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts
@@ -27,6 +27,11 @@ import {
type GhostTrustRegistry,
} from './ghostSignature.js';
import { isPathInsideDir } from './dirDeposit.js';
+import {
+ collectGhostContentFiles,
+ hashGhostContentFiles,
+ resolveGhostContentPathSync,
+} from './ghostContentTree.js';
import { checkSkillMdConsistency } from './skillSlot.js';
import {
createGhostInstallReceipt,
@@ -294,17 +299,18 @@ export class GhostManager {
const candidates = [...new Set([localePath, fallbackPath].filter((value): value is string => Boolean(value)))];
for (const candidatePath of candidates) {
try {
- const absPath = path.join(dir, ...candidatePath.split('/'));
+ // 逐段解析(判据与批准侧 readApprovedLocaleResources、技能目录同源)。
+ // 上一版在这里用 realpath + 目录钳制自成一套:同一件事两种写法,改了一处
+ // 忘另一处正是这条链路反复出问题的形态,现在统一成"链接一律拒"。
+ const absPath = resolveGhostContentPathSync(dir, candidatePath, {
+ expect: 'file',
+ label: 'ghost locale',
+ });
const stat = fs.lstatSync(absPath);
- if (!stat.isFile() || stat.size > GHOST_LOCALE_MAX_BYTES) {
+ if (stat.size > GHOST_LOCALE_MAX_BYTES) {
throw new Error(`locale 文件缺失或超过 ${GHOST_LOCALE_MAX_BYTES} 字节`);
}
- const realDir = fs.realpathSync.native(dir);
- const realLocalePath = fs.realpathSync.native(absPath);
- if (!isPathInsideDir(realDir, realLocalePath)) {
- throw new Error('locale 文件经软链解析后位于插件目录之外');
- }
- const raw = JSON.parse(fs.readFileSync(realLocalePath, 'utf8'));
+ const raw = JSON.parse(fs.readFileSync(absPath, 'utf8'));
const validated = validateGhostManifestLocaleResource(raw, manifest);
if (!validated.ok) throw new Error(validated.reason);
return resolveGhostManifestLocale(runtimeManifest, validated.resource);
@@ -397,10 +403,15 @@ export class GhostManager {
*/
private readInstalledIconDataUrl(dir: string, manifest: GhostManifest): string | null {
if (manifest.icon === undefined) return null;
- const iconPath = path.join(dir, ...manifest.icon.split('/'));
try {
- const stat = fs.statSync(iconPath);
- if (!stat.isFile() || stat.size > MAX_GHOST_ICON_BYTES) {
+ // 逐段解析而不是 `stat` 直读:`stat` 静默穿透链接,会把插件目录之外的字节
+ // 读成 icon 下发给 renderer 并钉进 receipt。判据与技能目录 / locale 同源。
+ const iconPath = resolveGhostContentPathSync(dir, manifest.icon, {
+ expect: 'file',
+ label: 'ghost icon',
+ });
+ const stat = fs.lstatSync(iconPath);
+ if (stat.size > MAX_GHOST_ICON_BYTES) {
this.options.log?.warn('ghost icon skipped: missing or oversize', { dir, icon: manifest.icon });
return null;
}
@@ -1089,9 +1100,14 @@ export class GhostManager {
const resources: Record<string, GhostManifestLocaleResource> = {};
for (const localePath of Object.values(manifest.locales ?? {})) {
if (!localePath) continue;
- const absPath = path.join(dir, ...localePath.split('/'));
+ // 逐段解析:只 lstat 最终段挡不住"中间段被换成链接"——那会把插件目录之外的
+ // JSON 读成已批准的界面文案钉进 receipt。判据与技能目录同源。
+ const absPath = resolveGhostContentPathSync(dir, localePath, {
+ expect: 'file',
+ label: 'bundled locale',
+ });
const stat = fs.lstatSync(absPath);
- if (!stat.isFile() || stat.size > GHOST_LOCALE_MAX_BYTES) {
+ if (stat.size > GHOST_LOCALE_MAX_BYTES) {
throw new Error(`bundled locale missing or oversized: ${localePath}`);
}
const raw = JSON.parse(fs.readFileSync(absPath, 'utf8')) as unknown;
@@ -1276,45 +1292,22 @@ async function pathExists(p: string): Promise<boolean> {
}
}
+/**
+ * 安装目录内容指纹(`packageSha256`,审计用的漂移检测器,不作授权判据)。
+ *
+ * 遍历、类型判定与指纹格式全部取自 `ghostContentTree`,与技能指纹
+ * `hashApprovedSkillContent`、随包种子指纹 `fingerprintDirContent` 同一份实现;
+ * 这里的显式策略是"点开头条目不算内容、非普通条目一律拒"。跟随链接在这条路径上
+ * 最多多写一次批准、不构成绕过,判据对齐是因为"同一判据散落多处且各处不一致"
+ * 本身就是缺陷温床。
+ */
async function hashApprovedDirectory(root: string): Promise<string> {
- const files: string[] = [];
- const collect = async (relativeDir: string): Promise<void> => {
- const absoluteDir = path.join(root, relativeDir);
- const entries = await fs.promises.readdir(absoluteDir, { withFileTypes: true });
- for (const entry of entries) {
- if (entry.name.startsWith('.')) continue;
- const relativePath = relativeDir
- ? `${relativeDir}/${entry.name}`
- : entry.name;
- // 判据与姊妹函数 hashApprovedSkillContent 对齐:逐条 lstat、链接显式拒,不依赖
- // Dirent 的类型位。这里本身只是漂移检测器(packageSha256 不作授权判据),跟随
- // 链接最多多写一次批准、不构成绕过;对齐是因为"同一判据散落两处且两处不一致"
- // 本身就是缺陷温床。
- const entryStat = await fs.promises.lstat(path.join(absoluteDir, entry.name));
- if (entryStat.isSymbolicLink()) {
- throw new Error(`bundled Plugin contains a link entry: ${relativePath}`);
- }
- if (entryStat.isDirectory()) {
- await collect(relativePath);
- } else if (entryStat.isFile()) {
- files.push(relativePath);
- } else {
- throw new Error(`bundled Plugin contains a non-regular entry: ${relativePath}`);
- }
- }
- };
- await collect('');
- files.sort();
- const hash = crypto.createHash('sha256');
- for (const relativePath of files) {
- hash.update(relativePath);
- hash.update('\0');
- // 同 hashApprovedSkillContent:流式喂 hash,不让安装目录里的超大文件整份进内存。
- const stream = fs.createReadStream(path.join(root, ...relativePath.split('/')));
- for await (const chunk of stream) hash.update(chunk as Buffer);
- hash.update('\0');
- }
- return hash.digest('hex');
+ const { files } = await collectGhostContentFiles(root, {
+ dotEntries: 'skip',
+ nonRegular: 'throw',
+ label: 'bundled Plugin',
+ });
+ return hashGhostContentFiles(root, files);
}
/**
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 32540725cd..26de748b4a 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/GhostManager.test.ts
@@ -8,9 +8,11 @@ import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
import {
GHOST_SKILL_MD_MAX_BYTES,
ghostInstallApprovalToken,
+ validateGhostManifest,
type InstalledGhost,
} from '../../../shared/ghost';
import { GhostManager } from '../GhostManager';
+import { hashApprovedSkillContent } from '../ghostInstallReceipt';
/** 每个用例独立的临时仓库根 + 源文件目录(规则 23:测试路径一律 os.tmpdir)。 */
let workDir: string;
@@ -100,6 +102,56 @@ async function updateGhost(
});
}
+describe('hashApprovedSkillContent · item.dir 路径段校验', () => {
+ it('rejects a link in an intermediate path segment instead of hashing bytes from outside', async () => {
+ // 回归点:只 lstat 最终段是不够的 —— 中间段被换成软链 / junction 时 OS 会静默穿透,
+ // 对最终段 lstat 报的是"真目录、非链接",于是指纹从技能目录之外取字节。首次批准
+ // 那条路径的指纹是现算的,外部内容会被钉成"批准字节"再复制成快照,而 frontmatter
+ // 一致性校验只看 name/description(manifest 里公开可抄),拦不住。所以这里必须抛错,
+ // 不能返回一个哈希。
+ const validated = validateGhostManifest({
+ ...goodManifest('skilled'),
+ slots: ['tool', 'skill'],
+ skill: { items: [{ dir: 'skills/demo', name: 'demo', description: 'Demo skill' }] },
+ });
+ if (!validated.ok) throw new Error(validated.reason);
+
+ const base = path.join(workDir, 'plugin');
+ const evil = path.join(workDir, 'evil');
+ await fs.promises.mkdir(path.join(base, 'skills', 'demo'), { recursive: true });
+ await fs.promises.mkdir(path.join(evil, 'demo'), { recursive: true });
+ await fs.promises.writeFile(
+ path.join(base, 'skills', 'demo', 'SKILL.md'),
+ '---\nname: demo\ndescription: Demo skill\n---\n\nApproved instructions\n',
+ );
+ await fs.promises.writeFile(
+ path.join(evil, 'demo', 'SKILL.md'),
+ '---\nname: demo\ndescription: Demo skill\n---\n\nrm -rf everything\n',
+ );
+
+ // 正常结构先能算出来,确认用例本身走到了目标代码。
+ await expect(hashApprovedSkillContent(validated.manifest, base)).resolves.toHaveProperty(
+ 'skills/demo',
+ );
+
+ // 把**中间段** skills 换成指向外部的链接。
+ await fs.promises.rm(path.join(base, 'skills'), { recursive: true, force: true });
+ try {
+ await fs.promises.symlink(
+ evil,
+ path.join(base, 'skills'),
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ } catch {
+ return; // 该环境建不了链接(无权限),跳过;判定逻辑与其他平台同源。
+ }
+
+ await expect(hashApprovedSkillContent(validated.manifest, base)).rejects.toThrow(
+ /path segment is a link/,
+ );
+ });
+});
+
describe('GhostManager · install', () => {
it('按宿主语言返回本地化清单,切换语言后 list 立即更新,不支持语言固定回退英文', async () => {
const manifest = {
@@ -889,6 +941,21 @@ describe('GhostManager · Host approval receipt', () => {
});
});
+ it('invalidates a schema v1 receipt instead of trusting its legacy content digests', async () => {
+ await manager.install(await makeCindy('approved.cindy', goodManifest()));
+ const receipt = JSON.parse(
+ await fs.promises.readFile(receiptPath(), 'utf8'),
+ ) as Record<string, unknown>;
+ // v2 改了内容摘要 framing;旧 receipt 的摘要不能拿来继续授权,必须 fail closed。
+ receipt.schemaVersion = 1;
+ await fs.promises.writeFile(receiptPath(), 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;
@@ -1058,6 +1125,35 @@ describe('GhostManager · author / icon(身份卡展示字段)', () => {
expect(listed[0].manifest.author).toBe('Lizi');
});
+ it('never reads icon bytes from outside the plugin dir when a path segment is a link', async () => {
+ // 回归点:`stat` 静默穿透链接 —— 中间段 `assets` 被换成指向外部的链接时,
+ // 上一版会把插件目录之外的字节读成 icon 下发给 renderer(批准路径上还会钉进
+ // receipt)。判据改成逐段解析后,这里只能降级成"没有图标"。
+ const legacyDir = path.join(rootDir, 'legacy');
+ const outside = path.join(workDir, 'outside-assets');
+ await fs.promises.mkdir(legacyDir, { recursive: true });
+ await fs.promises.mkdir(outside, { recursive: true });
+ await fs.promises.writeFile(path.join(outside, 'icon.png'), 'OUTSIDE');
+ await fs.promises.writeFile(
+ path.join(legacyDir, 'ghost.json'),
+ JSON.stringify({ ...iconManifest(), id: 'legacy' }),
+ );
+ try {
+ await fs.promises.symlink(
+ outside,
+ path.join(legacyDir, 'assets'),
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ } catch {
+ return; // 该环境建不了链接(无权限),跳过;判定逻辑与其他平台同源。
+ }
+
+ const listed = manager.list();
+ expect(listed).toHaveLength(1);
+ expect(listed[0].manifest.id).toBe('legacy');
+ expect(listed[0].iconDataUrl).toBeUndefined();
+ });
+
it('不带 icon/author 的旧清单不受影响(无 iconDataUrl 字段)', async () => {
await manager.install(await makeCindy('plain.cindy', goodManifest()));
const listed = manager.list();
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/ghostContentTree.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/ghostContentTree.test.ts
new file mode 100644
index 0000000000..6c68ef2fb8
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/__tests__/ghostContentTree.test.ts
@@ -0,0 +1,210 @@
+/**
+ * ghostContentTree.test.ts —— 插件内容目录判据(唯一实现)的单测。
+ *
+ * 这个模块存在的理由就是"同一判据别再散落多处",所以判据本身的回归点集中钉在
+ * 这里:类型判定一律 lstat、路径逐段解析、点开头与非普通条目的策略组合。
+ * 规则 23:全部路径在 os.tmpdir 下,收尾清理。
+ */
+
+import fs from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+import { afterEach, beforeEach, describe, expect, it } from 'vitest';
+
+import {
+ classifyGhostDirEntry,
+ classifyGhostDirEntrySync,
+ collectGhostContentFiles,
+ hashGhostContentFiles,
+ resolveGhostContentPath,
+ resolveGhostContentPathSync,
+} from '../ghostContentTree';
+
+let workDir: string;
+
+beforeEach(async () => {
+ workDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-content-tree-'));
+});
+
+afterEach(async () => {
+ await fs.promises.rm(workDir, { recursive: true, force: true });
+});
+
+/** 建目录链接;该环境无权限时返回 false 让用例跳过(判定逻辑与其他平台同源)。 */
+async function tryLinkDir(target: string, linkPath: string): Promise<boolean> {
+ try {
+ await fs.promises.symlink(
+ target,
+ linkPath,
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ return true;
+ } catch {
+ return false;
+ }
+}
+
+describe('classifyGhostDirEntry', () => {
+ it('separates regular files, real directories and links', async () => {
+ const file = path.join(workDir, 'a.txt');
+ const dir = path.join(workDir, 'sub');
+ const link = path.join(workDir, 'linked');
+ await fs.promises.writeFile(file, 'bytes');
+ await fs.promises.mkdir(dir);
+
+ expect(await classifyGhostDirEntry(file)).toBe('file');
+ expect(await classifyGhostDirEntry(dir)).toBe('directory');
+ expect(classifyGhostDirEntrySync(file)).toBe('file');
+ expect(classifyGhostDirEntrySync(dir)).toBe('directory');
+
+ if (!(await tryLinkDir(dir, link))) return;
+ // 关键:链接指向真目录,但判据看 lstat,所以是 link 而不是 directory。
+ expect(await classifyGhostDirEntry(link)).toBe('link');
+ expect(classifyGhostDirEntrySync(link)).toBe('link');
+ });
+});
+
+describe('resolveGhostContentPath', () => {
+ it('rejects a link in an intermediate segment instead of silently reading outside', async () => {
+ // 回归点:只 lstat 最终段是不够的 —— 中间段被换成链接时 OS 会静默穿透,对最终段
+ // lstat 报的是"真目录、非链接",于是字节从插件目录之外取。
+ const base = path.join(workDir, 'plugin');
+ const outside = path.join(workDir, 'outside');
+ await fs.promises.mkdir(path.join(base, 'skills', 'demo'), { recursive: true });
+ await fs.promises.mkdir(path.join(outside, 'demo'), { recursive: true });
+
+ await expect(
+ resolveGhostContentPath(base, 'skills/demo', { expect: 'directory', label: 'x' }),
+ ).resolves.toBe(path.join(base, 'skills', 'demo'));
+
+ await fs.promises.rm(path.join(base, 'skills'), { recursive: true, force: true });
+ if (!(await tryLinkDir(outside, path.join(base, 'skills')))) return;
+
+ await expect(
+ resolveGhostContentPath(base, 'skills/demo', { expect: 'directory', label: 'x' }),
+ ).rejects.toThrow(/path segment is a link/);
+ expect(() =>
+ resolveGhostContentPathSync(base, 'skills/demo', { expect: 'directory', label: 'x' }),
+ ).toThrow(/path segment is a link/);
+ });
+
+ it('enforces the expected kind of the final segment', async () => {
+ await fs.promises.mkdir(path.join(workDir, 'assets'), { recursive: true });
+ await fs.promises.writeFile(path.join(workDir, 'assets', 'icon.png'), 'png');
+
+ await expect(
+ resolveGhostContentPath(workDir, 'assets/icon.png', { expect: 'file', label: 'icon' }),
+ ).resolves.toBe(path.join(workDir, 'assets', 'icon.png'));
+ await expect(
+ resolveGhostContentPath(workDir, 'assets', { expect: 'file', label: 'icon' }),
+ ).rejects.toThrow(/not a regular file/);
+ await expect(
+ resolveGhostContentPath(workDir, 'assets/icon.png', {
+ expect: 'directory',
+ label: 'icon',
+ }),
+ ).rejects.toThrow(/not a directory/);
+ });
+});
+
+describe('collectGhostContentFiles', () => {
+ it('includes dot entries for skill content and rejects links there', async () => {
+ const dir = path.join(workDir, 'skill');
+ await fs.promises.mkdir(path.join(dir, 'refs'), { recursive: true });
+ await fs.promises.writeFile(path.join(dir, 'SKILL.md'), 'md');
+ await fs.promises.writeFile(path.join(dir, '.helper'), 'dot bytes');
+ await fs.promises.writeFile(path.join(dir, 'refs', 'a.md'), 'a');
+
+ const tree = await collectGhostContentFiles(dir, {
+ dotEntries: 'include',
+ nonRegular: 'throw',
+ label: 'approved skill',
+ });
+ // 技能目录里的点开头文件同样算内容:技能指令可以引用它。
+ expect(tree.files).toEqual(['.helper', 'SKILL.md', 'refs/a.md']);
+ expect(tree.hasNonRegularEntry).toBe(false);
+
+ if (!(await tryLinkDir(path.join(workDir, 'skill'), path.join(dir, 'loop')))) return;
+ await expect(
+ collectGhostContentFiles(dir, {
+ dotEntries: 'include',
+ nonRegular: 'throw',
+ label: 'approved skill',
+ }),
+ ).rejects.toThrow(/rejects link entry/);
+ });
+
+ it('keeps dot entries out of the content hash but still type-checks them', async () => {
+ // 回归点:上一版对点开头条目直接 continue,于是名为 `.x` 的链接既不进指纹、
+ // 也不翻状态位 —— 安装目录被塞进链接却判成"与种子逐字节相同"。
+ const dir = path.join(workDir, 'installed');
+ await fs.promises.mkdir(dir, { recursive: true });
+ await fs.promises.writeFile(path.join(dir, 'main.js'), '// brain');
+ await fs.promises.writeFile(path.join(dir, '.disabled'), '');
+
+ const before = await collectGhostContentFiles(dir, {
+ dotEntries: 'skip',
+ nonRegular: 'flag',
+ label: 'seed',
+ });
+ expect(before.files).toEqual(['main.js']);
+ expect(before.hasNonRegularEntry).toBe(false);
+
+ if (!(await tryLinkDir(workDir, path.join(dir, '.sneaky')))) return;
+ const after = await collectGhostContentFiles(dir, {
+ dotEntries: 'skip',
+ nonRegular: 'flag',
+ label: 'seed',
+ });
+ expect(after.files).toEqual(['main.js']);
+ expect(after.hasNonRegularEntry).toBe(true);
+ // 内容哈希不受影响(链接没有内容),判定靠独立的类型状态位。
+ expect(await hashGhostContentFiles(dir, after.files)).toBe(
+ await hashGhostContentFiles(dir, before.files),
+ );
+ });
+});
+
+describe('hashGhostContentFiles', () => {
+ it('hashes path + bytes so identical trees match and any byte change does not', async () => {
+ const a = path.join(workDir, 'a');
+ const b = path.join(workDir, 'b');
+ for (const dir of [a, b]) {
+ await fs.promises.mkdir(path.join(dir, 'nested'), { recursive: true });
+ await fs.promises.writeFile(path.join(dir, 'main.js'), '// brain');
+ await fs.promises.writeFile(path.join(dir, 'nested', 'x.txt'), 'x');
+ }
+ const options = { dotEntries: 'skip', nonRegular: 'throw', label: 't' } as const;
+ const treeA = await collectGhostContentFiles(a, options);
+ const treeB = await collectGhostContentFiles(b, options);
+ expect(await hashGhostContentFiles(a, treeA.files)).toBe(
+ await hashGhostContentFiles(b, treeB.files),
+ );
+
+ await fs.promises.writeFile(path.join(b, 'nested', 'x.txt'), 'y');
+ expect(await hashGhostContentFiles(a, treeA.files)).not.toBe(
+ await hashGhostContentFiles(b, treeB.files),
+ );
+ });
+
+ it('uses unambiguous framing when file bytes contain NUL separators', async () => {
+ const oneFile = path.join(workDir, 'one-file');
+ const twoFiles = path.join(workDir, 'two-files');
+ await fs.promises.mkdir(oneFile);
+ await fs.promises.mkdir(twoFiles);
+ await fs.promises.writeFile(path.join(oneFile, 'a'), Buffer.from('x\0b\0y'));
+ await fs.promises.writeFile(path.join(twoFiles, 'a'), 'x');
+ await fs.promises.writeFile(path.join(twoFiles, 'b'), 'y');
+
+ const options = { dotEntries: 'include', nonRegular: 'throw', label: 't' } as const;
+ const oneTree = await collectGhostContentFiles(oneFile, options);
+ const twoTree = await collectGhostContentFiles(twoFiles, options);
+
+ expect(oneTree.files).toEqual(['a']);
+ expect(twoTree.files).toEqual(['a', 'b']);
+ expect(await hashGhostContentFiles(oneFile, oneTree.files)).not.toBe(
+ await hashGhostContentFiles(twoFiles, twoTree.files),
+ );
+ });
+});
diff --git a/apps/desktop/src/main/cindy-brain/ghostContentTree.ts b/apps/desktop/src/main/cindy-brain/ghostContentTree.ts
new file mode 100644
index 0000000000..76dfebb2e4
--- /dev/null
+++ b/apps/desktop/src/main/cindy-brain/ghostContentTree.ts
@@ -0,0 +1,230 @@
+import crypto from 'node:crypto';
+import fs from 'node:fs';
+import path from 'node:path';
+
+/**
+ * ghostContentTree —— 「插件内容目录怎么读」的**唯一判据**。
+ *
+ * 为什么存在这个模块:插件链路上有六处各自 readdir + 判类型的实现(技能指纹、
+ * 技能快照拷贝、安装目录漂移指纹、随包种子指纹、种子复制、Forge 打包收集),
+ * 还有五处各自 `path.join(dir, ...rel.split('/'))` 之后再判一次类型。它们本该
+ * 是同一条判据,却分别用 Dirent 类型位 / `lstat` / `stat` / realpath 钳制写过,
+ * 于是每一轮审查都能在其中一处找到没覆盖的角落 —— 补一处、下一轮换另一处。
+ *
+ * 所以类型判定与相对路径解析在本模块各只有一份实现,差异只允许以**显式策略
+ * 参数**表达(点开头条目算不算内容、非普通条目是拒还是只记状态位)。新增读插件
+ * 内容的代码一律从这里取判据,不要再就地 readdir + isDirectory()。
+ */
+
+/**
+ * 目录条目类型。`link` 与 `other` 都属于"非普通条目",单独区分只为错误信息
+ * 能说清是链接还是别的(FIFO / 设备节点等)。
+ */
+export type GhostDirEntryKind = 'file' | 'directory' | 'link' | 'other';
+
+/**
+ * 类型判据的唯一实现:一律看 `lstat`,**不信 Dirent 的类型位**。
+ *
+ * Dirent 的类型位来自 readdir 的批量结果,当前 libuv 把 reparse point(软链与
+ * Windows junction)都报成 link,但那是实现细节、Node 公开契约没保证;判据自己
+ * 拿 lstat 说话,哪天类型位把 junction 报成 directory 也不会跟进去。
+ */
+function kindOfStat(stat: fs.Stats): GhostDirEntryKind {
+ if (stat.isSymbolicLink()) return 'link';
+ if (stat.isDirectory()) return 'directory';
+ if (stat.isFile()) return 'file';
+ return 'other';
+}
+
+export async function classifyGhostDirEntry(absPath: string): Promise<GhostDirEntryKind> {
+ return kindOfStat(await fs.promises.lstat(absPath));
+}
+
+export function classifyGhostDirEntrySync(absPath: string): GhostDirEntryKind {
+ return kindOfStat(fs.lstatSync(absPath));
+}
+
+/** 普通条目 = 真目录或普通文件;其余(链接等)一律非普通。 */
+export function isRegularGhostDirEntry(kind: GhostDirEntryKind): boolean {
+ return kind === 'file' || kind === 'directory';
+}
+
+export interface ResolveGhostContentPathOptions {
+ /** 最终段期望的类型。 */
+ expect: 'directory' | 'file';
+ /** 错误信息前缀(如 `approved skill` / `bundled locale`)。 */
+ label: string;
+}
+
+/**
+ * 解析清单声明的相对路径,**逐段**确认每一段都是真目录 / 最终段是期望类型。
+ *
+ * 只 lstat 最终段是不够的:中间段被换成软链 / Windows junction 时 OS 会静默穿透
+ * —— 对最终段 lstat 报的是"真目录、非链接"(已实测),于是字节从插件目录之外取。
+ * 首次批准那条路径尤其致命:技能指纹是现算的,外部内容会被钉成"批准字节"再复制
+ * 成快照,而 `checkSkillMdConsistency` 只校验 frontmatter 的 name/description,
+ * 这两个值在 manifest 里公开可抄,拦不住。
+ *
+ * `baseDir` 自身不在这里校验(它由调用方给出:安装根下的 `<id>` 若被换成链接,
+ * `GhostManager.list()` 的 `entry.isDirectory()` 已经把它整条跳过;状态根下的
+ * temp / 快照目录是宿主自己创建的)。相对路径的结构安全由清单校验保证
+ * (`isSafeGhostRelativePath` / skill dir 正则:无盘符、无反斜杠、无 `.`/`..` 段)。
+ */
+export async function resolveGhostContentPath(
+ baseDir: string,
+ relPath: string,
+ options: ResolveGhostContentPathOptions,
+): Promise<string> {
+ const segments = relPath.split('/').filter((segment) => segment.length > 0);
+ let current = baseDir;
+ for (const [index, segment] of segments.entries()) {
+ current = path.join(current, segment);
+ assertSegment(
+ await classifyGhostDirEntry(current),
+ index === segments.length - 1 ? options.expect : 'directory',
+ relPath,
+ options.label,
+ );
+ }
+ return current;
+}
+
+export function resolveGhostContentPathSync(
+ baseDir: string,
+ relPath: string,
+ options: ResolveGhostContentPathOptions,
+): string {
+ const segments = relPath.split('/').filter((segment) => segment.length > 0);
+ let current = baseDir;
+ for (const [index, segment] of segments.entries()) {
+ current = path.join(current, segment);
+ assertSegment(
+ classifyGhostDirEntrySync(current),
+ index === segments.length - 1 ? options.expect : 'directory',
+ relPath,
+ options.label,
+ );
+ }
+ return current;
+}
+
+function assertSegment(
+ kind: GhostDirEntryKind,
+ expect: 'directory' | 'file',
+ relPath: string,
+ label: string,
+): void {
+ if (kind === 'link') {
+ throw new Error(`${label} path segment is a link: ${relPath}`);
+ }
+ if (kind !== expect) {
+ throw new Error(
+ `${label} path segment is not a ${expect === 'directory' ? 'directory' : 'regular file'}: ${relPath}`,
+ );
+ }
+}
+
+export interface CollectGhostContentOptions {
+ /**
+ * 点开头条目:`include` = 算内容(技能目录 —— 技能指令可以引用目录里的任意
+ * 文件,漏掉一类就是漏掉一条改写通道);`skip` = 不算内容(安装目录 / 随包种子
+ * —— `.disabled`、`.cindy-trust.json` 是用户与宿主状态,不是插件内容)。
+ *
+ * `skip` 下点开头条目仍然**要过类型判定**:名为 `.x` 的链接不进内容指纹,但
+ * 会按 `nonRegular` 策略处理。点开头**目录**整条跳过(不递归、不进指纹):清单
+ * 声明的相对路径首字符必须是 `[a-zA-Z0-9_]`,任何声明都不可能指向点开头目录里
+ * 的文件,所以它们既不会被当代码加载、也不会被当技能读取。
+ */
+ dotEntries: 'include' | 'skip';
+ /**
+ * 非普通条目(链接 / FIFO 等):`throw` = 立即拒(授权判据路径);`flag` = 只翻
+ * `hasNonRegularEntry`,不进内容指纹(对账判据路径 —— 需要"判不一致"而不是抛错,
+ * 才能走重新播种把目录换回随包字节)。
+ *
+ * `flag` 下**不能拿 sentinel 喂进哈希**:任何 sentinel 都能被"同路径下内容恰好
+ * 等于该 sentinel 的普通文件"撞上(已实测:内容为 `non-regular` 的普通文件与同名
+ * junction 的摘要完全相等),于是被塞进链接的目录仍会被判成逐字节相同。所以类型
+ * 状态是独立字段,不掺进字节流。
+ */
+ nonRegular: 'throw' | 'flag';
+ /** 错误信息前缀。 */
+ label: string;
+}
+
+export interface GhostContentTree {
+ /** 普通文件的相对路径(正斜杠归一化保证双平台一致),已排序。 */
+ files: string[];
+ /** 是否遇到过非普通条目(仅 `nonRegular: 'flag'` 时可能为 true)。 */
+ hasNonRegularEntry: boolean;
+}
+
+/** 递归收集目录里的普通文件相对路径;类型判定与策略见 `CollectGhostContentOptions`。 */
+export async function collectGhostContentFiles(
+ rootDir: string,
+ options: CollectGhostContentOptions,
+): Promise<GhostContentTree> {
+ const files: string[] = [];
+ let hasNonRegularEntry = false;
+
+ const collect = async (relativeDir: string): Promise<void> => {
+ const absoluteDir = path.join(rootDir, ...relativeDir.split('/').filter(Boolean));
+ for (const entry of await fs.promises.readdir(absoluteDir, { withFileTypes: true })) {
+ const isDotEntry = entry.name.startsWith('.');
+ const relativePath = relativeDir ? `${relativeDir}/${entry.name}` : entry.name;
+ const kind = await classifyGhostDirEntry(path.join(absoluteDir, entry.name));
+ if (!isRegularGhostDirEntry(kind)) {
+ // 类型判定排在点开头过滤**之前**:名为 `.x` 的链接同样是一条改写通道,
+ // 不能因为"点开头不算内容"就连它是不是链接都不看。
+ if (options.nonRegular === 'throw') {
+ throw new Error(
+ `${options.label} rejects ${kind === 'link' ? 'link' : 'non-regular'} entry: ${relativePath}`,
+ );
+ }
+ hasNonRegularEntry = true;
+ continue;
+ }
+ if (isDotEntry && options.dotEntries === 'skip') continue;
+ if (kind === 'directory') {
+ await collect(relativePath);
+ } else {
+ files.push(relativePath);
+ }
+ }
+ };
+
+ await collect('');
+ files.sort();
+ return { files, hasNonRegularEntry };
+}
+
+/**
+ * 内容指纹:版本前缀 + 长度前缀路径 + 每文件 SHA-256。
+ *
+ * 不使用 `path \0 bytes \0` 这类分隔符编码:文件内容可以合法包含 NUL,于是
+ * `{ a: "x\0b\0y" }` 与 `{ a: "x", b: "y" }` 会在进入 SHA-256 前形成完全
+ * 相同的字节流。路径使用 UTF-8 字节长度前缀,文件内容先流式收成固定 32 字节摘要,
+ * 因此文件边界无歧义。
+ *
+ * 文件仍然流式读取,不整份进内存 —— 插件目录里除 SKILL.md 之外的文件没有尺寸
+ * 上限,整份 readFile 会让一个塞进来的超大文件把 Host 撑爆。
+ */
+export async function hashGhostContentFiles(
+ rootDir: string,
+ files: readonly string[],
+): Promise<string> {
+ const hash = crypto.createHash('sha256');
+ hash.update('cindy-ghost-content-v2\0');
+ for (const relativePath of files) {
+ const pathBytes = Buffer.from(relativePath, 'utf8');
+ const pathLength = Buffer.allocUnsafe(8);
+ pathLength.writeBigUInt64BE(BigInt(pathBytes.byteLength));
+ hash.update(pathLength);
+ hash.update(pathBytes);
+
+ const fileHash = crypto.createHash('sha256');
+ const stream = fs.createReadStream(path.join(rootDir, ...relativePath.split('/')));
+ for await (const chunk of stream) fileHash.update(chunk as Buffer);
+ hash.update(fileHash.digest());
+ }
+ return hash.digest('hex');
+}
diff --git a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
index 35e832cdbb..ac5aa65bf0 100644
--- a/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostInstallReceipt.ts
@@ -12,9 +12,20 @@ import {
type GhostManifestLocaleResource,
type GhostTrustInfo,
} from '../../shared/ghost.js';
+import {
+ classifyGhostDirEntry,
+ collectGhostContentFiles,
+ hashGhostContentFiles,
+ isRegularGhostDirEntry,
+ resolveGhostContentPath,
+} from './ghostContentTree.js';
import { checkSkillMdConsistency } from './skillSlot.js';
-const RECEIPT_SCHEMA_VERSION = 1;
+// v2 pairs receipts with the unambiguous ghostContentTree framing. Keeping v1
+// readable would let an old ambiguous digest authorize a snapshot under the
+// new verifier, so old receipts intentionally fail closed and require approval
+// to be written again.
+const RECEIPT_SCHEMA_VERSION = 2;
const MAX_RECEIPT_BYTES = 2 * 1024 * 1024;
const MAX_ICON_DATA_URL_BYTES = 768 * 1024;
/**
@@ -191,7 +202,13 @@ export class GhostInstallReceiptStore {
// 校验过的那一份。因此**先复制到 temp,再对 temp 里(即将成为快照的)那份字节
// 做全部权威校验**,校验通过才 rename 就位。
for (const item of items) {
- const source = path.join(skillSourceDir, ...item.dir.split('/'));
+ // 与算指纹同一个解析入口:逐段确认真目录,挡住"中间段被换成链接"这条从技能
+ // 目录之外取字节的路子。两侧必须共用,否则一侧穿透、一侧不穿透,复制的和
+ // 算指纹的就不是同一组字节。
+ const source = await resolveGhostContentPath(skillSourceDir, item.dir, {
+ expect: 'directory',
+ label: 'approved skill',
+ });
// 复制前的便宜预检:只为早失败、少做无用功(避免整份拷一个超大 SKILL.md)。
// **这不是安全边界** —— 它读的是可变源目录,结论随时可能过期,真正说话的是
// 下面对 temp 的校验。
@@ -316,9 +333,11 @@ export function createGhostInstallReceipt(input: {
/**
* 逐 skill item 目录算规范化内容指纹(排序后的相对路径 + 字节)。
*
- * 与 `hashApprovedDirectory` 的差别:技能目录**不跳过点文件**——技能指令可以引用
- * 目录里的任意文件,漏掉一类就是漏掉一条改写通道;非普通条目一律拒,与快照拷贝
- * 侧 `copyRegularDirectory` 同一判据。
+ * 判据全部取自 `ghostContentTree`(路径逐段解析 + 条目类型判定 + 指纹格式),与
+ * 快照拷贝侧 `copyRegularDirectory`、安装目录漂移指纹 `hashApprovedDirectory`、
+ * 随包种子指纹 `fingerprintDirContent` 共用同一份实现。差异只有显式策略:技能
+ * 目录**不跳过点开头条目**(技能指令可以引用目录里的任意文件,漏掉一类就是漏掉
+ * 一条改写通道),非普通条目一律拒。
*/
export async function hashApprovedSkillContent(
manifest: GhostManifest,
@@ -329,45 +348,16 @@ export async function hashApprovedSkillContent(
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;
- // 逐条 lstat 而不是信 Dirent 的类型位:当前 libuv 把 reparse point(软链与
- // Windows junction)都报成 link,但那是实现细节、Node 公开契约没保证。判据
- // 自己拿 lstat 说话,链接一律显式拒 —— 否则哪天类型位把 junction 报成
- // directory,这里就会跟进去把技能目录之外的字节算进批准指纹。
- const entryStat = await fs.promises.lstat(path.join(itemRoot, relativeDir, entry.name));
- if (entryStat.isSymbolicLink()) {
- throw new Error(`approved skill rejects link entry: ${item.dir}/${relativePath}`);
- }
- if (entryStat.isDirectory()) {
- await collect(relativePath);
- } else if (entryStat.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,不整份读进内存:技能目录里除 SKILL.md 之外的文件没有尺寸上限
- // (SKILL.md 的上限在调用方 ensureSkillSnapshot 里先判),整份 readFile 会让
- // 一个塞进来的超大辅助文件把 Host 撑爆。摘要与逐份读取完全一致。
- const stream = fs.createReadStream(path.join(itemRoot, ...relativePath.split('/')));
- for await (const chunk of stream) hash.update(chunk as Buffer);
- hash.update('\0');
- }
- result[item.dir] = hash.digest('hex');
+ const itemRoot = await resolveGhostContentPath(sourceDir, item.dir, {
+ expect: 'directory',
+ label: 'approved skill',
+ });
+ const { files } = await collectGhostContentFiles(itemRoot, {
+ dotEntries: 'include',
+ nonRegular: 'throw',
+ label: `approved skill ${item.dir}`,
+ });
+ result[item.dir] = await hashGhostContentFiles(itemRoot, files);
}
return result;
}
@@ -495,25 +485,26 @@ function isRevision(value: string): boolean {
}
async function copyRegularDirectory(source: string, target: string): Promise<void> {
- const sourceStat = await fs.promises.lstat(source);
- if (!sourceStat.isDirectory()) throw new Error(`skill source is not a directory: ${source}`);
+ // 类型判据与 hashApprovedSkillContent 同源(ghostContentTree):两侧必须同形,
+ // 否则指纹算的和快照拷的可能不是同一组字节。
+ if ((await classifyGhostDirEntry(source)) !== 'directory') {
+ throw new Error(`skill source is not a directory: ${source}`);
+ }
await fs.promises.mkdir(target, { recursive: true });
const entries = await fs.promises.readdir(source, { withFileTypes: true });
for (const entry of entries) {
const from = path.join(source, entry.name);
const to = path.join(target, entry.name);
- // 判据与 hashApprovedSkillContent 同形:逐条 lstat、链接显式拒,不依赖 Dirent
- // 的类型位。两侧必须同形,否则指纹算的和快照拷的可能不是同一组字节。
- const entryStat = await fs.promises.lstat(from);
- if (entryStat.isSymbolicLink()) {
- throw new Error(`skill snapshot rejects link entry: ${from}`);
+ const kind = await classifyGhostDirEntry(from);
+ if (!isRegularGhostDirEntry(kind)) {
+ throw new Error(
+ `skill snapshot rejects ${kind === 'link' ? 'link' : 'non-regular'} entry: ${from}`,
+ );
}
- if (entryStat.isDirectory()) {
+ if (kind === 'directory') {
await copyRegularDirectory(from, to);
- } else if (entryStat.isFile()) {
- await fs.promises.copyFile(from, to, fs.constants.COPYFILE_EXCL);
} else {
- throw new Error(`skill snapshot rejects non-regular entry: ${from}`);
+ await fs.promises.copyFile(from, to, fs.constants.COPYFILE_EXCL);
}
}
}
diff --git a/apps/desktop/src/main/cindy-brain/ghostLocaleFiles.ts b/apps/desktop/src/main/cindy-brain/ghostLocaleFiles.ts
index 736210c6b6..1b271ed45e 100644
--- a/apps/desktop/src/main/cindy-brain/ghostLocaleFiles.ts
+++ b/apps/desktop/src/main/cindy-brain/ghostLocaleFiles.ts
@@ -6,12 +6,17 @@ import {
validateGhostManifestLocaleResource,
type GhostManifest,
} from '../../shared/ghost.js';
+import { classifyGhostDirEntrySync } from './ghostContentTree.js';
export type GhostLocaleDirectoryValidation = { ok: true } | { ok: false; reason: string };
/**
* Resolve a manifest path one segment at a time so case-insensitive filesystems
* cannot hide a casing mismatch that would later produce a different ZIP entry.
+ *
+ * 遍历留在本地(它要报"磁盘实际大小写"这种只有这里需要的诊断),但**条目类型判定
+ * 走 ghostContentTree**:链接一律不算目录/文件,与技能指纹、快照拷贝、打包收集同
+ * 一份判据,不再各自信 Dirent 的类型位。
*/
function resolveExactFile(rootDir: string, relativePath: string): string {
const segments = relativePath.split('/');
@@ -32,7 +37,8 @@ function resolveExactFile(rootDir: string, relativePath: string): string {
throw new Error(`路径不存在:${relativePath}`);
}
const isLast = index === segments.length - 1;
- if (isLast ? !exact.isFile() : !exact.isDirectory()) {
+ const kind = classifyGhostDirEntrySync(path.join(current, exact.name));
+ if (kind !== (isLast ? 'file' : 'directory')) {
throw new Error(`路径不是${isLast ? '文件' : '目录'}:${relativePath}`);
}
current = path.join(current, exact.name);