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): 随包种子与 Forge 打包对非普通条目 fail closed

Yuewei-LLdc2f4cbc0cc8
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/builtinGhostProvisioner.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/builtinGhostProvisioner.test.ts
index 449f0ba731..79c8f00829 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/builtinGhostProvisioner.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/builtinGhostProvisioner.test.ts
@@ -4,7 +4,7 @@ import path from 'node:path';
import { afterEach, describe, expect, it, vi } from 'vitest';
-import { provisionBuiltinGhosts } from '../builtinGhostProvisioner.js';
+import { fingerprintDirContent, provisionBuiltinGhosts } from '../builtinGhostProvisioner.js';
const tempDirs: string[] = [];
@@ -20,6 +20,253 @@ afterEach(async () => {
);
});
+describe('fingerprintDirContent', () => {
+ /** 建链接;该环境无权限时返回 false 让调用方跳过(判定逻辑与其他平台同源)。 */
+ async function tryLink(target: string, linkPath: string): Promise<boolean> {
+ try {
+ await fs.promises.symlink(
+ target,
+ linkPath,
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ return true;
+ } catch {
+ return false;
+ }
+ }
+
+ it('flags a planted link instead of folding it into the content hash', async () => {
+ const root = await makeTempDir();
+ const installed = path.join(root, 'installed');
+ const outside = path.join(root, 'outside');
+ await fs.promises.mkdir(installed, { recursive: true });
+ await fs.promises.mkdir(outside, { recursive: true });
+ await fs.promises.writeFile(path.join(installed, 'main.js'), '// brain');
+ await fs.promises.writeFile(path.join(outside, 'leak.txt'), 'outside bytes');
+
+ const before = await fingerprintDirContent(installed);
+ expect(before.hasNonRegularEntry).toBe(false);
+
+ if (!(await tryLink(outside, path.join(installed, 'linked')))) return;
+
+ const after = await fingerprintDirContent(installed);
+ // 类型状态独立于哈希:内容哈希不变(链接没有内容),但状态位翻过来。
+ expect(after.hasNonRegularEntry).toBe(true);
+ expect(after.hash).toBe(before.hash);
+ });
+
+ it('keeps type out of the hash so a sentinel-valued regular file stays distinguishable', async () => {
+ // **这是契约/文档用例,不是回归用例**:它无法表达修复前的状态(那时没有
+ // hasNonRegularEntry 字段,代码都编译不过),已实测在"sentinel 进哈希 + 有状态位"
+ // 的混合态下同样会绿。真正的回归点是本文件下面那条端到端用例
+ // (`re-seeds when a seed file was replaced by a link...`)—— 判据落在 provisioner
+ // 的决策上,才能在旧实现下变红。
+ // 这里只钉住契约:类型信息不掺进字节流,所以"内容恰为 sentinel 的普通文件"与
+ // "同名链接"始终可区分。
+ const root = await makeTempDir();
+ const withFile = path.join(root, 'with-file');
+ const withLink = path.join(root, 'with-link');
+ const target = path.join(root, 'target');
+ await fs.promises.mkdir(withFile, { recursive: true });
+ await fs.promises.mkdir(withLink, { recursive: true });
+ await fs.promises.mkdir(target, { recursive: true });
+ await fs.promises.writeFile(path.join(withFile, 'entry'), 'non-regular');
+
+ if (!(await tryLink(target, path.join(withLink, 'entry')))) return;
+
+ const fileSide = await fingerprintDirContent(withFile);
+ const linkSide = await fingerprintDirContent(withLink);
+ expect(fileSide.hasNonRegularEntry).toBe(false);
+ expect(linkSide.hasNonRegularEntry).toBe(true);
+ // 即便两侧哈希相同也不会被误判为一致 —— 判定还要看类型状态。
+ expect(
+ fileSide.hash === linkSide.hash && fileSide.hasNonRegularEntry === linkSide.hasNonRegularEntry,
+ ).toBe(false);
+ });
+
+ it('matches identical link-free directories under the v2 encoding', async () => {
+ // 同一套 v2 编码下,内容相同的普通目录必须得到相同指纹;这个用例不主张与旧版
+ // 摘要兼容(v2 framing 本来就会主动改变旧摘要)。
+ const root = await makeTempDir();
+ const a = path.join(root, 'a');
+ const b = path.join(root, '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');
+ await fs.promises.writeFile(path.join(dir, '.disabled'), '');
+ }
+ const fa = await fingerprintDirContent(a);
+ const fb = await fingerprintDirContent(b);
+ expect(fa.hash).toBe(fb.hash);
+ expect(fa.hasNonRegularEntry).toBe(false);
+ });
+});
+
+describe('builtinGhostProvisioner 安装目录被塞入链接时重新播种', () => {
+ it('re-seeds when a seed file was replaced by a link, even if its bytes could spoof a hash sentinel', async () => {
+ // 决定性用例:判定必须落在 provisioner 的**决策**上,而不是指纹结构上。
+ // 把非普通条目当 sentinel 喂进哈希的实现里,种子文件 `entry` 内容恰为该 sentinel
+ // 时,同名链接与它的摘要完全相等(已实测),于是安装目录被判成"逐字节一致"而跳过
+ // 重新播种 —— 目录永远修不回来,随后批准又必然失败,插件卡在不可用。
+ const root = await makeTempDir();
+ const seedRoot = path.join(root, 'seeds');
+ const repoRoot = path.join(root, 'installed');
+ const seedDir = path.join(seedRoot, 'linked-seed');
+ const installedDir = path.join(repoRoot, 'linked-seed');
+ const outside = path.join(root, 'outside');
+ const manifest = JSON.stringify({
+ schemaVersion: 2,
+ id: 'linked-seed',
+ name: 'Linked seed',
+ version: '1.0.0',
+ kind: 'chip',
+ entry: 'main.js',
+ slots: ['tool'],
+ tools: [{ name: 'run', description: 'Run it' }],
+ });
+ await fs.promises.mkdir(seedDir, { recursive: true });
+ await fs.promises.mkdir(installedDir, { recursive: true });
+ await fs.promises.mkdir(outside, { recursive: true });
+ await fs.promises.writeFile(path.join(outside, 'leak.txt'), 'outside bytes');
+ for (const dir of [seedDir, installedDir]) {
+ await fs.promises.writeFile(path.join(dir, 'ghost.json'), manifest);
+ await fs.promises.writeFile(path.join(dir, 'main.js'), '// brain');
+ // 内容刻意等于旧实现的 sentinel 字符串。
+ await fs.promises.writeFile(path.join(dir, 'entry'), 'non-regular');
+ }
+
+ // 安装侧把这个普通文件换成同名链接。
+ await fs.promises.rm(path.join(installedDir, 'entry'));
+ try {
+ await fs.promises.symlink(
+ outside,
+ path.join(installedDir, 'entry'),
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ } catch {
+ return; // 该环境建不了链接(无权限),跳过;判定逻辑与其他平台同源。
+ }
+
+ const outcome = await provisionBuiltinGhosts({
+ seedRootDirs: [seedRoot],
+ repoRootDir: repoRoot,
+ log: { info: vi.fn(), warn: vi.fn() },
+ });
+
+ expect(outcome.updated.map((m) => m.id)).toContain('linked-seed');
+ expect(outcome.skipped).not.toContain('linked-seed');
+ // 重新播种后安装目录回到随包字节:链接消失,普通文件回来。
+ expect((await fs.promises.lstat(path.join(installedDir, 'entry'))).isFile()).toBe(true);
+ });
+});
+
+describe('builtinGhostProvisioner 安装目录被塞入点开头链接时重新播种', () => {
+ it('re-seeds when a dot-named link was planted, even though dot entries stay out of the hash', async () => {
+ // 回归点:指纹跳过点开头条目(`.disabled` 是用户状态不是内容),上一版对它们
+ // 直接 continue —— 于是名为 `.x` 的链接既不进指纹也不翻类型状态位,安装目录被
+ // 塞进链接却判成"与种子逐字节相同"而跳过播种。现在类型判定排在点开头过滤之前。
+ const root = await makeTempDir();
+ const seedRoot = path.join(root, 'seeds');
+ const repoRoot = path.join(root, 'installed');
+ const seedDir = path.join(seedRoot, 'dotlink');
+ const installedDir = path.join(repoRoot, 'dotlink');
+ const outside = path.join(root, 'outside');
+ const manifest = JSON.stringify({
+ schemaVersion: 2,
+ id: 'dotlink',
+ name: 'Dot link',
+ version: '1.0.0',
+ kind: 'chip',
+ entry: 'main.js',
+ slots: ['tool'],
+ tools: [{ name: 'run', description: 'Run it' }],
+ });
+ await fs.promises.mkdir(seedDir, { recursive: true });
+ await fs.promises.mkdir(installedDir, { recursive: true });
+ await fs.promises.mkdir(outside, { recursive: true });
+ for (const dir of [seedDir, installedDir]) {
+ await fs.promises.writeFile(path.join(dir, 'ghost.json'), manifest);
+ await fs.promises.writeFile(path.join(dir, 'main.js'), '// brain');
+ }
+ // 内容字节完全一致,唯一差别是安装侧多了一条点开头链接。
+ try {
+ await fs.promises.symlink(
+ outside,
+ path.join(installedDir, '.sneaky'),
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ } catch {
+ return; // 该环境建不了链接(无权限),跳过;判定逻辑与其他平台同源。
+ }
+
+ const outcome = await provisionBuiltinGhosts({
+ seedRootDirs: [seedRoot],
+ repoRootDir: repoRoot,
+ log: { info: vi.fn(), warn: vi.fn() },
+ });
+
+ expect(outcome.updated.map((m) => m.id)).toContain('dotlink');
+ expect(outcome.skipped).not.toContain('dotlink');
+ // 重新播种后链接消失(点开头条目不随种子复制),下一轮启动即判一致、不再反复播种。
+ expect(fs.existsSync(path.join(installedDir, '.sneaky'))).toBe(false);
+ });
+});
+
+describe('builtinGhostProvisioner 坏种子 fail closed', () => {
+ it('种子含非普通条目时跳过,不交换目录也不申请批准', async () => {
+ const root = await makeTempDir();
+ const seedRoot = path.join(root, 'seeds');
+ const repoRoot = path.join(root, 'installed');
+ const seedDir = path.join(seedRoot, 'bad-seed');
+ const outside = path.join(root, 'outside');
+ await fs.promises.mkdir(seedDir, { recursive: true });
+ await fs.promises.mkdir(outside, { recursive: true });
+ await fs.promises.writeFile(
+ path.join(seedDir, 'ghost.json'),
+ JSON.stringify({
+ schemaVersion: 2,
+ id: 'bad-seed',
+ name: 'Bad seed',
+ version: '1.0.0',
+ kind: 'chip',
+ entry: 'main.js',
+ slots: ['tool'],
+ tools: [{ name: 'run', description: 'Run it' }],
+ }),
+ );
+ await fs.promises.writeFile(path.join(seedDir, 'main.js'), '// brain');
+ try {
+ await fs.promises.symlink(
+ outside,
+ path.join(seedDir, '.linked'),
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ } catch {
+ return;
+ }
+ const warn = vi.fn();
+
+ const outcome = await provisionBuiltinGhosts({
+ seedRootDirs: [seedRoot],
+ repoRootDir: repoRoot,
+ log: { info: vi.fn(), warn },
+ });
+
+ expect(outcome.skipped).toContain('bad-seed');
+ expect(outcome.installed).toEqual([]);
+ expect(outcome.approved).toEqual([]);
+ expect(fs.existsSync(path.join(repoRoot, 'bad-seed'))).toBe(false);
+ expect(warn).toHaveBeenCalledWith(
+ 'builtin ghost provisioning failed',
+ expect.objectContaining({
+ id: 'bad-seed',
+ error: expect.stringContaining('non-regular'),
+ }),
+ );
+ });
+});
+
describe('builtinGhostProvisioner locale validation', () => {
it('locale 资源翻译错位时跳过官方种子,不把损坏翻译播种给用户', async () => {
const root = await makeTempDir();
diff --git a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
index f94fea3331..1b6753fc3b 100644
--- a/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
+++ b/apps/desktop/src/main/cindy-brain/__tests__/forge.test.ts
@@ -99,6 +99,82 @@ describe('packGhostDir', () => {
});
});
+ it('rejects a source directory that contains a Host-managed root', async () => {
+ // 源目录是受管根的**祖先**:单向判定放行时,递归打包会走进 cindy-brain /
+ // ghost-install-state,把已安装插件字节、批准 receipt 与技能快照一并打进 .cindy。
+ // 只要在 owner 数据目录里放一个 ghost.json 就能触发,所以判定必须双向。
+ const ownerData = path.join(workDir, 'owner-data');
+ const managedRoot = path.join(ownerData, 'cindy-brain');
+ await fs.promises.mkdir(managedRoot, { recursive: true });
+ await fs.promises.writeFile(
+ path.join(managedRoot, 'receipt.json'),
+ JSON.stringify({ secret: 'approved state' }),
+ );
+ await fs.promises.writeFile(
+ path.join(ownerData, 'ghost.json'),
+ JSON.stringify(GOOD_MANIFEST),
+ );
+ await fs.promises.writeFile(path.join(ownerData, 'main.js'), '// authoring source');
+
+ await expect(
+ packGhostDir(ownerData, { forbiddenRootDirs: [managedRoot] }),
+ ).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'SOURCE_IS_INSTALLED_PLUGIN',
+ });
+ });
+
+ it('does not follow a link inside the source dir into a Host-managed root', async () => {
+ // **契约用例,不是回归用例**:改动前 Dirent 的类型位也把 junction 报成 link,
+ // 所以这条在旧实现下同样是绿的。钉住的是契约本身 —— 双向包含判定挡的是"源目录是
+ // 受管根的祖先",这条挡的是另一半(源目录里放一条指向受管根的链接);判类型一律
+ // lstat、不信 Dirent 类型位之后,这一半不再依赖 libuv 的实现细节。
+ const managedRoot = path.join(workDir, 'managed');
+ await fs.promises.mkdir(managedRoot, { recursive: true });
+ await fs.promises.writeFile(
+ path.join(managedRoot, 'receipt.json'),
+ JSON.stringify({ secret: 'approved state' }),
+ );
+ const dir = await makeSrcDir({
+ 'ghost.json': JSON.stringify(GOOD_MANIFEST),
+ 'main.js': '// authoring source',
+ });
+ try {
+ await fs.promises.symlink(
+ managedRoot,
+ path.join(dir, 'state'),
+ process.platform === 'win32' ? 'junction' : 'dir',
+ );
+ } catch {
+ return; // 该环境建不了链接(无权限),跳过;判定逻辑与其他平台同源。
+ }
+
+ const result = await packGhostDir(dir, { forbiddenRootDirs: [managedRoot] });
+ expect(result.ok, JSON.stringify(result)).toBe(true);
+ if (!result.ok) return;
+ const JSZip = (await import('jszip')).default;
+ const zip = await JSZip.loadAsync(await fs.promises.readFile(result.cindyPath));
+ expect(Object.keys(zip.files).sort()).toEqual(['ghost.json', 'main.js']);
+ });
+
+ it('rejects a declared file that is a link instead of packing a package without it', async () => {
+ // `stat` 会穿透链接让声明检查过关,而收集步按类型跳过链接 —— 包里就少了 main.js,
+ // 错误延迟到用户装入时才现形。打包期直接拒,报清楚。
+ const dir = await makeSrcDir({ 'ghost.json': JSON.stringify(GOOD_MANIFEST) });
+ const realEntry = path.join(workDir, 'real-main.js');
+ await fs.promises.writeFile(realEntry, '// outside');
+ try {
+ await fs.promises.symlink(realEntry, path.join(dir, 'main.js'), 'file');
+ } catch {
+ return; // 该环境建不了链接(无权限),跳过;判定逻辑与其他平台同源。
+ }
+
+ await expect(packGhostDir(dir)).resolves.toMatchObject({
+ ok: false,
+ errorCode: 'ENTRY_MISSING',
+ });
+ });
+
it('allows an independent authoring directory outside managed roots', async () => {
const dir = await makeSrcDir({
'ghost.json': JSON.stringify(GOOD_MANIFEST),
diff --git a/apps/desktop/src/main/cindy-brain/builtinGhostProvisioner.ts b/apps/desktop/src/main/cindy-brain/builtinGhostProvisioner.ts
index 1f81a64d9f..9ea4a12b28 100644
--- a/apps/desktop/src/main/cindy-brain/builtinGhostProvisioner.ts
+++ b/apps/desktop/src/main/cindy-brain/builtinGhostProvisioner.ts
@@ -8,6 +8,12 @@ import {
validateGhostManifest,
type GhostManifest,
} from '../../shared/ghost.js';
+import {
+ classifyGhostDirEntry,
+ collectGhostContentFiles,
+ hashGhostContentFiles,
+ resolveGhostContentPathSync,
+} from './ghostContentTree.js';
import { validateGhostLocaleResourcesInDirectory } from './ghostLocaleFiles.js';
/**
@@ -390,10 +396,21 @@ export async function provisionBuiltinGhosts(deps: ProvisionDeps): Promise<Provi
}
// 4) 指纹比对(忽略点开头文件:`.disabled` 是用户状态不是内容)。
+ // 种子是随应用发布的第一方输入,出现链接/FIFO/设备节点属于打包事故:
+ // 必须整颗 fail closed,不能在复制时静默丢掉条目后批准一个残缺安装。
+ const seedFingerprint = await fingerprintDirContent(seedDir);
+ if (seedFingerprint.hasNonRegularEntry) {
+ throw new Error('builtin seed contains a link or non-regular entry');
+ }
if (installedExists) {
- const seedHash = await hashDirContent(seedDir);
- const installedHash = await hashDirContent(installedDir);
- if (seedHash === installedHash) {
+ const installedFingerprint = await fingerprintDirContent(installedDir);
+ // 安装侧含非普通条目 = 一律判不一致,走重新播种把目录换回随包字节。
+ // 否则它既修不回来(判成相同就跳过播种),随后 hashApprovedDirectory 又会因
+ // 非普通条目抛错、批准被撤销,插件每次启动都卡在不可用。
+ if (
+ !installedFingerprint.hasNonRegularEntry &&
+ seedFingerprint.hash === installedFingerprint.hash
+ ) {
outcome.approved.push(manifest);
outcome.skipped.push(id);
continue;
@@ -543,13 +560,22 @@ export function listEnterpriseSeedIds(seedRootDirs: string[], log?: BuiltinProvi
return [...ids].sort();
}
-/** 种子目录里的 icon → data URL(缺失/超限/读失败降级 null,不拖垮列表)。 */
+/**
+ * 种子目录里的 icon → data URL(缺失/超限/读失败降级 null,不拖垮列表)。
+ *
+ * 路径解析走 `ghostContentTree` 的逐段判定:`stat` 会静默穿透链接,把种子目录之外
+ * 的字节读成 icon 塞进设置页(与"清单声明的相对路径必须落在插件目录内"同一条判据,
+ * 不因为它只是张图就换一套写法)。
+ */
function readSeedIconDataUrl(seedDir: string, manifest: GhostManifest): string | null {
if (manifest.icon === undefined) return null;
try {
- const iconPath = path.join(seedDir, ...manifest.icon.split('/'));
- const stat = fs.statSync(iconPath);
- if (!stat.isFile() || stat.size > MAX_RESTORABLE_ICON_BYTES) return null;
+ const iconPath = resolveGhostContentPathSync(seedDir, manifest.icon, {
+ expect: 'file',
+ label: 'builtin seed icon',
+ });
+ const stat = fs.lstatSync(iconPath);
+ if (stat.size > MAX_RESTORABLE_ICON_BYTES) return null;
const mime = ghostIconMimeType(manifest.icon);
if (!mime) return null;
return `data:${mime};base64,${fs.readFileSync(iconPath).toString('base64')}`;
@@ -597,36 +623,35 @@ function readSeedManifest(seedDir: string, id: string, log?: BuiltinProvisionerL
}
/**
- * 目录内容指纹:相对路径排序后逐个 hash(路径 + 字节),点开头条目跳过。
- * 意识包极小(zip 通道上限才 8MB),启动算一遍开销可忽略。
+ * 目录内容指纹 + 一个**不进哈希**的类型状态。意识包极小(zip 通道上限才 8MB),
+ * 启动算一遍开销可忽略。
+ *
+ * 遍历与类型判定取自 `ghostContentTree`(与技能指纹、快照拷贝、安装目录漂移指纹
+ * 同一份实现);这里的显式策略是"点开头条目不算内容(`.disabled` 是用户状态)、
+ * 非普通条目只记状态位不抛错"—— 因为本判据的收敛动作是**重新播种**,不是拒绝。
+ *
+ * 非普通条目(软链 / Windows junction 等)不读内容,也**不能拿 sentinel 喂进哈希** ——
+ * 任何这样的 sentinel 都能被"同路径下内容恰好等于该 sentinel 的普通文件"撞上(已实测:
+ * 内容为 `non-regular` 的普通文件与同名 junction 的摘要完全相等),于是被塞进链接的
+ * 安装目录仍会被判成"与种子逐字节相同"。所以它作为独立字段参与比较,不掺进字节流。
*/
-export async function hashDirContent(dir: string): Promise<string> {
- const files = collectFiles(dir, '');
- files.sort();
- const hash = crypto.createHash('sha256');
- for (const rel of files) {
- hash.update(rel);
- hash.update('\0');
- hash.update(await fs.promises.readFile(path.join(dir, rel)));
- hash.update('\0');
- }
- return hash.digest('hex');
+export interface DirContentFingerprint {
+ /** 普通文件的 v2 内容指纹;链接等非普通条目不掺进字节流。 */
+ hash: string;
+ /** 是否含既非目录也非普通文件的条目(含点开头的那些)。 */
+ hasNonRegularEntry: boolean;
}
-/** 递归收集相对文件路径(正斜杠归一化保证双平台指纹一致;点开头跳过)。 */
-function collectFiles(rootDir: string, relBase: string): string[] {
- const abs = path.join(rootDir, relBase);
- const result: string[] = [];
- for (const entry of fs.readdirSync(abs, { withFileTypes: true })) {
- if (entry.name.startsWith('.')) continue;
- const rel = relBase.length === 0 ? entry.name : `${relBase}/${entry.name}`;
- if (entry.isDirectory()) {
- result.push(...collectFiles(rootDir, rel));
- } else if (entry.isFile()) {
- result.push(rel);
- }
- }
- return result;
+export async function fingerprintDirContent(dir: string): Promise<DirContentFingerprint> {
+ const tree = await collectGhostContentFiles(dir, {
+ dotEntries: 'skip',
+ nonRegular: 'flag',
+ label: 'builtin seed content',
+ });
+ return {
+ hash: await hashGhostContentFiles(dir, tree.files),
+ hasNonRegularEntry: tree.hasNonRegularEntry,
+ };
}
/**
@@ -671,16 +696,31 @@ async function swapInSeed(
}
}
-/** 递归复制目录,点开头条目跳过(种子里的 .DS_Store 等垃圾不落仓库)。 */
+/**
+ * 递归复制目录,点开头条目跳过(种子里的 .DS_Store 等垃圾不落仓库)。
+ *
+ * 类型判定同样走 `ghostContentTree`:非普通条目直接抛错。种子里出现链接属于打包
+ * 事故;既不能跟随复制把外部字节铺进安装目录,也不能静默丢掉后批准残缺安装。
+ * 主流程在交换目录前已有同形自检,这里逐条复制前再判一次类型,缩小检查与使用之间
+ * 的窗口,并挡住预检后、该条目被读取前已经发生的类型替换。
+ */
async function copyDirSkippingDotEntries(from: string, to: string): Promise<void> {
await fs.promises.mkdir(to, { recursive: true });
for (const entry of await fs.promises.readdir(from, { withFileTypes: true })) {
- if (entry.name.startsWith('.')) continue;
const src = path.join(from, entry.name);
const dest = path.join(to, entry.name);
- if (entry.isDirectory()) {
+ const kind = await classifyGhostDirEntry(src);
+ // 与 collectGhostContentFiles 同序:先判类型,再按名称决定是否忽略内容。
+ // 否则复制期间出现的 `.x` 链接会被静默跳过,第二道 fail-closed 防线名不副实。
+ if (kind !== 'directory' && kind !== 'file') {
+ throw new Error(
+ `builtin seed rejects ${kind === 'link' ? 'link' : 'non-regular'} entry: ${src}`,
+ );
+ }
+ if (entry.name.startsWith('.')) continue;
+ if (kind === 'directory') {
await copyDirSkippingDotEntries(src, dest);
- } else if (entry.isFile()) {
+ } else {
await fs.promises.copyFile(src, dest);
}
}
diff --git a/apps/desktop/src/main/cindy-brain/forge.ts b/apps/desktop/src/main/cindy-brain/forge.ts
index 7205a5b9a4..88be838c27 100644
--- a/apps/desktop/src/main/cindy-brain/forge.ts
+++ b/apps/desktop/src/main/cindy-brain/forge.ts
@@ -24,6 +24,10 @@ import {
validateGhostManifest,
type GhostManifest,
} from '../../shared/ghost.js';
+import {
+ classifyGhostDirEntry,
+ resolveGhostContentPath,
+} from './ghostContentTree.js';
import { validateGhostLocaleResourcesInDirectory } from './ghostLocaleFiles.js';
import { isPathInsideDir } from './dirDeposit.js';
import { checkSkillMdConsistency } from './skillSlot.js';
@@ -475,12 +479,19 @@ export async function scaffoldGhostDir(
message: err instanceof Error ? err.message : String(err),
};
}
- if (isPathInsideDir(resolvedForbiddenRoot, realTarget)) {
+ // 与打包侧同形的双向判定。祖先方向这一半在这里是 defense-in-depth 而不是修洞:
+ // 骨架目标若是受管根的祖先,该目录必然已存在,最终 rename 会以 TARGET_EXISTS 拒掉。
+ // 仍然写出来,是为了不让"上游守卫够不够用"依赖读者去推断下游 rename 的语义 ——
+ // 判定散落且各自只覆盖一半,正是这条链路反复出问题的成因。
+ if (
+ isPathInsideDir(resolvedForbiddenRoot, realTarget) ||
+ isPathInsideDir(realTarget, resolvedForbiddenRoot)
+ ) {
return {
ok: false,
errorCode: 'INVALID_INPUT',
message:
- 'dir 不能落在已安装插件目录或 Host 管理的状态目录内;请在工作目录里换一个独立的作者目录',
+ 'dir 不能落在已安装插件目录或 Host 管理的状态目录内,也不能是它们的上级目录;请在工作目录里换一个独立的作者目录',
};
}
}
@@ -589,7 +600,14 @@ export async function packGhostDir(
const realSourceDir = await fs.promises.realpath(dir);
for (const forbiddenRoot of options.forbiddenRootDirs ?? []) {
const resolvedForbiddenRoot = await resolveThroughExistingAncestor(forbiddenRoot);
- if (isPathInsideDir(resolvedForbiddenRoot, realSourceDir)) {
+ // 判定必须**双向**:源目录落在受管根内要拒(拿已安装插件当源码),源目录是受管根的
+ // 祖先也要拒 —— 后者下面的递归打包会走进 cindy-brain / ghost-install-state,把
+ // 已安装插件字节、批准 receipt 与技能快照一并打进 .cindy。单向判定时,只要在
+ // owner 数据目录里放一个 ghost.json 就能触发。
+ if (
+ isPathInsideDir(resolvedForbiddenRoot, realSourceDir) ||
+ isPathInsideDir(realSourceDir, resolvedForbiddenRoot)
+ ) {
return {
ok: false,
errorCode: 'SOURCE_IS_INSTALLED_PLUGIN',
@@ -638,10 +656,16 @@ export async function packGhostDir(
for (const item of manifest.skill?.items ?? []) mustExist.push(`${item.dir}/SKILL.md`);
for (const rel of mustExist) {
try {
- const st = await fs.promises.stat(path.join(dir, rel));
- if (!st.isFile()) throw new Error('not a file');
+ // 逐段解析(判据同装入侧 ghostContentTree):`stat` 会穿透链接,让"声明的
+ // 文件是链接"通过检查,而下面的收集步按类型跳过链接 —— 包就少了这个文件,
+ // 错误延迟到用户装入时才现形。这里直接拒,报清楚。
+ await resolveGhostContentPath(dir, rel, { expect: 'file', label: 'forge source' });
} catch {
- return { ok: false, errorCode: 'ENTRY_MISSING', message: `清单声明的文件不存在:${rel}` };
+ return {
+ ok: false,
+ errorCode: 'ENTRY_MISSING',
+ message: `清单声明的文件不存在或不是普通文件(链接不可打包):${rel}`,
+ };
}
}
@@ -697,10 +721,16 @@ export async function packGhostDir(
};
}
seenPackPaths.add(foldedRel);
- if (e.isDirectory()) {
+ // 类型判定走 ghostContentTree(一律 lstat,不信 Dirent 类型位):非普通条目
+ // 既不递归也不收集 —— 递归进一条指向 cindy-brain / ghost-install-state 的
+ // 链接就会把已安装插件字节、批准 receipt 与技能快照打进 .cindy。源目录与
+ // 受管根的**双向**包含判定挡住了"源目录是受管根祖先"那一半,这里挡的是
+ // "源目录里放一条链接指进去"那一半,两半都要在。
+ const kind = await classifyGhostDirEntry(abs);
+ if (kind === 'directory') {
const bad = await walk(abs, rel);
if (bad) return bad;
- } else if (e.isFile()) {
+ } else if (kind === 'file') {
files.push({ rel, abs });
totalBytes += (await fs.promises.stat(abs)).size;
if (files.length > maxFiles) {