Consider it done. The open-source AI agent that works out of the box · 想到,就能做到。开源、开箱即用的 AI Agent。
TypeScript agentai-agentai-assistantandroidclaude-codecodexelectroniosllmmacosreact-nativetypescriptwindows
feat(plugins): 插件详情页新增导出 .cindy 菜单项 (#953)
xxxcc89e9b7fd6934
diff --git a/apps/desktop/src/main/cindy-brain/GhostManager.ts b/apps/desktop/src/main/cindy-brain/GhostManager.tsindex 24477e077e..a6f0b472b5 100644--- a/apps/desktop/src/main/cindy-brain/GhostManager.ts+++ b/apps/desktop/src/main/cindy-brain/GhostManager.ts@@ -28,8 +28,8 @@ import { isPathInsideDir } from './dirDeposit.js';import { checkSkillMdConsistency } from './skillSlot.js';/** 普通沙箱插件维持小包上限;随包 Node/CLI 允许更大的预打包产物。 */-const MAX_BASIC_CINDY_FILE_BYTES = 8 * 1024 * 1024;-const MAX_NODE_CINDY_FILE_BYTES = 128 * 1024 * 1024;+export const MAX_BASIC_CINDY_FILE_BYTES = 8 * 1024 * 1024;+export const MAX_NODE_CINDY_FILE_BYTES = 128 * 1024 * 1024;/** 身份卡本身只应是小 JSON;先限流读取,避免在识别包类型前被单文件撑爆内存。 */const MAX_GHOST_MANIFEST_BYTES = 256 * 1024;/**@@ -38,10 +38,10 @@ const MAX_GHOST_MANIFEST_BYTES = 256 * 1024;*/const MAX_GHOST_ICON_BYTES = 512 * 1024; // 512 KB/** 解压后总大小/条目数上限;Node 包允许携带已打包 CLI,但仍有硬闸。 */-const MAX_BASIC_UNCOMPRESSED_BYTES = 32 * 1024 * 1024;-const MAX_NODE_UNCOMPRESSED_BYTES = 256 * 1024 * 1024;-const MAX_BASIC_ZIP_ENTRIES = 256;-const MAX_NODE_ZIP_ENTRIES = 2_048;+export const MAX_BASIC_UNCOMPRESSED_BYTES = 32 * 1024 * 1024;+export const MAX_NODE_UNCOMPRESSED_BYTES = 256 * 1024 * 1024;+export const MAX_BASIC_ZIP_ENTRIES = 256;+export const MAX_NODE_ZIP_ENTRIES = 2_048;/** 停用标记文件名(安装目录内;存在即停用)。 */const DISABLED_MARKER_FILE = '.disabled';/** 安装时已验证的信任结果快照(作者包不能提供,staging 阶段由主机写)。 */diff --git a/apps/desktop/src/main/cindy-brain/__tests__/exportGhostPackage.test.ts b/apps/desktop/src/main/cindy-brain/__tests__/exportGhostPackage.test.tsnew file mode 100644index 0000000000..3a7c40c0e3--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/__tests__/exportGhostPackage.test.ts@@ -0,0 +1,478 @@+import crypto from 'node:crypto';+import fs from 'node:fs';+import os from 'node:os';+import path from 'node:path';++import JSZip from 'jszip';+import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';++import type { InstalledGhost } from '../../../shared/ghost';+import { exportGhostPackage, sanitizeExportFileNamePart } from '../exportGhostPackage';+import { signGhostPackage } from '../ghostSignature';++/** 测试用发布者密钥对(每次进程一对,签名/验签都走真实 ed25519)。 */+const { privateKey: publisherKey } = crypto.generateKeyPairSync('ed25519');++/** 每个用例独立的临时安装目录(规则 23:测试路径一律 os.tmpdir)。 */+let workDir: string;+let ghostDir: string;++beforeEach(async () => {+ workDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'cindy-ghost-export-test-'));+ ghostDir = path.join(workDir, 'hello');+ await fs.promises.mkdir(path.join(ghostDir, 'locales'), { recursive: true });+ await fs.promises.writeFile(path.join(ghostDir, 'ghost.json'), JSON.stringify({+ schemaVersion: 2,+ id: 'hello',+ name: 'Hello 插件',+ version: '1.2.0',+ kind: 'chip',+ entry: 'main.js',+ slots: ['tool'],+ tools: [{ name: 'do_thing', description: '做点事' }],+ }));+ await fs.promises.writeFile(path.join(ghostDir, 'main.js'), 'console.log("hi")');+ await fs.promises.writeFile(path.join(ghostDir, 'locales', 'en.json'), '{}');+ // 主机保留文件 + 系统残渣:导出必须跳过(可过装入校验)。+ await fs.promises.writeFile(path.join(ghostDir, '.disabled'), '');+ await fs.promises.writeFile(path.join(ghostDir, '.cindy-trust.json'), '{}');+ await fs.promises.writeFile(path.join(ghostDir, '.DS_Store'), '');+});++afterEach(async () => {+ await fs.promises.rm(workDir, { recursive: true, force: true });+});++function makeGhost(): InstalledGhost {+ return {+ manifest: {+ schemaVersion: 2,+ id: 'hello',+ name: 'Hello 插件',+ version: '1.2.0',+ kind: 'chip',+ entry: 'main.js',+ slots: ['tool'],+ tools: [{ name: 'do_thing', description: '做点事' }],+ },+ dir: ghostDir,+ enabled: true,+ };+}++/**+ * 给夹具目录写一份真实签名的 cindy-signatures.json:用 signGhostPackage+ * 对 paths 指定的文件(相对 ghostDir,posix 风格)打包签名,取签名文件+ * 落盘。导出会对签名包做装入级验签,假签名必然 verify_failed。+ */+async function writeStatement(paths: string[]): Promise<void> {+ const zip = new JSZip();+ for (const p of paths) {+ zip.file(p, await fs.promises.readFile(path.join(ghostDir, ...p.split('/'))));+ }+ const pkg = await zip.generateAsync({ type: 'nodebuffer' });+ const signed = await signGhostPackage(pkg, {+ publisherName: 'test',+ privateKey: publisherKey,+ });+ const signedZip = await JSZip.loadAsync(signed);+ const sigText = await signedZip.file('cindy-signatures.json')!.async('string');+ await fs.promises.writeFile(path.join(ghostDir, 'cindy-signatures.json'), sigText);+}++function makeDeps(overrides: Partial<Parameters<typeof exportGhostPackage>[1]> = {}) {+ return {+ listInstalled: () => [makeGhost()],+ showSaveDialog: vi.fn(async ({ defaultPath }: { defaultPath: string }) => ({+ canceled: false,+ filePath: path.join(workDir, path.basename(defaultPath)),+ })),+ getDownloadsDir: () => workDir,+ fileTypeLabel: 'Cindy Plugin',+ writeFile: (filePath: string, data: Buffer) => fs.promises.writeFile(filePath, data),+ inspectPackage: async () => true,+ ...overrides,+ };+}++describe('exportGhostPackage', () => {+ it('打包安装目录为可重新装入的 .cindy(跳过主机点文件)', async () => {+ const deps = makeDeps();+ const result = await exportGhostPackage('hello', deps);+ expect(result.status).toBe('saved');+ if (result.status !== 'saved') return;++ const zip = await JSZip.loadAsync(await fs.promises.readFile(result.savedPath));+ const names = Object.values(zip.files)+ .filter((entry) => !entry.dir)+ .map((entry) => entry.name)+ .sort();+ // 根部主机保留文件(.disabled/.cindy-trust.json)与 .DS_Store 被跳过;+ // 包本体内容原样保留。+ expect(names).toEqual(['ghost.json', 'locales/en.json', 'main.js']);+ const manifest = JSON.parse(await zip.files['ghost.json'].async('string')) as { id: string };+ expect(manifest.id).toBe('hello');+ });++ it('签名包:导出 statement 闭包,被覆盖的根部 .DS_Store 保留', async () => {+ // 打包时根部已有 .DS_Store 的签名包:statement 覆盖它,导出必须保留,+ // 否则重装校验缺文件失败;主机保留文件(.disabled/.cindy-trust.json)+ // 不在 statement 里,天然不进入导出包。+ await writeStatement(['.DS_Store', 'ghost.json', 'locales/en.json', 'main.js']);+ const result = await exportGhostPackage('hello', makeDeps());+ expect(result.status).toBe('saved');+ if (result.status !== 'saved') return;+ const zip = await JSZip.loadAsync(await fs.promises.readFile(result.savedPath));+ const names = Object.keys(zip.files);+ expect(names).toContain('.DS_Store');+ expect(names).toContain('cindy-signatures.json');+ expect(names).toContain('ghost.json');+ expect(names).not.toContain('.disabled');+ expect(names).not.toContain('.cindy-trust.json');++ // 未签名包:根部 .DS_Store 是装入后 Finder 残渣,跳过。+ await fs.promises.rm(path.join(ghostDir, 'cindy-signatures.json'));+ const unsignedResult = await exportGhostPackage('hello', makeDeps());+ expect(unsignedResult.status).toBe('saved');+ if (unsignedResult.status !== 'saved') return;+ const unsignedZip = await JSZip.loadAsync(await fs.promises.readFile(unsignedResult.savedPath));+ expect(Object.keys(unsignedZip.files)).not.toContain('.DS_Store');+ });++ it('签名包:statement 之外的杂散文件不进入导出包(任意深度 Finder 残渣)', async () => {+ // 用户用 Finder 浏览过子目录:嵌套 .DS_Store 是装入后生成的,+ // statement 不覆盖它,保留会让重装校验多出 statement 外文件。+ await fs.promises.writeFile(path.join(ghostDir, 'locales', '.DS_Store'), '');+ await writeStatement(['ghost.json', 'locales/en.json', 'main.js']);+ const result = await exportGhostPackage('hello', makeDeps());+ expect(result.status).toBe('saved');+ if (result.status !== 'saved') return;+ const zip = await JSZip.loadAsync(await fs.promises.readFile(result.savedPath));+ const names = Object.keys(zip.files);+ expect(names).not.toContain('locales/.DS_Store');+ expect(names).not.toContain('.DS_Store');+ expect(names).toContain('locales/en.json');+ });++ it('签名包内容被篡改(哈希与 statement 不符):如实 read_failed', async () => {+ await writeStatement(['ghost.json', 'locales/en.json', 'main.js']);+ await fs.promises.writeFile(path.join(ghostDir, 'main.js'), 'tampered-content');+ const result = await exportGhostPackage('hello', makeDeps());+ expect(result).toEqual({ status: 'error', code: 'read_failed' });+ });++ it('产物未过装入校验:如实 verify_failed,不碰用户既有目标文件', async () => {+ // 装入目录被改坏(如 statement/review 签名失效、manifest 不合法)+ // 的情形由装入校验本尊拦下——导出不能报成功;用户选择覆盖旧备份+ // 时,既有文件必须原样保留,只清理临时文件。+ const target = path.join(workDir, 'old-backup.cindy');+ await fs.promises.writeFile(target, 'old-bytes');+ const result = await exportGhostPackage('hello', makeDeps({+ showSaveDialog: vi.fn(async () => ({ canceled: false, filePath: target })),+ inspectPackage: async () => false,+ }));+ expect(result).toEqual({ status: 'error', code: 'verify_failed' });+ await expect(fs.promises.readFile(target, 'utf8')).resolves.toBe('old-bytes');+ const leftovers = (await fs.promises.readdir(workDir)).filter((name) =>+ name.startsWith('.cindy-export-'),+ );+ expect(leftovers).toEqual([]);+ });++ it('用户选择覆盖既有文件且校验通过:目标被完整新包替换', async () => {+ const target = path.join(workDir, 'existing.cindy');+ await fs.promises.writeFile(target, 'old-bytes');+ const result = await exportGhostPackage('hello', makeDeps({+ showSaveDialog: vi.fn(async () => ({ canceled: false, filePath: target })),+ }));+ expect(result).toEqual({ status: 'saved', savedPath: target });+ const zip = await JSZip.loadAsync(await fs.promises.readFile(target));+ expect(Object.keys(zip.files)).toContain('ghost.json');+ });++ it('目录内容超过装入侧条目上限:如实 too_large', async () => {+ // 普通(非 Node)插件装入上限 256 条目;运行期写入的杂散文件可能+ // 把目录撑过上限,导出不能成功却装不回。+ for (let i = 0; i < 260; i++) {+ await fs.promises.writeFile(path.join(ghostDir, `cache-${i}.dat`), 'x');+ }+ const result = await exportGhostPackage('hello', makeDeps());+ expect(result).toEqual({ status: 'error', code: 'too_large' });+ });++ it('签名包读取期间目录被更新:哈希不符触发整体重读', async () => {+ await writeStatement(['ghost.json', 'locales/en.json', 'main.js']);+ // 第一次读 main.js 返回陈旧字节(模拟并发更新读到旧目录):+ // 哈希与 statement 不符,必须整体重读,最终包内容应为真实字节。+ const realReadFile = fs.promises.readFile;+ let staleServed = false;+ const spy = vi.spyOn(fs.promises, 'readFile').mockImplementation(async (p: any, opts: any) => {+ if (String(p).endsWith('main.js') && !staleServed) {+ staleServed = true;+ return Buffer.from('stale-bytes');+ }+ return realReadFile(p, opts) as any;+ });+ try {+ const result = await exportGhostPackage('hello', makeDeps());+ expect(result.status).toBe('saved');+ if (result.status !== 'saved') return;+ expect(staleServed).toBe(true);+ const zip = await JSZip.loadAsync(await fs.promises.readFile(result.savedPath));+ await expect(zip.files['main.js'].async('string')).resolves.toBe('console.log("hi")');+ } finally {+ spy.mockRestore();+ }+ });++ it('遍历期间目录被改写时整体重读,导出与最终状态一致的包', async () => {+ // 第二遍(校验遍)枚举根部前改写 main.js:第一遍的字节与第二遍的+ // 元数据对不上,必须重读;最终包内容应是改写后的版本。+ const realOpendir = fs.promises.opendir;+ let rootReads = 0;+ const spy = vi.spyOn(fs.promises, 'opendir').mockImplementation(async (p: any) => {+ if (String(p) === ghostDir) {+ rootReads += 1;+ if (rootReads === 2) {+ await fs.promises.writeFile(+ path.join(ghostDir, 'main.js'),+ 'console.log("version-2-content")',+ );+ }+ }+ return realOpendir(p) as any;+ });+ try {+ const result = await exportGhostPackage('hello', makeDeps());+ expect(result.status).toBe('saved');+ if (result.status !== 'saved') return;+ expect(rootReads).toBeGreaterThan(2);+ const zip = await JSZip.loadAsync(await fs.promises.readFile(result.savedPath));+ await expect(zip.files['main.js'].async('string')).resolves.toBe(+ 'console.log("version-2-content")',+ );+ } finally {+ spy.mockRestore();+ }+ });++ it('嵌套点文件与 node_modules 属于包内容,未签名导出必须保留', async () => {+ await fs.promises.mkdir(path.join(ghostDir, 'node_modules', 'dep'), { recursive: true });+ await fs.promises.writeFile(path.join(ghostDir, 'node_modules', 'dep', 'index.js'), 'x');+ await fs.promises.mkdir(path.join(ghostDir, 'data'), { recursive: true });+ await fs.promises.writeFile(path.join(ghostDir, 'data', '.keep'), '');+ // 嵌套 .DS_Store 可能是作者包内容;未签名包只有根部主机残渣才跳过。+ await fs.promises.writeFile(path.join(ghostDir, 'data', '.DS_Store'), '');++ const result = await exportGhostPackage('hello', makeDeps());+ expect(result.status).toBe('saved');+ if (result.status !== 'saved') return;+ const zip = await JSZip.loadAsync(await fs.promises.readFile(result.savedPath));+ const names = Object.values(zip.files)+ .filter((entry) => !entry.dir)+ .map((entry) => entry.name)+ .sort();+ expect(names).toContain('node_modules/dep/index.js');+ expect(names).toContain('data/.keep');+ expect(names).toContain('data/.DS_Store');+ expect(names).not.toContain('.disabled');+ expect(names).not.toContain('.cindy-trust.json');+ });++ it('空目录作为显式条目保留(随包模板/输出目录,两条路径)', async () => {+ await fs.promises.mkdir(path.join(ghostDir, 'templates', 'empty'), { recursive: true });++ // 未签名:walk 收集空目录。+ const unsigned = await exportGhostPackage('hello', makeDeps());+ expect(unsigned.status).toBe('saved');+ if (unsigned.status !== 'saved') return;+ const unsignedZip = await JSZip.loadAsync(await fs.promises.readFile(unsigned.savedPath));+ expect(unsignedZip.files['templates/empty/']?.dir).toBe(true);++ // 签名:dir 条目不参与 statement 哈希,补回不影响验签。+ await writeStatement(['ghost.json', 'locales/en.json', 'main.js']);+ const signed = await exportGhostPackage('hello', makeDeps());+ expect(signed.status).toBe('saved');+ if (signed.status !== 'saved') return;+ const signedZip = await JSZip.loadAsync(await fs.promises.readFile(signed.savedPath));+ expect(signedZip.files['templates/empty/']?.dir).toBe(true);+ });++ it('symlink 条目不跟随,不打进导出包', async () => {+ const outside = path.join(workDir, 'outside-secret');+ await fs.promises.mkdir(outside);+ await fs.promises.writeFile(path.join(outside, 'secret.txt'), 'secret');+ await fs.promises.symlink(outside, path.join(ghostDir, 'linked-dir'));+ await fs.promises.symlink(+ path.join(outside, 'secret.txt'),+ path.join(ghostDir, 'linked-file.js'),+ );++ const result = await exportGhostPackage('hello', makeDeps());+ expect(result.status).toBe('saved');+ if (result.status !== 'saved') return;+ const zip = await JSZip.loadAsync(await fs.promises.readFile(result.savedPath));+ const names = Object.values(zip.files)+ .filter((entry) => !entry.dir)+ .map((entry) => entry.name);+ expect(names).not.toContain('linked-dir/secret.txt');+ expect(names).not.toContain('linked-file.js');+ });++ it('默认文件名携带插件名与版本号,落在下载目录', async () => {+ const showSaveDialog = vi.fn(async () => ({ canceled: true }));+ await exportGhostPackage('hello', makeDeps({ showSaveDialog }));+ expect(showSaveDialog).toHaveBeenCalledWith({+ defaultPath: path.join(workDir, 'Hello 插件-1.2.0.cindy'),+ filters: [{ name: 'Cindy Plugin', extensions: ['cindy'] }],+ });+ });++ it('未安装返回 not_installed;非法 id 返回 invalid_id', async () => {+ await expect(exportGhostPackage('missing', makeDeps())).resolves.toEqual({+ status: 'not_installed',+ });+ await expect(exportGhostPackage('../escape', makeDeps())).resolves.toEqual({+ status: 'invalid_id',+ });+ await expect(exportGhostPackage(42, makeDeps())).resolves.toEqual({+ status: 'invalid_id',+ });+ });++ it('导出前先把字节快照进内存:对话框期间目录被换掉也不混版本', async () => {+ let resolveDialog: ((value: { canceled: boolean; filePath?: string }) => void) | null = null;+ const showSaveDialog = vi.fn(+ () =>+ new Promise<{ canceled: boolean; filePath?: string }>((resolve) => {+ resolveDialog = resolve;+ }),+ );+ const pending = exportGhostPackage('hello', makeDeps({ showSaveDialog }));+ // 等快照与压缩完成、对话框弹出后再模拟"更新换目录"。+ await vi.waitFor(() => expect(showSaveDialog).toHaveBeenCalled());+ await fs.promises.rm(ghostDir, { recursive: true, force: true });+ await fs.promises.mkdir(ghostDir, { recursive: true });+ await fs.promises.writeFile(path.join(ghostDir, 'ghost.json'), '{"id":"hello","version":"9.9.9"}');+ resolveDialog!({ canceled: false, filePath: path.join(workDir, 'out.cindy') });++ const result = await pending;+ expect(result.status).toBe('saved');+ if (result.status !== 'saved') return;+ const zip = await JSZip.loadAsync(await fs.promises.readFile(result.savedPath));+ // 内容仍是快照时的 1.2.0 完整包,不是换目录后的残缺新版。+ const names = Object.values(zip.files)+ .filter((entry) => !entry.dir)+ .map((entry) => entry.name)+ .sort();+ expect(names).toEqual(['ghost.json', 'locales/en.json', 'main.js']);+ });++ it('多字节名称组合后按 UTF-8 字节截断,不超 255 分量上限', async () => {+ // 64 个中文字符的名 + 32 个中文字符的版本:按码元各截 80 也仍有+ // 96 码元 × 3 字节 + '.cindy' > 255 字节,Linux 上会 ENAMETOOLONG。+ const ghost = makeGhost();+ ghost.manifest = {+ ...ghost.manifest,+ name: '插'.repeat(64),+ version: '版'.repeat(32),+ };+ const showSaveDialog = vi.fn(+ async (_opts: { defaultPath: string }) => ({ canceled: true as const }),+ );+ await exportGhostPackage('hello', makeDeps({+ listInstalled: () => [ghost],+ showSaveDialog,+ }));+ const defaultPath = showSaveDialog.mock.calls[0]?.[0].defaultPath ?? '';+ const base = path.basename(defaultPath);+ expect(Buffer.byteLength(base, 'utf8')).toBeLessThanOrEqual(255);+ expect(base.endsWith('.cindy')).toBe(true);+ });++ it('版本号含路径分隔符时清洗后再拼默认文件名', async () => {+ const ghost = makeGhost();+ ghost.manifest = { ...ghost.manifest, version: '1/../../etc' };+ const showSaveDialog = vi.fn(+ async (_opts: { defaultPath: string }) => ({ canceled: true as const }),+ );+ await exportGhostPackage('hello', makeDeps({+ listInstalled: () => [ghost],+ showSaveDialog,+ }));+ const defaultPath = showSaveDialog.mock.calls[0]?.[0].defaultPath ?? '';+ expect(path.dirname(defaultPath)).toBe(workDir);+ expect(path.basename(defaultPath)).toBe('Hello 插件-1 .. .. etc.cindy');+ });++ it('取消保存返回 canceled,不写盘', async () => {+ const writeFile = vi.fn();+ const result = await exportGhostPackage('hello', makeDeps({+ showSaveDialog: vi.fn(async () => ({ canceled: true })),+ writeFile,+ }));+ expect(result).toEqual({ status: 'canceled' });+ expect(writeFile).not.toHaveBeenCalled();+ });++ it('写盘失败返回 write_failed', async () => {+ const result = await exportGhostPackage('hello', makeDeps({+ writeFile: () => Promise.reject(new Error('disk full')),+ }));+ expect(result).toEqual({ status: 'error', code: 'write_failed' });+ });++ it('用户选择覆盖既有文件时,写出完整新包内容', async () => {+ const target = path.join(workDir, 'existing.cindy');+ await fs.promises.writeFile(target, 'old-bytes');+ const result = await exportGhostPackage('hello', makeDeps({+ showSaveDialog: vi.fn(async () => ({ canceled: false, filePath: target })),+ }));+ expect(result).toEqual({ status: 'saved', savedPath: target });+ const zip = await JSZip.loadAsync(await fs.promises.readFile(target));+ const names = Object.values(zip.files)+ .filter((entry) => !entry.dir)+ .map((entry) => entry.name)+ .sort();+ expect(names).toEqual(['ghost.json', 'locales/en.json', 'main.js']);+ });++ it('安装目录不可读返回 read_failed', async () => {+ const ghost = makeGhost();+ ghost.dir = path.join(workDir, 'gone');+ const result = await exportGhostPackage('hello', makeDeps({+ listInstalled: () => [ghost],+ }));+ expect(result).toEqual({ status: 'error', code: 'read_failed' });+ });+});++describe('sanitizeExportFileNamePart', () => {+ it('剥掉文件系统非法字符与首尾点,折叠空白', () => {+ expect(sanitizeExportFileNamePart('my <plugin>: "v2"?')).toBe('my plugin v2');+ expect(sanitizeExportFileNamePart(' 多空 白 ')).toBe('多空 白');+ expect(sanitizeExportFileNamePart('..hidden')).toBe('hidden');+ });++ it('全非法字符时回落为空(调用方用 id 兜底)', () => {+ expect(sanitizeExportFileNamePart('<>:"/\\|?*')).toBe('');+ });++ it('剥掉 Windows 禁止的尾随点/空格', () => {+ expect(sanitizeExportFileNamePart('plugin. ')).toBe('plugin');+ expect(sanitizeExportFileNamePart('v1.0.')).toBe('v1.0');+ });++ it('Windows 保留设备名加前缀避让', () => {+ expect(sanitizeExportFileNamePart('aux')).toBe('_aux');+ expect(sanitizeExportFileNamePart('CON')).toBe('_CON');+ expect(sanitizeExportFileNamePart('com1')).toBe('_com1');+ expect(sanitizeExportFileNamePart('auxiliary')).toBe('auxiliary');+ });++ it('带扩展名的 Windows 保留设备名同样避让(按词干判断)', () => {+ expect(sanitizeExportFileNamePart('CON.txt')).toBe('_CON.txt');+ expect(sanitizeExportFileNamePart('nul.backup')).toBe('_nul.backup');+ expect(sanitizeExportFileNamePart('console.log')).toBe('console.log');+ });+});diff --git a/apps/desktop/src/main/cindy-brain/exportGhostPackage.ts b/apps/desktop/src/main/cindy-brain/exportGhostPackage.tsnew file mode 100644index 0000000000..6c1ab309fd--- /dev/null+++ b/apps/desktop/src/main/cindy-brain/exportGhostPackage.ts@@ -0,0 +1,601 @@+/**+ * exportGhostPackage+ * ---------------------------------------------------------------------------+ * 插件详情页「导出 .cindy」的打包业务体:把已装插件的安装目录重新打成+ * .cindy zip 包,供 main IPC handler 经系统保存对话框落盘。+ *+ * 设计(第一性原理:导出包必须可原样通过装入校验):+ *+ * 1) 签名包 —— 包内容由 statement 定义,不由目录枚举定义。+ * 装入校验 = 对 zip 重建 statement 并逐条等于 cindy-signatures.json+ * 里的 statement。因此导出 = statement 闭包 + 签名文件本身:逐文件+ * 读盘、重算 sha256 与 statement 比对,全部命中则导出包可证可重装。+ * statement 之外的任何内容(主机保留文件、Finder 残渣、任意深度的+ * .DS_Store、symlink 目标)天然不进入导出包,无需启发式过滤;任何+ * 文件缺失/哈希不符 = 目录被并发更新或篡改,整体重读后仍不符则+ * 如实报错。一致性、签名口径、竞争防护在这一步坍缩为同一件事。+ *+ * 2) 未签名包 —— 没有 statement 可锚定,退回目录归档:跳过根部主机+ * 保留文件与根部 .DS_Store(装入后残渣),symlink 不跟随,逐文件+ * 读字节并自算 sha256;校验遍重读重哈希逐位比对——内容级一致性,+ * 与路径/尺寸/mtime 等元数据碰撞彻底无关。任何文件在读窗口内被+ * 增删改都会哈希不符或条目错位,整体重读。+ *+ * 两路共用:包先在内存里打完再弹保存对话框——用户挑选位置期间插件被+ * 更新/卸载都不影响已抓内容。产物落盘前后过装入同口径的闸:体积在+ * 快照阶段增量限流(与 GhostManager 同一组常量,Node 插件运行期可能+ * 把目录写大;签名包先用 statement 声明口径短路);写盘后、上报成功+ * 前过装入校验本尊 GhostManager.inspect(带真实 trust registry,+ * statement/review 签名被篡改、manifest/node.entry 被改坏等「成功却+ * 装不回」的情形都拦在这里,不过闸删掉已写文件如实报错)。+ * Electron 对话框、安装目录解析与落盘全部注入,便于内存 harness 测试。+ */++import crypto from 'node:crypto';+import fs from 'node:fs';+import path from 'node:path';++import JSZip from 'jszip';++import { isValidGhostId, type InstalledGhost } from '../../shared/ghost.js';+import {+ MAX_BASIC_CINDY_FILE_BYTES,+ MAX_BASIC_UNCOMPRESSED_BYTES,+ MAX_BASIC_ZIP_ENTRIES,+ MAX_NODE_CINDY_FILE_BYTES,+ MAX_NODE_UNCOMPRESSED_BYTES,+ MAX_NODE_ZIP_ENTRIES,+} from './GhostManager.js';+import { GHOST_SIGNATURE_FILE, MAX_SIGNATURE_FILE_BYTES } from './ghostSignature.js';++export type ExportGhostPackageResult =+ | { status: 'saved'; savedPath: string }+ | { status: 'canceled' }+ | { status: 'invalid_id' }+ | { status: 'not_installed' }+ | {+ status: 'error';+ code:+ | 'read_failed'+ | 'compress_failed'+ | 'dialog_failed'+ | 'write_failed'+ | 'too_large'+ | 'verify_failed';+ };++export interface ExportGhostPackageDeps {+ /** 已装插件清单(GhostManager.list 的事实源)。 */+ listInstalled: () => InstalledGhost[];+ showSaveDialog(opts: {+ defaultPath: string;+ filters: Array<{ name: string; extensions: string[] }>;+ }): Promise<{ canceled: boolean; filePath?: string }>;+ /** 保存对话框 defaultPath 的目录部分(下载目录)。 */+ getDownloadsDir(): string;+ /** 保存对话框文件类型标签(调用方按当前 locale 本地化)。 */+ fileTypeLabel: string;+ writeFile(filePath: string, data: Buffer): Promise<void>;+ /**+ * 装入校验本尊(GhostManager.inspect + 装入侧不变量):临时产物写盘后、+ * 发布到目标前调用,返回是否通过。签名/未签名都过这道闸——statement+ * 被篡改成自洽、review 签名损坏、manifest/node.entry 被改坏、指令与+ * 其他已装插件撞名等「导出成功却装不回」的情形都由它拦下。+ */+ inspectPackage(filePath: string): Promise<boolean>;+}++/** 插件名清洗成文件名片段:空白折叠、剥掉文件系统非法字符,截断防爆长度。 */+const WINDOWS_RESERVED_BASENAME = /^(con|prn|aux|nul|com[1-9]|lpt[1-9])$/i;++export function sanitizeExportFileNamePart(name: string): string {+ let cleaned = name+ .replace(/[<>:"/\\|?*\x00-\x1f]/g, ' ')+ .replace(/\s+/g, ' ')+ .trim()+ .replace(/^\.+/, '')+ .slice(0, 80)+ .trim()+ // Windows 禁止尾随点/空格(截断后可能新产生,最后再剥一次)。+ .replace(/[. ]+$/, '');+ // Windows 保留设备名(含带扩展名形式,如 CON.txt 同样非法):+ // 按首个点前的词干判断,命中加前缀避让。+ const stem = cleaned.split('.', 1)[0] ?? cleaned;+ if (WINDOWS_RESERVED_BASENAME.test(stem)) cleaned = `_${cleaned}`;+ return cleaned;+}++/**+ * 按 UTF-8 字节数截断(评审 P1):文件系统按字节卡 255,按 UTF-16 码元+ * slice 管不住多字节字符(64 个中文名 + 32 个中文版本号会超)。+ * 按码点累加,不在多字节字符中间切断。+ */+function capToByteLength(s: string, maxBytes: number): string {+ if (Buffer.byteLength(s, 'utf8') <= maxBytes) return s;+ let out = '';+ let bytes = 0;+ for (const ch of s) {+ const b = Buffer.byteLength(ch, 'utf8');+ if (bytes + b > maxBytes) break;+ out += ch;+ bytes += b;+ }+ return out;+}++/** 完整文件名(不含扩展名)的字节上限:255 分量上限 - '.cindy'。 */+const MAX_EXPORT_BASENAME_BYTES = 249;++/** 导出包的一个条目。 */+interface PackageEntry {+ rel: string;+ data: Buffer;+}++// ---------------------------------------------------------------------------+// 签名包:statement 闭包+// ---------------------------------------------------------------------------++interface SignedDoc {+ /** 签名文件原始字节(原样进入导出包)。 */+ raw: Buffer;+ files: Array<{ path: string; sha256: string; bytes: number }>;+}++/**+ * 读取并解析签名文件。返回 null 表示插件未签名(文件不存在);文件存在+ * 但超上限或结构非法时抛错——装入侧只认 64KB 内的签名文件,超限签名+ * 反正过不了装入;静默降级成未签名导出会让重装后信任等级失真,+ * 不如如实报错。+ */+async function readSignedDoc(dir: string): Promise<SignedDoc | null> {+ const sigPath = path.join(dir, GHOST_SIGNATURE_FILE);+ // 先 stat 再读(评审 P1):超上限的签名文件反正过不了装入,不把它+ // 完整读进内存;读后再查一次字节数,挡住 stat 后被改大的窗口。+ let stat: fs.Stats;+ try {+ stat = await fs.promises.stat(sigPath);+ } catch (err) {+ if ((err as NodeJS.ErrnoException)?.code === 'ENOENT') return null;+ throw err;+ }+ if (stat.size > MAX_SIGNATURE_FILE_BYTES) throw new Error('signature file too large');+ const raw = await fs.promises.readFile(sigPath);+ if (raw.byteLength > MAX_SIGNATURE_FILE_BYTES) {+ throw new Error('signature file too large');+ }+ const doc = JSON.parse(raw.toString('utf8')) as {+ statement?: { files?: Array<{ path?: unknown; sha256?: unknown; bytes?: unknown }> };+ };+ const files = doc?.statement?.files;+ if (!Array.isArray(files)) throw new Error('invalid signature statement');+ const parsed: SignedDoc['files'] = [];+ for (const item of files) {+ if (+ typeof item?.path !== 'string' ||+ typeof item?.sha256 !== 'string' ||+ typeof item?.bytes !== 'number'+ ) {+ throw new Error('invalid signature statement entry');+ }+ parsed.push({ path: item.path, sha256: item.sha256, bytes: item.bytes });+ }+ return { raw, files: parsed };+}++/** statement 路径必须相对且不逃逸——装入侧已校验,这里防一手目录被改。 */+function isSafeStatementPath(p: string): boolean {+ if (p.length === 0 || p.startsWith('/') || p.includes('\\')) return false;+ return !p.split('/').includes('..');+}++/**+ * 按 statement 闭包读包:逐文件读盘并重算 sha256 比对。任何文件缺失、+ * 长度或哈希不符都返回 null(目录被并发更新/篡改,调用方整体重试)。+ * 通过即导出包内容——不多不少,可证可重装。+ */+async function readSignedEntries(dir: string, doc: SignedDoc): Promise<PackageEntry[] | null> {+ const out: PackageEntry[] = [{ rel: GHOST_SIGNATURE_FILE, data: doc.raw }];+ for (const item of doc.files) {+ if (!isSafeStatementPath(item.path)) return null;+ // 先 stat 对尺寸:与 statement 不符必然哈希也不符,不必把可能超限+ // 的文件读进内存(评审 P1:巨型缓存文件要先挡在分配之前)。+ let data: Buffer;+ try {+ const stat = await fs.promises.stat(path.join(dir, ...item.path.split('/')));+ if (stat.size !== item.bytes) return null;+ data = await fs.promises.readFile(path.join(dir, ...item.path.split('/')));+ } catch {+ return null;+ }+ if (data.byteLength !== item.bytes) return null;+ if (crypto.createHash('sha256').update(data).digest('hex') !== item.sha256) return null;+ out.push({ rel: item.path, data });+ }+ return out;+}++// ---------------------------------------------------------------------------+// 未签名包:目录归档 + 元数据双遍一致性校验+// ---------------------------------------------------------------------------++/**+ * 未签名包的跳过口径:根部主机保留文件与根部系统残渣。+ * 嵌套条目一律保留——它们可能是作者包内容。+ */+const EXPORT_SKIP_ROOT_FILES = new Set(['.disabled', '.cindy-trust.json', '.DS_Store']);+function shouldSkipExportEntry(name: string, relBase: string): boolean {+ return relBase === '' && EXPORT_SKIP_ROOT_FILES.has(name);+}++interface TreeFile extends PackageEntry {+ sha256: string;+}++type TreeMeta = Omit<TreeFile, 'data'>;++function sha256hex(data: Buffer): string {+ return crypto.createHash('sha256').update(data).digest('hex');+}++/**+ * 递归枚举安装目录,逐文件读字节并算 sha256。withData=true 时保留字节+ * (第一遍);否则只留哈希(校验遍)。两遍都锚定字节——一致性判定与+ * 路径/尺寸/mtime 等元数据碰撞彻底无关。symlink/junction 不跟随:只+ * 归档安装目录自身的真实内容。结果按 rel 排序供逐位比对。+ * 空目录(子树内不含保留文件)与文件一起记录、一起进两遍比对——目录+ * 结构也在一致性信封内。枚举走 opendir 流式迭代(评审 P1:readdir+ * 一次性物化 Dirent[],单目录海量条目会先分配再计数)。+ * 限流(评审 P1):+ * - 第一遍(budget):文件与目录都计条目;单文件先 stat,超剩余字节+ * 直接中止,不把巨型文件读进内存;+ * - 校验遍(expect):读取量被第一遍锚住——stat 尺寸与第一遍不符必然+ * 不一致,不读内容;第一遍没有的新文件同理(必然不一致)。+ */+interface TreePass<T> {+ items: T[];+ emptyDirs: string[];+}++async function walkTree(+ dir: string,+ withData: true,+ budget: { entriesLeft: number; bytesLeft: number },+): Promise<TreePass<TreeFile>>;+async function walkTree(+ dir: string,+ withData: false,+ expect: Map<string, number>,+): Promise<TreePass<TreeMeta>>;+async function walkTree(+ dir: string,+ withData: boolean,+ limit: { entriesLeft: number; bytesLeft: number } | Map<string, number>,+): Promise<TreePass<TreeFile | TreeMeta>> {+ const items: Array<TreeFile | TreeMeta> = [];+ const emptyDirs: string[] = [];+ const walk = async (cur: string, relBase: string): Promise<boolean> => {+ let hasContent = false;+ for await (const entry of await fs.promises.opendir(cur)) {+ if (shouldSkipExportEntry(entry.name, relBase)) continue;+ if (entry.isSymbolicLink()) continue;+ const abs = path.join(cur, entry.name);+ const rel = relBase ? `${relBase}/${entry.name}` : entry.name;+ if (entry.isDirectory()) {+ if (withData) {+ const budget = limit as { entriesLeft: number; bytesLeft: number };+ budget.entriesLeft -= 1;+ if (budget.entriesLeft < 0) throw new ExportTooLargeError();+ }+ const subHas = await walk(abs, rel);+ if (!subHas) emptyDirs.push(rel);+ hasContent = hasContent || subHas;+ } else if (entry.isFile()) {+ if (withData) {+ const budget = limit as { entriesLeft: number; bytesLeft: number };+ const stat = await fs.promises.stat(abs);+ if (stat.size > budget.bytesLeft) throw new ExportTooLargeError();+ const data = await fs.promises.readFile(abs);+ budget.entriesLeft -= 1;+ budget.bytesLeft -= Math.max(stat.size, data.byteLength);+ if (budget.entriesLeft < 0 || budget.bytesLeft < 0) {+ throw new ExportTooLargeError();+ }+ items.push({ rel, data, sha256: sha256hex(data) });+ } else {+ const expect = limit as Map<string, number>;+ const expectedSize = expect.get(rel);+ const stat =+ expectedSize !== undefined ? await fs.promises.stat(abs) : null;+ if (expectedSize === undefined || stat!.size !== expectedSize) {+ // 第一遍没有的新文件/尺寸被换:与第一遍必然不一致,+ // 不读内容(校验遍读取量由第一遍锚住)。+ items.push({ rel, sha256: '' });+ } else {+ const data = await fs.promises.readFile(abs);+ items.push({ rel, sha256: sha256hex(data) });+ }+ }+ hasContent = true;+ }+ }+ return hasContent;+ };+ await walk(dir, '');+ items.sort((a, b) => a.rel.localeCompare(b.rel));+ emptyDirs.sort();+ return { items, emptyDirs };+}++/**+ * 未签名包的一致性快照:更新会整体换目录、卸载会删目录,单遍逐文件读+ * 可能跨越两个文件系统状态。读完后第二遍重读重哈希——任何文件或目录+ * 在读窗口内被增删改都会哈希不符或条目错位;通过校验的包(文件+空+ * 目录)等于校验遍时刻的单一目录状态。+ */+async function snapshotUnsignedTree(+ dir: string,+ budget: { entriesLeft: number; bytesLeft: number },+): Promise<{ files: TreeFile[]; emptyDirs: string[] } | null> {+ const first = await walkTree(dir, true, budget);+ const expect = new Map(first.items.map((file) => [file.rel, file.data.byteLength]));+ const verify = await walkTree(dir, false, expect);+ const filesConsistent =+ first.items.length === verify.items.length &&+ first.items.every(+ (file, i) =>+ file.rel === verify.items[i]!.rel && file.sha256 === verify.items[i]!.sha256,+ );+ const dirsConsistent =+ first.emptyDirs.length === verify.emptyDirs.length &&+ first.emptyDirs.every((rel, i) => rel === verify.emptyDirs[i]);+ return filesConsistent && dirsConsistent+ ? { files: first.items, emptyDirs: first.emptyDirs }+ : null;+}++// ---------------------------------------------------------------------------+// 共用:带重试的快照(增量限流) + 打包 + 对话框落盘+// ---------------------------------------------------------------------------++/**+ * 快照入口:签名包走 statement 闭包,未签名包走目录归档。任一路在并发+ * 变更下拿不到一致结果(含更新/卸载途中的瞬时 IO 失败)就整体重试,+ * 上限 SNAPSHOT_MAX_ATTEMPTS 次;持续冲突返回 null,由调用方如实报错+ * 请用户重试。+ *+ * 体积上限在读快照阶段增量执行(评审 P1):不等全部读进内存再判定——+ * 签名包先用 statement 声明的条目数/字节数短路,未签名包边遍历边累计,+ * 超限立刻中止返回 'too_large',不把超限内容读进内存。+ */+const SNAPSHOT_MAX_ATTEMPTS = 3;++/** 快照超限:与瞬时 IO 失败区分,不进重试。 */+class ExportTooLargeError extends Error {}++interface SnapshotLimits {+ maxEntries: number;+ maxUncompressed: number;+}++interface PackageSnapshot {+ entries: PackageEntry[];+ /**+ * 递归后不含任何包内文件的目录(显式空目录)。安装会保留包里的目录+ * 条目,导出丢掉会让重装后插件找不到随包的空输出/缓存/模板目录;+ * dir 条目不参与 statement 哈希,补回不影响验签。+ */+ emptyDirs: string[];+}++/**+ * 递归收集空目录(子树内没有计入包内容的文件)。keep 判定文件是否计入+ * 包内容:签名包为 statement 成员。symlink 不跟随,与 walkTree 同口径。+ * 遍历到的每个条目(含未被 statement 覆盖的文件)都扣额度(评审 P1:+ * 海量非覆盖文件不能只靠 empty 计数兜底),超限抛 ExportTooLargeError。+ */+async function collectEmptyDirs(+ dir: string,+ keep: (rel: string) => boolean,+ budget: { entriesLeft: number },+): Promise<string[]> {+ const empty: string[] = [];+ const walk = async (cur: string, relBase: string): Promise<boolean> => {+ let hasContent = false;+ for await (const entry of await fs.promises.opendir(cur)) {+ if (shouldSkipExportEntry(entry.name, relBase)) continue;+ if (entry.isSymbolicLink()) continue;+ budget.entriesLeft -= 1;+ if (budget.entriesLeft < 0) throw new ExportTooLargeError();+ const abs = path.join(cur, entry.name);+ const rel = relBase ? `${relBase}/${entry.name}` : entry.name;+ if (entry.isDirectory()) {+ const subHas = await walk(abs, rel);+ if (!subHas) empty.push(rel);+ hasContent = hasContent || subHas;+ } else if (entry.isFile()) {+ if (keep(rel)) hasContent = true;+ }+ }+ return hasContent;+ };+ await walk(dir, '');+ return empty;+}++async function snapshotPackage(+ dir: string,+ limits: SnapshotLimits,+): Promise<PackageSnapshot | 'too_large' | null> {+ for (let attempt = 0; attempt < SNAPSHOT_MAX_ATTEMPTS; attempt++) {+ try {+ const doc = await readSignedDoc(dir);+ if (doc) {+ // 先用 statement 声明的口径短路,避免读取超限内容。+ const declaredBytes = doc.files.reduce((sum, file) => sum + file.bytes, 0);+ if (declaredBytes > limits.maxUncompressed || doc.files.length + 1 > limits.maxEntries) {+ return 'too_large';+ }+ // 目录结构信封(评审 P1):空目录不在 statement 哈希覆盖内,+ // 运行期 mkdir/rmdir 也不改签名文件字节——唯一可靠的锚是+ // 「窗口内稳定」:文件哈希校验前后各收集一遍,不一致即重试。+ const covered = new Set(doc.files.map((file) => file.path));+ const keep = (rel: string) => covered.has(rel);+ const dirsBefore = await collectEmptyDirs(dir, keep, { entriesLeft: limits.maxEntries });+ const entries = await readSignedEntries(dir, doc);+ if (!entries) continue;+ const dirsAfter = await collectEmptyDirs(dir, keep, { entriesLeft: limits.maxEntries });+ const dirsStable =+ dirsBefore.length === dirsAfter.length &&+ [...dirsBefore].sort().every((rel, i) => rel === [...dirsAfter].sort()[i]);+ if (!dirsStable) continue;+ return { entries, emptyDirs: dirsAfter };+ } else {+ const budget = {+ entriesLeft: limits.maxEntries,+ bytesLeft: limits.maxUncompressed,+ };+ const tree = await snapshotUnsignedTree(dir, budget);+ if (tree) {+ return {+ entries: tree.files.map(({ rel, data }) => ({ rel, data })),+ emptyDirs: tree.emptyDirs,+ };+ }+ }+ } catch (err) {+ // 超限是确定性结果,不重试;其余(并发更新/卸载途中的目录短暂+ // 缺失、半写文件等瞬时失败)整体重读。+ if (err instanceof ExportTooLargeError) return 'too_large';+ }+ }+ return null;+}++export async function exportGhostPackage(+ id: unknown,+ deps: ExportGhostPackageDeps,+): Promise<ExportGhostPackageResult> {+ if (typeof id !== 'string' || !isValidGhostId(id)) {+ return { status: 'invalid_id' };+ }+ const ghost = deps.listInstalled().find((candidate) => candidate.manifest.id === id);+ if (!ghost) return { status: 'not_installed' };++ // 双保险:dir 来自 GhostManager 扫描,这里再确认它是真实目录(lstat+ // 不跟随链接),避免把被替换成 symlink/junction 的注册项当成打包源。+ try {+ const dirStat = await fs.promises.lstat(ghost.dir);+ if (!dirStat.isDirectory()) throw new Error('not a directory');+ } catch {+ return { status: 'error', code: 'read_failed' };+ }++ // 一致性快照(口径见文件头),体积上限在快照阶段增量执行——+ // snapshotPackage 返回 null = 持续并发冲突,'too_large' = 超装入上限。+ const isNode = Boolean(ghost.manifest.node);+ const limits: SnapshotLimits = {+ maxEntries: isNode ? MAX_NODE_ZIP_ENTRIES : MAX_BASIC_ZIP_ENTRIES,+ maxUncompressed: isNode ? MAX_NODE_UNCOMPRESSED_BYTES : MAX_BASIC_UNCOMPRESSED_BYTES,+ };+ const maxArchive = isNode ? MAX_NODE_CINDY_FILE_BYTES : MAX_BASIC_CINDY_FILE_BYTES;+ const snapshot = await snapshotPackage(ghost.dir, limits);+ if (snapshot === 'too_large') return { status: 'error', code: 'too_large' };+ if (!snapshot) return { status: 'error', code: 'read_failed' };++ const zip = new JSZip();+ for (const rel of snapshot.emptyDirs) {+ zip.folder(rel);+ }+ for (const file of snapshot.entries) {+ zip.file(file.rel, file.data);+ }+ if (Object.keys(zip.files).length > limits.maxEntries) {+ return { status: 'error', code: 'too_large' };+ }+ let buf: Buffer;+ try {+ buf = await zip.generateAsync({ type: 'nodebuffer', compression: 'DEFLATE' });+ } catch {+ // 压缩失败(zlib 等)如实落到结构化结果,不冒成未捕获的 IPC 异常。+ return { status: 'error', code: 'compress_failed' };+ }+ if (buf.byteLength > maxArchive) return { status: 'error', code: 'too_large' };++ const baseName = sanitizeExportFileNamePart(ghost.manifest.name) || ghost.manifest.id;+ // 版本同样来自作者清单,可能与名字一样含路径分隔符/控制字符,+ // 必须走同一道清洗再拼进默认文件名。组合后按 UTF-8 字节数截断——+ // 文件系统按字节卡 255,多字节字符按码元 slice 管不住。+ const versionPart = sanitizeExportFileNamePart(ghost.manifest.version);+ const baseComposed = capToByteLength(+ versionPart ? `${baseName}-${versionPart}` : baseName,+ MAX_EXPORT_BASENAME_BYTES,+ );+ const defaultFileName = `${baseComposed}.cindy`;++ let picked: { canceled: boolean; filePath?: string };+ try {+ picked = await deps.showSaveDialog({+ defaultPath: path.join(deps.getDownloadsDir(), defaultFileName),+ filters: [{ name: deps.fileTypeLabel, extensions: ['cindy'] }],+ });+ } catch {+ return { status: 'error', code: 'dialog_failed' };+ }+ if (picked.canceled || !picked.filePath) return { status: 'canceled' };++ // 先写临时文件 → inspect 校验 → 过闸才发布到目标(评审 P1):+ // 不过闸只清临时文件——直接写目标再删会在「用户选择覆盖旧备份且+ // 校验失败」时毁掉用户原有文件;先写目标也会在写一半崩溃时留下+ // 坏包。临时名带随机段,发布优先 rename(POSIX 原子覆盖);Windows+ // 不覆盖已存在目标,仅在 EPERM/EEXIST/EACCES 且目标确实存在时退化+ // unlink+rename(该路径只在用户显式选择覆盖时到达)。+ const targetPath = picked.filePath;+ const tempPath = path.join(+ path.dirname(targetPath),+ `.cindy-export-${process.pid}-${crypto.randomBytes(6).toString('hex')}.tmp`,+ );+ try {+ await deps.writeFile(tempPath, buf);+ } catch {+ await fs.promises.rm(tempPath, { force: true }).catch(() => {});+ return { status: 'error', code: 'write_failed' };+ }++ // 装入校验终闸(评审 P1):产物必须能原样过 GhostManager.inspect——+ // 它带真实 trust registry 与全部装入校验(review 签名、manifest、+ // node.entry、指令查重、条目/体积),statement 篡改成自洽、目录被+ // 改坏等情形都拦在这里,不产出「成功却装不回」的包。+ let installable = false;+ try {+ installable = await deps.inspectPackage(tempPath);+ } catch {+ installable = false;+ }+ if (!installable) {+ await fs.promises.rm(tempPath, { force: true }).catch(() => {});+ return { status: 'error', code: 'verify_failed' };+ }++ try {+ await fs.promises.rename(tempPath, targetPath);+ } catch (renameErr) {+ const code = (renameErr as NodeJS.ErrnoException)?.code;+ const targetExists =+ code === 'EPERM' || code === 'EEXIST' || code === 'EACCES'+ ? await fs.promises.access(targetPath).then(() => true, () => false)+ : false;+ if (!targetExists) {+ await fs.promises.rm(tempPath, { force: true }).catch(() => {});+ return { status: 'error', code: 'write_failed' };+ }+ try {+ await fs.promises.rm(targetPath, { force: true });+ await fs.promises.rename(tempPath, targetPath);+ } catch {+ await fs.promises.rm(tempPath, { force: true }).catch(() => {});+ return { status: 'error', code: 'write_failed' };+ }+ }+ return { status: 'saved', savedPath: targetPath };+}diff --git a/apps/desktop/src/main/cindy-brain/ghostSignature.ts b/apps/desktop/src/main/cindy-brain/ghostSignature.tsindex c92751ed55..742331bce0 100644--- a/apps/desktop/src/main/cindy-brain/ghostSignature.ts+++ b/apps/desktop/src/main/cindy-brain/ghostSignature.ts@@ -22,7 +22,7 @@ import {} from '../../shared/ghost.js';export const GHOST_SIGNATURE_FILE = 'cindy-signatures.json';-const MAX_SIGNATURE_FILE_BYTES = 64 * 1024;+export const MAX_SIGNATURE_FILE_BYTES = 64 * 1024;const MAX_SIGNED_CONTENT_BYTES = 256 * 1024 * 1024;export interface GhostTrustedKey {diff --git a/apps/desktop/src/main/cindy-brain/index.ts b/apps/desktop/src/main/cindy-brain/index.tsindex 255f5684cf..e5caa538e9 100644--- a/apps/desktop/src/main/cindy-brain/index.ts+++ b/apps/desktop/src/main/cindy-brain/index.ts@@ -35,6 +35,7 @@ import {} from '../appSessionState.js';import { getLayoutStore } from '../layout/index.js';import { GhostManager, type InstallRejection, type UninstallRejection } from './GhostManager.js';+import { exportGhostPackage } from './exportGhostPackage.js';import { GhostMutationCoordinator } from './ghostMutationCoordinator.js';import {clearBuiltinTombstone,@@ -3816,6 +3817,63 @@ export function registerGhostIpc(): void {return { ok: true };});+ // 详情页「导出 .cindy」:把已装插件的安装目录重新打成 zip 包,经系统+ // 保存对话框写到用户选定的位置。取消选择返回 { status: 'canceled' },+ // 不算错误;导出失败抛 IPC 错误(renderer 映射 toast)。+ // 快照是一致性快照(签名包逐文件 sha256 比对 statement;未签名包+ // 第二遍重读重哈希比对),导出与更新/卸载并发也不会产出混合版本+ // 的坏包。+ ipcMain.handle('ghosts:export', async (event, id: unknown) => {+ assertTrustedAppRendererEvent(event);+ // 官方保留前缀在本地装入链路被拒,导出产物装不回——renderer 菜单+ // 只是隐藏,handler 才是真正的强制边界(评审 P1)。+ if (typeof id === 'string') rejectReservedGhostId(id);+ const win = BrowserWindow.fromWebContents(event.sender);+ const result = await exportGhostPackage(id, {+ listInstalled: () => manager.list(),+ showSaveDialog: (opts) =>+ win ? dialog.showSaveDialog(win, opts) : dialog.showSaveDialog(opts),+ getDownloadsDir: () => app.getPath('downloads'),+ fileTypeLabel: t('settings.ghosts.detail.exportFileType'),+ writeFile: (filePath, data) => fs.promises.writeFile(filePath, data),+ // 装入校验本尊 + 装入侧不变量:manager.inspect 带真实 trust+ // registry;指令查重与 tokenBroker 门控只存在于 install/update,+ // inspect 不覆盖,这里按同一口径补齐(评审 P1)。+ inspectPackage: async (filePath) => {+ const probe = await manager.inspect(filePath);+ if ('rejection' in probe) return false;+ // tokenBroker 门控(同 rejectUnauthorizedTokenBroker):第三方包+ // 声明即不可装入,官方前缀豁免。+ const brokered = (probe.manifest.network?.secrets ?? []).some(+ (s) => s.oauth?.tokenBroker !== undefined,+ );+ if (brokered && !isOfficialGhostId(probe.manifest.id)) return false;+ // 指令查重(同 install/update):与当前已装撞名即拒,排除自身。+ const commandFold = probe.manifest.command?.toLowerCase();+ if (commandFold === undefined) return true;+ return !manager.list().some(+ (g) =>+ g.manifest.id !== probe.manifest.id &&+ g.manifest.command !== undefined &&+ g.manifest.command.toLowerCase() === commandFold,+ );+ },+ });+ switch (result.status) {+ case 'saved':+ log.info('ghost exported', { id: String(id) });+ return { status: 'saved' as const, savedPath: result.savedPath };+ case 'canceled':+ return { status: 'canceled' as const };+ case 'invalid_id':+ return throwIpcError('INVALID_PARAMS', 'id must be a valid Ghost id');+ case 'not_installed':+ return throwIpcError('NOT_FOUND', `意识 ${String(id)} 未安装`);+ case 'error':+ return throwIpcError('INTERNAL', `导出插件失败(${result.code})`);+ }+ });+// 内置意识状态(sendSync:设置页与已装清单同帧渲染,规则 7 无跳变)——// builtinIds 给列表分组/打"内置"标,enterpriseIds(其子集)把企业档单列// 一组,restorable 给"已抽离可恢复"灰态行。diff --git a/apps/desktop/src/preload/preload.ts b/apps/desktop/src/preload/preload.tsindex cac5913801..6f62203810 100644--- a/apps/desktop/src/preload/preload.ts+++ b/apps/desktop/src/preload/preload.ts@@ -885,6 +885,9 @@ contextBridge.exposeInMainWorld('electronAPI', {}> =>ipcRenderer.invoke('ghosts:inspect', lizFilePath),uninstall: (id: string): Promise<{ ok: true }> => ipcRenderer.invoke('ghosts:uninstall', id),+ /** 详情页「导出 .cindy」:main 打包安装目录 → 系统保存对话框落盘。 */+ export: (id: string): Promise<{ status: 'saved'; savedPath: string } | { status: 'canceled' }> =>+ ipcRenderer.invoke('ghosts:export', id),setEnabled: (id: string, enabled: boolean): Promise<{ ok: true }> =>ipcRenderer.invoke('ghosts:set-enabled', id, enabled),/** 目录级禁用清单(插件页项目范围视图;sendSync 保证切换同帧渲染)。 */diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsxindex 9f37371329..d6dbdb013c 100644--- a/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginDetailView.tsx@@ -15,6 +15,7 @@ import {ChevronDown,Copy,Cpu,+ Download,FileCode2,FilePen,FolderOpen,@@ -73,6 +74,8 @@ interface GhostPluginDetailViewProps {updateVersion?: string;updateBusy?: boolean;onUninstall: () => void;+ /** 导出 .cindy;当前详情非已装插件(纯市场视图)时缺省,菜单项不渲染。 */+ onExport?: () => void;toggleDisabled: boolean;onIconLoadError?: () => void;}@@ -133,6 +136,7 @@ export function GhostPluginDetailView({updateVersion,updateBusy = false,onUninstall,+ onExport,toggleDisabled,onIconLoadError,}: GhostPluginDetailViewProps) {@@ -282,6 +286,15 @@ export function GhostPluginDetailView({>{updateLabel ?? t('settings.ghosts.detail.updateFromFile')}</DropdownMenuItem>+ {onExport ? (+ <DropdownMenuItem+ onSelect={onExport}+ className="h-10 gap-2.5 rounded-lg px-3 text-13 focus:bg-[var(--surface-hover-soft)]"+ >+ <Download size={15} aria-hidden="true" />+ {t('settings.ghosts.detail.exportPackage')}+ </DropdownMenuItem>+ ) : null}<DropdownMenuSeparator className="mx-2 my-1 h-px bg-[var(--border-default)]" /><DropdownMenuItemonSelect={onUninstall}diff --git a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsxindex 0a9d93c359..547bff9511 100644--- a/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx+++ b/apps/desktop/src/renderer/features/plugin/GhostPluginPage.tsx@@ -44,6 +44,7 @@ import {diffGhostPermissionItems,ghostPanelKind,ghostPermissionItems,+ isOfficialGhostId,type GhostSetupStatus,} from '../../../shared/ghost';import type {@@ -627,6 +628,19 @@ export function GhostPluginPage() {}}, [handleUseGhost, selectedDetail, selectedGhost]);+ // 导出当前插件的 .cindy 包:main 侧打包安装目录 → 系统保存对话框落盘。+ // 取消选择静默返回;成功/失败都如实 toast。+ const handleExport = useCallback(async () => {+ if (!selectedDetail) return;+ try {+ const result = await window.electronAPI.ghosts.export(selectedDetail.id);+ if (result.status === 'canceled') return;+ toast.success(t('settings.ghosts.toast.exported', { name: selectedDetail.name }));+ } catch {+ toast.error(t('settings.ghosts.toast.exportFailed', { name: selectedDetail.name }));+ }+ }, [selectedDetail, t]);+const handleUninstall = useCallback(async () => {if (!selectedDetail) return;const ok = await confirm({@@ -868,6 +882,13 @@ export function GhostPluginPage() {}updateBusy={selectedMarketUpdate !== null && marketBusyId !== null}onUninstall={() => void handleUninstall()}+ // 官方保留前缀(cindy-/filo-/xd-)的插件走本地装入会被拒,+ // 导出产物无法重装,不提供导出项。+ onExport={+ selectedGhost && !isOfficialGhostId(selectedDetail.id)+ ? () => void handleExport()+ : undefined+ }toggleDisabled={scopeDir !== null && selectedGhost !== null && !selectedGhost.enabled}onIconLoadError={handleMarketIconLoadError}/>diff --git a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsxindex f86783eb6e..b76a24c102 100644--- a/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx+++ b/apps/desktop/src/renderer/features/plugin/__tests__/GhostPluginDetailSections.test.tsx@@ -274,6 +274,49 @@ describe('Ghost plugin detail sections', () => {expect(onUpdate).not.toHaveBeenCalled();});+ it('renders an export menu item only when onExport is provided', async () => {+ vi.stubGlobal(+ 'ResizeObserver',+ class {+ observe() {}+ unobserve() {}+ disconnect() {}+ },+ );+ const baseProps = {+ ghost: null,+ detail,+ panelStatus: 'Docked',+ onBack: vi.fn(),+ onToggle: vi.fn(),+ onUse: vi.fn(),+ onUpdate: vi.fn(),+ onUninstall: vi.fn(),+ toggleDisabled: false,+ };++ // 未提供 onExport(纯市场视图):菜单里不出现导出项。+ const { unmount } = render(<GhostPluginDetailView {...baseProps} />);+ fireEvent.pointerDown(+ screen.getByRole('button', { name: 'settings.ghosts.detail.moreActions' }),+ { button: 0, ctrlKey: false },+ );+ expect(screen.queryByRole('menuitem', { name: 'settings.ghosts.detail.exportPackage' })).toBeNull();+ unmount();++ // 提供 onExport(已装插件):点击触发导出回调。+ const onExport = vi.fn();+ render(<GhostPluginDetailView {...baseProps} onExport={onExport} />);+ fireEvent.pointerDown(+ screen.getByRole('button', { name: 'settings.ghosts.detail.moreActions' }),+ { button: 0, ctrlKey: false },+ );+ fireEvent.click(+ screen.getByRole('menuitem', { name: 'settings.ghosts.detail.exportPackage' }),+ );+ expect(onExport).toHaveBeenCalledTimes(1);+ });+it('uses one metadata color and orders author, then version', () => {const { container } = render(<GhostPluginMetadata author="Cindy" version="1.1.4" />);diff --git a/apps/desktop/src/renderer/i18n/locales/en/common.json b/apps/desktop/src/renderer/i18n/locales/en/common.jsonindex e6dfb5f241..fc33c0e9fd 100644--- a/apps/desktop/src/renderer/i18n/locales/en/common.json+++ b/apps/desktop/src/renderer/i18n/locales/en/common.json@@ -2841,6 +2841,8 @@"uninstalled": "Uninstalled \"{{name}}\"","installedAsleep": "Installed \"{{name}}\" (disabled — enable it here anytime)","updated": "\"{{name}}\" updated to v{{version}}",+ "exported": "Exported the .cindy file for \"{{name}}\"",+ "exportFailed": "Couldn't export \"{{name}}\" — try again","projectDisabled": "Turned off \"{{name}}\" for this project (applies to new sessions)","projectEnabled": "\"{{name}}\" now follows the global setting in this project"},@@ -3033,6 +3035,8 @@"useDisabled": "Enable this Plugin before using it","moreActions": "More Plugin Actions","updateFromFile": "Update from .cindy File…",+ "exportPackage": "Export .cindy File…",+ "exportFileType": "Cindy Plugin","settingsTitle": "{{name}} Settings","settingsUnavailableUntilRestore": "Restore the plugin to use this configuration again.","configurationTitle": "Configuration",diff --git a/apps/desktop/src/renderer/i18n/locales/ja/common.json b/apps/desktop/src/renderer/i18n/locales/ja/common.jsonindex 27919018b3..c8da843f26 100644--- a/apps/desktop/src/renderer/i18n/locales/ja/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ja/common.json@@ -2840,6 +2840,8 @@"uninstalled": "「{{name}}」をアンインストールしました","installedAsleep": "「{{name}}」をインストールしました(無効状態。ここでいつでも有効化できます)","updated": "「{{name}}」を v{{version}} に更新しました",+ "exported": "「{{name}}」の .cindy ファイルを書き出しました",+ "exportFailed": "「{{name}}」を書き出せませんでした。もう一度お試しください","projectDisabled": "「{{name}}」をこのプロジェクトで無効にしました(新しいセッションから適用)","projectEnabled": "「{{name}}」はこのプロジェクトでグローバル設定に従います"},@@ -3032,6 +3034,8 @@"useDisabled": "使用する前に Plugin を有効にしてください","moreActions": "その他の Plugin 操作","updateFromFile": ".cindy ファイルから更新…",+ "exportPackage": ".cindy ファイルを書き出す…",+ "exportFileType": "Cindy プラグイン","settingsTitle": "{{name}} の設定","settingsUnavailableUntilRestore": "この設定を再び使用するには、プラグインを復元してください。","configurationTitle": "設定",diff --git a/apps/desktop/src/renderer/i18n/locales/ko/common.json b/apps/desktop/src/renderer/i18n/locales/ko/common.jsonindex c365ae8b45..e2cf0399ab 100644--- a/apps/desktop/src/renderer/i18n/locales/ko/common.json+++ b/apps/desktop/src/renderer/i18n/locales/ko/common.json@@ -2840,6 +2840,8 @@"uninstalled": "\"{{name}}\" 제거됨","installedAsleep": "\"{{name}}\" 설치 완료 (비활성 상태이며 여기에서 언제든 활성화할 수 있습니다)","updated": "\"{{name}}\"이(가) v{{version}}(으)로 업데이트되었습니다",+ "exported": "\"{{name}}\"의 .cindy 파일을 내보냈습니다",+ "exportFailed": "\"{{name}}\"을(를) 내보내지 못했습니다. 다시 시도하세요","projectDisabled": "이 프로젝트에서 \"{{name}}\"을(를) 껐습니다(새 세션부터 적용)","projectEnabled": "\"{{name}}\"이(가) 이 프로젝트에서 전역 설정을 따릅니다"},@@ -3032,6 +3034,8 @@"useDisabled": "사용하기 전에 Plugin을 활성화하세요","moreActions": "Plugin 추가 작업","updateFromFile": ".cindy 파일에서 업데이트…",+ "exportPackage": ".cindy 파일 내보내기…",+ "exportFileType": "Cindy 플러그인","settingsTitle": "{{name}} 설정","settingsUnavailableUntilRestore": "이 설정을 다시 사용하려면 플러그인을 복원하세요.","configurationTitle": "설정",diff --git a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.jsonindex 8417bcdf3d..960a0ee1a1 100644--- a/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json+++ b/apps/desktop/src/renderer/i18n/locales/zh-CN/common.json@@ -2840,6 +2840,8 @@"uninstalled": "已卸载「{{name}}」","installedAsleep": "已安装「{{name}}」(未生效,可在此开启)","updated": "「{{name}}」已更新到 v{{version}}",+ "exported": "已导出「{{name}}」的 .cindy 文件",+ "exportFailed": "导出「{{name}}」失败,请重试","projectDisabled": "已在此项目停用「{{name}}」(新对话生效)","projectEnabled": "「{{name}}」在此项目恢复跟随全局"},@@ -3032,6 +3034,8 @@"useDisabled": "请先开启插件","moreActions": "更多插件操作","updateFromFile": "从 .cindy 文件更新…",+ "exportPackage": "导出 .cindy 文件…",+ "exportFileType": "Cindy 插件","settingsTitle": "{{name}} 设置","settingsUnavailableUntilRestore": "恢复插件后可继续使用这项配置。","configurationTitle": "配置",diff --git a/apps/desktop/src/renderer/vite-env.d.ts b/apps/desktop/src/renderer/vite-env.d.tsindex 7dc504dc2e..7184337b8b 100644--- a/apps/desktop/src/renderer/vite-env.d.ts+++ b/apps/desktop/src/renderer/vite-env.d.ts@@ -1144,6 +1144,10 @@ interface ElectronAPI {iconDataUrl?: string;}>;uninstall: (id: string) => Promise<{ ok: true }>;+ /** 详情页「导出 .cindy」:打包安装目录 → 保存对话框落盘。 */+ export: (+ id: string,+ ) => Promise<{ status: 'saved'; savedPath: string } | { status: 'canceled' }>;/** 启用/停用(停用 = 面板休眠,布局位置保留)。 */setEnabled: (id: string, enabled: boolean) => Promise<{ ok: true }>;/** 目录级禁用清单(插件页项目范围视图;sendSync 切换同帧渲染)。 */